Exemplo n.º 1
0
def _connect(cfg, mqtt_client):
    address = cfg['address']
    read_services = cfg['read']
    write_services = cfg.get('write', None)

    try:
        print('Attempting to connect to host {}'.format(address))
        p = btle.Peripheral(address, "random")
    except btle.BTLEException:
        print("Failed to connect to host {}".format(address))
        return None

    print("Connected to {}".format(address))

    chars_dict = dict()
    for svname, service in read_services.items():
        for chname, ch in service['characteristics'].items():
            chdev = enable_notify(p, service['UUID'], ch['UUID'])
            print('Notification enabled on {} '
                  'for service {}'.format(ch['UUID'], service['UUID']))
            chars_dict[chdev.getHandle()] = ch
            print('Characteristic {} on service {} is registered as name \''
                  '{}\''.format(ch['UUID'], service['UUID'], ch['mqtt_topic']))

    if write_services is not None:
        for svname, service in write_services.items():
            service_handle = p.getServiceByUUID(service['UUID'])
            for chname, ch in service['characteristics'].items():
                write_char = service_handle.getCharacteristics(ch['UUID'])
                ch['write_char'] = write_char[0]
                print(
                    'Characteristic {} on service write enabled on {}'.format(
                        ch['UUID'], service['UUID'], ch['mqtt_topic']))

    p.setDelegate(BTLEDelegate(chars_dict, mqtt_client, True))
    cfg['periferal'] = p
    return p
Exemplo n.º 2
0
 def connectproc(self):
     prevstate = self.connected
     self.conninprogress = True
     try:
         misc.addLog(
             rpieGlobals.LOG_LEVEL_INFO, "BLE connection initiated to " +
             str(self.taskdevicepluginconfig[0]))
         self.BLEPeripheral = btle.Peripheral(
             str(self.taskdevicepluginconfig[0]))
         self.connected = True
         self.afterconnection()
     except:
         self.setdisconnectstate()  # disconnected!
     self.conninprogress = False
     self.isconnected()
     publishchange = (self.connected != prevstate)
     if self.connected:
         self.set_value(2, self.connected, publishchange)
     else:
         self.set_value(1, 0, False)
         self.set_value(2, 0, publishchange, suserssi=-100, susebattery=0)
         misc.addLog(
             rpieGlobals.LOG_LEVEL_ERROR,
             "BLE connection failed " + str(self.taskdevicepluginconfig[0]))
         return False
     if self.connected and self.handshake:
         misc.addLog(
             rpieGlobals.LOG_LEVEL_INFO,
             "BLE connected to " + str(self.taskdevicepluginconfig[0]))
         self.waitnotifications = True
         while self.waitnotifications:
             try:
                 self.BLEPeripheral.waitForNotifications(0.5)
             except Exception as e:
                 self.waitnotifications = False
                 self.setdisconnectstate()  # disconnected!
         self.setdisconnectstate(False)  # disconnected!
def setblerequest(status, devicemac, bleHandle, bleValue):
    # Send the BLE request code via bluetooth to the valve
    global deviceblelock
    if trace:
        print("Connecting " + devicemac + "...")
    if deviceblelock == False:
        deviceblelock = True
        try:
            device = btle.Peripheral(str(devicemac))
            bleValueByte = bleValue.encode('utf-8')
            device.writeCharacteristic(0x0073, bleValueByte, withResponse=True)
        except btle.BTLEDisconnectError:
            print(
                "Connection error when sending BLE message to valve (BTLEDisconnectError)"
            )
            pass
        if trace:
            print("Wait " + str(waittime) + " seconds...")
        time.sleep(int(waittime))
        device.disconnect()
        deviceblelock = False
    else:
        time.sleep(5)
        setblerequest(status, devicemac, bleHandle, bleValue)
