示例#1
0
import sys
from bluepy.btle import UUID, Peripheral

dev_name_uuid = UUID(0x2A00)
if len(sys.argv) != 2:
    print("Fatal, must pass device address:", sys.argv[0], "<device address="
          ">")
    quit()
p = Peripheral(sys.argv[1], "public")
try:
    ch = p.getCharacteristics(uuid=dev_name_uuid)[0]
    if (ch.supportsRead()):
        print(ch.read())
finally:
    p.disconnect()
示例#2
0
for column in range(0, 172):
    for line in range(0, 72, 4):
        pixel_data = 0
        for pixel in range(0, 4):
            pixel_data = pixel_data << 2
            cursor = (172 * (line + pixel) + column) * 3
            pixel_data = (pixel_data | (blob[cursor] >> 6))
        pixels.append(pixel_data)

connected = False

while not connected:
    connected = True
    print("Connecting ...")
    try:
        p = Peripheral(target_mac, "public")
    except BTLEException:
        connected = False

command = p.getCharacteristics(uuid=uuid_command)[0]
data = p.getCharacteristics(uuid=uuid_data)[0]

print("Connected")

command.write(bytearray([1]), True)

for i in range(0, 194):
    bytes = []
    for j in range(0, 16):
        if len(pixels) > (i * 16 + j):
            bytes.append(pixels[i * 16 + j])
示例#3
0
from bluepy.btle import Peripheral, UUID

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

try:
    chList = p.getCharacteristics()
    for ch in chList:
        print('0x' + format(ch.getHandle(), '02X') + "  " + str(ch.uuid) + "  " + ch.propertiesToString())
finally:
    p.disconnect()

示例#4
0
        if self.SYN is False:  # and data.decode('ascii') is "SYN":
            self.SYN = True
            message = "SYN_ACK"
            print("received SYN")
            message = message.encode('ascii')
            self.peripheral.writeCharacteristic(hdl, message, True)
        elif self.SYN is True:
            if self.ACK is False:
                self.ACK = True
                message = "handshaking completed"
                print("received ACK")
                message = message.encode('ascii')
                self.peripheral.writeCharacteristic(hdl, message, True)
            elif self.ACK is True:
                print("Received message: " + data.decode('ascii'))
                message = input('>>')
                message = message.encode('ascii')
                self.peripheral.writeCharacteristic(hdl, message, True)
        else:
            print(data.decode('ascii'))


hc08 = Peripheral()
hc08.connect("a8:e2:c1:62:7f:bc", "public")

hc08.withDelegate(MyDelegate(hc08))

while True:
    print("Start waiting for messages...")
    hc08.waitForNotifications(10.0)
示例#5
0
        command = self.data_uri + "?sensorID= " + str(sensor_id) + "&humidity=" + str(hum) + "&temperature=" + str(temp) + "&airQuality=" + str(gas)
        requests.put(command)

    def read_data(self):
        command = self.data_uri
        requests.get(command)

#\\\\\\\\\\\\  GLOBAL VARIABLES  \\\\\\\\\\\\\\\\

modules_MACs = ['18:93:d7:14:5e:2b', 'c8:fd:19:3e:be:7f']
connected_modules = []
connection_threads = []
scanner = Scanner(0)
api = API_handler()

#\\\\\\\\\\\\  MAIN  \\\\\\\\\\\\\\\\
while len(connection_threads) < len(modules_MACs):
    print 'Scanning...'
    devices = scanner.scan(2)
    for d in devices:
        if d.addr in modules_MACs:
            p = Peripheral(d)
            connected_modules.append(p)
            print 'Module ' + d.addr + ' connected. Assigned ID = ' + str(len(connected_modules)-1)
            t = ConnectionHandlerThread(len(connected_modules)-1)
            t.start()
            connection_threads.append(t)
            # time.sleep(7)

print 'All devices are connected.'
示例#6
0
addCount = 0
for dev in devices:
    print " %d. Device %s (%s), RSSI=%d dB" % (addCount, dev.addr,
                                               dev.addrType, dev.rssi)
    addCount += 1
    scanDeviceList.append(dev.addr)
    for (adtype, desc, value) in dev.getScanData():
        print "  %s = %s" % (desc, value)

# deviceIndex = 1
deviceIndex = int(input("Input the device Index:"))

# print deviceIndex
print scanDeviceList[deviceIndex]

p = Peripheral(scanDeviceList[deviceIndex], "random")
pq = MyDelegate(p)
p.setDelegate(pq)

#Get UART Service
UARTService = p.getServiceByUUID(UART_service_uuid)
# Get The UART-Characteristics
UARTC = UARTService.getCharacteristics(UART_rx_char_uuid)[0]
#Get The handle the  UART-Characteristics
hUARTC = UARTC.getHandle()
# Search and get Get The UART-Characteristics "property" (UUID-0x2902 CCC-Client Characteristic Configuration))
#  wich is located in a handle in the range defined by the boundries of the UARTService
for desriptor in p.getDescriptors(
        hUARTC):  # The handle range should be read from the services
    if (desriptor.uuid == 0x2902
        ):  #      but is not done due to a Bluez/BluePy bug :(
