gobot.io/x/gobot@v1.16.0/examples/hello_api_video.go (about)

     1  // +build example
     2  //
     3  // Do not build by default.
     4  
     5  package main
     6  
     7  import (
     8  	"fmt"
     9  	"net/http"
    10  	"os"
    11  
    12  	"github.com/hybridgroup/mjpeg"
    13  	"gobot.io/x/gobot"
    14  	"gobot.io/x/gobot/api"
    15  	"gocv.io/x/gocv"
    16  )
    17  
    18  var (
    19  	deviceID int
    20  	err      error
    21  	webcam   *gocv.VideoCapture
    22  	stream   *mjpeg.Stream
    23  )
    24  
    25  func main() {
    26  	// parse args
    27  	deviceID := os.Args[1]
    28  
    29  	master := gobot.NewMaster()
    30  
    31  	a := api.NewAPI(master)
    32  
    33  	// add the standard C3PIO API routes manually.
    34  	a.AddC3PIORoutes()
    35  
    36  	// starts the API without the default C2PIO API and Robeaux web interface.
    37  	// However, the C3PIO API was added manually using a.AddC3PIORoutes() which
    38  	// means the REST API will be available, but not the web interface.
    39  	a.StartWithoutDefaults()
    40  
    41  	hello := master.AddRobot(gobot.NewRobot("hello"))
    42  
    43  	hello.AddCommand("hi_there", func(params map[string]interface{}) interface{} {
    44  		return fmt.Sprintf("This command is attached to the robot %v", hello.Name)
    45  	})
    46  
    47  	// open webcam
    48  	webcam, err = gocv.OpenVideoCapture(deviceID)
    49  	if err != nil {
    50  		fmt.Printf("Error opening capture device: %v\n", deviceID)
    51  		return
    52  	}
    53  	defer webcam.Close()
    54  
    55  	// create the mjpeg stream
    56  	stream = mjpeg.NewStream()
    57  	http.Handle("/video", stream)
    58  
    59  	// start capturing
    60  	go mjpegCapture()
    61  
    62  	master.Start()
    63  }
    64  
    65  func mjpegCapture() {
    66  	img := gocv.NewMat()
    67  	defer img.Close()
    68  
    69  	for {
    70  		if ok := webcam.Read(&img); !ok {
    71  			fmt.Printf("Device closed: %v\n", deviceID)
    72  			return
    73  		}
    74  		if img.Empty() {
    75  			continue
    76  		}
    77  
    78  		buf, _ := gocv.IMEncode(".jpg", img)
    79  		stream.UpdateJPEG(buf)
    80  	}
    81  }