Esempio n. 1
0
 def __init__(self, SerialNumber):
     self.periph        = None
     self.curr_val_char = None
     self.MacAddr       = None
     self.SN            = SerialNumber
     self.uuid          = UUID("b42e2a68-ade7-11e4-89d3-123b93f75cba")
Esempio n. 2
0
import binascii
import struct
import time
from bluepy.btle import UUID, Peripheral

temp_uuid = UUID(0x0001)

p = Peripheral("CA:34:A7:E4:DF:50", "random")

try:
    print("hello")
    ch = p.getCharacteristics(uuid=temp_uuid)
    #print(ch)
    for i in ch:
        print(i)
        if (i.supportsRead()):
            while 1:
                print("ayyyy")
                val = binascii.b2a_hex(ch.read())
                val = binascii.unhexlify(val)
                val = struct.unpack('f', val)[0]
                print(str(val) + " ay")
                time.sleep(1)
    print("after")

finally:
    p.disconnect()
Esempio n. 3
0
for dev in devices:
    print "%d: Devices %s (%s), RSSI=%d db" % (n, dev.addr, dev.addrType,
                                               dev.rssi)
    n += 1
    for (adtype, desc, value) in dev.getScanData():
        print "%s = %s" % (desc, value)

number = input('Enter your device number: ')
print('Device', number)
print(devices[number].addr)

print "Connecting ..."
dev = Peripheral(devices[number].addr, 'random')

print "Services ..."
for svc in dev.services:
    print str(svc)

try:
    testService = dev.getServiceByUUID(UUID(0xfff0))
    for ch in testService.getCharacteristics():
        print str(ch)
    # ch = dev.getCharacteristics(uuid=UUID(0xfff1))[0]
    for ch in dev.getCharacteristics(uuid=UUID(0xfff1)):
        if (ch.supportsRead()):
            print str(ch.read())
        else:
            print 'Not support read'
finally:
    dev.disconnect()
Esempio n. 4
0
import binascii
import struct
import time
from bluepy.btle import UUID, Peripheral

# Message constants
MSG_LOCK = 0x10
MSG_UNLOCK = 0x11
MSG_STATE_REQ = 0x12

# Define read and write UUIDs
read_uuid = UUID(0x2221)
write_uuid = UUID(0x2222)

# Create a connection to the RFduino
#p = Peripheral("F9:D8:C2:B9:77:E9", "random")
p = Peripheral("D4:2C:92:60:C2:D5", "random")

try:

    # Create handles for read and write characteristics
    w_ch = p.getCharacteristics(uuid=write_uuid)[0]
    r_ch = p.getCharacteristics(uuid=read_uuid)[0]

    # Tell the Lockitron to lock
    msg = struct.pack('i', MSG_LOCK)
    print "Writing: " + str(msg)
    w_ch.write(msg)

finally:
    p.disconnect()
Esempio n. 5
0
import binascii
import struct
import time
from bluepy.btle import UUID, Peripheral, DefaultDelegate

from PyQt5 import QtWidgets, QtCore, QtGui
from pyqtgraph import PlotWidget, plot
import pyqtgraph as pg

from numpy import *

import sys  # We need sys so that we can pass argv to QApplication
import os

red_uuid = UUID(0xddd1)

app = QtGui.QApplication([])
win = pg.GraphicsWindow(title="Signal from serial port")
p = win.addPlot(title="Realtime plot")
curve = p.plot()

windowWidth = 500                       # width of the window displaying the curve
Xm = linspace(0,0,windowWidth)          # create array that will contain the relevant time series     
ptr = -windowWidth                      # set first x position

class MyDelegate(DefaultDelegate):
    def __init__(self):
        DefaultDelegate.__init__(self)
        # ... initialise here

    def handleNotification(self, cHandle, data):
Esempio n. 6
0
class BLECharacteristicUUIDs: 
    deviceInformation_modelNumber =  UUID(0x2A24)
Esempio n. 7
0
 def __init__(self, uuid, characteristics):
     self.service_uuid = UUID(uuid)
     self.service = None
     self.characteristics = characteristics
    print(n, ": Device ", dev.addr, "(", dev.addrType, ")", ", RSSI= ",
          dev.rssi, " dB")
    n += 1
    for (adtype, desc, value) in dev.getScanData():
        print(desc, "=", value)
number = input('Enter your device number: ')
print('Device', number)
print(list(devices)[int(number)].addr)
print("Connecting...")
dev = Peripheral(list(devices)[int(number)].addr, 'random')
dev.withDelegate(ScanDelegate())
print("Services...")
for svc in dev.services:
    print(str(svc))
try:
    testService = dev.getServiceByUUID(UUID(0xa000))
    for ch in testService.getCharacteristics():
        print(str(ch))
    testService = dev.getServiceByUUID(UUID(0xb000))
    for ch in testService.getCharacteristics():
        print(str(ch))
    but_ch = dev.getCharacteristics(uuid=UUID(0xa001))[0]
    cccd = but_ch.getHandle() + 1
    dev.writeCharacteristic(cccd, bytes([0x01, 0x00]))
    if (but_ch.supportsRead()):
        print(but_ch.read())
    led_ch = dev.getCharacteristics(uuid=UUID(0xb001))[0]
    if (led_ch.supportsRead()):
        print(led_ch.read())
        led_light = led_ch.read()
    while True:
 def switch_led(self, state):
     led_control_ch = self.live_service.getCharacteristics(
         UUID(CONTROLS["LED"]))[0]
     led_control_ch.write(str.encode(state))
