// Start starts the MakeyButtonDriver and polls the state of the button at the given interval. // // Emits the Events: // Push int - On button push // Release int - On button release // Error error - On button error func (b *MakeyButtonDriver) Start() (errs []error) { state := 1 go func() { for { newValue, err := b.connection.DigitalRead(b.Pin()) if err != nil { gobot.Publish(b.Event(Error), err) } else if newValue != state && newValue != -1 { state = newValue if newValue == 0 { b.Active = true gobot.Publish(b.Event(Push), newValue) } else { b.Active = false gobot.Publish(b.Event(Release), newValue) } } select { case <-time.After(b.interval): case <-b.halt: return } } }() return }
// Start starts the GroveTemperatureSensorDriver and reads the Sensor at the given interval. // Emits the Events: // Data int - Event is emitted on change and represents the current temperature in celsius from the sensor. // Error error - Event is emitted on error reading from the sensor. func (a *GroveTemperatureSensorDriver) Start() (errs []error) { thermistor := 3975.0 a.temperature = 0 go func() { for { rawValue, err := a.Read() resistance := float64(1023.0-rawValue) * 10000 / float64(rawValue) newValue := 1/(math.Log(resistance/10000.0)/thermistor+1/298.15) - 273.15 if err != nil { gobot.Publish(a.Event(Error), err) } else if newValue != a.temperature && newValue != -1 { a.temperature = newValue gobot.Publish(a.Event(Data), a.temperature) } select { case <-time.After(a.interval): case <-a.halt: return } } }() return }
// TODO better pause and toogle handling func (gpsd *GpsdDriver) Start() (errs []error) { gpsd.w.GpsdWrite(START) go func() { var tpv gpsdjson.TPV for { if line, err := gpsd.r.GpsdRead(); err == nil { json.Unmarshal([]byte(line), &tpv) if tpv.Class == TPV { gobot.Publish(gpsd.Event(TPV), tpv) } } else { log.Println("Error reading on gpsd socket", err.Error()) gobot.Publish(gpsd.Event(ERROR), err) return } select { case <-time.After(gpsd.interval): case <-gpsd.halt: return } } }() return nil }
// HandleEvent publishes an specific event according to data received func (j *JoystickDriver) handleEvent(event sdl.Event) error { switch data := event.(type) { case *sdl.JoyAxisEvent: if data.Which == j.adaptor().joystick.InstanceID() { axis := j.findName(data.Axis, j.config.Axis) if axis == "" { return fmt.Errorf("Unknown Axis: %v", data.Axis) } gobot.Publish(j.Event(axis), data.Value) } case *sdl.JoyButtonEvent: if data.Which == j.adaptor().joystick.InstanceID() { button := j.findName(data.Button, j.config.Buttons) if button == "" { return fmt.Errorf("Unknown Button: %v", data.Button) } if data.State == 1 { gobot.Publish(j.Event(fmt.Sprintf("%s_press", button)), nil) } gobot.Publish(j.Event(fmt.Sprintf("%s_release", button)), nil) } case *sdl.JoyHatEvent: if data.Which == j.adaptor().joystick.InstanceID() { hat := j.findHatName(data.Value, data.Hat, j.config.Hats) if hat == "" { return fmt.Errorf("Unknown Hat: %v %v", data.Hat, data.Value) } gobot.Publish(j.Event(hat), true) } } return nil }
func (b *BLEMinidroneDriver) Init() (err error) { b.GenerateAllStates() // subscribe to battery notifications b.adaptor().Subscribe(DroneNotificationService, BatteryCharacteristic, func(data []byte, e error) { gobot.Publish(b.Event(Battery), data[len(data)-1]) }) // subscribe to flying status notifications b.adaptor().Subscribe(DroneNotificationService, FlightStatusCharacteristic, func(data []byte, e error) { if len(data) < 7 || data[2] != 2 { fmt.Println(data) return } gobot.Publish(b.Event(Status), data[6]) if (data[6] == 1 || data[6] == 2) && !b.flying { b.flying = true gobot.Publish(b.Event(Flying), true) } else if (data[6] == 0) && b.flying { b.flying = false gobot.Publish(b.Event(Landed), true) } }) return }
// Start inits leap motion driver by enabling gestures // and listening from incoming messages. // // Publishes the following events: // "message" - Emits Frame on new message received from Leap. // "hand" - Emits Hand when detected in message from Leap. // "gesture" - Emits Gesture when detected in message from Leap. func (l *LeapMotionDriver) Start() (errs []error) { enableGestures := map[string]bool{"enableGestures": true} b, err := json.Marshal(enableGestures) if err != nil { return []error{err} } _, err = l.adaptor().ws.Write(b) if err != nil { return []error{err} } go func() { var msg []byte var frame Frame for { receive(l.adaptor().ws, &msg) frame = l.ParseFrame(msg) gobot.Publish(l.Event("message"), frame) for _, hand := range frame.Hands { gobot.Publish(l.Event("hand"), hand) } for _, gesture := range frame.Gestures { gobot.Publish(l.Event("gesture"), gesture) } } }() return }
// Start writes initialization bytes and reads from adaptor // using specified interval to accelerometer andtemperature data func (h *MPU6050Driver) Start() (errs []error) { if err := h.initialize(); err != nil { return []error{err} } go func() { for { if err := h.connection.I2cWrite(mpu6050Address, []byte{MPU6050_RA_ACCEL_XOUT_H}); err != nil { gobot.Publish(h.Event(Error), err) continue } ret, err := h.connection.I2cRead(mpu6050Address, 14) if err != nil { gobot.Publish(h.Event(Error), err) continue } buf := bytes.NewBuffer(ret) binary.Read(buf, binary.BigEndian, &h.Accelerometer) binary.Read(buf, binary.BigEndian, &h.Gyroscope) binary.Read(buf, binary.BigEndian, &h.Temperature) <-time.After(h.interval) } }() return }
// Start initilizes i2c and reads from adaptor // using specified interval to update with new value func (w *WiichuckDriver) Start() (errs []error) { if err := w.connection.I2cStart(0x52); err != nil { return []error{err} } go func() { for { if err := w.connection.I2cWrite([]byte{0x40, 0x00}); err != nil { gobot.Publish(w.Event(Error), err) continue } if err := w.connection.I2cWrite([]byte{0x00}); err != nil { gobot.Publish(w.Event(Error), err) continue } newValue, err := w.connection.I2cRead(6) if err != nil { gobot.Publish(w.Event(Error), err) continue } if len(newValue) == 6 { if err = w.update(newValue); err != nil { gobot.Publish(w.Event(Error), err) continue } } <-time.After(w.interval) } }() return }
func ExampleOn() { e := gobot.NewEvent() gobot.On(e, func(s interface{}) { fmt.Println(s) }) gobot.Publish(e, 100) gobot.Publish(e, 200) }
// updateButtons publishes "c" and "x" events if present in data func (w *WiichuckDriver) updateButtons() { if w.data["c"] == 0 { gobot.Publish(w.Event(C), true) } if w.data["z"] == 0 { gobot.Publish(w.Event(Z), true) } }
func (b *ButtonDriver) update(newValue int) { if newValue == 1 { b.Active = true gobot.Publish(b.Event(Push), newValue) } else { b.Active = false gobot.Publish(b.Event(Release), newValue) } }
func (m *MakeyButtonDriver) update(newVal int) { if newVal == 0 { m.Active = true gobot.Publish(m.Events["push"], newVal) } else { m.Active = false gobot.Publish(m.Events["release"], newVal) } }
func ExampleOnce() { e := gobot.NewEvent() gobot.Once(e, func(s interface{}) { fmt.Println(s) fmt.Println("I will no longer respond to events") }) gobot.Publish(e, 100) gobot.Publish(e, 200) }
func (b *ButtonDriver) update(newVal int) { if newVal == 1 { b.Active = true gobot.Publish(b.Event("push"), newVal) } else { b.Active = false gobot.Publish(b.Event("release"), newVal) } }
// Start inits leap motion driver by enabling gestures // and listening from incoming messages. // // Publishes the following events: // "message" - Emits Frame on new message received from Leap. func (l *LeapMotionDriver) Start() (errs []error) { enableGestures := map[string]bool{ "enableGestures": true, "background": true, "optimizeHMD": true, } b, err := json.Marshal(enableGestures) if err != nil { return []error{err} } _, err = l.adaptor().ws.Write(b) if err != nil { return []error{err} } go func() { var msg []byte for { receive(l.adaptor().ws, &msg) gobot.Publish(l.Event("message"), l.ParseFrame(msg)) } }() return }
func NewJenkinsconnectDriver(a *JenkinsconnectAdaptor, name string) *JenkinsconnectDriver { j := &JenkinsconnectDriver{ name: name, connection: a, Eventer: gobot.NewEventer(), Commander: gobot.NewCommander(), } j.AddEvent(JobResult) j.AddCommand("ParseResults", func(params map[string]interface{}) interface{} { var snapshot JobOutcomeSnapshot result := ParseJobState(params) if (JobOutcome{}) != result { fmt.Printf("Result: %v\n", result) lastOutcome, ok := jobStates[result.Name] if ok { fmt.Printf("Last outcome: %v\n", lastOutcome) } snapshot.Outcome = result snapshot.RanAt = time.Now() jobStates[result.Name] = snapshot gobot.Publish(j.Event(JobResult), result) } return result }) return j }
// Start starts the SpheroDriver and enables Collision Detection. // Returns true on successful start. // // Emits the Events: // Collision sphero.CollisionPacket - On Collision Detected // SensorData sphero.DataStreamingPacket - On Data Streaming event // Error error- On error while processing asynchronous response func (s *SpheroDriver) Start() (errs []error) { go func() { for { packet := <-s.packetChannel err := s.write(packet) if err != nil { gobot.Publish(s.Event(Error), err) } } }() go func() { for { response := <-s.responseChannel s.syncResponse = append(s.syncResponse, response) } }() go func() { for { header := s.readHeader() if header != nil && len(header) != 0 { body := s.readBody(header[4]) data := append(header, body...) checksum := data[len(data)-1] if checksum != calculateChecksum(data[2:len(data)-1]) { continue } switch header[1] { case 0xFE: s.asyncResponse = append(s.asyncResponse, data) case 0xFF: s.responseChannel <- data } } } }() go func() { for { var evt []uint8 for len(s.asyncResponse) != 0 { evt, s.asyncResponse = s.asyncResponse[len(s.asyncResponse)-1], s.asyncResponse[:len(s.asyncResponse)-1] if evt[2] == 0x07 { s.handleCollisionDetected(evt) } else if evt[2] == 0x03 { s.handleDataStreaming(evt) } } time.Sleep(100 * time.Millisecond) } }() s.ConfigureCollisionDetection(DefaultCollisionConfig()) s.enableStopOnDisconnect() return }
func (n *NeuroskyDriver) parsePacket(data []byte) { buf := bytes.NewBuffer(data) for buf.Len() > 0 { b, _ := buf.ReadByte() switch b { case CodeEx: gobot.Publish(n.Events["Extended"], nil) case CodeSignalQuality: ret, _ := buf.ReadByte() gobot.Publish(n.Events["Signal"], ret) case CodeAttention: ret, _ := buf.ReadByte() gobot.Publish(n.Events["Attention"], ret) case CodeMeditation: ret, _ := buf.ReadByte() gobot.Publish(n.Events["Meditation"], ret) case CodeBlink: ret, _ := buf.ReadByte() gobot.Publish(n.Events["Blink"], ret) case CodeWave: buf.Next(1) var ret = make([]byte, 2) buf.Read(ret) gobot.Publish(n.Events["Wave"], ret) case CodeAsicEEG: var ret = make([]byte, 25) i, _ := buf.Read(ret) if i == 25 { gobot.Publish(n.Events["EEG"], n.parseEEG(ret)) } } } }
// parsePacket publishes event according to data parsed func (n *NeuroskyDriver) parsePacket(buf *bytes.Buffer) { for buf.Len() > 0 { b, _ := buf.ReadByte() switch b { case CodeEx: gobot.Publish(n.Event("extended"), nil) case CodeSignalQuality: ret, _ := buf.ReadByte() gobot.Publish(n.Event("signal"), ret) case CodeAttention: ret, _ := buf.ReadByte() gobot.Publish(n.Event("attention"), ret) case CodeMeditation: ret, _ := buf.ReadByte() gobot.Publish(n.Event("meditation"), ret) case CodeBlink: ret, _ := buf.ReadByte() gobot.Publish(n.Event("blink"), ret) case CodeWave: buf.Next(1) var ret = make([]byte, 2) buf.Read(ret) gobot.Publish(n.Event("wave"), int16(ret[0])<<8|int16(ret[1])) case CodeAsicEEG: ret := make([]byte, 25) i, _ := buf.Read(ret) if i == 25 { gobot.Publish(n.Event("eeg"), n.parseEEG(ret)) } } } }
// Start writes initialization bytes and reads from adaptor // using specified interval to accelerometer andtemperature data func (h *MPL115A2Driver) Start() (errs []error) { var temperature uint16 var pressure uint16 var pressureComp float32 if err := h.initialization(); err != nil { return []error{err} } go func() { for { if err := h.connection.I2cWrite(mpl115a2Address, []byte{MPL115A2_REGISTER_STARTCONVERSION, 0}); err != nil { gobot.Publish(h.Event(Error), err) continue } <-time.After(5 * time.Millisecond) if err := h.connection.I2cWrite(mpl115a2Address, []byte{MPL115A2_REGISTER_PRESSURE_MSB}); err != nil { gobot.Publish(h.Event(Error), err) continue } ret, err := h.connection.I2cRead(mpl115a2Address, 4) if err != nil { gobot.Publish(h.Event(Error), err) continue } if len(ret) == 4 { buf := bytes.NewBuffer(ret) binary.Read(buf, binary.BigEndian, &pressure) binary.Read(buf, binary.BigEndian, &temperature) temperature = temperature >> 6 pressure = pressure >> 6 pressureComp = float32(h.A0) + (float32(h.B1)+float32(h.C12)*float32(temperature))*float32(pressure) + float32(h.B2)*float32(temperature) h.Pressure = (65.0/1023.0)*pressureComp + 50.0 h.Temperature = ((float32(temperature) - 498.0) / -5.35) + 25.0 } <-time.After(h.interval) } }() return }
func (j *JoystickDriver) Start() bool { go func() { var event sdl.Event for { for event = sdl.PollEvent(); event != nil; event = sdl.PollEvent() { switch data := event.(type) { case *sdl.JoyAxisEvent: if data.Which == j.adaptor().joystick.InstanceID() { axis := j.findName(data.Axis, j.config.Axis) if axis == "" { fmt.Println("Unknown Axis:", data.Axis) } else { gobot.Publish(j.Event(axis), data.Value) } } case *sdl.JoyButtonEvent: if data.Which == j.adaptor().joystick.InstanceID() { button := j.findName(data.Button, j.config.Buttons) if button == "" { fmt.Println("Unknown Button:", data.Button) } else { if data.State == 1 { gobot.Publish(j.Event(fmt.Sprintf("%s_press", button)), nil) } else { gobot.Publish(j.Event(fmt.Sprintf("%s_release", button)), nil) } } } case *sdl.JoyHatEvent: if data.Which == j.adaptor().joystick.InstanceID() { hat := j.findHatName(data.Value, data.Hat, j.config.Hats) if hat == "" { fmt.Println("Unknown Hat:", data.Hat, data.Value) } else { gobot.Publish(j.Event(hat), true) } } } } time.Sleep(10 * time.Millisecond) } }() return true }
func (s *SpheroDriver) handleDataStreaming(data []uint8) { // ensure data is the right length: if len(data) != 90 { return } var dataPacket DataStreamingPacket buffer := bytes.NewBuffer(data[5:]) // skip header binary.Read(buffer, binary.BigEndian, &dataPacket) gobot.Publish(s.Event(SensorData), dataPacket) }
func (s *SpheroDriver) handleCollisionDetected(data []uint8) { // ensure data is the right length: if len(data) != 22 || data[4] != 17 { return } var collision CollisionPacket buffer := bytes.NewBuffer(data[5:]) // skip header binary.Read(buffer, binary.BigEndian, &collision) gobot.Publish(s.Event(Collision), collision) }
// Start begins process to read mavlink packets every m.Interval // and process them func (m *MavlinkDriver) Start() (errs []error) { go func() { for { packet, err := common.ReadMAVLinkPacket(m.adaptor().sp) if err != nil { gobot.Publish(m.Event("errorIO"), err) continue } gobot.Publish(m.Event("packet"), packet) message, err := packet.MAVLinkMessage() if err != nil { gobot.Publish(m.Event("errorMAVLink"), err) continue } gobot.Publish(m.Event("message"), message) <-time.After(m.interval) } }() return }
// Start starts the AnalogSensorDriver and reads the Analog Sensor at the given interval. // Emits the Events: // Data int - Event is emitted on change and represents the current reading from the sensor. // Error error - Event is emitted on error reading from the sensor. func (a *AnalogSensorDriver) Start() (errs []error) { value := 0 go func() { for { newValue, err := a.Read() if err != nil { gobot.Publish(a.Event(Error), err) } else if newValue != value && newValue != -1 { value = newValue gobot.Publish(a.Event(Data), value) } select { case <-time.After(a.interval): case <-a.halt: return } } }() return }
func (a *AnalogSensorDriver) Start() bool { value := 0 gobot.Every(a.Interval(), func() { newValue := a.Read() if newValue != value && newValue != -1 { value = newValue gobot.Publish(a.Event("data"), value) } }) return true }
func TestFirmataAdaptorI2cRead(t *testing.T) { a := initTestFirmataAdaptor() i := []byte{100} i2cReply := client.I2cReply{Data: i} go func() { <-time.After(10 * time.Millisecond) gobot.Publish(a.board.Event("I2cReply"), i2cReply) }() data, err := a.I2cRead(0x00, 1) gobottest.Assert(t, err, nil) gobottest.Assert(t, data, i) }
// Connect connects to the Client given conn. It first resets the firmata board // then continuously polls the firmata board for new information when it's // available. func (b *Client) Connect(conn io.ReadWriteCloser) (err error) { if b.connected { return ErrConnected } b.connection = conn b.Reset() initFunc := b.ProtocolVersionQuery gobot.Once(b.Event("ProtocolVersion"), func(data interface{}) { initFunc = b.FirmwareQuery }) gobot.Once(b.Event("FirmwareQuery"), func(data interface{}) { initFunc = b.CapabilitiesQuery }) gobot.Once(b.Event("CapabilityQuery"), func(data interface{}) { initFunc = b.AnalogMappingQuery }) gobot.Once(b.Event("AnalogMappingQuery"), func(data interface{}) { initFunc = func() error { return nil } b.ReportDigital(0, 1) b.ReportDigital(1, 1) b.connected = true }) for { if err := initFunc(); err != nil { return err } if err := b.process(); err != nil { return err } if b.connected { go func() { for { if !b.connected { break } if err := b.process(); err != nil { gobot.Publish(b.Event("Error"), err) } } }() break } } return }
// Start creates a go routine to listen from serial port // and parse buffer readings func (n *NeuroskyDriver) Start() (errs []error) { go func() { for { buff := make([]byte, 1024) _, err := n.adaptor().sp.Read(buff[:]) if err != nil { gobot.Publish(n.Event("error"), err) } else { n.parse(bytes.NewBuffer(buff)) } } }() return }
// EventStream returns a gobot.Event based on the following params: // // * source - "all"/"devices"/"device" (More info at: http://docs.spark.io/api/#reading-data-from-a-core-events) // * name - Event name to subscribe for, leave blank to subscribe to all events. // // A new event is emitted as a spark.Event struct func (s *SparkCoreAdaptor) EventStream(source string, name string) (event *gobot.Event, err error) { var url string switch source { case "all": url = fmt.Sprintf("%s/v1/events/%s?access_token=%s", s.APIServer, name, s.AccessToken) case "devices": url = fmt.Sprintf("%s/v1/devices/events/%s?access_token=%s", s.APIServer, name, s.AccessToken) case "device": url = fmt.Sprintf("%s/events/%s?access_token=%s", s.deviceURL(), name, s.AccessToken) default: err = errors.New("source param should be: all, devices or device") return } events, errors, err := eventSource(url) if err != nil { return } event = gobot.NewEvent() go func() { for { select { case ev := <-events: if ev.Event() != "" && ev.Data() != "" { gobot.Publish(event, Event{Name: ev.Event(), Data: ev.Data()}) } case ev := <-errors: gobot.Publish(event, Event{Error: ev}) } } }() return }