hybridgroup.gobot/driver.go

90 lines
1.7 KiB
Go
Raw Normal View History

2014-04-30 23:10:44 +08:00
package gobot
2013-10-24 13:00:03 +08:00
2014-06-24 11:33:59 +08:00
import (
"fmt"
"time"
)
2014-05-03 18:31:11 +08:00
2013-10-24 13:00:03 +08:00
type Driver struct {
Adaptor AdaptorInterface
Interval time.Duration
Pin string
Name string
2014-07-03 09:08:44 +08:00
commands map[string]func(map[string]interface{}) interface{}
Events map[string]*Event
2014-06-24 11:33:59 +08:00
Type string
2013-10-24 13:00:03 +08:00
}
type DriverInterface interface {
Start() bool
2014-04-01 05:25:20 +08:00
Halt() bool
adaptor() AdaptorInterface
2014-06-07 05:44:16 +08:00
setInterval(time.Duration)
2014-06-14 01:09:03 +08:00
interval() time.Duration
2014-06-07 05:44:16 +08:00
setName(string)
2014-06-14 01:09:03 +08:00
name() string
2014-07-03 09:08:44 +08:00
Commands() map[string]func(map[string]interface{}) interface{}
2014-06-24 11:33:59 +08:00
ToJSON() *JSONDevice
2014-06-07 05:44:16 +08:00
}
func (d *Driver) adaptor() AdaptorInterface {
return d.Adaptor
}
2014-06-07 05:44:16 +08:00
func (d *Driver) setInterval(t time.Duration) {
d.Interval = t
}
2014-06-14 01:09:03 +08:00
func (d *Driver) interval() time.Duration {
2014-06-07 05:44:16 +08:00
return d.Interval
}
func (d *Driver) setName(s string) {
d.Name = s
}
2014-06-14 01:09:03 +08:00
func (d *Driver) name() string {
2014-06-07 05:44:16 +08:00
return d.Name
2013-10-24 13:00:03 +08:00
}
2014-06-12 08:41:04 +08:00
2014-07-03 09:08:44 +08:00
func (d *Driver) Commands() map[string]func(map[string]interface{}) interface{} {
return d.commands
2014-06-12 08:41:04 +08:00
}
2014-06-14 01:09:03 +08:00
func (d *Driver) AddCommand(name string, f func(map[string]interface{}) interface{}) {
2014-07-03 09:08:44 +08:00
d.Commands()[name] = f
2014-06-12 08:41:04 +08:00
}
2014-06-24 11:33:59 +08:00
2014-07-03 09:08:44 +08:00
func NewDriver(name string, t string, a AdaptorInterface) *Driver {
2014-06-24 11:33:59 +08:00
if name == "" {
name = fmt.Sprintf("%X", Rand(int(^uint(0)>>1)))
}
return &Driver{
Type: t,
Name: name,
Interval: 10 * time.Millisecond,
2014-07-03 09:08:44 +08:00
commands: make(map[string]func(map[string]interface{}) interface{}),
2014-06-24 11:33:59 +08:00
Adaptor: a,
}
}
func (d *Driver) ToJSON() *JSONDevice {
jsonDevice := &JSONDevice{
Name: d.Name,
Driver: d.Type,
Commands: []string{},
Connection: nil,
}
if d.adaptor() != nil {
2014-07-03 09:08:44 +08:00
jsonDevice.Connection = d.adaptor().ToJSON()
2014-06-24 11:33:59 +08:00
}
2014-07-03 09:08:44 +08:00
commands := d.Commands()
2014-06-24 11:33:59 +08:00
for command := range commands {
jsonDevice.Commands = append(jsonDevice.Commands, command)
}
return jsonDevice
}