Esempio n. 10
0
class Nuimo:

    SERVICE_UUIDS = [
        UUID('0000180f-0000-1000-8000-00805f9b34fb'),  # Battery
        UUID('f29b1525-cb19-40f3-be5c-7241ecb82fd2'),  # Sensors
        UUID('f29b1523-cb19-40f3-be5c-7241ecb82fd1')  # LED Matrix
    ]

    CHARACTERISTIC_UUIDS = {
        UUID('00002a19-0000-1000-8000-00805f9b34fb'): 'BATTERY',
        UUID('f29b1529-cb19-40f3-be5c-7241ecb82fd2'): 'BUTTON',
        UUID('f29b1528-cb19-40f3-be5c-7241ecb82fd2'): 'ROTATION',
        UUID('f29b1527-cb19-40f3-be5c-7241ecb82fd2'): 'SWIPE',
        UUID('f29b1526-cb19-40f3-be5c-7241ecb82fd2'): 'FLY',
        UUID('f29b1524-cb19-40f3-be5c-7241ecb82fd1'): 'LED_MATRIX'
    }

    NOTIFICATION_CHARACTERISTIC_UUIDS = [
        #'BATTERY', # Uncomment only if you are not using the iOS emulator (iOS does't support battery updates without authentication)
        'BUTTON',
        'ROTATION',
        'SWIPE',
        'FLY'
    ]

    # Notification data
    NOTIFICATION_ON = struct.pack("BB", 0x01, 0x00)
    NOTIFICATION_OFF = struct.pack("BB", 0x00, 0x00)

    def __init__(self, macAddress):
        self.macAddress = macAddress

    def set_delegate(self, delegate):
        self.delegate = delegate

    def connect(self):
        self.peripheral = Peripheral(self.macAddress, addrType='random')
        # Retrieve all characteristics from desires services and map them from their UUID
        characteristics = list(
            itertools.chain(*[
                self.peripheral.getServiceByUUID(uuid).getCharacteristics()
                for uuid in Nuimo.SERVICE_UUIDS
            ]))
        characteristics = dict((c.uuid, c) for c in characteristics)
        # Store each characteristic's value handle for each characteristic name
        self.characteristicValueHandles = dict(
            (name, characteristics[uuid].getHandle())
            for uuid, name in Nuimo.CHARACTERISTIC_UUIDS.items())
        # Subscribe for notifications
        for name in Nuimo.NOTIFICATION_CHARACTERISTIC_UUIDS:
            self.peripheral.writeCharacteristic(
                self.characteristicValueHandles[name] + 1,
                Nuimo.NOTIFICATION_ON, True)
        self.peripheral.setDelegate(self.delegate)

    def waitForNotifications(self):
        self.peripheral.waitForNotifications(1.0)

    def displayLedMatrix(self, matrix, timeout, brightness=1.0):
        matrix = '{:<81}'.format(matrix[:81])
        bytes = list(
            map(
                lambda leds: reduce(
                    lambda acc, led: acc +
                    (1 << led if leds[led] not in [' ', '0'] else 0),
                    range(0, len(leds)), 0),
                [matrix[i:i + 8] for i in range(0, len(matrix), 8)]))
        self.peripheral.writeCharacteristic(
            self.characteristicValueHandles['LED_MATRIX'],
            struct.pack('BBBBBBBBBBBBB', bytes[0], bytes[1], bytes[2],
                        bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
                        bytes[8], bytes[9], bytes[10],
                        max(0, min(255, int(255.0 * brightness))),
                        max(0, min(255, int(timeout * 10.0)))), True)
Esempio n. 11
0
    def gather_data(self, on_error_flag=None, on_read_flag=None):
        sensors=[ "sunlight", "soil_temp", "air_temp", \
                  "vwc", "cal_vwc", "cal_air_temp", \
                  "cal_dli", "cal_ea", "cal_ecb", \
                  "cal_ec_porous", "pf_batt" ]

        tr = transform.DataTransformation()
        reading = dict.fromkeys(sensors)

        # Reading battery level from battery service
        battery_level_ch = self.battery_service.getCharacteristics(
            UUID(CONTROLS["BATTERY_LEVEL"]))[0]
        battery_level = 0

        try:
            # conversion from byte to decimal
            battery_level = ord(battery_level_ch.read())
            if "pf_batt" in reading.keys():
                reading["pf_batt"] = battery_level
        except Exception as err:
            #self.logger.exception(traceback.print_tb(err.__traceback__))
            self.logger.error("[{}] Exception occurred: {}".format(
                self.get_name(), str(err)))
            return None

        self.switch_led(FLAG_NOTIF_ENABLE)

        # iterate over the calibrated sensors characteristics
        for key, val in CAL_SENSORS.items():
            if key not in sensors:
                # Skip all sensors we aren't reading this time
                continue
            svchar_live = self.live_service.getCharacteristics(UUID(val))
            if len(svchar_live) <= 0:
                #self.logger.debug("No characteristic: {}, {}".format(key, val))
                continue

            char = svchar_live[0]
            if char.supportsRead():
                try:
                    if DEBUG_RAW_DATA and (key in [
                            "sunlight", "soil_ec", "air_temp", "soil_temp",
                            "vwc"
                    ]):
                        reading[key] = tr.unpack_U16(char.read())
                    elif not DEBUG_RAW_DATA:
                        if key == "sunlight":
                            reading[key] = tr.conv_light(
                                tr.unpack_U16(char.read()))
                        elif key == "soil_ec":
                            reading[key] = tr.conv_ec(
                                tr.unpack_U16(char.read()))
                            # Support cases where firmware is old
                            if reading["cal_dli"] == None:
                                reading["cal_dli"] = reading[key]
                                reading["cal_ea"] = reading[key]
                                reading["cal_ecb"] = reading[key]
                                reading["cal_ec_porous"] = reading[key]
                        elif key in "soil_temp":
                            reading[key] = tr.conv_temp(
                                tr.unpack_U16(char.read()))
                        elif key == "air_temp":
                            reading[key] = tr.conv_temp(
                                tr.unpack_U16(char.read()))
                            # Support cases where firmware is old
                            if reading["cal_air_temp"] == None:
                                reading["cal_air_temp"] = reading[key]
                        elif key == "vwc":
                            reading[key] = tr.conv_moisture(
                                tr.unpack_U16(char.read()))
                            # Support cases where firmware is old
                            if reading["cal_vwc"] == None:
                                reading["cal_vwc"] = reading[key]
                        else:
                            reading[key] = tr.decode_float32(char.read())

                except Exception as e:
                    self.logger.exception(
                        "[{}] Failed to read and decode sensor data: {}".
                        format(str(self.get_name()), char.read()))

        reading['ts'] = int(time.time())
        self.switch_led(FLAG_NOTIF_DISABLE)

        return reading
