2015-07-10 02:33:46 +08:00
|
|
|
package keyboard
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"github.com/hybridgroup/gobot"
|
|
|
|
)
|
|
|
|
|
2016-09-01 18:17:43 +08:00
|
|
|
const (
|
2016-12-01 06:32:20 +08:00
|
|
|
// Key board event
|
2016-09-01 18:17:43 +08:00
|
|
|
Key = "key"
|
|
|
|
)
|
|
|
|
|
2016-12-01 06:32:20 +08:00
|
|
|
// Driver is gobot software device to the keyboard
|
2016-09-26 03:27:37 +08:00
|
|
|
type Driver struct {
|
2015-07-10 02:33:46 +08:00
|
|
|
name string
|
2016-09-26 03:27:37 +08:00
|
|
|
connect func(*Driver) (err error)
|
|
|
|
listen func(*Driver)
|
2015-07-10 02:33:46 +08:00
|
|
|
stdin *os.File
|
|
|
|
gobot.Eventer
|
|
|
|
}
|
|
|
|
|
2016-12-01 06:32:20 +08:00
|
|
|
// NewDriver returns a new keyboard Driver.
|
|
|
|
//
|
2016-09-26 03:27:37 +08:00
|
|
|
func NewDriver() *Driver {
|
|
|
|
k := &Driver{
|
2016-10-04 01:06:37 +08:00
|
|
|
name: "Keyboard",
|
2016-09-26 03:27:37 +08:00
|
|
|
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
|
|
|
|
},
|
2016-09-26 03:27:37 +08:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2016-09-01 18:17:43 +08:00
|
|
|
k.Publish(Key, Parse(keybuf))
|
2015-07-10 02:33:46 +08:00
|
|
|
|
|
|
|
}
|
|
|
|
},
|
|
|
|
Eventer: gobot.NewEventer(),
|
|
|
|
}
|
|
|
|
|
2016-09-01 18:17:43 +08:00
|
|
|
k.AddEvent(Key)
|
2015-07-10 02:33:46 +08:00
|
|
|
|
|
|
|
return k
|
|
|
|
}
|
|
|
|
|
2016-12-01 06:32:20 +08:00
|
|
|
// 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
|
2016-09-26 03:27:37 +08:00
|
|
|
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
|
2016-12-01 06:32:20 +08:00
|
|
|
// publishing each as a key event
|
2016-11-08 02:35:04 +08:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2016-12-01 06:32:20 +08:00
|
|
|
// Halt stops keyboard driver
|
2016-11-08 02:35:04 +08:00
|
|
|
func (k *Driver) Halt() (err error) {
|
2015-07-10 02:33:46 +08:00
|
|
|
if originalState != "" {
|
|
|
|
return restore()
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|