示例#7
0
                   help="Human readable output",
                   action="store_true")
group.add_argument("-J", "--JSON", help="JSON output", action="store_true")

parser.add_argument("-v",
                    "--verbose",
                    help="debug output",
                    action="store_true")

args = parser.parse_args()

timeNow = (datetime.now()).strftime("%x %X")

# Connect to thornwave. Try twice, then fail
try:
    p = Peripheral(args.BLEaddress, addrType="random")

except BTLEException as ex:
    if args.verbose:
        print("Read failed. ", ex)
    time.sleep(10)
    try:
        p = Peripheral(args.BLEaddress, addrType="random")
    except:
        if args.verbose:
            print("Read failed. ", ex)
        exit

else:
    result = p.readCharacteristic(0x15)
    if args.verbose:
示例#8
0
 def connect(self, addr, addrType=bluepy.btle.ADDR_TYPE_RANDOM):
     self.disconnect()
     self.peripheral = Peripheral(addr, addrType)
示例#9
0
            'serv': '1810'
        },
        'glucose': {
            'char': '2A18',
            'serv': '1808'
        }
    }

    mapping_name = {
        'nonin3230': 'oximiter',
        'blesmart': 'bloodpressure',
        'mi band 2': 'heart_rate'
    }

    while True:
        devices = scanner.scan(5.0)
        if s.knowdevice:
            connector = Peripheral(s.UUID, "public")
            _type = mapping_name[s.name]
            value = BLEParser(
                connector,
                _type=_type,
                servUUID=mapping_value[_type]['serv'],
                charactUUID=mapping_value[_type]['char']).notify()
            requests.post('http://localhost:5000/devices/scan',
                          data=json.dumps(value),
                          headers=headers)
            connector.disconnect()
except Exception as e:
    print(str(e))
示例#10
0
    def on_command(self, topic, value):
        from bluepy import btle
        from bluepy.btle import Peripheral

        _, _, device_name, _ = topic.split("/")

        bot = self.devices[device_name]

        value = value.decode("utf-8")

        # It needs to be on separate if because first if can change method

        _LOGGER.debug(
            "Setting %s on %s device '%s' (%s)",
            value,
            repr(self),
            device_name,
            bot["mac"],
        )
        try:
            bot["bot"] = Peripheral(bot["mac"], "random")
            hand_service = bot["bot"].getServiceByUUID(
                "cba20d00-224d-11e6-9fb8-0002a5d5c51b"
            )
            hand = hand_service.getCharacteristics(
                "cba20002-224d-11e6-9fb8-0002a5d5c51b"
            )[0]
            if bot["pw"]:
                cmd = b'\x57\x11' + bot["pw"]
            else:
                cmd = b'\x57\x01'
            if value == STATE_ON:
                cmd += b'\x01'
                hand.write(cmd)
            elif value == STATE_OFF:
                cmd += b'\x02'
                hand.write(cmd)
            elif value == "PRESS":
                hand.write(cmd)
            bot["bot"].disconnect()
        except btle.BTLEException as e:
            logger.log_exception(
                _LOGGER,
                "Error setting %s on %s device '%s' (%s): %s",
                value,
                repr(self),
                device_name,
                bot["mac"],
                type(e).__name__,
            )
            return []

        try:
            return self.update_device_state(device_name, value)
        except btle.BTLEException as e:
            logger.log_exception(
                _LOGGER,
                "Error during update of %s device '%s' (%s): %s",
                repr(self),
                device_name,
                bot["mac"],
                type(e).__name__,
                suppress=True,
            )
            return []
示例#11
0
import binascii
from bluepy.btle import UUID, Peripheral

temp_uuid = UUID(0x12345678)

p = Peripheral("51:47:ea:08:a9:b8", "random")

try:
    ch = p.getCharacteristics(uuid=temp_uuid)[0]
    print binascii.b2a_hex(ch.read())
finally:
    p.disconnect()
示例#12
0
from RPLCD import CharLCD
from RPi import GPIO
import binascii
import struct
import time
from bluepy.btle import UUID, Peripheral

GPIO.setwarnings(False)

detection_UUID = UUID(0x180C)
p = Peripheral('f0:24:d3:40:e2:00', 'random')

lcd = CharLCD(numbering_mode=GPIO.BOARD,
              cols=16,
              rows=2,
              pin_rs=37,
              pin_e=35,
              pins_data=[33, 31, 29, 23])

