forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
camera_driver.go
82 lines (69 loc) · 1.73 KB
/
camera_driver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package opencv
import (
"errors"
"time"
cv "github.com/hybridgroup/go-opencv/opencv"
"github.com/hybridgroup/gobot"
)
var _ gobot.Driver = (*CameraDriver)(nil)
type capture interface {
RetrieveFrame(int) *cv.IplImage
GrabFrame() bool
}
type CameraDriver struct {
name string
camera capture
interval time.Duration
Source interface{}
start func(*CameraDriver) (err error)
gobot.Eventer
}
// NewCameraDriver creates a new driver with specified name and source.
// It also creates a start function to either set camera as a File or Camera capture.
func NewCameraDriver(name string, source interface{}, v ...time.Duration) *CameraDriver {
c := &CameraDriver{
name: name,
Eventer: gobot.NewEventer(),
Source: source,
interval: 10 * time.Millisecond,
start: func(c *CameraDriver) (err error) {
switch v := c.Source.(type) {
case string:
c.camera = cv.NewFileCapture(v)
case int:
c.camera = cv.NewCameraCapture(v)
default:
return errors.New("Unknown camera source")
}
return
},
}
if len(v) > 0 {
c.interval = v[0]
}
c.AddEvent("frame")
return c
}
func (c *CameraDriver) Name() string { return c.name }
func (c *CameraDriver) Connection() gobot.Connection { return nil }
// Start initializes camera by grabbing a frame
// every `interval` and publishing an frame event
func (c *CameraDriver) Start() (errs []error) {
if err := c.start(c); err != nil {
return []error{err}
}
go func() {
for {
if c.camera.GrabFrame() {
image := c.camera.RetrieveFrame(1)
if image != nil {
gobot.Publish(c.Event("frame"), image)
}
}
<-time.After(c.interval)
}
}()
return
}
// Halt stops camera driver
func (c *CameraDriver) Halt() (errs []error) { return }