示例#1
0
    def _tryQueryMbService(self, uuid):
        conn = GATTRequester(uuid, False, self.devName)
        try:
            conn.connect(False, "random")
            max_time = time.time() + 5
            while not conn.is_connected():
                if time.time() > max_time:
                    return False
                time.sleep(0.5)

            DEV_NAME_SERVICE_UUID = "00002a00-0000-1000-8000-00805f9b34fb"  # 2A00, device name
            try:
                value = "".join(conn.read_by_uuid(DEV_NAME_SERVICE_UUID))
            except RuntimeError as err:
                msg = err.message.lower()
                if "no attribute found":
                    return False
                else:
                    raise
            value = value.lower()
            return ("mibp" in value or "mib-push" in value)
        finally:
            if conn.is_connected():
                conn.disconnect()
                while conn.is_connected():
                    time.sleep(0.5)
示例#2
0
class Driver(object):
    handle = 0x16
    commands = {
        'press' : '\x57\x01\x00',
        'on'    : '\x57\x01\x01',
        'off'   : '\x57\x01\x02',
    }

    def __init__(self, device, bt_interface=None, timeout_secs=None):
        self.device = device
        self.bt_interface = bt_interface
        self.timeout_secs = timeout_secs if timeout_secs else 5
        self.req = None


    def connect(self):
        if self.bt_interface:
            self.req = GATTRequester(self.device, False, self.bt_interface)
        else:
            self.req = GATTRequester(self.device, False)

        self.req.connect(True, 'random')
        connect_start_time = time.time()
        while not self.req.is_connected():
            if time.time() - connect_start_time >= self.timeout_secs:
                raise RuntimeError('Connection to {} timed out after {} seconds'
                                   .format(self.device, self.timeout_secs))

    def run_command(self, command):
        return self.req.write_by_handle(self.handle, self.commands[command])
示例#3
0
文件: ble_comm.py 项目: EyeoT/PC_BLE
class IoTDevice(object):
    """
    IoTDevice represents a single EyeoT IoT (Arduino 101) BLE device, initialized by one of several authorized MAC
    addresses.

    Input: MAC address of the EyeoT device to control

    Output: Initialized EyeoT device containing the proper MAC address, service UUID, tx_command and rx_response
    characteristic UUIDs, tx_handle, and GATTRequester
    """
    def __init__(self, address):
        self.address = address
        self.service_uuid = arduino.service_uuid
        self.tx_command = arduino.tx_command
        self.rx_response = arduino.rx_response
        self.tx_handle = arduino.tx_handle
        self.rx_handle = arduino
        self.req = GATTRequester(address,
                                 False)  # initialize req but don't connect
        self.response = ble_consts.not_ready

    def connect(self):
        print("Connecting...\n")
        self.req.connect(True)
        print("Connection Successful! \n")

    def send_command(self, command):
        self.req.write_by_handle(arduino.tx_handle, command)
        print("Sent '{0}' command\n".format(ble_consts.commands[command]))

    def receive_response(self):
        self.response = int(
            self.req.read_by_handle(arduino.rx_handle)[0].encode('hex')) / 100
        print("Response '{0}' received!\n".format(
            ble_consts.responses[self.response]))
示例#4
0
 def __init__(self, address):
     self._requester = GATTRequester(address, False)
     self.led = Led(self)
     self.speaker = Speaker(self)
     self.microphone = Microphone(self)
     self.state = None
     self.name = None
     self.setup_datetime = None
示例#5
0
 def _connect(self):
     self.req = GATTRequester(self.device, False)
     self.req.connect(True, 'random')
     connect_start_time = time.time()
     while not self.req.is_connected():
         if time.time() - connect_start_time >= self.timeout_secs:
             raise RuntimeError('Connection to {} timed out after {} seconds'
                                .format(self.device, self.timeout_secs))