try:
    p.connect('f0:24:d3:40:e2:00', 'random')
    ch = p.getCharacteristic(uuid=detection_UUID)[0]
    if (ch.supportsRead()):
        while 1:
            vesselPresence = binascii.b2a_hex(ch.read())
            vesselPresence = binascii.unhexlify(vesselPresence)
            vesselPresence = struct.unpack('f', vesselPresence)[0]
            display = "Detected: " + str(vesselPresence)
            print(display)
            lcd.write_string(display)
            lcd.cursor_pos = (1, 3)
示例#13
0
OMRON_LATEST_DATA_UUID = UUID('%08X-7700-46F4-AA96-D5E974E32A54' %
                              (0x0C4C0000 + 0x3001))
OMRON_SENSOR_SERVICE_UUID = UUID('%08X-7700-46F4-AA96-D5E974E32A54' %
                                 (0x0C4C0000 + (0xFFF0 & 0x3000)))

parser = argparse.ArgumentParser(description='OMRONの環境センサーからLatestDataを取得します')
parser.add_argument("--addr",
                    required=True,
                    type=str,
                    help='環境センサーのMACアドレスを指定する')

args = parser.parse_args()

# 環境センサーに接続する
ble_peripheral = Peripheral()
print(f"connecting... {args.addr}")
ble_peripheral.connect(addr=args.addr, addrType="random")
print(f"ble_peripheral={ble_peripheral}")

# BLE サービスを取得
service = ble_peripheral.getServiceByUUID(uuidVal=OMRON_SENSOR_SERVICE_UUID)
print(f"service = {service}")

# BLE Characteristicsを取得
ble_char = service.getCharacteristics(forUUID=OMRON_LATEST_DATA_UUID)[0]
print(f"ble_char = {ble_char}")

# LatestDataから測定データの読み出し
raw_data = ble_char.read()
print(f"raw_data = {raw_data}")
    def __init__(self):
        DefaultDelegate.__init__(self)

    def handleNotification(self, cHandle, data):
        print "inside notification"
        print "Handle=", cHandle, "Battery level=", ord(data)


devices = Scanner()  # Scanner Object
temp = devices.scan(10)  # Start Scan

for dev in temp:
    if dev.getScanData(
    )[3][2] == "mr. singh":  # Check for the target BLE device name
        if dev.connectable:
            p = Peripheral(dev.addr, "random")  # Connect to the Device
            p.setDelegate(
                ScanDelegate()
            )  # Create internal Object of scandelegate class to handle the notifications

try:
    ch = p.getServiceByUUID(0x180F).getCharacteristics()[
        0]  # get battery level characteristic for battery Service
    print ch
    if (ch.read()):
        print ord(ch.read())  # Read the characteristic Value
        while True:
            if p.waitForNotifications(1.0):
                # handleNotification() was called
                continue
            print "Waiting..."
示例#15
0
#Enable bluetooth
print "Turning on Bluetooth"
os.system("rfkill unblock bluetooth")
time.sleep(3)

nowSecs = 0
nowKitchenSecs = 0
connectedToKitchen = False

kitchenMAC = "empty"
kitchenMAC = getMAC("KitchenBin")
kitchenPConnected = False

if kitchenMAC != "empty":
    kitchenP = Peripheral(kitchenMAC)
    kitchenP.setDelegate(MyDelegate())
    # Setup to turn notifications on, e.g.
    svc = kitchenP.getServiceByUUID('9a4587b1-4d85-4c75-b88b-faa619295a18')
    ch = svc.getCharacteristics()[0]
    print(ch.valHandle)

    kitchenP.writeCharacteristic(ch.valHandle + 1, "\x01\x00")
    kitchenPConnected = True

    print("connected to KitchenBin and waiting for notifications")

while 1:

    if kitchenPConnected == True:
        if kitchenP.waitForNotifications(1.0):
