hybridgroup.gobot/examples/hello_api_video.go

86 lines
1.6 KiB
Go
Raw Normal View History

//go:build example
// +build example
//
// Do not build by default.
package main
import (
"fmt"
"net/http"
"os"
"github.com/hybridgroup/mjpeg"
"gobot.io/x/gobot/v2"
"gobot.io/x/gobot/v2/api"
"gocv.io/x/gocv"
)
var (
deviceID int
err error
webcam *gocv.VideoCapture
stream *mjpeg.Stream
)
func main() {
// parse args
deviceID := os.Args[1]
manager := gobot.NewManager()
a := api.NewAPI(manager)
// add the standard C3PIO API routes manually.
a.AddC3PIORoutes()
// starts the API without the default C2PIO API and Robeaux web interface.
// However, the C3PIO API was added manually using a.AddC3PIORoutes() which
// means the REST API will be available, but not the web interface.
a.StartWithoutDefaults()
hello := manager.AddRobot(gobot.NewRobot("hello"))
hello.AddCommand("hi_there", func(params map[string]interface{}) interface{} {
return fmt.Sprintf("This command is attached to the robot %v", hello.Name)
})
// open webcam
webcam, err = gocv.OpenVideoCapture(deviceID)
if err != nil {
fmt.Printf("Error opening capture device: %v\n", deviceID)
return
}
defer webcam.Close()
// create the mjpeg stream
stream = mjpeg.NewStream()
http.Handle("/video", stream)
// start capturing
go mjpegCapture()
if err := manager.Start(); err != nil {
panic(err)
}
}
func mjpegCapture() {
img := gocv.NewMat()
defer img.Close()
for {
if ok := webcam.Read(&img); !ok {
fmt.Printf("Device closed: %v\n", deviceID)
return
}
if img.Empty() {
continue
}
buf, _ := gocv.IMEncode(".jpg", img)
stream.UpdateJPEG(buf)
}
}