Exemplo n.º 4
0
    def __enter__(self):
        """
        Context manager __enter__ for connecting the device
        :rtype: btle.Peripheral
        :return:
        """
        conn_state = "conn"
        if self._conn:
            # connection active, check if still connected
            try:
                conn_state = self._conn.getState()
            except (btle.BTLEInternalError, btle.BTLEDisconnectError):
                # connection not active, set _conn object to None
                self._conn = None

        if self._conn is None or conn_state != "conn":
            # no active connection, connect now
            self._conn = btle.Peripheral()
            self._conn.withDelegate(self)
            _LOGGER.debug("Trying to connect to %s", self._mac)
            self.connect(self._iface)
            _LOGGER.debug("Connected to %s", self._mac)

        return self
Exemplo n.º 5
0
def getTemp(device):
    peripheralDevice = device
    randomAddress = 'random'
    print('[i] Connecting to {}'.format(peripheralDevice))
    try:
        p = btle.Peripheral(peripheralDevice, randomAddress)
    except btle.BTLEDisconnectError:
        print('[w] Your BTLE device is not connected')
        print('[i] Quitting the program')
        exit(1)
        # for svc in p.getServices():
        #     print(f"Services : {svc.uuid.get}")

    svc = p.getServiceByUUID('e95d6100-251d-470a-a062-fa1922dfa9a8')
    temperature = svc.getCharacteristics(
        "e95d9250-251d-470a-a062-fa1922dfa9a8")[0]

    print('[i] End of the connection...')
    t = temperature.read()
    #a = accelerometer.read()

    #print("Temperature: {}".format(ord(t)))
    p.disconnect()
    return ord(t)
def InitPeripheralConnection(obj, address):

    global PeripheralConnection
    global PeripheralAddrName
    global SensorThread
    global lock_periphal
    global lock_CharRead

    tries = 0
    #lock_periphal.acquire()
    try:
        while not PeripheralAddrName and not PeripheralConnection and tries < 10:

            #print( "connecting to %s ...." % (address))
            try:
                if SensorThread:
                    #print("Found  SensorThread. Killing...")
                    SensorThread.running = False
                    time.sleep(5)

                PeripheralConnection = btle.Peripheral(address, addrType=btle.ADDR_TYPE_PUBLIC)
                #print("PeripheralConnection=%s" % (str(PeripheralConnection)))
                SensorThread = BLE_ReadSensorValues(PeripheralConnection, 4.5)
                SensorThread.start()
                PeripheralAddrName = address
                time.sleep(3)
            except Exception as e:
                if SensorThread:
                    SensorThread.running = False

                #print("InitPeripheralConnection::Couldn't connect::", str(e))
                tries += 1
                #print("connection attempt %d (%s)" % (tries + 1, str(obj)))
                time.sleep(1)
    finally:
        pass
Exemplo n.º 7
0
    def get_services(self, device):
        print(f"{device.addr} - attempting to fetch services")

        if not device.connectable:
            # Device is not currently in connectable state
            print(
                f"{device.addr} - services could not be fetched (not connectable)"
            )
            return []

        try:
            # Connect to the device and fetch services
            peripheral = btle.Peripheral(device)
            services = peripheral.getServices()

            if services is None:
                # Device has no services
                print(f"{device.addr} - has no services")
                return []

            services_dict = []
            for service in services:
                # Get characteristics of service
                services_dict.append({
                    "uuid":
                    service.uuid.getCommonName(),
                    "characteristics":
                    self.get_characteristics(service)
                })

            print(f"{device.addr} - fetched {len(services_dict)} services")
            return services_dict
        except btle.BTLEDisconnectError as exception:
            print(
                f"{device.addr} - services could not be fetched ({exception})")
            return []
Exemplo n.º 8
0
def sens_th1(mac):
    try:
        peripheral = btle.Peripheral(mac)
        characteristic = peripheral.readCharacteristic(0x28)
        (temp, humid, unknown1, unknown2,
         unknown3) = struct.unpack('<hhBBB', characteristic)
        sensorValue = {
            'created': getTimeSTR(),
            'Temperature': temp / 100,
            'Humidity': humid / 100,
            'external': unknown1,
            'unknown2': unknown2,
            'unknown3': unknown3,
            'RAW': characteristic,
        }
        return sensorValue

    except btle.BTLEException as e:
        logging.warning("[sens_th1] bulepy Exception:{}" + format(e))
        return None

    except Exception as e:
        logging.error("[sens_th1] Eception :{}" + format(e))
        return None