示例#16
0
def SCD_scan_and_connect( is_first = True ):
    global gTargetDevice
    #
    # scanning for a while
    #
    print ("SCD> BLE device scan %sstarted..." % ('re' if not is_first else ''), flush=True)

    tm = tm_s = time.time()
    while tm_s - tm < RESCAN_PERIOD:
        scanner = Scanner().withDelegate(ScanDelegate())
        devices = scanner.scan(SCAN_TIME)
        print ("\nSCD> BLE device scan completed... [%d] devices are scanned" % gScannedCount, flush=True)
        #
        # check to match BOSCH SCD device identifiers
        #
        for dev in devices:
            matching_count = 0
            for (adtype, desc, value) in dev.getScanData():
                if adtype == 255 and TARGET_MANUFA_UUID in value:
                    matching_count += 1
                    print("SCD> => found target (AD Type=%d) '%s' is '%s'" % (adtype, desc, value), flush=True)            
                if adtype == 9 and TARGET_DEVICE_NAME in value:
                    matching_count += 1
                    print("SCD> => found target (AD Type=%d) '%s' is '%s'" % (adtype, desc, value), flush=True)            
                if matching_count >= 2:
                    print("SCD> => found BOSCH SCD device!")
                    print("SCD> device address [%s], type=[%s], RSSI=[%d]dB" % (dev.addr, dev.addrType, dev.rssi), flush=True)
                    gTargetDevice = dev
                    break
            if gTargetDevice != None:
                break
        #
        # if none found then exiting    
        #
        if gTargetDevice == None:
            tm = time.time()
            print("SCD> no matching device found at [%s]... retry after %d sec..." \
                  % (datetime.datetime.fromtimestamp(tm).strftime('%Y-%m-%d %H:%M:%S'), RESCAN_INTERVAL), flush=True )
            if tm_s - tm >= RESCAN_PERIOD:
                print("SCD> no matching device found... exiting...", flush=True)
                sys.exit(-1)
            time.sleep(RESCAN_INTERVAL)
        else:
            break        
    #
    # connect
    #
    print("SCD> connecting [%s], type=[%s]" % (gTargetDevice.addr, gTargetDevice.addrType), flush=True)
    p = None
    retry = 0
    while p == None:
        try:
            p = Peripheral(gTargetDevice.addr, gTargetDevice.addrType)
        except:
            retry += 1
            print("SCD> => BLE device connection error occured [%d] time(s)... retry after 10 sec..." % retry, flush=True)
            if retry > 30:
                print("SCD> => BLE device connection error occured... exiting...", flush=True)
                sys.exit(-1)
            time.sleep(10)    
    #
    # should increase MTU##
    #           
    p.setMTU(SCD_MAX_MTU)
    #
    return p
示例#17
0
def scan_and_connect( is_first = True ):
    global SCAN_TIME
    global TARGET_MANUFA_UUID
    global TARGET_DEVICE_NAME
    global gTargetDevice
    #
    # scanning for a while
    #
    scanner = Scanner().withDelegate(ScanDelegate())
    if is_first:
        print ("+--- BLE Device scan started..." )
    else:
        print ("+--- BLE Device scan restarted..." )    
    devices = scanner.scan(SCAN_TIME)
    print ("\n+--- BLE Device scan completed... [%d] devices are scanned" % gScannedCount)
    #
    # check to match BOSCH SCD device identifiers
    #
    for dev in devices:
        matching_count = 0
        for (adtype, desc, value) in dev.getScanData():
            if adtype == 255 and TARGET_MANUFA_UUID in value:
                matching_count += 1
                print("\tfound target (AD Type=%d) '%s' is '%s'" % (adtype, desc, value))            
            if adtype == 9 and TARGET_DEVICE_NAME in value:
                matching_count += 1
                print("\tfound target (AD Type=%d) '%s' is '%s'" % (adtype, desc, value))            
            if matching_count >= 2:
                print("+--- Device address [%s], type=[%s], RSSI=[%d]dB" % (dev.addr, dev.addrType, dev.rssi))
                print("\tfound BOSCH SCD device!")
                gTargetDevice = dev
                break
        if gTargetDevice != None:
            break
    #
    # if none found then exiting    
    #
    if gTargetDevice == None:
        print("No matching device found... Exiting...")
        sys.exit(1)
    #
    # connect
    #
    print("+--- Connecting [%s], type=[%s]" % (gTargetDevice.addr, gTargetDevice.addrType))
    p = None
    retry = 0
    while p == None:
        try:
            p = Peripheral(gTargetDevice.addr, gTargetDevice.addrType)
        except:
            print("BLE Device connection error occured... Retry after 3 sec...")
            retry += 1
            if retry > 3:
                print("BLE Device connection error occured... Exiting...")
                sys.exit(-1)
            time.sleep(3)    
    #
    # should increase MTU
    #           
    p.setMTU(SCD_MAX_MTU)
    return p