Esempio n. 12
0
import struct
from bluepy.btle import Scanner, DefaultDelegate, UUID, Peripheral

#TARGET_UUID = "4d6fc88bbe756698da486866a36ec78e"
TARGET_device_adr = 'b4:e6:2d:d5:a8:57'
TARGET_UUID = "4c0002154d6fc88bbe756698da486866a36ec78e0001000100"
target_dev = None
UART_SERVICE_UUID = UUID("4fafc201-1fb5-459e-8fcc-c5c9c331914b")
uart_service = None
UART_WRITE_UUID = UUID("beb5483e-36e1-4688-b7f5-ea07361b26a8")
write_char = None
UART_READ_UUID = UUID("beb5483e-36e1-4688-b7f5-ea07361b26fa")
read_char = None
read_handle = None
read_cccd = None

#############################################
# Define scan callback
#############################################


class DefaultDelegate0:
    def __init__(self):
        pass

    def handleNotification(self, cHandle, data):
        DBG("Notification:", cHandle, "sent data", data)

    def handleDiscovery(self, scanEntry, isNewDev, isNewData):
        DBG("Discovered device", scanEntry.addr)
Esempio n. 13
0
import RPi.GPIO as GPIO
import struct
from bluepy.btle import UUID, Peripheral

threshold = 10.05

fromaddr = '*****@*****.**'
toaddrs  = '*****@*****.**'
msg = 'I need immediate service and I wanted you to know!'

# Credentials (if needed)
username = '******'
password = '******'


service_uuid = UUID("1493dd8e-8c3e-4e74-a4ff-6f0cd50005f9")
char_vibr_uuid = UUID("1493dd8e-8c3e-4e78-a4ff-6f0cd50005f9")

v = Peripheral(sys.argv[1])
Testsevice=v.getServiceByUUID(service_uuid)
try:
    ch_vibr = Testsevice.getCharacteristics(char_vibr_uuid)[0]

    while 1:
        vibrVal = struct.unpack('<f', ch_temp.read())[0]
        # The actual mail send
        if vibrVal > threshold
			server = smtplib.SMTP('smtp.gmail.com:587')
			server.starttls()
			server.login(username,password)
			server.sendmail(fromaddr, toaddrs, msg)
Esempio n. 14
0
import struct
from bluepy.btle import UUID, Peripheral, DefaultDelegate
import numpy as np
import matplotlib.pyplot as plt

import matplotlib
print(matplotlib.get_backend())

# x scale - time
t = []
# record the current time
t_now = 0
# y scale - muscle current
m = []

sensor_service = UUID(0x180D)

p = Peripheral('DE:5B:BA:87:4C:F7', 'random')

SensorService = p.getServiceByUUID(sensor_service)

ch = SensorService.getCharacteristics(0x2A37)[0]
print(UUID(ch.uuid).getCommonName())

chC = ch.getHandle()

for desc in p.getDescriptors(chC, 0x16):
    if desc.uuid == 0x2902:
        chC = desc.handle

p.writeCharacteristic(chC, struct.pack('<bb', 0x01, 0x00))
Esempio n. 15
0
def add_int_to_part_of_uuid(uuid, value, part=0):
    uuid = UUID(uuid)
    parts = str(uuid).split('-')
    fmt = "{:0" + str(len(parts[part])) + "x}"
    parts[part] = fmt.format(int(parts[part], 16) + value)
    return UUID("-".join(parts))
Esempio n. 16
0
class M365(Peripheral):
    RX_CHARACTERISTIC = UUID('6e400003-b5a3-f393-e0a9-e50e24dcca9e')
    TX_CHARACTERISTIC = UUID('6e400002-b5a3-f393-e0a9-e50e24dcca9e')

    def __init__(self, mac_address, callback=None, auto_reconnect=True):
        Peripheral.__init__(self)
        self.mac_address = mac_address
        self._auto_reconnect = auto_reconnect

        self.cached_state = {}
        self._callback = callback
        self._disconnected_callback = None
        self._connected_callback = None

        stream_handler = logging.StreamHandler()
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        stream_handler.setFormatter(formatter)

        log.addHandler(stream_handler)

    def set_connected_callback(self, cb):
        self._connected_callback = cb

    def set_disconnected_callback(self, cb):
        self._disconnected_callback = cb

    @staticmethod
    def _find_characteristic(uuid, chars):
        results = filter(lambda x: x.uuid == uuid, chars)
        for result in results:  # return the first match
            return result
        return None

    def _try_connect(self):
        log.info('Attempting to {}connect to Scooter: {}'.format('indefinitely ' if self._auto_reconnect else '',
                                                                  self.mac_address))

        while True:
            try:
                Peripheral.connect(self, self.mac_address, addrType=ADDR_TYPE_RANDOM)
                log.info('Successfully connected to Scooter: ' + self.mac_address)
                if self._connected_callback:
                    self._connected_callback(self)

                # Attach delegate
                self.withDelegate(M365Delegate(self))

                # Turn on notifications, otherwise there won't be any notification
                self.writeCharacteristic(0xc,  b'\x01\x00', True)
                self.writeCharacteristic(0x12, b'\x01\x00', True)

                self._all_characteristics = self.getCharacteristics()
                self._tx_char = M365._find_characteristic(M365.TX_CHARACTERISTIC, self._all_characteristics)
                self._rx_char = M365._find_characteristic(M365.RX_CHARACTERISTIC, self._all_characteristics)
                break

            except Exception as e:
                if self._auto_reconnect == True:
                    log.warning('{}, retrying'.format(e))
                else:
                    raise e

    def _try_reconnect(self):
        try:
            self.disconnect()
        except:
            pass
        if self._disconnected_callback:
            self._disconnected_callback(self)
        self._try_connect()

    def connect(self):
        self._try_connect()

    def request(self, message):
        while True:
            try:
                log.debug('Sending message: {}'.format([v for (k,v) in message.__dict__.items()]))
                log.debug('Sending bytes: {}'.format(phex(message._raw_bytes)))
                self._tx_char.write(message._raw_bytes)
                self._rx_char.read()
                break
            except Exception as e:
                if self._auto_reconnect == True:
                    log.warning('{}, reconnecting'.format(e))
                    self._try_reconnect()
                else:
                    raise e

    def waitForNotifications(self, timeout):
        try:
            Peripheral.waitForNotifications(self, timeout)
        except Exception as e:
            if self._auto_reconnect == True:
                log.warning('{}, reconnecting'.format(e))
                self._try_reconnect()
            else:
                raise e