示例#6
0
 def on_notification(self, handle, data):
     GATTRequester.on_notification(self, handle, data)
     if handle == 0x36:
         # print(type(data))
         # print(len(data))
         h1, h2, b3, humidity, temp = unpack("<HHBBH", data)
         temp = temp / 100
         print(f"{temp}*C and {humidity}% ({h1}, {h2}, {b3})")
示例#7
0
文件: toio.py 项目: ki4070ma/toio-py
 def __init__(self, addr):
     self.req = ""
     if not addr:
         return
     self.req = GATTRequester(addr, False)
     print("Connecting...: {}".format(addr))
     self.req.connect(wait=True, channel_type="random")
     print("Connected: {}".format(addr))
示例#8
0
 def __init__(self, addr):
     self.req = ""
     if not addr:
         return
     self.req = GATTRequester(addr, False)
     print("Connecting...: {}".format(addr))
     self.req.connect(True, 'random')
     print("Connected: {}".format(addr))
示例#9
0
 def __init__(self, event, *args):
     """
     Constructor - Sets up the GATTRequester
     """
     self.event = event
     self.notifications = []
     self.indications = []
     GATTRequester.__init__(self, *args)
示例#10
0
 def _connect(self, addr):
     self._log.info("BLE %s connecting ..." % addr)
     self.requester = GATTRequester(addr, False)
     self.requester.connect(True)
     chars = self.requester.discover_characteristics()
     self.characteristic = {}
     for char in chars:
         self.characteristic[char['uuid']] = char['value_handle']
     self._log.info("BLE %s connected OK" % self._addr)
示例#11
0
文件: ble_comm.py 项目: EyeoT/PC_BLE
 def __init__(self, address):
     self.address = address
     self.service_uuid = arduino.service_uuid
     self.tx_command = arduino.tx_command
     self.rx_response = arduino.rx_response
     self.tx_handle = arduino.tx_handle
     self.rx_handle = arduino
     self.req = GATTRequester(address,
                              False)  # initialize req but don't connect
     self.response = ble_consts.not_ready
示例#12
0
文件: Blimp.py 项目: younghj/flot
    def __init__(self, mac="C4:C3:00:01:07:3F"):
        # Check for empty arg and correct MAC address format
        # Default MAC address is given otherwise
        if not re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", mac.lower()):
            print("Using default MAC: C4:C3:00:01:07:3F")
            self.mac = "C4:C3:00:01:07:3F"
        else:
            self.mac = mac

        self.service = DiscoveryService()
        self.devices = self.service.discover(2)
        self.requester = GATTRequester(self.mac, False)