示例#18
0
    def __get_services_and_chars(self):
        for device in self.__devices_around:
            try:
                if self.__devices_around.get(
                        device) is not None and self.__devices_around[
                            device].get('scanned_device') is not None:
                    log.debug('Connecting to device: %s', device)
                    if self.__devices_around[device].get('peripheral') is None:
                        address_type = self.__devices_around[device][
                            'device_config'].get('addrType', "public")
                        peripheral = Peripheral(
                            self.__devices_around[device]['scanned_device'],
                            address_type)
                        self.__devices_around[device][
                            'peripheral'] = peripheral
                    else:
                        peripheral = self.__devices_around[device][
                            'peripheral']
                    try:
                        log.info(peripheral.getState())
                    except BTLEInternalError:
                        peripheral.connect(
                            self.__devices_around[device]['scanned_device'])
                    try:
                        services = peripheral.getServices()
                    except BTLEDisconnectError:
                        self.__check_and_reconnect(device)
                        services = peripheral.getServices()
                    for service in services:
                        if self.__devices_around[device].get(
                                'services') is None:
                            log.debug(
                                'Building device %s map, it may take a time, please wait...',
                                device)
                            self.__devices_around[device]['services'] = {}
                        service_uuid = str(service.uuid).upper()
                        if self.__devices_around[device]['services'].get(
                                service_uuid) is None:
                            self.__devices_around[device]['services'][
                                service_uuid] = {}

                            try:
                                characteristics = service.getCharacteristics()
                            except BTLEDisconnectError:
                                self.__check_and_reconnect(device)
                                characteristics = service.getCharacteristics()

                            if self.__config.get('buildDevicesMap', False):
                                for characteristic in characteristics:
                                    descriptors = []
                                    self.__check_and_reconnect(device)
                                    try:
                                        descriptors = characteristic.getDescriptors(
                                        )
                                    except BTLEDisconnectError:
                                        self.__check_and_reconnect(device)
                                        descriptors = characteristic.getDescriptors(
                                        )
                                    except BTLEGattError as e:
                                        log.debug(e)
                                    except Exception as e:
                                        log.exception(e)
                                    characteristic_uuid = str(
                                        characteristic.uuid).upper()
                                    if self.__devices_around[device][
                                            'services'][service_uuid].get(
                                                characteristic_uuid) is None:
                                        self.__check_and_reconnect(device)
                                        self.__devices_around[device][
                                            'services'][service_uuid][
                                                characteristic_uuid] = {
                                                    'characteristic':
                                                    characteristic,
                                                    'handle':
                                                    characteristic.handle,
                                                    'descriptors': {}
                                                }
                                    for descriptor in descriptors:
                                        log.debug(descriptor.handle)
                                        log.debug(str(descriptor.uuid))
                                        log.debug(str(descriptor))
                                        self.__devices_around[device][
                                            'services'][service_uuid][
                                                characteristic_uuid][
                                                    'descriptors'][
                                                        descriptor.
                                                        handle] = descriptor
                            else:
                                for characteristic in characteristics:
                                    characteristic_uuid = str(
                                        characteristic.uuid).upper()
                                    self.__devices_around[device]['services'][
                                        service_uuid][characteristic_uuid] = {
                                            'characteristic': characteristic,
                                            'handle': characteristic.handle
                                        }

                    if self.__devices_around[device]['is_new_device']:
                        log.debug('New device %s - processing.', device)
                        self.__devices_around[device]['is_new_device'] = False
                        self.__new_device_processing(device)
                    for interest_char in self.__devices_around[device][
                            'interest_uuid']:
                        characteristics_configs_for_processing_by_methods = {}

                        for configuration_section in self.__devices_around[
                                device]['interest_uuid'][interest_char]:
                            characteristic_uuid_from_config = configuration_section[
                                'section_config'].get("characteristicUUID")
                            if characteristic_uuid_from_config is None:
                                log.error(
                                    'Characteristic not found in config: %s',
                                    pformat(configuration_section))
                                continue
                            method = configuration_section[
                                'section_config'].get('method')
                            if method is None:
                                log.error('Method not found in config: %s',
                                          pformat(configuration_section))
                                continue
                            characteristics_configs_for_processing_by_methods[
                                method.upper()] = {
                                    "method":
                                    method,
                                    "characteristicUUID":
                                    characteristic_uuid_from_config
                                }
                        for method in characteristics_configs_for_processing_by_methods:
                            data = self.__service_processing(
                                device,
                                characteristics_configs_for_processing_by_methods[
                                    method])
                            for section in self.__devices_around[device][
                                    'interest_uuid'][interest_char]:
                                converter = section['converter']
                                converted_data = converter.convert(
                                    section, data)
                                self.statistics[
                                    'MessagesReceived'] = self.statistics[
                                        'MessagesReceived'] + 1
                                log.debug(data)
                                log.debug(converted_data)
                                self.__gateway.send_to_storage(
                                    self.get_name(), converted_data)
                                self.statistics[
                                    'MessagesSent'] = self.statistics[
                                        'MessagesSent'] + 1
            except BTLEDisconnectError:
                log.debug('Connection lost. Device %s', device)
                continue
            except Exception as e:
                log.exception(e)
示例#19
0
                None
            else:
                device_msg[1] = dev.addrType
                device_msg[0] = dev.addr
                print("%s %s %s" % (device_msg[0], value, device_msg[1]))
                break
    return device_msg
  
#scan for your device    
scanner = Scanner().withDelegate(ScanDelegate()) 
devices = scanner.scan(3.0)
remote = blue_scan()

#connect your device
print(remote) 
p = Peripheral(remote[0]) #remote[0]
p.setDelegate(ScanDelegate())

s = p.getServiceByUUID("0000ffe0-0000-1000-8000-00805f9b34fb")
c = s.getCharacteristics()[0]
 

def notification_thread():
    while True:
        if p.waitForNotifications(2.0):
            # handleNotification() was called
            continue
def send_thread():
    while True:
        cmd = input()
        tmp = c.write(bytes(cmd, "utf-8"), True)
示例#20
0
            data[s.name] = value[0] * s.scale
    logging.info('data received:', data)
    return data