Exemplo n.º 9
0
    def __init__(self, deviceAddress):
        btle.DefaultDelegate.__init__(self)

        # Address type must be "random" or it won't connect.
        self.peripheral = btle.Peripheral(deviceAddress, btle.ADDR_TYPE_RANDOM)
        self.peripheral.setDelegate(self)

        self.seq = 0

        # Attribute UUIDs are identical to Ollie.
        self.antidos = self.getSpheroCharacteristic('2bbd')
        self.wakecpu = self.getSpheroCharacteristic('2bbf')
        self.txpower = self.getSpheroCharacteristic('2bb2')
        self.roll = self.getSpheroCharacteristic('2ba1')
        self.notify = self.getSpheroCharacteristic('2ba6')

        # This startup sequence is also identical to the one for Ollie.
        # It even uses the same unlock code.
        print 'Sending antidos'
        self.antidos.write('011i3', withResponse=True)
        print 'Sending txpower'
        self.txpower.write('\x0007', withResponse=True)
        print 'Sending wakecpu'
        self.wakecpu.write('\x01', withResponse=True)
Exemplo n.º 10
0
	def __init__(self, deviceAddress):
		btle.DefaultDelegate.__init__(self)

		self.curCoords = b'\x00\x00'
		self.startCoords = b'\x0c\xfb'
		self.endCoords = b'\xf5\x1d'
		self.panStatus = ""

		self.peripheral = btle.Peripheral(deviceAddress, btle.ADDR_TYPE_PUBLIC)
		self.peripheral.setDelegate(self)

		for svc in self.peripheral.services:
			print str(svc)	

		self.service = self.peripheral.getServiceByUUID("0000fee9-0000-1000-8000-00805f9b34fb")	#Quintic 
		self.characteristic = self.service.getCharacteristics()

		for cha in self.characteristic:
			print str(cha)


		print "Notifications enabled"
		self.peripheral.writeCharacteristic(0x33, struct.pack('<BB', 0x01, 0x00), withResponse=True)
		self.peripheral.writeCharacteristic(0x30, struct.pack('<BB', 0x01, 0x00), withResponse=True)


		print "Device name:"
		hexdump(self.peripheral.readCharacteristic(0x0003))

		uuidWrite  = btle.UUID("d44bc439-abfd-45a2-b575-925416129600")	#44, 0x2C
		uuidRead  = btle.UUID("d44bc439-abfd-45a2-b575-925416129601")	#47, 0x2F
		uuid  = btle.UUID("d44bc439-abfd-45a2-b575-925416129610")		#50, 0x32

		self.chaWrite = self.service.getCharacteristics(uuidWrite)[0]
		self.chaRead = self.service.getCharacteristics(uuidRead)[0]
		self.cha = self.service.getCharacteristics(uuid)[0]
Exemplo n.º 11
0
def device_add_command(address, addr_type):
    """Adds the device but does not connect to it.
    
    Arguments:
        address (str): The MAC address of the device.
    """
    try:
        # check the mac address
        if is_valid_address(address):    
            global devices
            
            # check that the device exists
            if address not in devices:
                # check the address type
                if addr_type == btle.ADDR_TYPE_PUBLIC or addr_type == btle.ADDR_TYPE_RANDOM:
                    devices[address] = btle.Peripheral(address=address)
                else:
                    click.secho('Cannot add device, device address type {} not valid!'.format(addr_type), fg='red')
            else:
                click.secho('Command cannot be run. Device {} already exists!'.format(address), fg='red')
        else:
            click.secho('Command cannot be run. Device MAC {} not valid!'.format(address), fg='red') 
    except btle.BTLEException as e:
        click.secho('A BTLEException has occured!\n{}'.format(e), fg='red')
