def __init__(self,addr,version=AUTODETECT): Peripheral.__init__(self,addr) if version==AUTODETECT: svcs = self.discoverServices() if _TI_UUID(0xAA70) in svcs: version = SENSORTAG_2650 else: version = SENSORTAG_V1 if version==SENSORTAG_V1: print ("Connecting to V1") self.IRtemperature = IRTemperatureSensor(self) self.accelerometer = AccelerometerSensor(self) self.humidity = HumiditySensor(self) self.magnetometer = MagnetometerSensor(self) self.barometer = BarometerSensor(self) self.gyroscope = GyroscopeSensor(self) self.keypress = KeypressSensor(self) self.lightmeter = None elif version==SENSORTAG_2650: print ("Connecting to 2650") self._mpu9250 = MovementSensorMPU9250(self) self.IRtemperature = IRTemperatureSensorTMP007(self) self.accelerometer = AccelerometerSensorMPU9250(self._mpu9250) self.humidity = HumiditySensorHDC1000(self) self.magnetometer = MagnetometerSensorMPU9250(self._mpu9250) self.barometer = BarometerSensorBMP280(self) self.gyroscope = GyroscopeSensorMPU9250(self._mpu9250) self.keypress = KeypressSensor(self) self.lightmeter = OpticalSensorOPT3001(self)
def enableAllMovementAxis(self): # alle Achsen aktivieren, weil das speparate Aktivieren der Achsen die andere Achsen(bits) deaktiviert v = b'\xff\x00' # ByteString von 11111111 (=alle bits) Peripheral.writeCharacteristic(self, handle=0x003f, val=v, withResponse=True)
def __init__(self, addr, version=AUTODETECT): Peripheral.__init__(self, addr) if version == AUTODETECT: svcs = self.discoverServices() if _TI_UUID(0xAA70) in svcs: version = SENSORTAG_2650 else: version = SENSORTAG_V1 fwVers = self.getCharacteristics( uuid=AssignedNumbers.firmwareRevisionString) if len(fwVers) >= 1: self.firmwareVersion = fwVers[0].read().decode("utf-8") else: self.firmwareVersion = u'' if version == SENSORTAG_V1: self.accelerometer = AccelerometerSensor(self) self.gyroscope = GyroscopeSensor(self) elif version == SENSORTAG_2650: self._mpu9250 = MovementSensorMPU9250(self) self.accelerometer = AccelerometerSensorMPU9250(self._mpu9250) self.gyroscope = GyroscopeSensorMPU9250(self._mpu9250) self.lightmeter = OpticalSensorOPT3001(self) self.battery = BatterySensor(self)
def __init__(self,addr,version=AUTODETECT): Peripheral.__init__(self,addr) if version==AUTODETECT: svcs = self.discoverServices() if _TI_UUID(0xAA70) in svcs: version = SENSORTAG_2650 else: version = SENSORTAG_V1 if version==SENSORTAG_V1: self.IRtemperature = IRTemperatureSensor(self) self.accelerometer = AccelerometerSensor(self) self.humidity = HumiditySensor(self) self.magnetometer = MagnetometerSensor(self) self.barometer = BarometerSensor(self) self.gyroscope = GyroscopeSensor(self) self.keypress = KeypressSensor(self) self.lightmeter = None elif version==SENSORTAG_2650: self._mpu9250 = MovementSensorMPU9250(self) self.IRtemperature = IRTemperatureSensorTMP007(self) self.accelerometer = AccelerometerSensorMPU9250(self._mpu9250) self.humidity = HumiditySensorHDC1000(self) self.magnetometer = MagnetometerSensorMPU9250(self._mpu9250) self.barometer = BarometerSensorBMP280(self) self.gyroscope = GyroscopeSensorMPU9250(self._mpu9250) self.keypress = KeypressSensor(self) self.lightmeter = OpticalSensorOPT3001(self)
def __init__(self,addr): Peripheral.__init__(self,addr) self.discoverServices() self.Temperature = BPartTemperatureSensor(self) self.Light = BPartLightSensor(self) self.Humidity = BPartHumiditySensor(self) self.Acceleration = BPartAccelerometer(self)
def __init__(self, deviceAddr): Peripheral.__init__(self, deviceAddr) # Variables temporarily store the received sensor values self._light = None self._humidity = None self._acceleration = None self._temperature = None
def __init__(self,addr): Peripheral.__init__(self,addr) self.discoverServices() self.IRtemperature = IRTemperatureSensor(self) self.accelerometer = AccelerometerSensor(self) self.humidity = HumiditySensor(self) self.magnetometer = MagnetometerSensor(self) self.barometer = BarometerSensor(self) self.gyroscope = GyroscopeSensor(self)
def __init__(self, addr): Peripheral.__init__(self, addr) self.discoverServices() self.IRtemperature = IRTemperatureSensor(self) self.accelerometer = AccelerometerSensor(self) self.humidity = HumiditySensor(self) self.magnetometer = MagnetometerSensor(self) self.barometer = BarometerSensor(self) self.gyroscope = GyroscopeSensor(self)
def __init__(self, addr): Peripheral.__init__(self, addr) #r ne 344, in getServiceByUUID self.discoverServices() self.IRtemperature = IRTemperatureSensor(self) self.accelerometer = AccelerometerSensor(self) self.humidity = HumiditySensor(self) self.magnetometer = MagnetometerSensor(self) self.barometer = BarometerSensor(self) self.diodeled = DiodeledSensor(self) self.color = ColorSensor(self) self.keypress = KeypressSensor(self)
def connect(self): """ Connect to the board and configure it. Note: recreates various objects upon call. """ print("Init BLE connection with MAC: " + self.port) print("NB: if it fails, try with root privileges.") self.gang = Peripheral(self.port, 'random') # ADDR_TYPE_RANDOM print("Get mainservice...") self.service = self.gang.getServiceByUUID(BLE_SERVICE) print("Got:" + str(self.service)) print("Get characteristics...") self.char_read = self.service.getCharacteristics(BLE_CHAR_RECEIVE)[0] print("receive, properties: " + str(self.char_read.propertiesToString()) + ", supports read: " + str(self.char_read.supportsRead())) self.char_write = self.service.getCharacteristics(BLE_CHAR_SEND)[0] print("write, properties: " + str(self.char_write.propertiesToString()) + ", supports read: " + str(self.char_write.supportsRead())) self.char_discon = self.service.getCharacteristics( BLE_CHAR_DISCONNECT)[0] print("disconnect, properties: " + str(self.char_discon.propertiesToString()) + ", supports read: " + str(self.char_discon.supportsRead())) # set delegate to handle incoming data self.delegate = GanglionDelegate(self.scaling_output) self.gang.setDelegate(self.delegate) # enable AUX channel if self.aux: print("Enabling AUX data...") try: self.ser_write(b'n') except Exception as e: print("Something went wrong while enabling aux channels: " + str(e)) print("Turn on notifications") # nead up-to-date bluepy, cf https://github.com/IanHarvey/bluepy/issues/53 self.desc_notify = self.char_read.getDescriptors(forUUID=0x2902)[0] try: self.desc_notify.write(b"\x01") except Exception as e: print( "Something went wrong while trying to enable notification: " + str(e)) print("Connection established")
def __init__(self, addr): Peripheral.__init__(self,addr) self.discoverServices() for cUUID in self.services: print("== %s =="%str(cUUID)) print(self.getServiceByUUID(cUUID).getCharacteristics()) self.ctrl_SRV=self.getServiceByUUID(self._ctrlUUID) self.data_SRV=self.getServiceByUUID(self._dataUUID) self.data = self.data_SRV.getCharacteristics()[0] #print("== CTRL ==") #print(self.ctrl_SRV.getCharacteristics()) self.ctrl = self.ctrl_SRV.getCharacteristics()[0]
def readLight(self): data = Peripheral.readCharacteristic(self, 0x0044) data = struct.unpack('<h', data)[0] m = data & 0xFFF e = (data & 0xF000) >> 12 result = 0.01 * (m << e) return ("{:.2f}".format(result)) # Formatierung
def handle(self): data = 'dummy' print ("Client connected with: ", self.client_address) devaddr = "f1:99:d1:ce:d9:1d random" bleconn = Peripheral(devaddr) while len(data): data = self.request.recv(1024) self.request.send(data) cmd=asc2hex(data.decode('utf-8')).rstrip('0d0a') print ("data",len(data)) if len(data)!=0: bleconn.writeCharacteristic(0x0011,cmd) print("Client exited") bleconn.disconnect() self.request.close()
def readMagnetometer(self): data = Peripheral.readCharacteristic( self, 0x003c) # alle 18 bytes einlesen (zwei bytes je Achse) data = struct.unpack( "<9h", data )[6:7] # Umwandlung signed Integers(C) in Integer(Python) und Slicing data = data[0] # Umwandlung Tuple in Int return ("{:.2f}".format(data))
def __init__(self): try: self.p = Peripheral(BULB) characteristics = self.p.getCharacteristics() for c in characteristics: self.chars[c.getHandle()] = c except BTLEException as e: print str(e)
def readAccelerometer(self): data = Peripheral.readCharacteristic( self, 0x003c) # alle 18 bytes einlesen (zwei bytes je Achse) data = struct.unpack( "<9h", data )[3:6] # Umwandlung signed Integers(C) in Integer(Python) und Slicing x_y_z = tuple([elem * (4.0 / 32768.0) for elem in data ]) # Umrechnung gemäß Doku mit Acc.- Range 4G return x_y_z # optional als string' '.join(format(f, '.5f') for f in x_y_z)
def readGyroscope(self): data = Peripheral.readCharacteristic( self, 0x003c) # alle 18 bytes einlesen (zwei bytes je Achse) data = struct.unpack( "<9h", data )[0:3] # Umwandlung signed Integers(C) in Integer(Python) und Slicing x_y_z = tuple([elem * (500.0 / 65536.0) for elem in data]) # Umrechnung gemäß Doku return x_y_z # optional als string' '.join(format(f, '.5f') for f in x_y_z)
def readBarometer(self): data = Peripheral.readCharacteristic(self, 0x0034) # two 24-bit unsigned integers: the temperature in bytes 0-2, the pressure in bytes 3-5 (tL, tM, tH, pL, pM, pH) = struct.unpack('<6B', data) temp = ( tH * 65536 + tM * 256 + tL ) / 100.0 # nicht im return statement,Temperatur kommt vom Feuchtigkeitssensor press = (pH * 65536 + pM * 256 + pL) / 100.0 return ("{:.2f}".format(temp, press))
def __init__(self, addr, version=AUTODETECT): Peripheral.__init__(self, addr) if version == AUTODETECT: svcs = self.discoverServices() if _TI_UUID(0xAA70) in svcs: version = SENSORTAG_2650 else: version = SENSORTAG_V1 fwVers = self.getCharacteristics( uuid=AssignedNumbers.firmwareRevisionString) if len(fwVers) >= 1: self.firmwareVersion = fwVers[0].read().decode("utf-8") else: self.firmwareVersion = u'' if version == SENSORTAG_V1: self.IRtemperature = IRTemperatureSensor(self) self.accelerometer = AccelerometerSensor(self) self.humidity = HumiditySensor(self) self.magnetometer = MagnetometerSensor(self) self.barometer = BarometerSensor(self) self.gyroscope = GyroscopeSensor(self) self.keypress = KeypressSensor(self) self.lightmeter = None elif version == SENSORTAG_2650: self._mpu9250 = MovementSensorMPU9250(self) self.IRtemperature = IRTemperatureSensorTMP007(self) self.accelerometer = AccelerometerSensorMPU9250(self._mpu9250) self.humidity = HumiditySensorHDC1000(self) self.magnetometer = MagnetometerSensorMPU9250(self._mpu9250) self.barometer = BarometerSensorBMP280(self) self.gyroscope = GyroscopeSensorMPU9250(self._mpu9250) self.keypress = KeypressSensor(self) self.lightmeter = OpticalSensorOPT3001(self) self.battery = BatterySensor(self)
class BTconnect: chars = {} def __init__(self): try: self.p = Peripheral(BULB) characteristics = self.p.getCharacteristics() for c in characteristics: self.chars[c.getHandle()] = c except BTLEException as e: print str(e) def read_by_handle(self, handle): return self.chars[handle].read() def write_by_handle(self, handle, data): self.chars[handle].write(data, True)
def threaded_client(conn): conn.send(str.encode('Welcome, to smartLink\n')) while True: a='s' while a=='s': try: bleconn = Peripheral("f1:99:d1:ce:d9:1d random") while True: #-----------receive data from telnet--------------------- data=conn.recv(2048) if not data: a='n' break print("data",data[0]) if data[0]!=255: reply = 'Server output:' +data.decode('utf-8') print("raw server ouput",data.decode('utf-8')) cmd=asc2hex(data.decode('utf-8')).rstrip('0d0a') print("raw cmd:",cmd) bleconn.writeCharacteristic(0x0011,cmd) conn.sendall(str.encode(reply)) except socket.error as e: if isinstance(e.args, tuple): print("errno is %d" % e[0]) if e[0] == errno.EPIPE: # remote peer disconnected print("Detected remote disconnect") else: # determine and handle different error pass else: print("socket error ", e) bleconn.disconnect() conn.close() break except BTLEException as e: #conn.sendall(str.encode("ERROR!!!!")) print(e) #conn.sendall(str.encode("Try again (y/n)?")) bleconn.disconnect() conn.close()
def handle(self): data = 'dummy' isConnected=False print ("Client connected with: ", self.client_address) while len(data): data = self.request.recv(1024) if len(data)>0 and len(data)<5 and data[0]==99 and isConnected==False: #Not null, its (C)onnect command, 4 len command if data[1]>=48 and data[1]<=57: try: bleconn = Peripheral(elements[data[1]-48]) except BTLEException as e: self.request.send(b'error connecting to device\r\n') isConnected=False else: isConnected=True self.request.send(b'connected\r\n') bleconn.writeCharacteristic(0x000f,binascii.a2b_hex("0100")) if len(data)!=0 and isConnected==True: cmd=data.rstrip(b'\r\n') if cmd!=b'' and cmd[0]!=99 and cmd[0]!=100: #if command is not (c)onnect or (d)isconnect try: notify=bleconn.writeCharacteristicWn(0x0011,cmd,True) except BTLEException as e: isConnected=False self.request.send(b'error writing to device\r\n') else: isConnected=True self.request.send(notify['d'][0]) self.request.send(b'\r\n') if len(data)>0 and len(data)<5 and data[0]==100 and isConnected==True: # cmd=data.rstrip(b'\r\n') if cmd!=b'': bleconn.disconnect() self.request.send(b'disconnected\r\n') isConnected=False print("Client exited") if isConnected==True: bleconn.disconnect() self.request.close()
def handle(self): data = 'dummy' print("Client connected with: ", self.client_address) devaddr = "f1:99:d1:ce:d9:1d random" bleconn = Peripheral(devaddr) while len(data): data = self.request.recv(1024) self.request.send(data) cmd = asc2hex(data.decode('utf-8')).rstrip('0d0a') print("data", len(data)) if len(data) != 0: bleconn.writeCharacteristic(0x0011, cmd) print("Client exited") bleconn.disconnect() self.request.close()
def __init__(self): Peripheral.__init__(self, deviceAddr='98:07:2D:27:F1:86', iface=0)
def enableBarometer(self): Peripheral.writeCharacteristic(self, handle=0x0037, val=b'\x01', withResponse=True)
tipping.input['temp'] = float(temp) tipping.input['light'] = float(light) tipping.input['hum'] = float(hum) tipping.compute() output = float(tipping.output['switch_power']) print('temp=%f, `hum=%f`, `light=%f`, `sound=%f`, `air=%f`, `output=%f`' % (temp, hum, light, Sound, Air, output)) last = sqlget() print('last=%s' % last) if output >= 5: print("on") switch_staus = "on" if (sqlauto(1) == 1): print("Auto Model") with Peripheral('C1:8F:CC:DC:57:19', 'random') as p: ch = p.getCharacteristics(uuid=TX_CHAR_UUID)[0] val = binascii.a2b_hex('AA0630306655') ch.write(val) p.disconnect() if (last != switch_staus): print("Sql Insert On") sqlinsert(1, temp, hum, light, Sound, Air, output, 'on') else: print("Manual Model") else: print("off") switch_staus = "off" if (sqlauto(1) == 1): print("Auto Model") with Peripheral('C1:8F:CC:DC:57:19', 'random') as p:
def readHumidity(self): data = Peripheral.readCharacteristic(self, 0x002c) (rawT, rawH) = struct.unpack('<HH', data) RH = (rawH / 65536.0) * 100.0 return ("{:.2f}".format(RH))
def __init__(self, addr): self.conn = Peripheral(addr) self.conn.discoverServices() # To avoid bug(?) in getServiceByUUID self.info = None self.writeHnd = None
def __init__(self, addr): Peripheral.__init__(self, addr)
class OpenBCIBoard(object): """ Handle a connection to an OpenBCI board. Args: port: MAC address of the Ganglion Board. "None" to attempt auto-detect. aux: enable on not aux channels (i.e. switch to 18bit mode if set) impedance: measures impedance when start streaming timeout: in seconds, if set will try to disconnect / reconnect after a period without new data -- should be high if impedance check max_packets_to_skip: will try to disconnect / reconnect after too many packets are skipped baud, filter_data, daisy: Not used, for compatibility with v3 """ def __init__(self, port=None, baud=0, filter_data=False, scaled_output=True, daisy=False, log=True, aux=False, impedance=False, timeout=2, max_packets_to_skip=20): # unused, for compatibility with Cyton v3 API self.daisy = False # these one are used self.log = log # print_incoming_text needs log self.aux = aux self.streaming = False self.timeout = timeout self.max_packets_to_skip = max_packets_to_skip self.scaling_output = scaled_output self.impedance = False # might be handy to know API self.board_type = "ganglion" print("Looking for Ganglion board") if port == None: port = self.find_port() self.port = port # find_port might not return string self.connect() self.streaming = False # number of EEG channels and (optionally) accelerometer channel self.eeg_channels_per_sample = 4 self.aux_channels_per_sample = 3 self.imp_channels_per_sample = 5 self.read_state = 0 self.log_packet_count = 0 self.packets_dropped = 0 self.time_last_packet = 0 # Disconnects from board when terminated atexit.register(self.disconnect) def getBoardType(self): """ Returns the version of the board """ return self.board_type def setImpedance(self, flag): """ Enable/disable impedance measure """ self.impedance = bool(flag) def connect(self): """ Connect to the board and configure it. Note: recreates various objects upon call. """ print ("Init BLE connection with MAC: " + self.port) print ("NB: if it fails, try with root privileges.") self.gang = Peripheral(self.port, 'random') # ADDR_TYPE_RANDOM print ("Get mainservice...") self.service = self.gang.getServiceByUUID(BLE_SERVICE) print ("Got:" + str(self.service)) print ("Get characteristics...") self.char_read = self.service.getCharacteristics(BLE_CHAR_RECEIVE)[0] print ("receive, properties: " + str(self.char_read.propertiesToString()) + ", supports read: " + str(self.char_read.supportsRead())) self.char_write = self.service.getCharacteristics(BLE_CHAR_SEND)[0] print ("write, properties: " + str(self.char_write.propertiesToString()) + ", supports read: " + str(self.char_write.supportsRead())) self.char_discon = self.service.getCharacteristics(BLE_CHAR_DISCONNECT)[0] print ("disconnect, properties: " + str(self.char_discon.propertiesToString()) + ", supports read: " + str(self.char_discon.supportsRead())) # set delegate to handle incoming data self.delegate = GanglionDelegate(self.scaling_output) self.gang.setDelegate(self.delegate) # enable AUX channel if self.aux: print("Enabling AUX data...") try: self.ser_write(b'n') except Exception as e: print("Something went wrong while enabling aux channels: " + str(e)) print("Turn on notifications") # nead up-to-date bluepy, cf https://github.com/IanHarvey/bluepy/issues/53 self.desc_notify = self.char_read.getDescriptors(forUUID=0x2902)[0] try: self.desc_notify.ser_write(b"\x01") except Exception as e: print("Something went wrong while trying to enable notification: " + str(e)) print("Connection established") def init_streaming(self): """ Tell the board to record like crazy. """ try: if self.impedance: print("Starting with impedance testing") self.ser_write(b'z') else: self.ser_write(b'b') except Exception as e: print("Something went wrong while asking the board to start streaming: " + str(e)) self.streaming = True self.packets_dropped = 0 self.time_last_packet = timeit.default_timer() def find_port(self): """Detects Ganglion board MAC address -- if more than 1 around, will select first. Needs root privilege.""" print("Try to detect Ganglion MAC address. NB: Turn on bluetooth and run as root for this to work! Might not work with every BLE dongles.") scan_time = 5 print("Scanning for 5 seconds nearby devices...") # From bluepy example class ScanDelegate(DefaultDelegate): def __init__(self): DefaultDelegate.__init__(self) def handleDiscovery(self, dev, isNewDev, isNewData): if isNewDev: print ("Discovered device: " + dev.addr) elif isNewData: print ("Received new data from: " + dev.addr) scanner = Scanner().withDelegate(ScanDelegate()) devices = scanner.scan(scan_time) nb_devices = len(devices) if nb_devices < 1: print("No BLE devices found. Check connectivity.") return "" else: print("Found " + str(nb_devices) + ", detecting Ganglion") list_mac = [] list_id = [] for dev in devices: # "Ganglion" should appear inside the "value" associated to "Complete Local Name", e.g. "Ganglion-b2a6" for (adtype, desc, value) in dev.getScanData(): if desc == "Complete Local Name" and value.startswith("Ganglion"): list_mac.append(dev.addr) list_id.append(value) print("Got Ganglion: " + value + ", with MAC: " + dev.addr) break nb_ganglions = len(list_mac) if nb_ganglions < 1: print("No Ganglion found ;(") raise OSError('Cannot find OpenBCI Ganglion MAC address') if nb_ganglions > 1: print("Found " + str(nb_ganglions) + ", selecting first") print("Selecting MAC address " + list_mac[0] + " for " + list_id[0]) return list_mac[0] def ser_write(self, b): """Access serial port object for write""" self.char_write.ser_write(b) def ser_read(self): """Access serial port object for read""" return self.char_read.ser_read() def ser_inWaiting(self): """ Slightly different from Cyton API, return True if ASCII messages are incoming.""" # FIXME: might have a slight problem with thread because of notifications... if self.delegate.receiving_ASCII: # in case the packet indicating the end of the message drops, we use a 1s timeout if timeit.default_timer() - self.delegate.time_last_ASCII > 2: self.delegate.receiving_ASCII = False return self.delegate.receiving_ASCII def getSampleRate(self): return SAMPLE_RATE def getNbEEGChannels(self): """Will not get new data on impedance check.""" return self.eeg_channels_per_sample def getNbAUXChannels(self): """Might not be used depending on the mode.""" return self.aux_channels_per_sample def getNbImpChannels(self): """Might not be used depending on the mode.""" return self.imp_channels_per_sample def start_streaming(self, callback, lapse=-1): """ Start handling streaming data from the board. Call a provided callback for every single sample that is processed Args: callback: A callback function -- or a list of functions -- that will receive a single argument of the OpenBCISample object captured. """ if not self.streaming: self.init_streaming() start_time = timeit.default_timer() # Enclose callback funtion in a list if it comes alone if not isinstance(callback, list): callback = [callback] while self.streaming: # should the board get disconnected and we could not wait for notification anymore, a reco should be attempted through timeout mechanism try: # at most we will get one sample per packet self.waitForNotifications(1./self.getSampleRate()) except Exception as e: print("Something went wrong while waiting for a new sample: " + str(e)) # retrieve current samples on the stack samples = self.delegate.getSamples() self.packets_dropped = self.delegate.getMaxPacketsDropped() if samples: self.time_last_packet = timeit.default_timer() for call in callback: for sample in samples: call(sample) if(lapse > 0 and timeit.default_timer() - start_time > lapse): self.stop(); if self.log: self.log_packet_count = self.log_packet_count + 1; # Checking connection -- timeout and packets dropped self.check_connection() def waitForNotifications(self, delay): """ Allow some time for the board to receive new data. """ self.gang.waitForNotifications(delay) def test_signal(self, signal): """ Enable / disable test signal """ if signal == 0: self.warn("Disabling synthetic square wave") try: self.char_write.ser_write(b']') except Exception as e: print("Something went wrong while setting signal: " + str(e)) elif signal == 1: self.warn("Eisabling synthetic square wave") try: self.char_write.ser_write(b'[') except Exception as e: print("Something went wrong while setting signal: " + str(e)) else: self.warn("%s is not a known test signal. Valid signal is 0-1" %(signal)) def set_channel(self, channel, toggle_position): """ Enable / disable channels """ try: #Commands to set toggle to on position if toggle_position == 1: if channel is 1: self.ser.ser_write(b'!') if channel is 2: self.ser.ser_write(b'@') if channel is 3: self.ser.ser_write(b'#') if channel is 4: self.ser.ser_write(b'$') #Commands to set toggle to off position elif toggle_position == 0: if channel is 1: self.ser.ser_write(b'1') if channel is 2: self.ser.ser_write(b'2') if channel is 3: self.ser.ser_write(b'3') if channel is 4: self.ser.ser_write(b'4') except Exception as e: print("Something went wrong while setting channels: " + str(e)) """ Clean Up (atexit) """ def stop(self): print("Stopping streaming...") self.streaming = False # connection might be already down here try: if self.impedance: print("Stopping with impedance testing") self.ser_write(b'Z') else: self.ser_write(b's') except Exception as e: print("Something went wrong while asking the board to stop streaming: " + str(e)) if self.log: logging.warning('sent <s>: stopped streaming') def disconnect(self): if(self.streaming == True): self.stop() print("Closing BLE..") try: self.char_discon.ser_write(b' ') except Exception as e: print("Something went wrong while asking the board to disconnect: " + str(e)) # should not try to read/write anything after that, will crash try: self.gang.disconnect() except Exception as e: print("Something went wrong while shutting down BLE link: " + str(e)) logging.warning('BLE closed') """ SETTINGS AND HELPERS """ def warn(self, text): if self.log: #log how many packets where sent succesfully in between warnings if self.log_packet_count: logging.info('Data packets received:'+str(self.log_packet_count)) self.log_packet_count = 0; logging.warning(text) print("Warning: %s" % text) def check_connection(self): """ Check connection quality in term of lag and number of packets drop. Reinit connection if necessary. FIXME: parameters given to the board will be lost.""" # stop checking when we're no longer streaming if not self.streaming: return #check number of dropped packets and duration without new packets, deco/reco if too large if self.packets_dropped > self.max_packets_to_skip: self.warn("Too many packets dropped, attempt to reconnect") self.reconnect() elif self.timeout > 0 and timeit.default_timer() - self.time_last_packet > self.timeout: self.warn("Too long since got new data, attempt to reconnect") #if error, attempt to reconect self.reconnect() def reconnect(self): """ In case of poor connection, will shut down and relaunch everything. FIXME: parameters given to the board will be lost.""" self.warn('Reconnecting') self.stop() self.disconnect() self.connect() self.init_streaming()
def __init__(self, addr): Peripheral.__init__(self, addr) self.discoverServices()
def __init__(self, addr): Peripheral.__init__(self, addr, addrType=ADDR_TYPE_PUBLIC)
from btle import UUID, Peripheral, BTLEException import struct import math import pexpect import binascii if __name__ == "__main__": resp = pexpect.spawn('hciconfig hci0 up') resp.expect('.*') Debugging = False devaddr = "f1:99:d1:ce:d9:1d random" print("Connecting to:", devaddr) a = 's' while a == 's': try: conn = Peripheral(devaddr) while True: n = input("Ponga (s) para salir:") try: conn.writeCharacteristic(0x0011, str.encode(n)) except BTLEException as e: print("write error:") print(e) print("Try again? (s/n)") b = input() if b == 's': a = 's' break else: b = 'n' if n.strip() == 's':
def enableLight(self): Peripheral.writeCharacteristic(self, handle=0x0047, val=b'\x01', withResponse=True)
def readTemperature(self): data = Peripheral.readCharacteristic(self, 0x002c) (rawT, rawH) = struct.unpack('<HH', data) temp = (rawT / 65536.0) * 165.0 - 40.0 return ("{:.2f}".format(temp))
if __name__ == "__main__": import time #tag = SensorTag("BC:6A:29:AB:D3:7A") resp=pexpect.spawn('hciconfig hci0 up') resp.expect('.*') Debugging = False #devaddr = sys.argv[1] + " random" devaddr = "f1:99:d1:ce:d9:1d random" print("Connecting to:", devaddr) a='s' while a=='s': try: conn = Peripheral(devaddr) while True: n = input("Ponga (s) para salir:") cmd=asc2hex(n) try: conn.writeCharacteristic(0x0011,cmd) except BTLEException as e: print ("write error:") print (e) print ("Try again? (s/n)") b=input() if b == 's': a='s' break else: b='n'
if __name__ == "__main__": import time #tag = SensorTag("BC:6A:29:AB:D3:7A") resp=pexpect.spawn('hciconfig hci0 up') resp.expect('.*') Debugging = False #devaddr = sys.argv[1] + " random" devaddr = "de:2d:06:53:4b:ad random" print("Connecting to:", devaddr) a='s' while a=='s': try: conn = Peripheral(devaddr) while True: n = input("Ponga (s) para salir:") cmd='00:00' if n.strip() == '1': cmd='01:00' if n.strip() == '2': cmd='02:00' try: conn.writeCharacteristic(14,cmd) except BTLEException as e: print ("write error:") print (e) print ("Try again? (s/n)") b=input() if b == 's':
if __name__ == "__main__": import time #tag = SensorTag("BC:6A:29:AB:D3:7A") resp = pexpect.spawn('hciconfig hci0 up') resp.expect('.*') Debugging = False #devaddr = sys.argv[1] + " random" devaddr = "f1:99:d1:ce:d9:1d random" print("Connecting to:", devaddr) a = 's' while a == 's': try: conn = Peripheral(devaddr) while True: n = input("Ponga (s) para salir:") cmd = asc2hex(n) try: conn.writeCharacteristic(0x0011, cmd) except BTLEException as e: print("write error:") print(e) print("Try again? (s/n)") b = input() if b == 's': a = 's' break else: b = 'n'
class LEDE: def __init__(self, addr): self.conn = Peripheral(addr) self.conn.discoverServices() # To avoid bug(?) in getServiceByUUID self.info = None self.writeHnd = None def _read_info(self, service, characteristics_uuid): ch = service.getCharacteristics(characteristics_uuid) name = AssignedNumbers.getCommonName(ch[0].uuid) self.info[name] = ch[0].read().decode() def get_info(self): if self.info: return self.info self.info = {} svc = self.conn.getServiceByUUID('180A') # Device Information self._read_info(svc, '2a24') self._read_info(svc, '2a26') self._read_info(svc, '2a27') self._read_info(svc, '2a29') return self.info def _random(self): return random.randrange(256) def _checksum(self, cmd): s = 28 for i in cmd: s += i return s&255 def _pack_data(self, cmd, rdcs): cmd = list(cmd) if rdcs: cmd.append(self._random()) cmd.append(self._checksum(cmd)) cmd.append(0xd) return binascii.a2b_hex('aa0afc3a8601' + ''.join('%02X'%x for x in cmd)) def write(self, cmd, rdcs = True): if self.writeHnd is None: svc = self.conn.getServiceByUUID('fff0') # Control self.writeHnd = svc.getCharacteristics('fff1')[0] # Aka Handle 0x21 self.writeHnd.write(self._pack_data(cmd, rdcs)) time.sleep(.2) def disconnect(self): self.conn.disconnect() def command_on(self): """Switch the light on""" self.write((0x0a, 0x01, 0x01, 0x00, 0x28), False) def command_off(self): """Switch the light off""" self.write((0x0a, 0x01, 0x00, 0x01, 0x28), False) def command_white_reset(self): """Switch to White Mode""" self.write((0x0d, 0x06, 0x02, 0x80, 0x80, 0x80, 0x80, 0x80)) def command_set_brightness(self, value): """Set Brightness (value between 0 and 9)""" if value >= 0 and value <= 9: self.write((0x0c, 0x01, value + 2)) def command_set_cct(self, value): """Set Colour Temperature (value between 0 and 9)""" if value >= 0 and value <= 9: self.write((0x0e, 0x01, value + 2)) def command_rgb(self, red, green, blue): """Set RGB Colour""" self.write((0x0d, 0x06, 0x01, red&255, green&255, blue&255, 0x80, 0x80)) def command_preset(self, value): """Use Preset (value between 1 and 10)""" if value >= 0 and value <= 10: self.write((0x0b, 0x01, value)) def command_night_mode(self): """Start Night Mode (20 minutes)""" self.write((0x10, 0x02, 0x03, 0x01))
def __init__(self,addr): Peripheral.__init__(self,addr) self.result = 1
def __init__(self, addr, version=AUTODETECT): Peripheral.__init__(self, addr) if version == AUTODETECT: svcs = self.discoverServices() print(str(svcs))
def __init__(self,addr): Peripheral.__init__(self,addr) self.discoverServices()
import sys from btle import UUID, Peripheral if len(sys.argv) != 2: print("Fatal, must pass device address:", sys.argv[0], "<device address=" ">") quit() p = Peripheral(sys.argv[1], "random") services = p.getServices() #displays all services for service in services: print(service)
def __init__(self, deviceAddr): Peripheral.__init__(self, deviceAddr)
def __init__(self, addr): Peripheral.__init__(self, addr, addrType=ADDR_TYPE_RANDOM)
from btle import Peripheral, UUID simblee = Peripheral('CC:9B:84:26:0F:AC', 'random') serviceUUID = UUID('2A00') char = simblee.getCharacteristics(uuid = serviceUUID)[0] char.write('Simblee') print char.read() simblee.disconnect()
def enableHumidity(self): Peripheral.writeCharacteristic(self, handle=0x002f, val=b'\x01', withResponse=True)