def write_point(datum):
    """Writes the point to influx"""
    measurement = {
        "measurement": "weather",
        "tags": {
            "location": LOCATION
        },
        "time": datetime.now().isoformat(),
        "fields": datum
    }
    CHANNEL.basic_publish(exchange='',
                          routing_key='scribe',
                          body=json.dumps(measurement))


if __name__ == "__main__":
    try:
        p = Peripheral(WAVE_ADDRESS)
        write_point(get_data(p))
    except Exception:
        raise RuntimeError("Failed in main loop")
    else:
        print("Wrote data to tsdb")
    finally:
        p.disconnect()
示例#21
0
文件: uarm.py 项目: hrc2da/hiro
    def connect(self):
        """
        This function will open the port immediately. Function will wait for the READY Message for 5 secs.
        | Once received READY message, will finish connection.
        """
        if self.port_name is None and self.ble == False:
            ports = uarm_ports()
            if len(ports) > 0:
                self.port_name = ports[0]
            else:
                raise UArmConnectException(3)
        self.__data_buf = []
        self.__position_queue = LifoQueue()
        self.__menu_button_queue = LifoQueue()
        self.__play_button_queue = LifoQueue()
        self.__send_queue = Queue()
        self.__firmware_version = None
        self.__hardware_version = None
        self.__isReady = False
        self.serial_id = 1
        if self.ble == False:
            self.port = get_port_property(self.port_name)
            self.__receive_thread = threading.Thread(
                target=self.__receive_thread_process)
            self.__send_thread = threading.Thread(
                target=self.__send_thread_process)
            self.__receive_thread.setDaemon(True)
            self.__send_thread.setDaemon(True)

            self.msg_buff = {}
            self.__serial = serial.Serial(baudrate=115200, timeout=0.1)
            try:
                self.__serial.port = self.port.device
                printf("Connecting from port - {0}...".format(
                    self.port.device))
                self.__serial.open()
                self.__init_serial_core()
                self.__connect()
            except serial.SerialException as e:
                raise UArmConnectException(
                    0, "port: {}, Error: {}".format(self.port.device,
                                                    e.strerror))
        else:
            # set up the characteristic to write to the ble module at self.mac_address
            if self.mac_address is None:
                raise (ValueError(
                    "Scanning for peripherals is not yet implemented, please specify a mac address. --Matt."
                ))
            try:
                print("Connecting to BLE")
                self.ble_delegate = ble_delegate = UArmDelegate()
                self.peripheral = peripheral = Peripheral(
                    self.mac_address).withDelegate(ble_delegate)
                tries = 0
                while self.peripheral.getState() != 'conn':
                    self.peripheral.connect()
                    tries += 1
                    if tries > 5:
                        raise (f"Could not connect to {self.mac_address}"
                               )  # and hit an exception below

                self.services = services = list(peripheral.getServices())
                self.ble_channel = services[-1].getCharacteristics(
                )[0]  # hm-10 uses a custom characteristic on the third service to communicate
                # self.connection_state = True # this is a dumb hack, but I'm not sure how to query if connected with bluepy
            except Exception as e:
                raise UArmConnectException(0, str(e))
示例#22
0
    def connect(self, mac):
        from bluepy.btle import Peripheral

        self._peripheral = Peripheral(mac)