Exemplo n.º 12
0
def read_data(address):
    print("Connecting to", address)
    data = ''
    tries = 5
    while tries > 0:
        try:
            tries -= 1
            dev = btle.Peripheral(address)
            service = dev.getServiceByUUID(btle.UUID(SVC_UUID))
            for svc in dev.services:
                print(str(svc))
            for ch in service.getCharacteristics():
                print(str(ch))
            idsChrc = service.getCharacteristics(btle.UUID(DEV_IDS_CHR))[0]
            attrChrc = service.getCharacteristics(btle.UUID(DEV_ATTR_CHRC))[0]
            idsBytes = idsChrc.read()
            attrBytes = attrChrc.read()
            ids = bytes(idsBytes)
            attrs = bytes(attrBytes).decode('utf-8')
            print("ids, attrs", ids, attrs)
            break
        except Exception as e:
            print(e)
    return data
Exemplo n.º 13
0
    def __init__(self, mac, mesh_name="unpaired", mesh_password="******"):
        """
        Args :
            mac: The light's MAC address as a string in the form AA:BB:CC:DD:EE:FF
            mesh_name: The mesh name as a string.
            mesh_password: The mesh password as a string.
        """
        self.mac = mac
        self.mesh_id = 0
        self.btdevice = btle.Peripheral()
        self.session_key = None
        self.command_char = None
        self.mesh_name = mesh_name.encode()
        self.mesh_password = mesh_password.encode()

        # Light status
        self.white_brightness = None
        self.white_temp = None
        self.color_brightness = None
        self.red = None
        self.green = None
        self.blue = None
        self.mode = None
        self.status = None
Exemplo n.º 14
0
 def getInfo(self):
     # if properties=='READ', readType and readMsg
     info = {
     }  # {service1:{chara1:[handle, properties, readType, readMsg], chara2}}
     try:
         d = btle.Peripheral(self.addr, self.addrType)
     except:
         return 1
     try:
         for ser in d.getServices():
             dict1 = {}
             for chara in ser.getCharacteristics():
                 list1 = []
                 list1.append(str(chara.getHandle()))
                 list1.append(chara.propertiesToString())
                 if (chara.supportsRead()):
                     list1.append(type(chara.read()))
                     list1.append(chara.read())
                 dict1[str(chara)] = list1
             info[str(ser)] = dict1
     except:
         return 2
     d.disconnect()
     return info
Exemplo n.º 15
0
def main():
    # get args
    args = get_args()

    print("Connecting…")
    nano_sense = btle.Peripheral(args.mac_address)

    print("Discovering Services…")
    _ = nano_sense.services
    environmental_sensing_service = nano_sense.getServiceByUUID("181A")

    print("Discovering Characteristics…")
    _ = environmental_sensing_service.getCharacteristics()

    updateTime = read_updateTime(environmental_sensing_service)
    
    while True:
        print("\n")
        read_temperature(environmental_sensing_service)
        read_humidity(environmental_sensing_service)
        read_pressure(environmental_sensing_service)
        #read_color(environmental_sensing_service)

        time.sleep(updateTime) # transmission frequency set on IoT device
    def connect(self):
        #self.ble_device.connect()
        #print(self.ble_device)
        self.conn = btle.Peripheral(self.ble_device, btle.ADDR_TYPE_RANDOM)

        logger.debug("Attempting to discover characteristics...")

        #self.ble_device.discover([UART_SERVICE_UUID], [TX_CHAR_UUID, RX_CHAR_UUID])
        #conn = btle.Peripheral(self.ble_device, btle.ADDR_TYPE_RANDOM)

        # Find the UART service and its characteristics.
        self.uart = self.conn.getServiceByUUID(UART_SERVICE_UUID)
        self.rx = self.uart.getCharacteristics(RX_CHAR_UUID)[0]
        self.tx = self.uart.getCharacteristics(TX_CHAR_UUID)[0]

        # Turn on notification of RX characteristics using the callback above.
        logger.debug('Subscribing to RX characteristic changes...')

        #self.rx.write(struct.pack('<bb',0x01,0x00)) # doesn't work. not sure why
        #conn.writeCharacteristic(handle=self.rx.getHandle(),val=struct.pack('<bb', 0x00, 0x00))
        CONFIG_HANDLE = 0x000c
        self.conn.writeCharacteristic(handle=CONFIG_HANDLE,
                                      val=struct.pack('<bb', 0x01, 0x00))
        self.conn.setDelegate(SimpleDelegate(bleconn=self))
