gobot.io/x/gobot/v2@v2.1.0/examples/hello_api_video.go (about)

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