Example #1
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])
Example #2
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)
Example #3
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")
Example #4
0
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]))
Example #5
0
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)
Example #6
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()
        '''
Example #7
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"))
Example #8
0
class Reader:
    def __init__(self, address):
        self.requester1 = GATTRequester("40:06:A0:97:74:A9", False)
        self.requester2 = GATTRequester("40:06:A0:94:FE:F7", False)

        self.connect()
        self.send_data()
        #self.request_data()

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

        self.requester1.connect(True)
        self.requester2.connect(True)

        print("OK.")

    def request_data(self):
        data1 = self.requester1.read_by_uuid(
            "00001800-0000-1000-8000-00805f9b34fb")[0]
        data2 = self.requester2.read_by_uuid(
            "00001800-0000-1000-8000-00805f9b34fb")[0]

        try:
            print("Device name:", data1.decode("utf-8"))
        except AttributeError:
            print("Device name:", data1)

    def send_data(self):
        #data = str(bytearray("TTWU"))
        #print("Send Ok ,"+data)
        print("sidong off")
        self.requester1.write_by_handle(0x12, b'\x54\x52\x46\x68\x0D\x0A')
        self.requester2.write_by_handle(0x12, b'\x54\x52\x46\x68\x0D\x0A')
        #print("brake")
        #self.requester1.write_by_handle(0x12, b'\x54\x53\x53\x5A\x0D\x0A')
        #self.requester2.write_by_handle(0x12, b'\x54\x53\x53\x5A\x0D\x0A')
        print("Sidong ON")
        self.requester1.write_by_handle(0x12, b'\x54\x52\x4E\x60\x0D\x0A')
        self.requester2.write_by_handle(0x12, b'\x54\x52\x4E\x60\x0D\x0A')
        print("SPEED SLOW")
        #self.requester1.write_by_handle(0x12, b'\x54\x57\x32\x77\x0D\x0A')
        #self.requester2.write_by_handle(0x12, b'\x54\x57\x32\x77\x0D\x0A')
        print("SPEED FULL")
        self.requester1.write_by_handle(0x12, b'\x54\x57\x82\x27\x0D\x0A')
        self.requester2.write_by_handle(0x12, b'\x54\x57\x82\x27\x0D\x0A')
Example #9
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"))
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
Example #11
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)
Example #12
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()
Example #13
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)
Example #14
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])))
Example #15
0
#!/usr/bin/env python

from bluetooth.ble import GATTRequester

address = "F8:EF:FE:C6:35:AD"
nrf = GATTRequester("F8:EF:FE:C6:35:AD", False)
#nrf.write_by_handle(0x10, str(bytearray([14, 4, 56])))
nrf.connect(wait=True, channel_type="public")
print("OK")

# -*- mode: python; coding: utf-8 -*-

# Copyright (C) 2014, Oscar Acena <*****@*****.**>
# This software is under the terms of Apache License v2 or later.

#from __future__ import print_function
#
#import sys
#from bluetooth.ble import GATTRequester

#
#class JustConnect(object):
#    def __init__(self, address):
#        self.requester = GATTRequester(address, False)
#        self.connect()
#
#    def connect(self):
##        print("Connecting...", end=' ')
##        sys.stdout.flush()
#
#        self.requester.connect(True)
Example #16
0
from __future__ import print_function
from bluetooth.ble import DiscoveryService, GATTRequester
import sys
import time

service = DiscoveryService()
devices = service.discover(2)

for address, name in devices.items():
    print("name: {}, address: {}".format(name, address))
    r = GATTRequester(address)
    print("Connecting...", end=' ')
    sys.stdout.flush()
    print(dir(r), r.is_connected())
    time.sleep(2)
    r.connect(True)
Example #17
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)
Example #18
0
#    $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.
vh_sample = None
for c12c in characteristics:
Example #19
0
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")