Exemplo n.º 17
0
    def read(self):
        if (datetime.now() - timedelta(seconds=self.timeout) >
                self._last_read) and (self.busy == False):
            self._last_read = datetime.now()
            try:
                self.busy = True
                peripheral = btle.Peripheral(self.address)
                peripheral.writeCharacteristic(_HANDLE_WRITE_MODE_CHANGE,
                                               _DATA_MODE_CHANGE,
                                               withResponse=True)

                received_bytes = bytearray(
                    peripheral.readCharacteristic(_HANDLE_READ_SENSOR_DATA))
                #            print("ble read ",received_bytes) # DEBUG!
                self._temperature, self._light, self._moisture, self._conductivity = unpack(
                    '<hxIBhxxxxxx', received_bytes)
                self._temperature = float(self._temperature) / 10.0
                peripheral.disconnect()
                self.busy = False
                return True
            except Exception as e:
                print(e)
                self.busy = False
                return False
Exemplo n.º 18
0
 def __init__(self,addr):
     self.address=addr
     self.dev=btle.Peripheral(self.address,u'random')
     self.position=0.0
     self.velocity=0.0
     self.torque=0.0
     self.accel_x=0.0
     self.accel_y=0.0
     self.accel_z=0.0
     self.temp=0
     self.gyro_x=0
     self.gyro_y=0
     self.gyro_z=0
     for v in self.dev.getCharacteristics():
         if v.uuid==u'f1400001-8936-4d35-a0ed-dfcd795baa8c':
             self.motor_control_handle=v.getHandle()
         if v.uuid==u'f1400003-8936-4d35-a0ed-dfcd795baa8c':
             self.motor_led_handle=v.getHandle()
         if v.uuid==u'f1400004-8936-4d35-a0ed-dfcd795baa8c':
             self.motor_measurement_handle=v.getHandle()
         if v.uuid==u'f1400005-8936-4d35-a0ed-dfcd795baa8c':
             self.motor_imu_measurement_handle=v.getHandle()
         if v.uuid==u'f1400006-8936-4d35-a0ed-dfcd795baa8c':
             self.motor_settings_handle=v.getHandle()
Exemplo n.º 19
0
    def get_data(self, now=None):
        try:
            from bluepy import btle

            p = btle.Peripheral(self.address)

            #self.name = ''.join(map(chr, p.readCharacteristic(0x3)))
            #self.firmware = ''.join(map(chr, p.readCharacteristic(0x24)))
            if self.last_battery is None or (
                    utcnow() - self.last_battery).seconds >= 3600:
                self.battery = p.readCharacteristic(0x18)[0]
                self.last_battery = utcnow()

            delegate = XiomiHygroThermoDelegate()
            p.withDelegate(delegate)
            p.writeCharacteristic(0x10, bytearray([1, 0]), True)
            while not delegate.received:
                p.waitForNotifications(30.0)

            self.temperature = delegate.temperature
            self.humidity = delegate.humidity

            ok = True
        except Exception as ex:
            if isinstance(ex, btle.BTLEException):
                _LOGGER.warning("BT connection error: {}".format(ex))
            else:
                _LOGGER.error("Unexpected error: {}".format(ex))
            ok = False

        for i in [0, 1]:
            changed = self.entities[i].set_state(
                ok, self.battery,
                self.temperature if i == 0 else self.humidity)
            if (not now is None) and changed:
                self.entities[i].async_schedule_update_ha_state()
Exemplo n.º 20
0
from bluepy import btle

battery_handle = 0x0011


def get_battery(peripheral):
    """
	returns the battery level of the myo
	"""
    return peripheral.readCharacteristic(battery_handle)


if __name__ == "__main__":
    per = btle.Peripheral("EF:CD:C9:EA:16:6C")
    print get_battery(per)
Exemplo n.º 21
0
from bluepy import btle

btle_device = btle.Peripheral("00:13:AA:00:2A:9F")

for service in btle_device.services:
    print(str(service))