Esempio n. 17
0
import StandardBLEGATTCharacteristics
import GenericBTLEDevice

# Authentication Keys
AUTH_SEND_KEY = b'\x01'
AUTH_REQUEST_RANDOM_AUTH_NUMBER = b'\x02'
AUTH_SEND_ENCRYPTED_AUTH_NUMBER = b'\x03'
AUTH_BYTE = b'\x00'

AUTH_RESPONSE = b'\x10'
AUTH_SUCCESS = b'\x01'
AUTH_FAIL = b'\x04'

# Characteristics

UUID_SERVICE_MIBAND_SERVICE = UUID("FEE0")
UUID_SERVICE_MIBAND2_SERVICE = UUID("FEE1")

UUID_CHARACTERISTIC_CHUNKEDTRANSFER = [
    UUID_SERVICE_MIBAND_SERVICE, "00000020-0000-3512-2118-0009af100700"
]
UUID_CHARACTERISTIC_AUTH = [
    UUID_SERVICE_MIBAND2_SERVICE, "00000009-0000-3512-2118-0009af100700"
]
UUID_UNKNOWN_CHARACTERISTIC1 = [
    UUID_SERVICE_MIBAND_SERVICE, "00000001-0000-3512-2118-0009af100700"
]  # Also known as SENS in https://medium.com/machine-learning-world/how-i-hacked-xiaomi-miband-2-to-control-it-from-linux-a5bd2f36d3ad

# Commands
COMMAND_SET_PERIODIC_HR_MEASUREMENT_INTERVAL = b'\x14'
COMMAND_SET_HR_SLEEP = b'\x00'
Esempio n. 18
0
class Wave():

    UUID_DATETIME = UUID(0x2A08)
    UUID_HUMIDITY = UUID(0x2A6F)
    UUID_TEMPERATURE = UUID(0x2A6E)
    UUID_RADON_ST_AVG = UUID("b42e01aa-ade7-11e4-89d3-123b93f75cba")
    UUID_RADON_LT_AVG = UUID("b42e0a4c-ade7-11e4-89d3-123b93f75cba")

    def __init__(self, SerialNumber):
        self.mac_addr = None
        self.periph = None
        self.datetime_char = None
        self.humidity_char = None
        self.temperature_char = None
        self.radon_st_avg_char = None
        self.radon_lt_avg_char = None

    def scan(self):
        scanner = Scanner().withDelegate(DefaultDelegate())
        deviceFound = False
        searchCount = 0
        while deviceFound is False and searchCount < 50:
            devices = scanner.scan(0.1)  # 0.1 seconds scan period
            searchCount += 1
            for dev in devices:
                ManuData = dev.getValueText(255)
                SN = parseSerialNumber(ManuData)
                if (SN == SerialNumber):
                    MacAddr = dev.addr
                    deviceFound = True  # exits the while loop on next conditional check
                    break  # exit for loop

        if (deviceFound is not True):
            print "ERROR: Could not find device."
            print "GUIDE: (1) Please verify the serial number. (2) Ensure that the device is advertising. (3) Retry connection."
            sys.exit(1)
        else:
            self.mac_addr = MacAddr
            print "Found Wave Mac address %s" % (MacAddr)

    def connect(self):
        try:
            self.periph = Peripheral(self.mac_addr)
            self.datetime_char = self.periph.getCharacteristics(
                uuid=self.UUID_DATETIME)[0]
            self.humidity_char = self.periph.getCharacteristics(
                uuid=self.UUID_HUMIDITY)[0]
            self.temperature_char = self.periph.getCharacteristics(
                uuid=self.UUID_TEMPERATURE)[0]
            self.radon_st_avg_char = self.periph.getCharacteristics(
                uuid=self.UUID_RADON_ST_AVG)[0]
            self.radon_lt_avg_char = self.periph.getCharacteristics(
                uuid=self.UUID_RADON_LT_AVG)[0]
        except btle.BTLEException as e:
            print "Connecting error, retry..."
            time.sleep(60)

    def read(self, sensor_idx):
        if (sensor_idx == SENSOR_IDX_DATETIME and self.datetime_char != None):
            rawdata = self.datetime_char.read()
            rawdata = struct.unpack('HBBBBB', rawdata)
            data = datetime(rawdata[0], rawdata[1], rawdata[2], rawdata[3],
                            rawdata[4], rawdata[5])
            unit = " "
        elif (sensor_idx == SENSOR_IDX_HUMIDITY
              and self.humidity_char != None):
            rawdata = self.humidity_char.read()
            data = struct.unpack('H', rawdata)[0] * 1.0 / 100.0
            unit = " %rH"
        elif (sensor_idx == SENSOR_IDX_TEMPERATURE
              and self.temperature_char != None):
            rawdata = self.temperature_char.read()
            data = struct.unpack('h', rawdata)[0] * 1.0 / 100.0
            unit = " degC"
        elif (sensor_idx == SENSOR_IDX_RADON_ST_AVG
              and self.radon_st_avg_char != None):
            rawdata = self.radon_st_avg_char.read()
            data = struct.unpack('H', rawdata)[0] * 1.0
            unit = " Bq/m3"
        elif (sensor_idx == SENSOR_IDX_RADON_LT_AVG
              and self.radon_lt_avg_char != None):
            rawdata = self.radon_lt_avg_char.read()
            data = struct.unpack('H', rawdata)[0] * 1.0
            unit = " Bq/m3"
        else:
            print "ERROR: Unkown sensor ID or device not paired"
            print "GUIDE: (1) method connect() must be called first, (2) Ensure correct sensor_idx input value."
            sys.exit(1)
        return str(data) + unit

    def disconnect(self):
        if self.periph is not None:
            self.periph.disconnect()
            self.periph = None
            self.datetime_char = None
            self.humidity_char = None
            self.temperature_char = None
            self.radon_st_avg_char = None
            self.radon_lt_avg_char = None