示例#23
0
    def __init__(self, address, mambo):
        """
             Initialize with its BLE address - if you don't know the address, call findMambo
             and that will discover it for you.

             :param address: unique address for this mambo
             :param mambo: the Mambo object for this mambo (needed for callbacks for sensors)
             """
        self.address = address
        self.drone_connection = Peripheral()
        self.mambo = mambo

        # the following UUID segments come from the Mambo and from the documenation at
        # http://forum.developer.parrot.com/t/minidrone-characteristics-uuid/4686/3
        # the 3rd and 4th bytes are used to identify the service
        self.service_uuids = {
            'fa00': 'ARCOMMAND_SENDING_SERVICE',
            'fb00': 'ARCOMMAND_RECEIVING_SERVICE',
            'fc00': 'PERFORMANCE_COUNTER_SERVICE',
            'fd21': 'NORMAL_BLE_FTP_SERVICE',
            'fd51': 'UPDATE_BLE_FTP',
            'fe00': 'UPDATE_RFCOMM_SERVICE',
            '1800': 'Device Info',
            '1801': 'unknown',
        }
        # the following characteristic UUID segments come from the documentation at
        # http://forum.developer.parrot.com/t/minidrone-characteristics-uuid/4686/3
        # the 4th bytes are used to identify the characteristic
        # the usage of the channels are also documented here
        # http://forum.developer.parrot.com/t/ble-characteristics-of-minidrones/5912/2
        self.characteristic_send_uuids = {
            '0a': 'SEND_NO_ACK',  # not-ack commandsandsensors (PCMD only)
            '0b': 'SEND_WITH_ACK',  # ack commandsandsensors (all piloting commandsandsensors)
            '0c': 'SEND_HIGH_PRIORITY',  # emergency commandsandsensors
            '1e': 'ACK_COMMAND'  # ack for data sent on 0e
        }

        # counters for each packet (required as part of the packet)
        self.characteristic_send_counter = {
            'SEND_NO_ACK': 0,
            'SEND_WITH_ACK': 0,
            'SEND_HIGH_PRIORITY': 0,
            'ACK_COMMAND': 0,
            'RECEIVE_WITH_ACK': 0
        }

        # the following characteristic UUID segments come from the documentation at
        # http://forum.developer.parrot.com/t/minidrone-characteristics-uuid/4686/3
        # the 4th bytes are used to identify the characteristic
        # the types of commandsandsensors and data coming back are also documented here
        # http://forum.developer.parrot.com/t/ble-characteristics-of-minidrones/5912/2
        self.characteristic_receive_uuids = {
            '0e': 'ACK_DRONE_DATA',  # drone data that needs an ack (needs to be ack on 1e)
            '0f': 'NO_ACK_DRONE_DATA',  # data from drone (including battery and others), no ack
            '1b': 'ACK_COMMAND_SENT',  # ack 0b channel, SEND_WITH_ACK
            '1c': 'ACK_HIGH_PRIORITY',  # ack 0c channel, SEND_HIGH_PRIORITY
        }

        # these are the FTP incoming and outcoming channels
        # the handling characteristic seems to be the one to send commandsandsensors to (per the SDK)
        # information gained from reading ARUTILS_BLEFtp.m in the SDK
        self.characteristic_ftp_uuids = {
            '22': 'NORMAL_FTP_TRANSFERRING',
            '23': 'NORMAL_FTP_GETTING',
            '24': 'NORMAL_FTP_HANDLING',
            '52': 'UPDATE_FTP_TRANSFERRING',
            '53': 'UPDATE_FTP_GETTING',
            '54': 'UPDATE_FTP_HANDLING',
        }

        # FTP commandsandsensors (obtained via ARUTILS_BLEFtp.m in the SDK)
        self.ftp_commands = {
            "list": "LIS",
            "get": "GET"
        }

        # need to save for communication (but they are initialized in connect)
        self.services = None
        self.send_characteristics = dict()
        self.receive_characteristics = dict()
        self.handshake_characteristics = dict()
        self.ftp_characteristics = dict()

        self.data_types = {
            'ACK': 1,
            'DATA_NO_ACK': 2,
            'LOW_LATENCY_DATA': 3,
            'DATA_WITH_ACK': 4
        }

        # store whether a command was acked
        self.command_received = {
            'SEND_WITH_ACK': False,
            'SEND_HIGH_PRIORITY': False,
            'ACK_COMMAND': False
        }

        # instead of parsing the XML file every time, cache the results
        self.command_tuple_cache = dict()
        self.sensor_tuple_cache = dict()

        # maximum number of times to try a packet before assuming it failed
        self.max_packet_retries = 3
    else:
        suppString = str(i[1])
    if len(str(i[0])) == 1:
        suppString = '0' + str(i[0]) + suppString
    else:
        suppString = str(i[0]) + suppString
    ble_data.append(str.encode(suppString))
    # if int(i[1]/1000) == 0:
    #     ble_data.append(str.encode(str(i[0])+'0'+str(i[1])))
    # elif len(str(i[0])) == 1:
    #     ble_data.append(str.encode('0'+str(i[0])+'0'+str(i[1])))
    # else:
    #     ble_data.append(str.encode(str(i[0])+str(i[1])))
print(ble_data)
input()
p = Peripheral(addr, 'public')
s = p.getServiceByUUID("20ff121c-94e1-11e9-bc42-526af7764f64")
print("conectado")
carachteristics = s.getCharacteristics()[0]
for j in ble_data:
    carac = int(carachteristics.read())
    print(carac)
    # p.waitForNotifications()
    while carac != 33:
        if carac == 32:
            break
        pass
    carachteristics.write(j)
    print(j)
p.disconnect()
    def read(self):
        return self.dataChar.read()

    def readSetting(self):
        return self.confChar.read()

    def disconnect(self):
        self.periph.disconnect()


sensorTagMACaddress = "BC:6A:29:AC:48:40"

#Accelerometer sensor ble info of cc2540
accSvcUUID = 0xAA10  # accelerometor service uuid
accDataUUID = 0xAA11  # accelerometor data uuid
accConfUUID = 0xAA12  # accelerometer configuration uuid

# connect sensorTag
p = Peripheral(sensorTagMACaddress)
# instantiation of accelerometer object
accel = sensorBase(p, accSvcUUID, accConfUUID, accDataUUID)
# enable acceleromter
accel.enable()
# wait until sensor is ready
time.sleep(2.0)
# read data
rawData = struct.unpack('bbb', accel.read())
print(rawData)
#disconnect
accel.disconnect()
示例#26
0
class CharDelegate(DefaultDelegate):
    def __init__(self):
        DefaultDelegate.__init__(self)

    def handleNotification(self, cHandle, data):
        [lux] = struct.unpack('<f', data)
        print("Value: " + str(lux) + " lux")