Exemplo n.º 22
0
        print("Data received")

        #Get currente datetime
        now = datetime.datetime.now()

        #Is file exist, open it, create if not
        filename = now.strftime("%m-%y") + "_log.txt"

        #Open file in append mode
        file = open(filename, 'a')

        #Decide data
        decoded = data.decode('utf-8')

        #Write data with format a0,b0,...z0;a1,b1,..,z1;a2,b2,..,z2
        writer = file.write(decoded + ';')


BLELADDR = str("D4:36:39:67:7F:2A")
p = btle.Peripheral(BLELADDR)
p.withDelegate(ReadDelegate())

#Infinity loop
while True:
    #Notification will be handled ever Data received
    while p.waitForNotifications(1):
        pass

#Disconnect
p.disconnect()
Exemplo n.º 23
0
 def __init__(self):
     self.dev = btle.Peripheral(iface=0)
     print(self.dev.iface)
Exemplo n.º 24
0
    def do_decode_pcap(self, args):
        """
Creates a FIFO pipe at /tmp/pipe by default (or this can be specified). Stream an input PCAP format to parse the BTLE data:

    > decode_pcap
    > decode_pcap /tmp/pipe

For PCAP format (especially when using FIFO with Btlejack) use the 'll_phdr' format within the tool itself. E.g.:

    > btlejack -c <BDADDRESS> -w /tmp/pipe -x ll_phdr

Or use a static PCAP file as an input (this will also parse out the Write/Read commands and Handles):

    > decode_pcap /home/user/test.pcap

The supplemental arguments available are as follows:

    -a : Displays both inbound and outbound packets (Default: Outbound)
    -x : Displays data as raw hex rather than a decoded format
    -w : Add the Write commands to the internal storage for later replay via 'writeblk x'
    -r : Replay directly during PCAP parsing (Only via static PCAP file input) - Infers -w
"""

        filename = self.FIFO
        fifo_scapy = False
        decode_val = True
        _view_response = False
        self._pcap_add_write_blk = False
        _replay = False

        args = shlex.split(args)
        for arg in args:
            if re.match('([/][\w\d]{1,})', arg) or re.match(
                    '^((.+)\/([^/]+))$', arg):
                filename = arg
                continue
            elif arg == "-x":
                decode_val = False
                self.pp.info("Displaying Raw Hex")
                continue
            elif arg == "-a":
                _view_response = True
                self.pp.info("Displaying Inbound and Outbound")
            elif arg == "-w":
                self._pcap_add_write_blk = True
            elif arg == "-r":
                self._pcap_add_write_blk = True
                _replay = True

        if decode_val:
            self.pp.info("Decoding BLE Data")

        if not _view_response:
            self.pp.info("Displaying Outbound Only")

        if args:
            if re.match('([/][\w\d]{1,})',
                        filename) and ".pcap" not in filename:
                self.pp.info(f"Parsing PCAP via FIFO: {filename}")
                self.FIFO = filename
                fifo_scapy = True

            elif ".pcap" in filename:
                self.pp.info(f"Parsing PCAP as file: {filename}")
                fifo_scapy = False

        if fifo_scapy or not args:

            if os.path.exists(filename):
                self.pp.info(f"Using FIFO Pipe: {self.FIFO}")
            else:
                self.pp.info(f"Creating FIFO Pipe: {self.FIFO}")
                try:
                    self.make_pipe()
                except:
                    try:
                        self.destroy_pipe()
                        self.make_pipe()
                    except:
                        self.pp.error(
                            f"Error: Unable to make pipe: {self.FIFO}")
                        return

            self.pp.info("FIFO opened")
            fifo = open(filename, "rb", buffering=0)
            self._decode_pcap_fifo = True
            self.pp.ok("Opcode Command      : Handle : Data")
            while True:
                try:
                    for pkt in (PcapReader(fifo)):
                        try:
                            self.parse_pcap(pkt, decode_val, _view_response)
                        except:
                            continue
                except:
                    self.pp.info("Exited Decoder")
                    self.destroy_pipe()
                    if self._target_changed_pcap_decode and self._pcap_add_write_blk:
                        self.pp.ok(f"Set new target as {self._target}")
                    return

        else:
            self._decode_pcap_fifo = False
            self.pp.ok("Opcode Command      : Handle : Data")

            for pkt in PcapReader(filename):
                self.parse_pcap(pkt, decode_val, _view_response)

            if self._target_changed_pcap_decode and self._pcap_add_write_blk:
                self.pp.ok(f"Set new target as {self._target}")

            if _replay:
                try:
                    _device = btle.Peripheral(self._target,
                                              addrType=self._hci_type,
                                              iface=int(self._interface))
                except:
                    self.pp.error("Error: Unable to connect")
                    return

                for x in self._block_data:
                    self.pp.info(f"Sending write cmd: {x}")
                    self.write(x, _device)
