class BtServer(object): def __init__(self): super(BtServer, self).__init__() self.socket = BluetoothSocket(RFCOMM) self.client = {} def start(self): # empty host address means this machine self.socket.bind(("", PORT_ANY)) self.socket.listen(config['backlog']) self.port = self.socket.getsockname()[1] uuid = config['uuid'] advertise_service( self.socket, "Rewave Server", service_id=uuid, service_classes=[uuid, SERIAL_PORT_CLASS], profiles=[SERIAL_PORT_PROFILE] ) print('Waiting for connection on RFCOMM channel %d' % self.port) self.client['socket'], self.client['info'] = self.socket.accept() print("Accepted connection from ", self.client['info']) def kill(self): self.socket.close() def close_connection(self): self.client['socket'].close()
def _recv_client_data(client_socket: bluetooth.BluetoothSocket): data = b'' tmp_char = client_socket.recv(1) while tmp_char != b'\x00': data += tmp_char tmp_char = client_socket.recv(1) return data
def _send_client_response(client_socket: bluetooth.BluetoothSocket, return_data: bytes): if return_data is None: return_data = b'' parsed_return_data = struct.pack(f'I{len(return_data)}s', len(return_data), return_data) client_socket.send(parsed_return_data)
def connect(self): try: self.conn = BluetoothSocket( bluetooth.RFCOMM) # use RFCOMM protocol self.conn.bind( (self.address, self.port)) # empty address; use any available adapter self.address, self.port = self.conn.getsockname() self.conn.listen(1) uuid = self.config.get('BT_UUID') bluetooth.advertise_service( sock=self.conn, name='MDP-Group-15-Bluetooth-Server', service_id=uuid, service_classes=[uuid, bluetooth.SERIAL_PORT_CLASS], profiles=[bluetooth.SERIAL_PORT_PROFILE], ) print( f'Listening for Bluetooth connection on {self.address} port {self.port}' ) self.client, client_info = self.conn.accept() print(f'Connected to {client_info}') self._connected = True except Exception as e: print(f'Error with {self.get_name()}: {e}') self.disconnect() raise ConnectionError
def connect(self, protocol=None, device: str = None, port: int = None, service_uuid: str = None, service_name: str = None): """ Connect to a bluetooth device. You can query the advertised services through ``find_service``. :param protocol: Supported values: either 'RFCOMM'/'L2CAP' (str) or bluetooth.RFCOMM/bluetooth.L2CAP int constants (int) :param device: Device address or name :param port: Port number :param service_uuid: Service UUID :param service_name: Service name """ from bluetooth import BluetoothSocket addr, port, protocol = self._get_addr_port_protocol(protocol=protocol, device=device, port=port, service_uuid=service_uuid, service_name=service_name) sock = self._get_sock(protocol=protocol, device=addr, port=port) if sock: self.close(device=addr, port=port) sock = BluetoothSocket(protocol) self.logger.info('Opening connection to device {} on port {}'.format(addr, port)) sock.connect((addr, port)) self.logger.info('Connected to device {} on port {}'.format(addr, port)) self._socks[(addr, port)] = sock
def __init__(self, establish_bt=True): self.folder = path.dirname(path.abspath(__file__)) try: with open(path.join(self.folder, 'settings.yaml')) as settings_file: self.settings = yaml.safe_load(settings_file) except FileNotFoundError: print( "Create a settings.yaml file by copying settings-example.yaml") raise self.server_sock = None self.client_sock = None if establish_bt: self.server_sock = BluetoothSocket(RFCOMM) self.server_sock.bind(("", PORT_ANY)) self.server_sock.listen(1) uuid = "28ccf815-245e-436f-a002-8e72a67422a8" # doesn't appear to do anything on RasPi... advertise_service(self.server_sock, "LightNet", service_id=uuid, service_classes=[uuid, SERIAL_PORT_CLASS], profiles=[SERIAL_PORT_PROFILE]) self.broadcast_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.broadcast_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.broadcast_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
def _create_client(self): assert self.uuid is not None logger.info("searching service %s (UUID: %s) @ %s" % (self.name, self.uuid, self.upstream_addr or 'anywhere')) service_matches = [] while len(service_matches) == 0: try: service_matches = bt.find_service(uuid=self.uuid, address=self.upstream_addr) if len(service_matches) == 0: sleep(1) except KeyboardInterrupt: break first_match = service_matches[0] port = first_match["port"] name = first_match["name"] host = first_match["host"] logger.info("connecting to App \"%s\" on %s" % (name, host)) # Create the client socket sock = BluetoothSocket(bt.RFCOMM) sock.connect((host, port)) return sock
def waitForConnection(self): # enable visibility if not self.sys_bus: self.sys_bus = dbus.SystemBus() # do only once (since we turn off the timeout) # alternatively set DiscoverableTimeout = 0 in /etc/bluetooth/main.conf # and run hciconfig hci0 piscan, from robertalab initscript hci0 = self.sys_bus.get_object('org.bluez', '/org/bluez/hci0') props = dbus.Interface(hci0, 'org.freedesktop.DBus.Properties') props.Set('org.bluez.Adapter1', 'DiscoverableTimeout', dbus.UInt32(0)) props.Set('org.bluez.Adapter1', 'Discoverable', True) if not self.bt_server: self.bt_server = BluetoothSocket(bluetooth.RFCOMM) self.bt_server.settimeout( 0.5) # half second to make IO interruptible self.bt_server.bind(("", bluetooth.PORT_ANY)) self.bt_server.listen(1) while True: try: (con, info) = self.bt_server.accept() con.settimeout(0.5) # half second to make IO interruptible self.bt_connections.append(con) return len(self.bt_connections) - 1 except bluetooth.btcommon.BluetoothError as e: if not self._isTimeOut(e): logger.error("unhandled Bluetooth error: %s", repr(e)) break return -1
def get_local_address(): hci = BluetoothSocket(HCI) fd = hci.fileno() buf = array.array('B', [0] * 96) ioctl(fd, _bluetooth.HCIGETDEVINFO, buf, 1) data = struct.unpack_from("H8s6B", buf.tostring()) return data[2:8][::-1]
def __init__(self, bdaddress=None): self.cport = 0x11 # HID's control PSM self.iport = 0x13 # HID' interrupt PSM self.backlog = 1 self.address = "" if bdaddress: self.address = bdaddress # create the HID control socket self.csock = BluetoothSocket(L2CAP) self.csock.bind((self.address, self.cport)) set_l2cap_mtu(self.csock, 64) self.csock.settimeout(2) self.csock.listen(self.backlog) # create the HID interrupt socket self.isock = BluetoothSocket(L2CAP) self.isock.bind((self.address, self.iport)) set_l2cap_mtu(self.isock, 64) self.isock.settimeout(2) self.isock.listen(self.backlog) self.connected = False self.client_csock = None self.caddress = None self.client_isock = None self.iaddress = None
def allocate_code(self): """Acquires and returns a string suitable for finding the key via Bluetooth. Returns None if no powered on adapter could be found.""" # TODO: when we have magic-wormhole we should perform this operation in async # and show the loading spinning wheel bt_data = None try: code = get_local_bt_address().upper() except NoBluezDbus as e: log.debug("Bluetooth service seems to be unavailable: %s", e) except NoAdapter as e: log.debug("Bluetooth adapter is not available: %s", e) except UnpoweredAdapter as e: log.debug("Bluetooth adapter is turned off: %s", e) else: if self.server_socket is None: self.server_socket = BluetoothSocket(RFCOMM) # We create a bind with the Bluetooth address we have in the system self.server_socket.bind((code, PORT_ANY)) # Number of unaccepted connections that the system will allow before refusing new connections backlog = 1 self.server_socket.listen(backlog) log.info("sockname: %r", self.server_socket.getsockname()) port = self.server_socket.getsockname()[1] log.info("BT Code: %s %s", code, port) bt_data = "BT={0};PT={1}".format(code, port) return bt_data
def listen_for_rfcomm_connection(self): """ Starts bluetooth interfaces """ # prepare bluetooth server self.server_sock = BluetoothSocket(RFCOMM) self.server_sock.bind(("", PORT_ANY)) self.server_sock.listen(1) self.rfcomm_channel = self.server_sock.getsockname()[1] # start listening for incoming connections advertise_service( self.server_sock, self.service_name, service_id=self.service_uuid, service_classes=[self.service_uuid, SERIAL_PORT_CLASS], profiles=[SERIAL_PORT_PROFILE]) LOGGER.info('waiting for connection on RFCOMM channel %d' % self.rfcomm_channel) # accept received connection self.client_sock, self.client_info = self.server_sock.accept() self.state = self.__states__.STATE_CONNECTED LOGGER.info('accepted connection from %r', self.client_info) # start listening for data self.consume_bus()
def client_init(server_name): """ initialize client socket """ logging.debug("client initialization") server_address = None devices = discover_devices() for device_address in devices: device_name = lookup_name(device_address) logging.debug("found device : %s", device_name) if device_name == server_name: server_address = device_address break if server_address is None: logging.error("could not connect to %s", server_name) sys.exit(0) client_socket = BluetoothSocket(RFCOMM) client_socket.connect((server_address, PORT)) # handle callback function if connected_callback is not None: connected_callback() return client_socket
def allocate_code(self): try: code = get_local_bt_address().upper() except dbus.exceptions.DBusException as e: if e.get_dbus_name() == "org.freedesktop.systemd1.NoSuchUnit": log.info("No Bluetooth devices found, probably the bluetooth service is not running") elif e.get_dbus_name() == "org.freedesktop.DBus.Error.UnknownObject": log.info("No Bluetooth devices available") else: log.error("An unexpected error occurred %s", e.get_dbus_name()) self.code = None return None if self.server_socket is None: self.server_socket = BluetoothSocket(RFCOMM) # We can also bind only the mac found with get_local_bt_address(), anyway # even with multiple bt in a single system BDADDR_ANY is not a problem self.server_socket.bind((socket.BDADDR_ANY, PORT_ANY)) # Number of unaccepted connections that the system will allow before refusing new connections backlog = 1 self.server_socket.listen(backlog) log.info("sockname: %r", self.server_socket.getsockname()) port = self.server_socket.getsockname()[1] log.info("BT Code: %s %s", code, port) bt_data = "BT={0};PT={1}".format(code, port) return bt_data
def _connect_to_server(self): ''' Establishes a connection with the Tremium Hub Bluetooth server ''' bluetooth_port = self.config_manager.config_data["bluetooth-port"] try: # creating a new socket self.server_s = BluetoothSocket() self.server_s.bind( (self.config_manager. config_data["bluetooth-adapter-mac-client"], bluetooth_port)) # connecting to the hub time.sleep(0.25) self.server_s.connect( (self.config_manager. config_data["bluetooth-adapter-mac-server"], bluetooth_port)) self.server_s.settimeout( self.config_manager.config_data["bluetooth-comm-timeout"]) time.sleep(0.25) # handling server connection failure except Exception as e: self.server_s.close() time_str = datetime.datetime.fromtimestamp( time.time()).strftime('%Y-%m-%d_%H-%M-%S') logging.error( "{0} - NodeBluetoothClient failed to connect to server : {1}". format(time_str, e)) raise
def client_loop(client: bt.BluetoothSocket, cursor: sqlite3.Cursor, connection: sqlite3.Connection): while True: try: print('Try receiving') raw = client.recv(1024) print(f'Received {len(raw)} bytes: {raw}') query = decode_message(raw) query_type = query.WhichOneof("query") print(f'Query type: {query_type}') if query_type == 'get_ids': response = encode_ids(cursor) elif query_type == 'get_flower_data': flower_id = query.get_flower_data.flower_id since_time = query.get_flower_data.since_time response = encode_flower_data(flower_id, since_time, cursor) elif query_type == 'set_watering': flower_id = query.set_watering.flower_id hour = query.set_watering.hour days = query.set_watering.days set_watering(flower_id, hour, days, cursor, connection) response = encode_watering_set() else: continue raw_send = response.SerializeToString() client.send(raw_send) print(f'Sent {len(raw_send)} bytes: {raw_send}') except bt.btcommon.BluetoothError as e: print(e) client.close() break
def main(): # Setup logging setup_logging() # We need to wait until Bluetooth init is done time.sleep(10) # Make device visible os.system("hciconfig hci0 piscan") # Create a new server socket using RFCOMM protocol server_sock = BluetoothSocket(RFCOMM) # Bind to any port server_sock.bind(("", PORT_ANY)) # Start listening server_sock.listen(1) # Get the port the server socket is listening port = server_sock.getsockname()[1] # The service UUID to advertise uuid = "7be1fcb3-5776-42fb-91fd-2ee7b5bbb86d" # Start advertising the service advertise_service(server_sock, "RaspiBtSrv", service_id=uuid, service_classes=[uuid, SERIAL_PORT_CLASS], profiles=[SERIAL_PORT_PROFILE]) # These are the operations the service supports # Feel free to add more operations = ["ping", "example"] # Main Bluetooth server loop while True: print("Waiting for connection on RFCOMM channel %d" % port) client_sock = None try: # This will block until we get a new connection client_sock, client_info = server_sock.accept() print("Accepted connection from ", client_info) # Read the data sent by the client data = client_sock.recv(1024) if len(data) == 0: break print("Received [%s]" % data) # Handle the request if data == "getop": response = "op:%s" % ",".join(operations) elif data == "ping": response = "msg:Pong" elif data == "example": response = "msg:This is an example" # Insert more here else: response = "msg:Not supported" client_sock.send(response) print("Sent back [%s]" % response) except IOError: pass except KeyboardInterrupt: if client_sock is not None: client_sock.close() server_sock.close() print("Server going down") break
def createClient(self, address, port=3): if address == "first": address = self.searchDevices()[0] self.client_socket = BluetoothSocket(RFCOMM) print "Trying to connect.." self.client_socket.connect((address, port)) print "Connected!" self.connected = True
def __init__(self, is_server: bool = True): self.is_server = is_server self._threads = {} self._connections = {} self.socket = BluetoothSocket(RFCOMM) self.socket_is_ready = False self.socket_thread = self.spawn_thread("Accepting", self._accept, True).start()
def connect(self, host=None, port=4): """Open a connection to the TimeBox.""" # Create the client socket if host is None: host = self.DEFAULTHOST #print("connecting to %s at %s" % (self.host, self.port)) self.socket = BluetoothSocket(RFCOMM) self.socket.connect((host, port)) self.socket.setblocking(0)
def task(self): # Waiting until Bluetooth init is done time.sleep(self.wakeup_time) # Make device visible self.scm.set_bluetooth_visible() # Create a new server socket using RFCOMM protocol server_sock = BluetoothSocket(RFCOMM) # Bind to any port server_sock.bind(("", PORT_ANY)) # Start listening server_sock.listen(self.max_simultaneous_connections) # Get the port the server socket is listening port = server_sock.getsockname()[1] # Main bluetooth server loop while True: logger.info( 'Waiting for bluetooth connection on channel {}'.format(port)) client_sock = None try: # Block until we get a new connection client_sock, client_info = server_sock.accept() logger.info('Accepted connection from {}'.format(client_info)) # Read the data sent by the client command = client_sock.recv(1024) if len(command) == 0: continue logger.info('Received [{}]'.format(command)) # Handle the request response = self.handle_request(command) client_sock.send(response) logger.info('Sent back [{}]'.format(response)) except IOError: pass except KeyboardInterrupt: if client_sock is not None: client_sock.close() server_sock.close() logger.info('Bluetooth server going down') break
def createServer(self, port=3): self.server_socket = BluetoothSocket(RFCOMM) self.server_socket.bind(("", port)) self.server_socket.listen(1) print "Trying to connect.." self.client_socket, _ = self.server_socket.accept() print "Connected!" self.connected = True
def run_bt_server(account): """Adapted from: https://github.com/EnableTech/raspberry-bluetooth-demo""" import pdb pdb.set_trace() server_sock = BluetoothSocket(RFCOMM) server_sock.bind(("", PORT_ANY)) server_sock.listen(1) port = server_sock.getsockname()[1] print ("listening on port %d" % port) uuid = "1e0ca4ea-299d-4335-93eb-27fcfe7fa848" advertise_service( server_sock, "Mock Detector", service_id=uuid, service_classes=[uuid, SERIAL_PORT_CLASS], profiles=[SERIAL_PORT_PROFILE], # protocols=[OBEX_UUID], ) print("Waiting for connection on RFCOMM channel %d" % port) client_sock, client_info = server_sock.accept() print("Accepted connection from ", client_info) try: while True: data = client_sock.recv(1024) if len(data) == 0: break print("received [%s]" % data) if data == b'ETH_ADDRESS\r\n': client_sock.send( "ETH_ADDRESS::0x{}\r\nEND\r\n".format(account.address()) ) elif data.startswith('SIGNED_MESSAGE::'): start = len('SIGNED_MESSAGE::') user_address = data[start:start+42] message = account.create_signed_message( user_address, int(time.time()) ) client_sock.send(message) except IOError: pass print("disconnected") client_sock.close() server_sock.close() print("all done")
def connect_device(self): if not self.scanservices(): self.logging.error('Not found valid service.') return False self.logging.info("Service found. Connecting to \"%s\" on %s..." % (self.service["name"], self.service["host"])) self.sock = BluetoothSocket(RFCOMM) self.sock.connect((self.service["host"], self.service["port"])) self.sock.settimeout(60) self.logging.info("Device connected.") return True
def connect(addr): socket = BluetoothSocket(RFCOMM) while True: try: socket.connect((addr, 1)) break except Exception as e: print("Failed to connect trying, again in 1 sec.") time.sleep(1) print("Connected to {} on channel {}".format(addr, 1)) return socket
def __init__(self, server_address, RequestHandlerClass): self.server_address = server_address self.RequestHandlerClass = RequestHandlerClass self.socket = BluetoothSocket(RFCOMM) try: self.socket.bind((server_address[0], server_address[1])) # self.server_address = self.socket.getsockname() self.socket.listen(self.request_queue_size) except Exception: self.server_close() raise
def __init__(self, mac): super(DataReceiver, self).__init__() self.MAC = mac self.message = "" self.data = "" self.socket = BluetoothSocket(RFCOMM) self.dallas_temp_data = [] self.dht_temp_data = [] self.dht_humid_data = [] self.sound_data = [] self.time_list = [] self.startTime = 0 self.data_to_send = SendingData(self.MAC)
def connect(self, target): """Connect to target MAC (the keyboard must already be known to the target)""" print("[*] Connecting to {}".format(target)) self.scontrol = BluetoothSocket(L2CAP) self.sinterrupt = BluetoothSocket(L2CAP) self.scontrol.connect((target, self.P_CTRL)) self.sinterrupt.connect((target, self.P_INTR)) self.ccontrol = self.scontrol self.cinterrupt = self.sinterrupt
def connect(self): if self.address is None and not self.scandevices(): return False if not self.scanservices(): return False logging.info("Service found. Connecting to \"%s\" on %s..." % (self.service["name"], self.service["host"])) self.sock = BluetoothSocket(RFCOMM) self.sock.connect((self.service["host"], self.service["port"])) self.sock.settimeout(60) logging.info("Connected.") self.registerCrcKeyToBt() return True
def connect(self): if self.address is None and not self.scandevices(): return False if not self.scanservices(): return False logging.info('Service found: connecting to %s on %s...' % (self.service['name'], self.service['host'])) self.sock = BluetoothSocket() self.sock.connect((self.service['host'], self.service['port'])) self.sock.settimeout(60) logging.info('Connected.') self.registerCrcKeyToBt() return True
def connect(self, host=None, port=4): """Open a connection to the TimeBox.""" #try: # Create the client socket # if host is None: # self.logger.info('Host is none, so using default..') # host = self.DEFAULTHOST self.currentHost = self.host self.logger.info('Connecting to {0}'.format(self.currentHost)) #print("connecting to %s at %s" % (self.host, self.port)) self.socket = BluetoothSocket(RFCOMM) self.socket.connect((self.currentHost, port)) self.socket.setblocking(0)
def bluetooth_connect(): if os.environ.get('BLUETOOTH_STUB'): return None devices = discover_devices( duration=4, lookup_names=True, flush_cache=True, lookup_class=False) for address, name in devices: if name == device_name: socket = BluetoothSocket() socket.connect((address, bluetooth_port)) return socket raise Exception( 'Could not find device of name ' + device_name)
def listen_for_rfcomm_connection(self): """ Starts bluetooth interfaces """ # prepare bluetooth server self.server_sock = BluetoothSocket(RFCOMM) self.server_sock.bind(("", PORT_ANY)) self.server_sock.listen(1) self.rfcomm_channel = self.server_sock.getsockname()[1] # start listening for incoming connections try: advertise_service( sock=self.server_sock, name=self.service_name, service_id=self.service_uuid, service_classes=[self.service_uuid, SERIAL_PORT_CLASS], profiles=[SERIAL_PORT_PROFILE] ) except: LOGGER.exception("[ERROR] failed to advertise service") return LOGGER.info('waiting for connection on RFCOMM channel %d', self.rfcomm_channel) # accept received connection self.client_sock, self.client_info = self.server_sock.accept() self.state = self.__states__.STATE_CONNECTED LOGGER.info('accepted connection from %r', self.client_info) # start listening for data self.consume_bus()
def createClient(self, address, port = 3): if address == "first": address = self.searchDevices()[0] self.client_socket=BluetoothSocket( RFCOMM ) print "Trying to connect.." self.client_socket.connect((address, port)) print "Connected!" self.connected = True
class BtServer(object): def __init__(self, socket=None): super(BtServer, self).__init__() self.socket = socket def start(self): print('start called') if not self.socket: print('non socket, creating one') self.socket = BluetoothSocket(RFCOMM) # empty host address means this machine self.socket.bind(("", PORT_ANY)) self.socket.listen(config['backlog']) advertise_service( self.socket, "Rewave Server", service_id=config['uuid'], service_classes=[config['uuid'], SERIAL_PORT_CLASS], profiles=[SERIAL_PORT_PROFILE] ) self.port = self.socket.getsockname()[1] # need port for ref. self.accept() def stop(self): print("server stop called") self.socket.close() try: self.client_socket.close() except AttributeError as e: # in case if no client is connected pass def recv(self, buffer=2048): print('recv called') try: return self.client_socket.recv(buffer).decode(encoding='UTF-8') except UnicodeDecodeError as e: # return raw if unable to unicode decode return self.client_socket.recv(buffer) def send(self, data): self.client_socket.send(data) def close_connection(self): print("close_connection called") self.client_socket.close() def accept(self): # blocking call print("accept Called. Waiting for connection on RFCOMM channel", self.port) self.client_socket = self.socket.accept()[0] # returns socket, name
def createServer(self, port = 3): self.server_socket=BluetoothSocket( RFCOMM ) self.server_socket.bind(("", port)) self.server_socket.listen(1) print "Trying to connect.." self.client_socket, _ = self.server_socket.accept() print "Connected!" self.connected = True
def listen(self): """Listen for incoming client connections""" print("[*] Waiting for connections") self.scontrol = BluetoothSocket(L2CAP) self.sinterrupt = BluetoothSocket(L2CAP) # bind these sockets to a port - port zero to select next available self.scontrol.bind((self.bdaddr, self.P_CTRL)) self.sinterrupt.bind((self.bdaddr, self.P_INTR)) # start listening on the server sockets (only allow 1 connection) self.scontrol.listen(1) self.sinterrupt.listen(1) self.ccontrol, cinfo = self.scontrol.accept() print("[*] Connection on the control channel from {}" .format(cinfo[0])) self.cinterrupt, cinfo = self.sinterrupt.accept() print("[*] Connection on the interrupt channel from {}" .format(cinfo[0]))
def connect(self, connectedIntSock=None): self.restartIdleTime() try: if not self.id: # == None or == 0 print "note: skipping connect in mote.connect, id not valid." return if connectedIntSock: self.intSock = connectedIntSock else: self.intSock = BluetoothSocket(L2CAP) self.intSock.connect( (self.id, self.INTERRUPT_PORT) ) self.ctrlSock = BluetoothSocket(L2CAP) self.ctrlSock.connect( (self.id, self.CONTROL_PORT) ) if self.ctrlSock and self.intSock: print "Connected to", self.id self.connected = True except bluetooth.BluetoothError, e: if e.message=="time out": print "Timed out when connected to mote." raise MoteConnectFailed() else: raise
def start(self): print('start called') if not self.socket: print('non socket, creating one') self.socket = BluetoothSocket(RFCOMM) # empty host address means this machine self.socket.bind(("", PORT_ANY)) self.socket.listen(config['backlog']) advertise_service( self.socket, "Rewave Server", service_id=config['uuid'], service_classes=[config['uuid'], SERIAL_PORT_CLASS], profiles=[SERIAL_PORT_PROFILE] ) self.port = self.socket.getsockname()[1] # need port for ref. self.accept()
class PantojoBluetoothReceiver: PANTOJO_BLUETOOTH_PORT = 3 MAX_PACKET_SIZE = 34 def __init__(self): self.server_socket = BluetoothSocket(RFCOMM) self.server_socket.bind(("", self.PANTOJO_BLUETOOTH_PORT)) def open(self): self.server_socket.listen(1) self.client_socket, self.client_info = self.server_socket.accept() def recv(self): return self.client_socket.recv(self.MAX_PACKET_SIZE).strip() def close(self): self.client_socket.close() self.server_socket.close()
def myThread(self,run_event): server_sock=BluetoothSocket(RFCOMM) #TODO:allow to change the port server_sock.bind(("", PORT)) server_sock.listen(1) client_sock, client_info = server_sock.accept() print("Accepted connection from ", client_info) success="" #success=struct.pack('8B',0xa0,0x00,0x08,0xcb,0x00,0x00,0x00,0x01) #success success=struct.pack('3B',0xa0,0x00,0x03) #success data = client_sock.recv(1024) client_sock.send(success) while run_event.is_set(): print('Waiting') data = client_sock.recv(1024) if len(data) == 0: break client_sock.send(success) self.decodeMessage(data) return
def __init__(self, addr): self._addr = addr self._inSocket = BluetoothSocket(L2CAP) self._outSocket = BluetoothSocket(L2CAP) self._connected = False
def __init__(self): super(BtServer, self).__init__() self.socket = BluetoothSocket(RFCOMM) self.client = {}
class Mote: INTERRUPT_PORT = 19 CONTROL_PORT = 17 def __init__(self, id=None, name=""): self.id = id self.name = name self.connected = False self.irMode = None self.reportMode = None self.dataLock = Lock() self.dataPoints = [] self.dataPointsAndSize = [] self.dataPointsFull = [] self.dataPointsFullFirstPart = [] self.buttonEvents = [] # A,B,1,2,Home,Plus,Minus,Left,Right,Up,Down self.buttonState = {"a":bool(0), "b":bool(0), 1:bool(0), 2:bool(0), "h":bool(0), "p":bool(0), "m":bool(0), "l":bool(0), "r":bool(0), "u":bool(0), "d":bool(0)} self.readThread = None self.idleStartTime = time.time() self.idleLastPoint = (0.0,0.0) def getIdleSecs(self): return time.time() - self.idleStartTime def restartIdleTime(self): self.idleStartTime = time.time() def isIrModeFull(self): #if self.reportMode == 0x3e or self.reportMode == 0x3f: if self.irMode == "f": return True else: return False def isIrModeExt(self): #if self.reportMode == 0x33: if self.irMode == "e": return True else: return False def isIrModeBasic(self): #if self.reportMode == 0x36 or self.reportMode == 0x37: if self.irMode == "b": return True else: return False def getServices(self): return getServices(self.id) def connect(self, connectedIntSock=None): self.restartIdleTime() try: if not self.id: # == None or == 0 print "note: skipping connect in mote.connect, id not valid." return if connectedIntSock: self.intSock = connectedIntSock else: self.intSock = BluetoothSocket(L2CAP) self.intSock.connect( (self.id, self.INTERRUPT_PORT) ) self.ctrlSock = BluetoothSocket(L2CAP) self.ctrlSock.connect( (self.id, self.CONTROL_PORT) ) if self.ctrlSock and self.intSock: print "Connected to", self.id self.connected = True except bluetooth.BluetoothError, e: if e.message=="time out": print "Timed out when connected to mote." raise MoteConnectFailed() else: raise
class BluetoothConnection(object): def __init__(self): self.client_socket = None self.server_socket = None self.connected = False def createServer(self, port = 3): self.server_socket=BluetoothSocket( RFCOMM ) self.server_socket.bind(("", port)) self.server_socket.listen(1) print "Trying to connect.." self.client_socket, _ = self.server_socket.accept() print "Connected!" self.connected = True def createClient(self, address, port = 3): if address == "first": address = self.searchDevices()[0] self.client_socket=BluetoothSocket( RFCOMM ) print "Trying to connect.." self.client_socket.connect((address, port)) print "Connected!" self.connected = True def searchDevices(self): return discover_devices() def receiveData(self, bufsize = 1024): if self.connected: return self.client_socket.recv(bufsize) else: print "Not yet connected!" def sendFile(self, filename): f = open(filename, 'r') data = f.readlines() for line in data: self.sendData(line) f.close() def receiveFile(self, filename, bufsize = 4096): data = self.receiveData(bufsize) f = open(filename, 'w') f.writelines(data) f.flush() f.close() def sendData(self, data): if self.connected: self.client_socket.send(data) def closeConnection(self): if self.server_socket is not None: self.server_socket.close() self.client_socket.close() self.connected = False
class BTKbDevice(): """Bluetooth HID keyboard device""" # control and interrupt service ports P_CTRL = 17 # Service port (control) from SDP record P_INTR = 19 # Service port (interrupt) from SDP record # D-Bus path of the BlueZ profile PROFILE_DBUS_PATH = "/bluez/syss/btkbd_profile" # file path of the SDP record SDP_RECORD_PATH = "{}{}".format(sys.path[0], "/sdp_record.xml") # device UUID UUID = "00001124-0000-1000-8000-00805f9b34fb" def __init__(self): """Initialize Bluetooth keyboard device""" # read config file with address and device name print("[*] Read configuration file") config = configparser.ConfigParser() config.read("../keyboard.conf") try: self.bdaddr = config['default']['BluetoothAddress'] self.device_name = config['default']['DeviceName'] self.device_short_name = config['default']['DeviceShortName'] self.interface = config['default']['Interface'] self.spoofing_method = config['default']['SpoofingMethod'] self.auto_connect = config['auto_connect']['AutoConnect'] self.connect_target = config['auto_connect']['Target'] except KeyError: sys.exit("[-] Could not read all required configuration values") print("[*] Initialize Bluetooth device") self.configure_device() self.register_bluez_profile() def configure_device(self): """Configure bluetooth hardware device""" print("[*] Configuring emulated Bluetooth keyboard") # power on Bluetooth device p = subprocess.run(['btmgmt', '--index', self.interface, 'power', 'off'], stdout=subprocess.PIPE) time.sleep(OS_CMD_SLEEP) # spoof device address if configured if self.spoofing_method == 'bdaddr': print("[+] Spoof device {} address {} via btmgmt". format(self.interface, self.bdaddr)) # power on Bluetooth device p = subprocess.run(['btmgmt', '--index', self.interface, 'power', 'on'], stdout=subprocess.PIPE) time.sleep(OS_CMD_SLEEP) # set Bluetooth address using bdaddr software tool with manual # reset, so that we have to power on the device p = subprocess.run(['bdaddr', '-i', self.interface, '-r', self.bdaddr], stdout=subprocess.PIPE) time.sleep(OS_CMD_SLEEP) # power on Bluetooth device p = subprocess.run(['btmgmt', '--index', self.interface, 'power', 'on'], stdout=subprocess.PIPE) time.sleep(OS_CMD_SLEEP) # set device class print("[+] Set device class") p = subprocess.run(['btmgmt', '--index', self.interface, 'class', '5', '64'], stdout=subprocess.PIPE) time.sleep(OS_CMD_SLEEP) # set device name and short name print("[+] Set device name: {} ({})". format(self.device_name, self.device_short_name)) p = subprocess.run(['btmgmt', '--index', self.interface, 'name', self.device_name, self.device_short_name], stdout=subprocess.PIPE) # set device to connectable p = subprocess.run(['btmgmt', '--index', self.interface, 'connectable', 'on'], stdout=subprocess.PIPE) time.sleep(OS_CMD_SLEEP) # power on Bluetooth device p = subprocess.run(['btmgmt', '--index', self.interface, 'power', 'on'], stdout=subprocess.PIPE) time.sleep(OS_CMD_SLEEP) elif self.spoofing_method == 'btmgmt': print("[+] Spoof device {} address {} via btmgmt". format(self.interface, self.bdaddr)) # set Bluetooth address print("[+] Set Bluetooth address: {}".format(self.bdaddr)) p = subprocess.run(['btmgmt', '--index', self.interface, 'public-addr', self.bdaddr], stdout=subprocess.PIPE) print(p.stdout) if "fail" in str(p.stdout, "utf-8"): print("[-] Error setting Bluetooth address") sys.exit(1) # power on Bluetooth device using btmgmt software tool p = subprocess.run(['btmgmt', '--index', self.interface, 'power', 'on'], stdout=subprocess.PIPE) # print(p.stdout) time.sleep(OS_CMD_SLEEP) # set device class print("[+] Set device class") p = subprocess.run(['btmgmt', '--index', self.interface, 'class', '5', '64'], stdout=subprocess.PIPE) # print(p.stdout) time.sleep(OS_CMD_SLEEP) # set device name and short name print("[+] Set device name: {} ({})". format(self.device_name, self.device_short_name)) p = subprocess.run(['btmgmt', '--index', self.interface, 'name', self.device_name, self.device_short_name], stdout=subprocess.PIPE) # print(p.stdout) time.sleep(OS_CMD_SLEEP) # set device to connectable p = subprocess.run(['btmgmt', '--index', self.interface, 'connectable', 'on'], stdout=subprocess.PIPE) # print(p.stdout) time.sleep(OS_CMD_SLEEP) # turn on discoverable mode print("[+] Turn on discoverable mode") p = subprocess.run(['bluetoothctl', 'discoverable', 'on'], stdout=subprocess.PIPE) # print(p.stdout) def register_bluez_profile(self): """Setup and register BlueZ profile""" print("Configuring Bluez Profile") # setup profile options service_record = self.read_sdp_service_record() opts = { "ServiceRecord": service_record, "Role": "server", "RequireAuthentication": False, "RequireAuthorization": False } # retrieve a proxy for the bluez profile interface bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object("org.bluez", "/org/bluez"), "org.bluez.ProfileManager1") profile = BTKbdBluezProfile(bus, BTKbDevice.PROFILE_DBUS_PATH) manager.RegisterProfile(BTKbDevice.PROFILE_DBUS_PATH, BTKbDevice.UUID, opts) print("[*] Profile registered") def read_sdp_service_record(self): """Read SDP service record""" print("[*] Reading service record") try: fh = open(BTKbDevice.SDP_RECORD_PATH, "r") except Exception: sys.exit("[*] Could not open the SDP record. Exiting ...") return fh.read() def listen(self): """Listen for incoming client connections""" print("[*] Waiting for connections") self.scontrol = BluetoothSocket(L2CAP) self.sinterrupt = BluetoothSocket(L2CAP) # bind these sockets to a port - port zero to select next available self.scontrol.bind((self.bdaddr, self.P_CTRL)) self.sinterrupt.bind((self.bdaddr, self.P_INTR)) # start listening on the server sockets (only allow 1 connection) self.scontrol.listen(1) self.sinterrupt.listen(1) self.ccontrol, cinfo = self.scontrol.accept() print("[*] Connection on the control channel from {}" .format(cinfo[0])) self.cinterrupt, cinfo = self.sinterrupt.accept() print("[*] Connection on the interrupt channel from {}" .format(cinfo[0])) def connect(self, target): """Connect to target MAC (the keyboard must already be known to the target)""" print("[*] Connecting to {}".format(target)) self.scontrol = BluetoothSocket(L2CAP) self.sinterrupt = BluetoothSocket(L2CAP) self.scontrol.connect((target, self.P_CTRL)) self.sinterrupt.connect((target, self.P_INTR)) self.ccontrol = self.scontrol self.cinterrupt = self.sinterrupt def send_string(self, message): """Send a string to the host machine""" self.cinterrupt.send(message)
class Wiimote: def __init__(self, addr): self._addr = addr self._inSocket = BluetoothSocket(L2CAP) self._outSocket = BluetoothSocket(L2CAP) self._connected = False def __del__(self): self.disconnect() def _send(self, *data, **kwargs): check_connection = True if "check_connection" in kwargs: check_connection = kwargs["check_connection"] if check_connection and not self._connected: raise IOError("No wiimote is connected") self._inSocket.send("".join(map(chr, data))) def disconnect(self): if self._connected: self._inSocket.close() self._outSocket.close() self._connected = False def connect(self, timeout=0): if self._connected: return None self._inSocket.connect((self._addr, 0x13)) self._outSocket.connect((self._addr, 0x11)) self._inSocket.settimeout(timeout) self._outSocket.settimeout(timeout) # TODO give the choice of the mode to the user # Set the mode of the data reporting of the Wiimote with the last byte of this sending # 0x30 : Only buttons (2 bytes) # 0x31 : Buttons and Accelerometer (3 bytes) # 0x32 : Buttons + Extension (8 bytes) # 0x33 : Buttons + Accel + InfraRed sensor (12 bytes) # 0x34 : Buttons + Extension (19 bytes) # 0x35 : Buttons + Accel + Extension (16 bytes) # 0x36 : Buttons + IR sensor (10 bytes) + Extension (9 bytes) # 0x37 : Buttons + Accel + IR sensor (10 bytes) + Extension (6 bytes) # 0x3d : Extension (21 bytes) # 0x3e / 0x3f : Buttons + Accel + IR sensor (36 bytes). Need two reports for a sigle data unit. self._send(0x52, 0x12, 0x00, 0x33, check_connection=False) # Enable the IR camera # Enable IR Camera (Send 0x04 to Output Report 0x13) # Enable IR Camera 2 (Send 0x04 to Output Report 0x1a) # Write 0x08 to register 0xb00030 # Write Sensitivity Block 1 to registers at 0xb00000 # Write Sensitivity Block 2 to registers at 0xb0001a # Write Mode Number to register 0xb00033 # Write 0x08 to register 0xb00030 (again) # Put a sleep of 50ms to avoid a bad configuration of the IR sensor # Sensitivity Block 1 is : 00 00 00 00 00 00 90 00 41 # Sensitivity Block 2 is : 40 00 # The mode number is 1 if there is 10 bytes for the IR. # The mode number is 3 if there is 12 bytes for the IR. # The mode number is 5 if there is 36 bytes for the IR. time.sleep(0.050) self._send(0x52, 0x13, 0x04, check_connection=False) time.sleep(0.050) self._send(0x52, 0x1A, 0x04, check_connection=False) time.sleep(0.050) self._send( 0x52, 0x16, 0x04, 0xB0, 0x00, 0x30, 1, 0x08, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, check_connection=False, ) time.sleep(0.050) self._send( 0x52, 0x16, 0x04, 0xB0, 0x00, 0x06, 1, 0x90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, check_connection=False, ) time.sleep(0.050) self._send( 0x52, 0x16, 0x04, 0xB0, 0x00, 0x08, 1, 0x41, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, check_connection=False, ) time.sleep(0.050) self._send( 0x52, 0x16, 0x04, 0xB0, 0x00, 0x1A, 1, 0x40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, check_connection=False, ) time.sleep(0.050) self._send( 0x52, 0x16, 0x04, 0xB0, 0x00, 0x33, 1, 0x03, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, check_connection=False, ) time.sleep(0.050) self._send( 0x52, 0x16, 0x04, 0xB0, 0x00, 0x30, 1, 0x08, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, check_connection=False, ) self._connected = True def vibrate(self, duration=1): self._send(0x52, 0x15, 0x01) time.sleep(duration) self._send(0x52, 0x15, 0x00) def setLed(self, binary): self._send(0x52, 0x11, int(n << 4)) def _getData(self, check_connection=True): if check_connection and not self._connected: raise IOError("No wiimote is connected") data = self._inSocket.recv(19) if len(data) != 19: raise IOError("Impossible to receive all data") return list(map(ord, data)) def _checkButton(self, bit, mask): return self._getData()[bit] & mask != 0 def buttonAPressed(self): return self._checkButton(3, 0x08) def buttonBPressed(self): return self._checkButton(3, 0x04) def buttonUpPressed(self): return self._checkButton(2, 0x08) def buttonDownPressed(self): return self._checkButton(2, 0x04) def buttonLeftPressed(self): return self._checkButton(2, 0x01) def buttonRightPressed(self): return self._checkButton(2, 0x02) def buttonPlusPressed(self): return self._checkButton(2, 0x10) def buttonMinusPressed(self): return self._checkButton(3, 0x10) def buttonHomePressed(self): return self._checkButton(3, 0x80) def buttonOnePressed(self): return self._checkButton(3, 0x02) def buttonTwoPressed(self): return self._checkButton(3, 0x01) # 0x80 means no movement def getAcceleration(self): d = self._getData() ax = d[4] << 2 | d[2] & (0x20 | 0x40) ay = d[5] << 1 | d[3] & 0x20 az = d[6] << 1 | d[3] & 0x40 return (ax, ay, az) def getIRPoints(self): d = self._getData() x1 = d[7] | ((d[9] & (0b00110000)) << 4) y1 = d[8] | ((d[9] & (0b11000000)) << 2) i1 = d[9] & 0b00001111 x2 = d[10] | ((d[12] & (0b00110000)) << 4) y2 = d[11] | ((d[12] & (0b11000000)) << 2) i2 = d[12] & 0b00001111 x3 = d[13] | ((d[15] & (0b00110000)) << 4) y3 = d[14] | ((d[15] & (0b11000000)) << 2) i3 = d[15] & 0b00001111 x4 = d[16] | ((d[18] & (0b00110000)) << 4) y4 = d[17] | ((d[18] & (0b11000000)) << 2) i4 = d[18] & 0b00001111 return [(x1, y2, i1), (x2, y2, i2), (x3, y3, i3), (x4, y4, i4)]
def __init__(self): BluetoothSocket.__init__(self, RFCOMM)
def __init__(self): self.server_socket = BluetoothSocket(RFCOMM) self.server_socket.bind(("", self.PANTOJO_BLUETOOTH_PORT))
#!/usr/bin/env python3 # coding: utf-8 from bluetooth import BluetoothSocket host_BD = 'B8:27:EB:A5:03:6C' port = 3 backlog = 2 size = 1024 blueth = BluetoothSocket(bluetooth.RFCOMM) blueth.bind((host_BD, port)) blueth.listen(backlog) try: client, client_info = blueth.accept() while True: data = client.recv(1024) if data: print(data) except: print("Closing socket") client.close() blueth.close()
def find_key(self, bt_mac, mac): self.client_socket = BluetoothSocket(RFCOMM) message = b"" try: self.client_socket.setblocking(False) try: self.client_socket.connect((bt_mac, self.port)) except BluetoothError as be: if be.args[0] == "(115, 'Operation now in progress')": pass else: raise be success = False while not self.stopped and not success: r, w, e = yield threads.deferToThread(select.select, [self.client_socket], [], [], 0.5) if r: log.info("Connection established") self.client_socket.setblocking(True) success = True # try to receive until the sender closes the connection try: while True: part_message = self.client_socket.recv(self.size) log.debug("Read %d bytes: %r", len(part_message), part_message) message += part_message except BluetoothError as be: if be.args[0] == "(104, 'Connection reset by peer')": log.info("Bluetooth connection closed, let's check if we downloaded the key") else: raise be mac_key = fingerprint_from_keydata(message) verified = None if mac: verified = mac_verify(mac_key.encode('ascii'), message, mac) if verified: success = True else: log.info("MAC validation failed: %r", verified) success = False message = b"" except BluetoothError as be: if be.args[0] == "(16, 'Device or resource busy')": log.info("Probably has been provided a partial bt mac") elif be.args[0] == "(111, 'Connection refused')": log.info("The sender refused our connection attempt") elif be.args[0] == "(112, 'Host is down')": log.info("The sender's Bluetooth is not available") elif be.args[0] == "(113, 'No route to host')": log.info("An error occurred with Bluetooth, if present probably the device is not powered") else: log.info("An unknown bt error occurred: %s" % be.args[0]) key_data = None success = False returnValue((key_data, success, be)) except Exception as e: log.error("An error occurred connecting or receiving: %s" % e) key_data = None success = False returnValue((key_data, success, e)) if self.client_socket: self.client_socket.close() returnValue((message.decode("utf-8"), success, None))
fdin.settimeout(0.1) while connected == 1: try: msg = fdin.recv(23) except BluetoothError: continue if len(msg) >= 7: for c in range(3): sensor[c] = ord(msg[4 + c]) fdin.close() fdout.close() connected = -1 # Try to connect to Wiimote print 'connecting to Wiimote ' + ADDRESS + ', please press buttons 1 and 2' fdin = BluetoothSocket(L2CAP) fdin.connect((ADDRESS, 0x13)) fdout = BluetoothSocket(L2CAP) fdout.connect((ADDRESS, 0x11)) if not fdin or not fdout: raise 'could not connect to Wiimote, check the address' # Open window pygame.init() window = pygame.display.set_mode((WIDTH, HEIGHT), 0) pygame.display.set_caption('Wiiewer') # Run listener old = [127] * 3 sensor = [127] * 3 connected = 1 thread.start_new_thread(listener, ()) fdout.send("\x52\x12\x00\x31")
class BluetoothInterface(BaseInterface): """The Bluetooth interface definition for communication with wireless client devices.""" __interface_name__ = 'bluetooth' def __init__(self, controller): """ Initializes a bluetooth service that may be consumed by a remote client. Arguments --------- controller : controllers.base.BaseController the parent controller that is instantiated this interface """ super(BluetoothInterface, self).__init__() self.controller = controller self.client_sock = None self.client_info = None self.rfcomm_channel = None self.service_name = self.get_setting('service_name') self.service_uuid = self.get_setting('service_uuid') self.server_sock = None self.thread = None def connect(self): """Creates a new thread that listens for an incoming bluetooth RFCOMM connection.""" LOGGER.info('creating thread for bluetooth interface...') self.thread = threading.Thread(target=self.listen_for_rfcomm_connection) self.thread.daemon = True self.thread.start() def listen_for_rfcomm_connection(self): """ Starts bluetooth interfaces """ # prepare bluetooth server self.server_sock = BluetoothSocket(RFCOMM) self.server_sock.bind(("", PORT_ANY)) self.server_sock.listen(1) self.rfcomm_channel = self.server_sock.getsockname()[1] # start listening for incoming connections try: advertise_service( sock=self.server_sock, name=self.service_name, service_id=self.service_uuid, service_classes=[self.service_uuid, SERIAL_PORT_CLASS], profiles=[SERIAL_PORT_PROFILE] ) except: LOGGER.exception("[ERROR] failed to advertise service") return LOGGER.info('waiting for connection on RFCOMM channel %d', self.rfcomm_channel) # accept received connection self.client_sock, self.client_info = self.server_sock.accept() self.state = self.__states__.STATE_CONNECTED LOGGER.info('accepted connection from %r', self.client_info) # start listening for data self.consume_bus() def disconnect(self): """ Closes Bluetooth connection and resets handle """ LOGGER.info('destroying bluetooth interface...') self.state = self.__states__.STATE_DISCONNECTING if self.client_sock and hasattr(self.client_sock, 'close'): self.client_sock.close() self.client_sock = None if self.server_sock and hasattr(self.server_sock, 'close'): self.server_sock.close() self.server_sock = None # reset the bluetooth interface self.thread = None self.perform_hci0_reset() self.state = self.__states__.STATE_READY @staticmethod def perform_hci0_reset(): """Resets the bluetooth hci0 device via hciconfig command line interface.""" try: LOGGER.info('performing hci0 down/up...') subprocess.Popen('hciconfig hci0 down', shell=True).communicate() subprocess.Popen('hciconfig hci0 up', shell=True).communicate() LOGGER.info('hci0 down/up has completed') except Exception as exception: LOGGER.exception("Failed to restart hci0 - %r", exception) def receive(self, data): """ Processes received data from Bluetooth socket Arguments --------- data : basestring the data received from the bluetooth connection """ try: packet = json.loads(data.decode('utf-8')) LOGGER.info('received packet via bluetooth: %r', packet['data']) # invoke bound method (if set) if self.receive_hook and hasattr(self.receive_hook, '__call__'): self.receive_hook(packet['data']) except Exception as exception: LOGGER.exception('error: %r', exception) def send(self, data): """ Sends data via Bluetooth socket connection Arguments --------- data : basestring the data to be sent via this interface """ if self.state != self.__states__.STATE_CONNECTED: LOGGER.error('error: send() was called but state is not connected') return False try: LOGGER.info('sending IBUSPacket(s)...') packets = [] for packet in data: packets.append(packet.as_serializable_dict()) # encapsulate ibus packets and send data = {"data": json.dumps(packets)} # TODO : is an inner json.dumps necessary? LOGGER.info(data) self.client_sock.send(json.dumps(data)) except Exception: # socket was closed, graceful restart LOGGER.exception('bluetooth send exception') self.reconnect() def consume_bus(self): """ Start listening for incoming data """ try: LOGGER.info('starting to listen for bluetooth data...') read_buffer_length = self.get_setting('read_buffer_length', int) while self.client_sock: data = self.client_sock.recv(read_buffer_length) if len(data) > 0: self.receive(data) except Exception as exception: LOGGER.exception('android device was disconnected - %r', exception) self.reconnect()