forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
examples: add example that uses both the API and also a custom handle…
…r with MJPEG streaming from an attached camera Signed-off-by: Ron Evans <[email protected]>
- Loading branch information
1 parent
2c8f9e8
commit 1e58136
Showing
1 changed file
with
78 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
// +build example | ||
// | ||
// Do not build by default. | ||
|
||
package main | ||
|
||
import ( | ||
"fmt" | ||
"net/http" | ||
"os" | ||
|
||
"github.com/hybridgroup/mjpeg" | ||
"gobot.io/x/gobot" | ||
"gobot.io/x/gobot/api" | ||
"gocv.io/x/gocv" | ||
) | ||
|
||
var ( | ||
deviceID int | ||
err error | ||
webcam *gocv.VideoCapture | ||
stream *mjpeg.Stream | ||
) | ||
|
||
func main() { | ||
// parse args | ||
deviceID := os.Args[1] | ||
|
||
master := gobot.NewMaster() | ||
|
||
a := api.NewAPI(master) | ||
a.AddC3PIORoutes() | ||
a.AddRobeauxRoutes() | ||
a.StartRaw() | ||
|
||
hello := master.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() | ||
|
||
// start capturing | ||
go mjpegCapture() | ||
|
||
// handle video stream | ||
http.Handle("/video", stream) | ||
|
||
master.Start() | ||
} | ||
|
||
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) | ||
} | ||
} |