Exemplo n.º 25
0
            if data[0] == 'I':
                print("Interaction Code: %s" % payload[0])
        else:
            print("handleNotification handle 0x%04X unknown" % (cHandle))


notifOn = b"\x01\x00"
notifOff = b"\x00\x00"
gf_ble_mac = "BB:A0:50:03:31:19"
GATTUUID = "0000cdd0-0000-1000-8000-00805f9b34fb"
WRITEUUID = "0003cdd2-0000-1000-8000-00805f9b0131"
NOTIFYUUID = "0003cdd1-0000-1000-8000-00805f9b0131"

print("Connecting to BLE device MAC: " + gf_ble_mac)

per = btle.Peripheral(gf_ble_mac)
services = per.getServices()
services[2].getCharacteristics(WRITEUUID)
gfService = per.getServiceByUUID(GATTUUID)
writechar = gfService.getCharacteristics(WRITEUUID)[0]
writehandle = gfService.getCharacteristics(WRITEUUID)[0].getHandle()
notifychar = gfService.getCharacteristics(NOTIFYUUID)[0]
notifyhandle = gfService.getCharacteristics(NOTIFYUUID)[0].getHandle()
per.withDelegate(MyDelegate(notifyhandle))

print("Enabling notifications...")
char = per.getCharacteristics(uuid=NOTIFYUUID)[0]
ccc_desc = char.getDescriptors(forUUID=0x2902)[0]
ccc_desc.write(notifOn, withResponse=True)
print("\tDone")
per.waitForNotifications(0.5)
Exemplo n.º 26
0
    def do_writeblk(self, args):
        """
Enter multiple 'write' commands as 'Handle Data':

    > write
    > 0x1e 5468697349736154657374
    > 0x09 5468697349736154657374
    > 0xa3 5468697349736154657374
    > end

Note: If you suffix the command with 'string' this will be converted to a hex string:

    > write
    > 0x1e 5468697349736154657374
    > 0x09 'ThisIsATest' string
    > 0xa3 5468697349736154657374
    > end

Alternatively, if you've already run a block previously, you can re-run this by sending the 'x' argument:

    > write -x
"""
        _send_stored_block = False
        _send_repeat = False
        args = shlex.split(args)
        for arg in args:
            if arg == "-x":
                _send_stored_block = True

        if _send_stored_block is False:
            self._block_data = []
            _block_input = ""
            self.pp.info(
                "Enter one command per line as 'handle data' and then 'end' to finish. E.g: 0x1e 305721e4a290 "
            )
            while True:
                _block_input = input()
                if _block_input.lower() != "end":
                    self._block_data.append(_block_input)
                else:
                    self.pp.info("Write command input finished!")
                    _send_stored_block = True
                    break

        if len(self._block_data) > 0 and _send_stored_block:
            self.pp.info("Sending previous block of write commands...")
            self.pp.info("Connecting...")

            try:
                _device = btle.Peripheral(self._target,
                                          addrType=self._hci_type,
                                          iface=int(self._interface))
            except:
                self.pp.error("Error: Unable to connect")
                return

            self.pp.ok(f"Connected to {self._target}")

            for x in self._block_data:
                self.pp.info(f"Sending write cmd: {x}")
                self.write(x, _device)

            self.pp.ok("Commands sent")

        else:
            self.pp.warn("No write commands specified")