示例#13
0
class Reader(object):
    def __init__(self, address):
        self.requester = GATTRequester(address, False)
        self.connect()
        self.request_data()

    def connect(self):
        print("Connecting...", end=' ')
        sys.stdout.flush()

        self.requester.connect(True)
        print("OK!")

    def request_data(self):
        #for each in self.requester.discover_characteristics():
        #    print(each)
        #    print(self.requester.read_by_handle(each['handle']))
        path = "../server/info_pipe"
        if os.path.exists(path):
            os.unlink(path)
            #os.remove(path)
            print("Removed old pipe")

        print("Begin reading data: ")
        while (True):
            data = self.requester.read_by_uuid(
                #"0x2902")
                "0000aaaa-0000-1000-8000-00805f9b34fb")
            #"0000181c-0000-1000-8000-00805f9b34fbC")
            #"00002a00-0000-1000-8000-00805f9b34fb")
            #print(data)
            data = [ord(datum) for datum in data[0]]
            try:
                os.mkfifo(path)
            except:
                #print("pipe already exists")
                pass
            fifo = open(path, 'w')

            #copy & add randomness to data to show how aggregation
            data1 = ",".join(
                [str(random.uniform(i - 1.5, i + 1.5)) for i in data[:]])
            data2 = ",".join(
                [str(random.uniform(i - 1.5, i + 1.5)) for i in data[:]])
            data3 = ",".join(
                [str(random.uniform(i - 1.5, i + 1.5)) for i in data[:]])
            print(str(data1))
            fifo.write(data1 + "\n" + data2 + "\n" + data3)
            fifo.close()
        '''
示例#14
0
    def connect(self, device, bt_interface=None, timeout_secs=None):
        self.bt_interface = bt_interface
        self.timeout_secs = timeout_secs if timeout_secs else 5
        self.req = None
        self.device = device
        if self.bt_interface:
            self.req = GATTRequester(self.device, False, self.bt_interface)
        else:
            self.req = GATTRequester(self.device, False)

        self.req.connect(True, 'random')
        connect_start_time = time.time()
        while not self.req.is_connected():
            if time.time() - connect_start_time >= self.timeout_secs:
                raise RuntimeError('Connection to {} timed out after {} seconds'
                                   .format(self.device, self.timeout_secs))
示例#15
0
class Reader(object):
    def __init__(self, address):
        self.requester = GATTRequester(address, False)
        self.connect()
        self.request_data()

    def connect(self):
        print("Connecting...", end=" ")
        sys.stdout.flush()

        self.requester.connect(True)
        print("OK!")

    def request_data(self):
        data = self.requester.read_by_uuid("00002a00-0000-1000-8000-00805f9b34fb")[0]
        print("Device name: " + data.decode("utf-8"))
示例#16
0
class Reader(object):
    def __init__(self, address):
        self.requester = GATTRequester(address, False)
        self.connect()
        self.request_data()

    def connect(self):
        print("Connecting...", end=' ')
        sys.stdout.flush()

        self.requester.connect(True)
        print("OK!")

    def request_data(self):
        data = self.requester.read_by_uuid(
                "00002a00-0000-1000-8000-00805f9b34fb")[0]
        print("Device name: " + data.decode("utf-8"))
示例#17
0
class Cloudpets(object):
    def __init__(self, address):
        self._requester = GATTRequester(address, False)
        self.led = Led(self)
        self.speaker = Speaker(self)
        self.microphone = Microphone(self)
        self.state = None
        self.name = None
        self.setup_datetime = None

    def connect(self):
        self._requester.connect(True)
        self._retrieve_config()

    def disconnect(self):
        self._requester.disconnect()

    def _read_value(self, handle):
        return self._requester.read_by_handle(handle)

    def _send_command(self, handle, cmd):
        self._requester.write_by_handle(handle, str(bytearray(cmd)))

    def _retrieve_config(self):
        response = self._read_value(HANDLES['config'])[0]
        self.name = MODELS[int(response[:2])]
        self.setup_datetime = datetime.strptime(response[2:], "%m_%d_%H_%M_%S")
示例#18
0
文件: toio.py 项目: ki4070ma/toio-py
class Toio(object):
    HANDLER = {'motor': "TBU"}
    DIRECTION = {'fwd': 1, 'bck': 2}
    MOTOR = {'1st': 1, '2nd': 2}
    SPEED_MAX = 100

    def __init__(self, addr):
        self.req = ""
        if not addr:
            return
        self.req = GATTRequester(addr, False)
        print("Connecting...: {}".format(addr))
        self.req.connect(wait=True, channel_type="random")
        print("Connected: {}".format(addr))

    def request_data(self, uuid):
        return self.req.read_by_uuid(uuid)[0]

    def write_data(self, handler, data):
        self.req.write_by_handle(handler, data)

    def disconnect(self):
        self.req.disconnect()

    def is_connected(self):
        if not self.req:
            return False
        return self.req.is_connected()

    def _move(self, motor_1st_dir, motor_1st_speed, motor_2nd_dir, motor_2nd_speed, duration_sec):
        self.write_data(self.HANDLER['motor'], str(
            bytearray([2, self.MOTOR['1st'], motor_1st_dir, motor_1st_speed, self.MOTOR['2nd'], motor_2nd_dir, motor_2nd_speed, int(duration_sec * 100)])))
        import time
        time.sleep(duration_sec)

    def straight(self):
        self._move(self.DIRECTION['fwd'], self.SPEED_MAX, self.DIRECTION['fwd'], self.SPEED_MAX, 1)

    def turn_left(self):
        self._move(self.DIRECTION['fwd'], self.SPEED_MAX / 2, self.DIRECTION['fwd'], self.SPEED_MAX, 1)

    def turn_right(self):
        self._move(self.DIRECTION['fwd'], self.SPEED_MAX, self.DIRECTION['fwd'], self.SPEED_MAX / 2, 1)

    def back(self):
        self._move(self.DIRECTION['bck'], self.SPEED_MAX, self.DIRECTION['bck'], self.SPEED_MAX, 1)

    def spin_turn_180(self):
        self._move(self.DIRECTION['bck'], self.SPEED_MAX, self.DIRECTION['fwd'], self.SPEED_MAX, 0.5)

    def spin_turn_360(self):
        self._move(self.DIRECTION['bck'], self.SPEED_MAX, self.DIRECTION['fwd'], self.SPEED_MAX, 1)
示例#19
0
class Reader(object):
    def __init__(self, address):
        self.requester = GATTRequester(address, False)
        self.connect()
        self.request_data()

    def connect(self):
        print("Connecting...")
        sys.stdout.flush()

        self.requester.connect(True)
        print("OK!")

    def request_data(self):
        data = self.requester.read_by_uuid(
            "0003cdd0-0000-1000-8000-00805f9b0131")[0]
        try:
            print("Device name: " + data.decode("utf-8"))
        except AttributeError:
            print("Device name: " + data)
示例#20
0
def connect(device: str, bt_interface: str, timeout: float):
    if bt_interface:
        req = GATTRequester(device, False, bt_interface)
    else:
        req = GATTRequester(device, False)

    req.connect(False, 'random')
    connect_start_time = time.time()

    while not req.is_connected():
        if time.time() - connect_start_time >= timeout:
            raise ConnectionError(
                'Connection to {} timed out after {} seconds'.format(
                    device, timeout))
        time.sleep(0.1)

    yield req

    if req.is_connected():
        req.disconnect()
def get_serial(bluetooth_address_s):
    global serial_map
    if bluetooth_address_s in serial_map:
        return serial_map[bluetooth_address_s]
    macaddress = ':'.join([bluetooth_address_s[i: i+2] for i in range(0, len(bluetooth_address_s), 2)])
    requester = GATTRequester(macaddress, False)
    try:
        requester.connect(True, channel_type="random")
        data = requester.read_by_uuid("00002a25-0000-1000-8000-00805f9b34fb")
        serial = data[0]
        serial_map[bluetooth_address_s] = serial
        requester.disconnect()
        return serial
    except:
        import traceback
        traceback.print_exc()
        return None
示例#22
0
class BluezBleInterface(BleInterface):
    def __init__(self, *args, **kwargs):
        super(BluezBleInterface, self).__init__(*args, **kwargs)
        self._addr = kwargs.get('addr')
        self._log.info("Started interface {0}.".format(self))

    def __del__(self):
        self._disconnect()

    def _connect(self, addr):
        self._log.info("BLE %s connecting ..." % addr)
        self.requester = GATTRequester(addr, False)
        self.requester.connect(True)
        chars = self.requester.discover_characteristics()
        self.characteristic = {}
        for char in chars:
            self.characteristic[char['uuid']] = char['value_handle']
        self._log.info("BLE %s connected OK" % self._addr)

    def _disconnect(self):
        self.requester.disconnect()

    def _read_uuid(self, reg, type='float'):
        value = self.requester.read_by_uuid(reg)[0]
        if type == 'float':
            return struct.unpack('H', value)[0] * 1.0
        elif type == 'string':
            try:
                value = value.decode("utf-8")
            except AttributeError:
                pass
            return value
        else:
            return value

    def _write_uuid(self, reg, value, type='float'):
        if type == 'string':
            value = struct.pack('B', value)
        self.requester.write_by_handle(self.characteristic[reg], value)
示例#23
0
def server(addr, port, ble=False):
    global running
    print(f'Creating {"BLE" if ble else "BL"} connection')
    if not ble:
        sock = Socket(RFCOMM)
        sock.connect((addr, port))
    else:
        sock = GATTRequester(addr)
    while running:
        lock.acquire()
        data = b''.join((key_to_order(order, speed) for order in orders))
        data += b''.join((key_to_stop_order(order) for order in stop_orders))
        stop_orders.clear()
        lock.release()
        if not ble:
            sock.send(data)
        else:
            for b in data:
                sock.write_by_handle(port, bytes([b]))
        sleep(.02)
    sock.close()
示例#24
0
class Reader():
    def __init__(self, address):
        self.requester = GATTRequester(address, False)
        self.connect()
        self.request_data()
        self.turn()

    def connect(self):
        print("Connecting...", end=' ')
        sys.stdout.flush()

        self.requester.connect(True)
        print("OK!")

    def request_data(self):
        data = self.requester.read_by_handle(0x03)
        print("Device name: " + str(data))

        candle = self.requester.read_by_handle(0x23)
        print("Candle: " + str(candle))

    def turn(self):
        self.requester.write_by_handle(0x0016, str(bytearray([0, 0, 0, 0])))
示例#25
0
 def __init__(self, address):
     self.requester = GATTRequester(address, False)
     self.connect()
     self.request_data()
示例#26
0
 def __init__(self, *args):
     GATTRequester.__init__(self, *args)
示例#27
0
文件: Blimp.py 项目: younghj/flot
class Blimp:

    def __init__(self, mac="C4:C3:00:01:07:3F"):
        # Check for empty arg and correct MAC address format
        # Default MAC address is given otherwise
        if not re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", mac.lower()):
            print("Using default MAC: C4:C3:00:01:07:3F")
            self.mac = "C4:C3:00:01:07:3F"
        else:
            self.mac = mac

        self.service = DiscoveryService()
        self.devices = self.service.discover(2)
        self.requester = GATTRequester(self.mac, False)

    def find_blimp(self, blimp_name):
        self.devices = self.service.discover(2)
        for address, name in self.devices:
            if name == blimp_name:
                self.mac = address
                print(blimp_name + " found with MAC Address " + address)
                break

    def connect(self):
        try:
            self.requester.connect(True)
        except:
            print("Failed to connect; Make sure target is turned on and correct MAC address is provided")

    def disconnect(self):
        try:
            self.requester.disconnect(True)
        except:
            print("Failed to disconnect; try again")

    def is_connected(self):
        return self.requester.is_connected()

    # Enter value between -32767 to 32767
    # Negative value commands backward thrust, and vice versa with positive value, for left propeller
    def left(self, value):

        if self.is_connected():
            if -32768 < value < 32768:
                if value < 0:
                    command = '{:04x}'.format(-1*int(value))
                else:
                    command = '{:04x}'.format(65535 - int(value))

                self.requester.write_by_handle(34, command.decode('hex'))
            else:
                print("Command value is must be integer between -32767 & 32767")
        else:
            print("First connect to target before commanding thrust")

    # Enter value between -32767 to 32767
    # Negative value commands backward thrust, and vice versa with positive value, for right propeller
    def right(self, value):
        
        if self.is_connected():
            if -32768 < value < 32768:
                if value < 0:
                    command = '{:04x}'.format(-1*int(value))
                else:
                    command = '{:04x}'.format(65535 - int(value))

                self.requester.write_by_handle(36, command.decode('hex'))
            else:
                print("Command value is must be integer between -32767 & 32767")
        else:
            print("First connect to target before commanding thrust")

    # Enter value between -32767 to 32767
    # Negative value commands backward thrust, and vice versa with positive value, for down propeller
    def down(self, value):

        if self.is_connected():
            if -32768 < value < 32768:
                if value < 0:
                    command = '{:04x}'.format(-1*int(value))
                else:
                    command = '{:04x}'.format(65535 - int(value))

                self.requester.write_by_handle(38, command.decode('hex'))
            else:
                print("Command value is must be integer between -32767 & 32767")
        else:
            print("First connect to target before commanding thrust")

    # Function to stop all actuators
    def stop(self):
        if self.is_connected():
                command = '{:04x}'.format(65535)
                self.requester.write_by_handle(34, command.decode('hex'))
                self.requester.write_by_handle(36, command.decode('hex'))
                self.requester.write_by_handle(38, command.decode('hex'))
        else:
            print("Command failed; not connected to target")
示例#28
0
 def __init__(self, address):
     self.requester = GATTRequester(address, False)
     self.connect()
     self.request_data()
示例#29
0
    def __init__(self, address):
        self.requester = GATTRequester(address, False)
        self.connect()
	t = threading.Thread(name=address,target=self.periodical_request)
        t.daemon = True
        t.start()
示例#30
0
#    SM,2,0000
#    @TMR2
#    $VAR1=@,2
#    SHW,0072,$VAR1
#    SM,2,0010
#
# The characteristic handle (72 in the example above) must match the handle created for the service.
#

import time
from bluetooth.ble import GATTRequester

#
# the MAC address of the BLE device.  Replace 'D8:80:39:FC:7B:F5' with the address of your device.
#
grq = GATTRequester('D8:80:39:FC:7B:F5', False)

grq.connect()
print("Waiting to connect...")
while not grq.is_connected():
    time.sleep(1)
print("Connected.")

characteristics = grq.discover_characteristics()

#
# the UUID of the service on the BLE device.
#
sample_uuid = '59c889e0-5364-11e7-b114-b2f933d5fe66'

# find the handle for the characteristic.
示例#31
0
class Reader(object):
    def __init__(self, address):
        self.requester = GATTRequester(address, False)
        self.connect()
	t = threading.Thread(name=address,target=self.periodical_request)
        t.daemon = True
        t.start()

    def connect(self):
        self.requester.connect(True,"random","medium",0,32)
        print ("Connected")

    def request_uuid(self):
        self.uuid = self.requester.read_by_uuid("D6F8BDCC-3885-11E6-AC61-9E71128CAE77")[0]
        print("uuid read:", self.uuid)
        if len(self.uuid) < 37:
            self.uuid = self.uuid + self.requester.read_by_uuid("D6F8BDCC-3885-11E6-AC61-9E71128CAE77")[0]
        print("complete uuid:", self.uuid[0:35])   

    def periodical_request(self):
        tracked_devices.append(threading.current_thread().getName())
        try:
            self.request_uuid()
        except RuntimeError:
            tracked_devices.remove(threading.current_thread().getName())
            return
        count = 0
        while True:
            self.request_data()
            count = count + 1
            print("Count:",count)
            time.sleep(1)
    


    def request_data(self):
        if not self.requester.is_connected():
            print("Reconnecting")
            self.requester.disconnect()
            try:
                self.requester.connect(True,"random","medium",0,32)
            except RuntimeError:
                # End the thread bc cannot reconnect
                if threading.current_thread().getName() in tracked_devices:
                    # should be in the tracked devices list
                    # remove when thread is going to end
                    tracked_devices.remove(threading.current_thread().getName())
                else :
                    print("Error: thread should be tracked")
                print("Encountered error when reconnecting. Now exit thread.")
                sys.exit()
            print("Reconnected")
        try:
            start_time = current_milli_time()
            data = self.requester.read_by_uuid(
                "16864516-21E0-11E6-B67B-9E71128CAE77")[0]
        except RuntimeError as e:
            print("RuntimeError", e)
            self.requester.disconnect()
            return
        try:
            d = decode_string_to_double(data)
            print ("Device name:",self.uuid,"Device motion:", d) 
            if socket_open:
                socket_connect.sendMotionAndUUID(d,self.uuid)
            motion_manager.process_data(self.uuid[0:35], self.uuid[36],d)
        except AttributeError:
            print ("Device name: " + data)
示例#32
0
 def __init__(self, notif_event, *args):
     GATTRequester.__init__(self, *args)
     self.hevent = notif_event
     self.data = []
     self.logger = logging.getLogger("main.parrot_ble.CustomRequester")