YOUR_ADDRESS = "c0:98:e5:49:00:00"  # Replace address with your device address
YOUR_SERVICE_UUID = "de97aeee-0e7e-4720-8038-4dc47aa9562f"
YOUR_CHAR_UUID = "de97aeef-0e7e-4720-8038-4dc47aa9562f"

try:
    buckler = Peripheral(YOUR_ADDRESS)
    buckler.setDelegate(CharDelegate())

    print("connected")

    sv = buckler.getServiceByUUID(YOUR_SERVICE_UUID)

    # Enable notifications:
    ch = sv.getCharacteristics(YOUR_CHAR_UUID)[0]
    buckler.writeCharacteristic(ch.valHandle + 1, b"\x01\x00")

    while True:
        if buckler.waitForNotifications(2.0):
            print("Got notification")
finally:
    buckler.disconnect()
示例#27
0
            print "Discovered device", dev.addr
        elif isNewData:
            print "Received new data from", dev.addr


scanner = Scanner().withDelegate(ScanDelegate())
devices = scanner.scan(0.1)

macAddress = "4b:4e:4f:00:00:01"

for dev in devices:
    print "Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi)
    for (adtype, desc, value) in dev.getScanData():
        print "  %s = %s" % (desc, value)

periph = Peripheral(macAddress)
services = periph.getServices()
for service in services:
    print "Service UUID : %s" % (service.uuid.getCommonName())
    characteristics = service.getCharacteristics()
    for char in characteristics:
        print "UUID : %s, property : %s" % (char.uuid.getCommonName(),
                                            char.propertiesToString())
        if (char.uuid.getCommonName() == "626f6972-6564-656c-616c-636f6f6c0100"
            ):
            knocks = struct.unpack("<b", char.read())[0]
            print knocks
periph.disconnect()

url = "http://192.168.0.10/plugins/knocklet/core/api/knocklet.api.php"
headers = {'content-type': 'application/json'}
示例#28
0
    print(msg)


scanner = Scanner()
devices = scanner.scan(10.0)
txUUID = "6e400002-b5a3-f393-e0a9-e50e24dcca9e"

msg = "21420894"

for dev in devices:
    for (adtype, desc, value) in dev.getScanData():
        if ("Complete" in desc):
            print "  %s = %s" % (desc, value)
            if ("Adafruit" in value):
                print "Found bluefruit. Creating Peripheral for " + dev.addr
                p = Peripheral(
                    dev.addr, "random"
                )  # BluePy default is "public" so we have to set it to random or it won't connect
                tx = p.getCharacteristics(uuid=txUUID)[0]
                try:
                    tx.write(binascii.unhexlify(msg), True)
                except BTLEException:
                    print BTLEException.message
                except BaseException:
                    print "BaseException caught in Thread"
                    print BaseException.message
                except Exception:
                    print "Caught unknown exception"
                    print Exception.message
                p.disconnect()
示例#29
0
char_light_uuid = UUID("1305b3ca-096e-4366-9f68-1ae8df01f27b")
char_temp_uuid = UUID("1305b3ca-096e-4366-9f68-1ae8df01f279")
char_humid_uuid = UUID("1305b3ca-096e-4366-9f68-1ae8df01f27a")
char_pressure_uuid = UUID("1305b3ca-096e-4366-9f68-1ae8df01f27c")
char_co2_uuid = UUID("bec2f36b-e4c4-455d-90a4-25b0e8c255b5")
char_voc_uuid = UUID("1305b3ca-096e-4366-9f68-1ae8df01f27d")

deviceFrequency = 30

#takes input of device adress and if no adress present then logs error
if len(sys.argv) != 2:
    print("Fatal, must pass device address:", sys.argv[0], "<device address="
          ">")
    quit()

p = Peripheral(sys.argv[1])
print("Connected")

#for service in p.getServices():
#    print(service.uuid)

ButtonService = p.getServiceByUUID(service_uuid)
print("Got service")
try:
    ch_light = ButtonService.getCharacteristics(char_light_uuid)[0]
    ch_temp = ButtonService.getCharacteristics(char_temp_uuid)[0]
    ch_humid = ButtonService.getCharacteristics(char_humid_uuid)[0]
    ch_pressure = ButtonService.getCharacteristics(char_pressure_uuid)[0]
    ch_voc = ButtonService.getCharacteristics(char_voc_uuid)[0]
    ch_co2 = ButtonService.getCharacteristics(char_co2_uuid)[0]
示例#30
0
 def connect(self):
     self._p = Peripheral(deviceAddr=self._mac, iface=self._iface)
     self._p.setDelegate(self)