Exemplo n.º 27
0
    def do_scan(self, args):
        """
Perform a BLE scan for devices within range. Optional argument is a timeout for scan time:

    > scan
    > scan 3
    > scan 20
"""
        if not self._interface:
            return

        # Set scanner timeout - default 5 seconds
        if args:
            _timeout = int(args)
        else:
            _timeout = 2

        # Start scanner
        self.pp.info("Starting BLE scan...")
        scanner = btle.Scanner(self._interface)
        try:
            self._devices = scanner.scan(timeout=_timeout)
        except:
            self.pp.error(
                f"Error: Can't connect to Bluetooth interface hci{self._interface}"
            )
            return

        self.pp.ok("Scan complete!")
        self.pp.info(
            f"Identifying device names for {str(len(self._devices))} devices.."
        )

        _headerrow = [
            'Bluetooth Address', 'Device Name', 'RSSI', 'Connectable',
            'Address Type'
        ]

        self._targetcompletions = []
        _rows = []
        self._disc_devices = []

        for x in self._devices:
            _address = x.addr
            _rssi = x.rssi
            if _rssi > -50:
                _rssi = self.pp.green(str(_rssi))
            elif _rssi <= -50 and _rssi > -65:
                _rssi = self.pp.yellow(str(_rssi))
            else:
                _rssi = self.pp.red(str(_rssi))

            _type = x.addrType

            if x.connectable == 1 or x.connectable == "1":
                _connect = True

                _connect_str = self.pp.green("True")
            else:
                _connect = False
                _connect_str = self.pp.red("False")

            # Attempt to read Device Name
            if _connect and _type.lower().strip() == "public":

                try:
                    _device = btle.Peripheral(_address,
                                              addrType=self._hci_type,
                                              iface=int(self._interface))
                    _device_name = _device.readCharacteristic(0x3).decode(
                        "utf-8")
                    _device.disconnect()
                except:
                    _device_name = ""
            else:
                _device_name = ""

            _row = [_address, _device_name, _rssi, _connect_str, _type]
            self._targetcompletions.append(_address)
            _rows.append(_row)
            self._disc_devices.append(_row)
        self.displayDevices("")
Exemplo n.º 28
0

for x in range(0, len(device_addr)):

    os.system("sudo hciconfig hci0 down")
    time.sleep(1)
    os.system("sudo hciconfig hci0 up")
    time.sleep(1)

    print("connecting to %s ... " % (device_addr[x]))
    textout = open("/home/pi/temp_log.txt", "a")
    textout.write("\nconnecting to %s at " % device_addr[x])
    textout.write(now.strftime("%m-%d-%Y %H:%M") + "\n")

    try:
        dev = btle.Peripheral(device_addr[x], "random")
        dev.setDelegate(MyDelegate())
        print("connected")

        service_uuid = btle.UUID(BLE_SERVICE_UUID)
        ble_service = dev.getServiceByUUID(service_uuid)

        uuidConfig = btle.UUID(BLE_CHARACTERISTIC_UUID)
        data_chrc = ble_service.getCharacteristics(uuidConfig)[0]
        data_chrc = data_chrc.valHandle + 1

        dev.writeCharacteristic(data_chrc, "\x01\x00")

        time.sleep(1.0)  # Allow sensor to stabilise

        while True:
Exemplo n.º 29
0
        print(
            "Offset calibration and 2 Point calibration can't be used together"
        )
        os._exit(1)
if not args.name:
    args.name = args.device

if args.callback:
    dataThread = threading.Thread(target=thread_SendingData)
    dataThread.start()

signal.signal(signal.SIGINT, signal_handler)

if args.device:

    p = btle.Peripheral()
    cnt = 0

    connected = False
    #logging.basicConfig(level=logging.DEBUG)
    logging.basicConfig(level=logging.ERROR)
    logging.debug("Debug: Starting script...")
    pid = os.getpid()
    bluepypid = None
    unconnectedTime = None
    connectionLostCounter = 0

    watchdogThread = threading.Thread(target=watchDog_Thread)
    watchdogThread.start()
    logging.debug("watchdogThread started")
Exemplo n.º 30
0
 def _connect(self):
     logging.info("Connecting...")
     self.conn = btle.Peripheral(self.device_mac, btle.ADDR_TYPE_RANDOM)
     #self.conn.setSecurityLevel("medium")
     logging.info("Connected...")
     self._enable()