hybridgroup.gobot/platforms/keyboard/keyboard_driver.go

94 lines
1.5 KiB
Go
Raw Normal View History

2015-07-10 02:33:46 +08:00
package keyboard
import (
"log"
"os"
"github.com/hybridgroup/gobot"
)
const (
// Key board event
Key = "key"
)
// Driver is gobot software device to the keyboard
type Driver struct {
2015-07-10 02:33:46 +08:00
name string
connect func(*Driver) (err error)
listen func(*Driver)
2015-07-10 02:33:46 +08:00
stdin *os.File
gobot.Eventer
}
// NewDriver returns a new keyboard Driver.
//
func NewDriver() *Driver {
k := &Driver{
name: "Keyboard",
connect: func(k *Driver) (err error) {
2015-07-10 02:33:46 +08:00
if err := configure(); err != nil {
return err
}
k.stdin = os.Stdin
return
},
listen: func(k *Driver) {
2015-07-10 02:33:46 +08:00
ctrlc := bytes{3}
for {
var keybuf bytes
k.stdin.Read(keybuf[0:3])
if keybuf == ctrlc {
proc, err := os.FindProcess(os.Getpid())
if err != nil {
log.Fatal(err)
}
proc.Signal(os.Interrupt)
break
}
k.Publish(Key, Parse(keybuf))
2015-07-10 02:33:46 +08:00
}
},
Eventer: gobot.NewEventer(),
}
k.AddEvent(Key)
2015-07-10 02:33:46 +08:00
return k
}
// Name returns the Driver Name
func (k *Driver) Name() string { return k.name }
// SetName sets the Driver Name
func (k *Driver) SetName(n string) { k.name = n }
// Connection returns the Driver Connection
func (k *Driver) Connection() gobot.Connection { return nil }
2015-07-10 02:33:46 +08:00
// Start initializes keyboard by grabbing key events as they come in and
// publishing each as a key event
func (k *Driver) Start() (err error) {
if err = k.connect(k); err != nil {
return err
2015-07-10 02:33:46 +08:00
}
go k.listen(k)
return
}
// Halt stops keyboard driver
func (k *Driver) Halt() (err error) {
2015-07-10 02:33:46 +08:00
if originalState != "" {
return restore()
}
return
}