gobot.io/x/gobot/v2@v2.1.0/platforms/microbit/temperature_driver.go (about)

     1  package microbit
     2  
     3  import (
     4  	"bytes"
     5  
     6  	"gobot.io/x/gobot/v2"
     7  	"gobot.io/x/gobot/v2/platforms/ble"
     8  )
     9  
    10  // TemperatureDriver is the Gobot driver for the Microbit's built-in thermometer
    11  type TemperatureDriver struct {
    12  	name       string
    13  	connection gobot.Connection
    14  	gobot.Eventer
    15  }
    16  
    17  const (
    18  	// BLE services
    19  	temperatureService = "e95d6100251d470aa062fa1922dfa9a8"
    20  
    21  	// BLE characteristics
    22  	temperatureCharacteristic = "e95d9250251d470aa062fa1922dfa9a8"
    23  
    24  	// Temperature event
    25  	Temperature = "temperature"
    26  )
    27  
    28  // NewTemperatureDriver creates a Microbit TemperatureDriver
    29  func NewTemperatureDriver(a ble.BLEConnector) *TemperatureDriver {
    30  	n := &TemperatureDriver{
    31  		name:       gobot.DefaultName("Microbit Temperature"),
    32  		connection: a,
    33  		Eventer:    gobot.NewEventer(),
    34  	}
    35  
    36  	n.AddEvent(Temperature)
    37  
    38  	return n
    39  }
    40  
    41  // Connection returns the BLE connection
    42  func (b *TemperatureDriver) Connection() gobot.Connection { return b.connection }
    43  
    44  // Name returns the Driver Name
    45  func (b *TemperatureDriver) Name() string { return b.name }
    46  
    47  // SetName sets the Driver Name
    48  func (b *TemperatureDriver) SetName(n string) { b.name = n }
    49  
    50  // adaptor returns BLE adaptor
    51  func (b *TemperatureDriver) adaptor() ble.BLEConnector {
    52  	return b.Connection().(ble.BLEConnector)
    53  }
    54  
    55  // Start tells driver to get ready to do work
    56  func (b *TemperatureDriver) Start() (err error) {
    57  	// subscribe to temperature notifications
    58  	b.adaptor().Subscribe(temperatureCharacteristic, func(data []byte, e error) {
    59  		var l int8
    60  		buf := bytes.NewBuffer(data)
    61  		val, _ := buf.ReadByte()
    62  		l = int8(val)
    63  
    64  		b.Publish(b.Event(Temperature), l)
    65  	})
    66  
    67  	return
    68  }
    69  
    70  // Halt stops Temperature driver (void)
    71  func (b *TemperatureDriver) Halt() (err error) {
    72  	return
    73  }