Esempio n. 19
0
    # for each device  in the list of devices
    roehladdress = ""
    for dev in devices:
        # print  the device's MAC address, its address type,
        # and Received Signal Strength Indication that shows how strong the signal was when the script received the broadcast.
        print("Device %s (%s), RSSI=%d dB" %
              (dev.addr, dev.addrType, dev.rssi))

        for (adtype, desc, value) in dev.getScanData():
            if (value == "Roehl-M001"):
                roehladdress = dev.addr
                print("%s  %s = %s" % (roehladdress, desc, value))

    print("---hello---")
    # temp_uuid = UUID(0xff01)
    service_uuid = UUID(0x00ff)
    print(roehladdress)
    print(sys.argv[1])
    print(sys.argv[2])
    print(sys.argv[3])

    if len(roehladdress) < 5:
        print("device not find")
        scanner = None
        p = None
        ch_name = None
        ch_result = None
        ch_write = None
        continue
        # sys.exit()
    print(
Esempio n. 20
0
class BLEServicesUUIDs: 
    deviceInformation =  UUID(0x180A)
Esempio n. 21
0
number = int(number)
n = 0
for dev in devices:
    print("%d: Device %s (%s), RSSI=%d dB" %
          (n, dev.addr, dev.addrType, dev.rssi))
    if n == number:
        word = dev.addr
    n = n + 1
    for (adtype, desc, value) in dev.getScanData():
        print(" %s = %s" % (desc, value))

print(word)
print("Connecting...")
dev = Peripheral(word, 'random')
print("Services...")
for svc in dev.services:
    print(str(svc))

try:
    testService = dev.getServiceByUUID(UUID(0xfff0))
    for ch in testService.getCharacteristics():
        print(str(ch))
    for i in range(1, 50):
        ch = dev.getCharacteristics(uuid=UUID(0xfff1))[0]
        if (ch.supportsRead()):
            print(ch.read())
            time.sleep(2)

finally:
    dev.disconnect()
Esempio n. 22
0
import sys
import binascii
import struct
import time
from bluepy.btle import UUID, Peripheral

button_service_uuid = UUID(0xA000)
button_char_uuid    = UUID(0xA001)

if len(sys.argv) != 2:
  print "Fatal, must pass device address:", sys.argv[0], "<device address="">"
  quit()

p = Peripheral(sys.argv[1], "random")
ButtonService=p.getServiceByUUID(button_service_uuid)

try:
    ch = ButtonService.getCharacteristics(button_char_uuid)[0]
    if (ch.supportsRead()):
        while 1:
            val = binascii.b2a_hex(ch.read())
            print ("0x" + val)
            time.sleep(1)

finally:
    p.disconnect()
Esempio n. 23
0
train_size = 0
# knn_table = numpy.(shape(,6))

knn_table = pd.DataFrame(columns=B_COLUMNS)
# knn_table = pd.Series()
# knn_table = np.dot(knn_table,knn_table.T)
# knn_table = np.array([B_TABLE.keys().values,len(B_TABLE.keys())])
# print(knn_table)

#
# The Characteristics and services used
# The service is Heart Rate Monitor
# For the Characteristics there are the standard Heart Rate and Nbeacons Locations Characteristics
#
hrm_measure = '---'
hrm_char_uuid = UUID(0x2A37) # Heart Rate Characteristic
hrm_service_uuid = UUID(0x180D) # Heart Rate Monitor Service
location_char_uuid = UUID(0x2A69) # Location Characteristic
training_char_uuid = UUID(0x2AAD) # Training Characteristic

fig = plt.figure()
ax = fig.add_subplot(1,1,1,)
hrm_label = plt.gcf().text(0.2, 0.15, "Heart Rate:  "+hrm_measure, fontsize=14)
# ax2 = fig.add_subplot(2,2,2,)


time_prev = 0

#acquire(); release()
# threading.Semaphore(0)
mutex_access_table = threading.Lock()
Esempio n. 24
0
def _TI_UUID(val):
    return UUID("%08X-0451-4000-b000-000000000000" % (0xF0000000 + val))
    def update(self):
        _LOGGER.debug("Flowerpower updating data")
        from bluepy.btle import UUID, Peripheral, Scanner, DefaultDelegate
        periph = None

        try:

            # Connect to device
            _LOGGER.debug('Connecting')
            periph = Peripheral(self._mac)

            if (periph is None):
                _LOGGER.debug('Not connected')
            else:
                services = periph.getServices()

                #                ['daily_light_integral', 'Daily Light Integral', 'mol/m2/d', None, None],
                #    sensors.append(Sensor("Daily Light Integral"    , "39e1fa01-84a8-11e2-afba-0002a5d5c51b", '<H', "mol/m2/d\t", 1.0))
                curr_val_char = periph.getCharacteristics(
                    uuid=UUID("39e1fa01-84a8-11e2-afba-0002a5d5c51b"))[0]
                if (curr_val_char is None):
                    _LOGGER.debug('Not connected')
                else:
                    _LOGGER.debug('Reading data')
                    rawdata = curr_val_char.read()
                    _LOGGER.debug("Data:{}".format(' '.join(
                        map(str, list(rawdata)))))
                    self._state['daily_light_integral'] = struct.unpack(
                        'H', rawdata)[0]

#                ['soil_ec', 'Soil EC', 'dS/m', None, None],
#    sensors.append(Sensor("SOIL_EC"                 , "39e1fa02-84a8-11e2-afba-0002a5d5c51b", '<H', "\t", 1.0))
                curr_val_char = periph.getCharacteristics(
                    uuid=UUID("39e1fa02-84a8-11e2-afba-0002a5d5c51b"))[0]
                if (curr_val_char is None):
                    _LOGGER.debug('Not connected')
                else:
                    _LOGGER.debug('Reading data')
                    rawdata = curr_val_char.read()
                    _LOGGER.debug("Data:{}".format(' '.join(
                        map(str, list(rawdata)))))
                    self._state['soil_ec'] = struct.unpack('H', rawdata)[0]

#                ['soil_temperature', 'Soil Temperature', TEMP_CELSIUS, None, DEVICE_CLASS_TEMPERATURE],
#    sensors.append(Sensor("SOIL_TEMPERATURE"        , "39e1fa03-84a8-11e2-afba-0002a5d5c51b", '<H', "C\t", 1.0))
                curr_val_char = periph.getCharacteristics(
                    uuid=UUID("39e1fa03-84a8-11e2-afba-0002a5d5c51b"))[0]
                if (curr_val_char is None):
                    _LOGGER.debug('Not connected')
                else:
                    _LOGGER.debug('Reading data')
                    rawdata = curr_val_char.read()
                    _LOGGER.debug("Data:{}".format(' '.join(
                        map(str, list(rawdata)))))
                    self._state['soil_temperature'] = struct.unpack(
                        'H', rawdata)[0] / 32.0

#    sensors.append(Sensor("AIR_TEMPERATURE"         , "39e1fa04-84a8-11e2-afba-0002a5d5c51b", '<H', "C\t", 1.0))
#                ['air_temperature', 'Air Temperature', TEMP_CELSIUS, None, DEVICE_CLASS_TEMPERATURE],
                curr_val_char = periph.getCharacteristics(
                    uuid=UUID("39e1fa04-84a8-11e2-afba-0002a5d5c51b"))[0]
                if (curr_val_char is None):
                    _LOGGER.debug('Not connected')
                else:
                    _LOGGER.debug('Reading data')
                    rawdata = curr_val_char.read()
                    _LOGGER.debug("Data:{}".format(' '.join(
                        map(str, list(rawdata)))))
                    self._state['air_temperature'] = struct.unpack(
                        'H', rawdata)[0] / 32.0

#    sensors.append(Sensor("SOIL_MOISTURE"           , "39e1fa05-84a8-11e2-afba-0002a5d5c51b", '<H', "%\t", 1.0))
#                ['soil_moisture', 'Soil Moisture', '%', None, DEVICE_CLASS_HUMIDITY],
                curr_val_char = periph.getCharacteristics(
                    uuid=UUID("39e1fa05-84a8-11e2-afba-0002a5d5c51b"))[0]
                if (curr_val_char is None):
                    _LOGGER.debug('Not connected')
                else:
                    _LOGGER.debug('Reading data')
                    rawdata = curr_val_char.read()
                    _LOGGER.debug("Data:{}".format(' '.join(
                        map(str, list(rawdata)))))
                    self._state['soil_moisture'] = struct.unpack(
                        'H', rawdata)[0] / 32.0

#                ['calibrated_soil_moisture', 'Calibrated Soil Moisture', '%', None, DEVICE_CLASS_HUMIDITY],
#    sensors.append(Sensor("CALIBRATED_SOIL_MOISTURE", "39e1fa09-84a8-11e2-afba-0002a5d5c51b", 'f', "%\t", 1.0))
                curr_val_char = periph.getCharacteristics(
                    uuid=UUID("39e1fa09-84a8-11e2-afba-0002a5d5c51b"))[0]
                if (curr_val_char is None):
                    _LOGGER.debug('Not connected')
                else:
                    _LOGGER.debug('Reading data')
                    rawdata = curr_val_char.read()
                    _LOGGER.debug("Data:{}".format(' '.join(
                        map(str, list(rawdata)))))
                    self._state['calibrated_soil_moisture'] = struct.unpack(
                        'f', rawdata)[0]

#                ['calibrated_air_temperature', 'Calibrated Air Temperature', TEMP_CELSIUS, None, DEVICE_CLASS_TEMPERATURE],
#    sensors.append(Sensor("CALIBRATED_AIR_TEMP"     , "39e1fa0a-84a8-11e2-afba-0002a5d5c51b", 'f', "C\t", 1.0))
                curr_val_char = periph.getCharacteristics(
                    uuid=UUID("39e1fa0a-84a8-11e2-afba-0002a5d5c51b"))[0]
                if (curr_val_char is None):
                    _LOGGER.debug('Not connected')
                else:
                    _LOGGER.debug('Reading data')
                    rawdata = curr_val_char.read()
                    _LOGGER.debug("Data:{}".format(' '.join(
                        map(str, list(rawdata)))))
                    self._state['calibrated_air_temperature'] = struct.unpack(
                        'f', rawdata)[0]

#    sensors.append(Sensor("Battery"                 , UUID(0x2A19), 'B', "%\t", 1.0))
#                ['battery_level', 'Battery Level', '%', None, DEVICE_CLASS_HUMIDITY],
                curr_val_char = periph.getCharacteristics(uuid=UUID(0x2A19))[0]
                if (curr_val_char is None):
                    _LOGGER.debug('Not connected')
                else:
                    _LOGGER.debug('Reading data')
                    rawdata = curr_val_char.read()
                    _LOGGER.debug("Data:{}".format(' '.join(
                        map(str, list(rawdata)))))
                    self._state['battery_level'] = struct.unpack('B',
                                                                 rawdata)[0]

#    ['calibrated_daily_light_integral', 'calibrated Daily Light Integral', 'mol/m2/d', None, DEVICE_CLASS_ILLUMINANCE],
#    sensors.append(Sensor("CALIBRATED_DLI"          , "39e1fa0b-84a8-11e2-afba-0002a5d5c51b", 'f', "mol/m2/d\t", 1.0))
                curr_val_char = periph.getCharacteristics(
                    uuid=UUID("39e1fa0b-84a8-11e2-afba-0002a5d5c51b"))[0]
                if (curr_val_char is None):
                    _LOGGER.debug('Not connected')
                else:
                    _LOGGER.debug('Reading data')
                    rawdata = curr_val_char.read()
                    _LOGGER.debug("Data:{}".format(' '.join(
                        map(str, list(rawdata)))))
                    self._state[
                        'calibrated_daily_light_integral'] = struct.unpack(
                            'f', rawdata)[0]

#    sensors.append(Sensor("LIVE_MODE_PERIOD"        , "39e1fa06-84a8-11e2-afba-0002a5d5c51b", '<H', "%\t", 1.0))
#    sensors.append(Sensor("LED"                     , "39e1fa07-84a8-11e2-afba-0002a5d5c51b", '<H', "%\t", 1.0))
#    sensors.append(Sensor("LAST_MOVE_DATE"          , "39e1fa08-84a8-11e2-afba-0002a5d5c51b", '<H', "%\t", 1.0))
#    sensors.append(Sensor("CALIBRATED_DLI"          , "39e1fa0b-84a8-11e2-afba-0002a5d5c51b", 'f', "mol/m2/d\t", 1.0))
#    sensors.append(Sensor("CALIBRATED_EA"           , "39e1fa0c-84a8-11e2-afba-0002a5d5c51b", 'f', "\t", 1.0))
#    sensors.append(Sensor("CALIBRATED_ECB"          , "39e1fa0d-84a8-11e2-afba-0002a5d5c51b", 'f', "dS/m\t", 1.0))
#    sensors.append(Sensor("CALIBRATED_EC_POROUS"    , "39e1fa0e-84a8-11e2-afba-0002a5d5c51b", 'f', "dS/m\t", 1.0))
#    sensors.append(Sensor("Firmware"                , UUID(0x2A26), 'HBBBBB', "\t", 1.0))

        except:
            _LOGGER.debug('Not connected, error')


#            _LOGGER.debug('Resetting bluetooth')
#            subprocess.Popen(["sudo", "systemctl", "restart", "bluetooth"]).wait(5)
#            subprocess.Popen(["sudo", "hciconfig", 'hci0', "reset"]).wait(5)
        finally:
            if periph is not None:
                _LOGGER.debug('Disconnecting')
                periph.disconnect()
Esempio n. 26
0
import binascii
from bluepy.btle import UUID, Peripheral

temp_uuid = UUID(0x2A19)

p = Peripheral("6D:E7:DE:A9:7A:7D", "random")

try:
    ch = p.getCharacteristics(uuid=temp_uuid)[0]
    print binascii.b2a_hex(ch.read())
finally:
    p.disconnect()
Esempio n. 27
0

class MyDelegate(DefaultDelegate):
    def __init__(self):
        DefaultDelegate.__init__(self)

    def handleNotification(self, cHandle, data):
        #for i in range(0,15):
        #	sys.stdout.write(((data[i])))
        #	sys.stdout.write(',')
        print ' '.join("{:02x}".format(ord(c)) for c in data)
        sys.stdout.flush()


if __name__ == '__main__':
    iiot_uuid = UUID(0x2800)

p = Peripheral("24:71:89:1A:A9:27")
p.setDelegate(MyDelegate())

data_UUID = _TI_UUID(0xAA00)
sensor_UUID = _TI_UUID(0xAA01)
timestamp_UUID = _TI_UUID(0xAA02)
conf_UUID = 0x2902

data_service = p.getServiceByUUID(data_UUID)
print data_service

sensor_characteristic = data_service.getCharacteristics(sensor_UUID)
print sensor_characteristic
Esempio n. 28
0
def connect(pi):
    from bluepy.btle import Scanner, DefaultDelegate, Peripheral, ADDR_TYPE_RANDOM, UUID, BTLEException
    device = None
    addr = None

    _LOGGER.debug("Starting plejd connection")

    disconnect(pi)

    scanner = Scanner()

    for i in range(1, 10):
        devs = sorted(list(scanner.scan(1)), key=lambda d: d.rssi)[::-1]

        for d in devs:
            for (adtype, desc, value) in d.getScanData():
                if (adtype == 8 and value == "P mesh"):
                    try:
                        dev = Peripheral(d, addrType=ADDR_TYPE_RANDOM)
                        if dev.getServiceByUUID(UUID(PLEJD_SERVICE)):
                            device = dev
                        else:
                            dev.disconnect()

                        break
                    except BTLEException as e:
                        _LOGGER.warning(
                            "failed connecting to device '%s' : '%s'" %
                            (d.addr, e))
            if device:
                break

        if device is None:
            _LOGGER.warning("no device found on iteration %d" % (i))
        else:
            break

    if device == None:
        _LOGGER.warning("Failed to find a Plejd device to connect to")
        return

    _LOGGER.debug("Connected to Plejd device '%s'" % (device.addr))

    pi["device"] = device
    pi["address"] = binascii.a2b_hex(device.addr.replace(':', ''))[::-1]
    pi["handles"] = {}
    pi["handles"]["last_data"] = pi["device"].getCharacteristics(
        uuid=UUID(LAST_DATA_UUID))[0].getHandle()
    pi["handles"]["auth"] = pi["device"].getCharacteristics(
        uuid=UUID(AUTH_UUID))[0].getHandle()
    pi["handles"]["ping"] = pi["device"].getCharacteristics(
        uuid=UUID(PING_UUID))[0].getHandle()
    pi["handles"]["data"] = pi["device"].getCharacteristics(
        uuid=UUID(DATA_UUID))[0].getHandle()

    class PlejdDelegate(DefaultDelegate):
        def handleNotification(self, handle, value):
            if handle == pi["handles"]["last_data"]:
                dec = plejd_enc_dec(pi["key"], pi["address"], value)
                # check if this is a device we care about
                if dec[0] in PLEJD_DEVICES:
                    device = PLEJD_DEVICES[dec[0]]
                else:
                    _LOGGER.debug("no match for device '%d' (%s)" %
                                  (dec[0], binascii.b2a_hex(dec)))
                    return
                dim = 0xffff
                state = None
                if dec[3:5] == b'\x00\xc8' or dec[3:5] == b'\x00\x98':
                    # 00c8 and 0098 both mean state+dim
                    state = dec[5]
                    dim = int.from_bytes(dec[6:8], 'little')
                elif dec[3:5] == b'\x00\x97':
                    # 0097 is state only
                    state = dec[5]
                else:
                    _LOGGER.debug("no match for command '%s' (%s)" %
                                  (binascii.b2a_hex(dec[3:5], dec)))
                    return
                if (state == 0):
                    state = False
                else:
                    state = True

                device.update_state(state, dim)

    class PlejdNotificationThread(Thread):
        def __init__(self):
            Thread.__init__(self)
            self.stopped = True
            _LOGGER.debug("setting up notification thread")

        def stop(self):
            _LOGGER.debug("stopping notification thread")
            self.stopped = True

        import time

        def run(self):
            from bluepy.btle import BTLEInternalError
            _LOGGER.debug("starting notification thread")
            self.stopped = False
            while True:
                try:
                    pi["device"].waitForNotifications(1)
                except BTLEInternalError as e:
                    _LOGGER.warning("Encountered bluepy internal error: '%s'" %
                                    (e))
                if self.stopped:
                    break

            _LOGGER.debug("exiting notification thread")

    authenticate(pi)
    # the notification handle is last_data + 2
    pi["device"].writeCharacteristic(pi["handles"]["last_data"] + 2,
                                     b'\x02\x00')
    pi["device"].withDelegate(PlejdDelegate())
    pi["thread"] = PlejdNotificationThread()
    pi["thread"].start()

    _LOGGER.debug("all plejd setup completed")
Esempio n. 29
0
from gtts import gTTS
import numpy as np
import time  #常规时间操作模块
import datetime  #时间复杂操作模块(定时)
from bluepy.btle import UUID, Peripheral
import sys
import struct
import binascii  #进制转化模块
import os
import signal
import skywriter
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animation
##---------------bluetooth setting-------------------------
RX_SERVICE_UUID = UUID(
    '6e400001-b5a3-f393-e0a9-e50e24dcca9e')  ##只有这个是蓝牙插座的UUID
RX_CHAR_UUID = UUID('6e400003-b5a3-f393-e0a9-e50e24dcca9e')  ##接受设备uuid
TX_CHAR_UUID = UUID('6e400002-b5a3-f393-e0a9-e50e24dcca9e')  ##发送设备uuid
switch_staus = "off"
##---------------bluetooth setting end---------------------
off = 's'
on = 'l'
X = 'l'
window = tk.Tk()
window.title("控制界面")
T = Text(window, width=50)
S = Scrollbar(window)
S.pack(side=LEFT, fill=Y)
T.pack(side=LEFT, fill=Y)
S.config(command=T.yview)
T.config(yscrollcommand=S.set)
Esempio n. 30
0
        self.current_index = 0
        self.dft = [0] * 256

    def handleNotification(self, cHandle, data):
        # convert data to readable integer
        fft_input = binascii.b2a_hex(data)
        fft_input = binascii.unhexlify(fft_input)
        longueur = len(fft_input)
        dft_treated = []
        for i in range(0, 20):
            dft_treated.append(ord(fft_input[i]))
        for i in range(0, longueur, 5):
            self.read_val(dft_treated, i)

if __name__ == "__main__":
    rx_uuid = UUID(0x2221)
    sample_size = 128
    # p = Peripheral("D9:35:6A:75:9F:9D", "random") # Rfduino sur usb
    continuer = True
    while(continuer):
        try:
            p = Peripheral("D1:7F:06:ED:66:DC", "random")  # Rfduino sur pcb
            continuer = False
        except:
            print "Module bluetooth deja connecte, nouvel essai dans 3 sec..."
            time.sleep(3)
    p.withDelegate(MyDelegate())
    Analyser.set_p(p)
    print " device connected..."

    try:
Esempio n. 31
0
def main():
    config = read_config('/xiaomi/config/config.json')
    logger = configure_logger(config)
    client = initialize_db_connection(config=config, logger=logger)

    uuid_characteristic_temperature_fine = UUID(
        "00002a6e-0000-1000-8000-00805f9b34fb")  #handle 21
    uuid_characteristic_temperature_coarse = UUID(
        "00002a1f-0000-1000-8000-00805f9b34fb")  #handle 18
    uuid_characteristic_humidity = UUID(
        "00002a6f-0000-1000-8000-00805f9b34fb")  #handle 24
    uuid_characteristic_battery = UUID(
        "00002a19-0000-1000-8000-00805f9b34fb")  #handle 14

    while True:
        handle_connections(config=config, logger=logger)

        if connections is not None:
            for connection in connections:
                try:
                    characteristics = connection.getCharacteristics()
                except BTLEDisconnectError as e:
                    logger.warning("%s device is not connected",
                                   connection.addr)
                    connections.remove(connection)  #Remove disconnected device
                    continue

                for p in config['devices']:
                    if connection.addr is config['devices'][p]['mac_address']:
                        perip = p

                values = []

                for characteristic in characteristics:
                    if characteristic.uuid == uuid_characteristic_temperature_coarse:
                        values.insert(
                            0,
                            int.from_bytes(characteristic.read(),
                                           byteorder="little") / 10)
                    if characteristic.uuid == uuid_characteristic_humidity:
                        values.insert(
                            1,
                            int.from_bytes(characteristic.read(),
                                           byteorder="little") / 100)
                    if characteristic.uuid == uuid_characteristic_battery:
                        values.insert(
                            2,
                            int.from_bytes(characteristic.read(),
                                           byteorder="little"))

                logger.debug("Temp: %sC°\tHum: %s%%\tBat: %s%%\t%s\t%s",
                             str(values[0]), str(values[1]), str(values[2]),
                             connection.addr, perip)

                data_entry = [{
                    "measurement": perip,
                    "fields": {
                        "temperature": values[0],
                        "humidity": values[1],
                        "battery": values[2]
                    }
                }]
                #print (data_entry)

                if client.write_points(data_entry) is True:
                    logger.debug('SENT')

                values.clear()
        logger.debug('Active connections: %s', len(connections))
        #time.sleep(config['update_time']*60)
        time.sleep(config['update_time'] * 60)