def run(self): self._logger.info('Mqtt running start') self._bluetooth_client = BluetoothClient(server=self._mqtt_address, data_received_callback=self.data_received_handler, auto_connect=False, power_up_device=True, encoding=None) self._logger.info('Mqtt client created') while True: self._logger.info('Mqtt client try to connect') try: self._bluetooth_client.connect() except OSError as e: self._logger.info(f'Mqtt client connection error: {e}') time.sleep(30) continue except Exception as e: self._logger.exception(e) raise e self._is_mqtt_connected = True self._logger.info('Mqtt client connected') while True: if not self._bluetooth_client.connected: self._logger.info('Mqtt client disconnected') self._is_mqtt_connected = False break self._is_mqtt_connected = False time.sleep(10)
def __init__(self): self.target_name = "HC-06" self.target_address = None port = 3 nearby_devices = bluetooth.discover_devices() for bdaddr in nearby_devices: if self.target_name == bluetooth.lookup_name(bdaddr): self.target_address = bdaddr break if self.target_address is not None: print("found target bluetooth device with address ", self.target_address) self.c = BluetoothClient(self.target_address, self.data_received)
def test_client_default_values(): def data_received(data): pass bts = BluetoothServer(data_received, device = "hci1") btc = BluetoothClient(bta1.address, data_received) assert btc.data_received_callback == data_received assert btc.device == "hci0" assert btc.server == bta1.address assert btc.client_address == bta0.address assert btc.connected assert btc.port == 1 assert btc.encoding == "utf-8" btc.disconnect() bts.stop()
def test_volume_data(): from random import choice, randint import string no_of_transmissions = randint(100, 200) test_data = '' received = Event() def data_received_server(data): assert data == test_data bts.send(test_data) def data_received_client(data): assert data == test_data received.set() bts = BluetoothServer(data_received_server, device = "hci0") btc = BluetoothClient(bta0.address, data_received_client, device = "hci1") for test_no in range(no_of_transmissions): test_data = ''.join(choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(randint(30,100))) print(test_data) btc.send(test_data) assert received.wait(1) received.clear() btc.disconnect() bts.stop()
def test_client_alt_values(): def data_received(data): pass bts = BluetoothServer(None, port=2, encoding=None) btc = BluetoothClient(bta0.address, data_received, device="hci1", auto_connect=False, port=2, encoding=None) assert btc.data_received_callback == data_received assert btc.device == "hci1" assert btc.client_address == bta1.address assert not btc.connected assert btc.port == 2 assert btc.encoding == None btc.connect() assert btc.connected btc.disconnect() assert not btc.connected bts.stop()
def test_client_connect_disconnect(): client_connected = Event() client_disconnected = Event() def when_client_connects(): client_connected.set() def when_client_disconnects(): client_disconnected.set() bts = BluetoothServer(None) btc = BluetoothClient(bta0.address, None, device = "hci1", auto_connect = False) bts.when_client_connects = when_client_connects bts.when_client_disconnects = when_client_disconnects btc.connect() assert btc.connected assert bts.client_address == btc.client_address assert client_connected.wait(1) btc.disconnect() assert not btc.connected assert client_disconnected.wait(1) bts.stop()
class robot(): def data_received(self, data): print(data) def __init__(self): self.target_name = "HC-06" self.target_address = None port = 3 nearby_devices = bluetooth.discover_devices() for bdaddr in nearby_devices: if self.target_name == bluetooth.lookup_name(bdaddr): self.target_address = bdaddr break if self.target_address is not None: print("found target bluetooth device with address ", self.target_address) self.c = BluetoothClient(self.target_address, self.data_received) def run(self): left, right = 0, 0 while (1): time.sleep(0.01) events = get_gamepad() maxSpeed = 60 maxDivision = 255 / maxSpeed for event in events: if event.code == "ABS_Y": left = int(((event.state - 127) * 2) / maxDivision) if event.code == "ABS_RZ": right = int(((event.state - 127) * 2) / maxDivision) value = "<{0},{1}>".format(left, right) print(value) self.c.send(value)
class PharaonService(Node): def __init__(self): super().__init__("pharaon_service") self.srv = self.create_service(Trigger, "/pharaon/deploy", self.activate_callback) self.bt = BluetoothClient("00:14:03:06:61:BA", self.data_received) self.get_logger().info("Pharaon has been started") def data_received(self, data): """Callback upon data received.""" self.get_logger().info(data) def activate_callback(self, request, response): """Callback called upon trigger.""" try: self.bt.send("deploy;") response.success = True response.message = "Pharaon requested to deploy" self.get_logger().info(response.message) except BaseException as e: response.success = False response.message = f"Pharaon failed to deploy with {e}" self.get_logger().warn(response.message) return response
def __connect_to_cruncher(self): try: self.__bt_client = BluetoothClient("B8:27:EB:55:22:18", self.data_received, auto_connect=True) if (self.__debug): print( "Bluetooth client initialised, ready for Cruncher comms:") except: type, value, traceback = sys.exc_info() if (self.__debug): print( "Bluetooth client not initialised, Cruncher comms won't work" ) print('Error Details %s: %s %s' % (type, value, traceback)) time.sleep(1)
def sendIP(): """ Repeatedly sends the string containing IP address to target. Requires the MAC address of the target to be hardcoded. Receives back IP address from target and saves it for UDP connection Blocks until we connect with base station """ global flag flag = True c = BluetoothClient('B8:27:EB:2A:46:91', data_received, power_up_device=True) while flag: c.send(client_IP) time.sleep(1) c.disconnect()
def test_send_receive(): data_received_at_server = Event() data_received_at_client = Event() def data_received_server(data): assert data == "hiserver" data_received_at_server.set() def data_received_client(data): assert data == "hiclient" data_received_at_client.set() bts = BluetoothServer(data_received_server, device = "hci0") btc = BluetoothClient(bta0.address, data_received_client, device = "hci1") btc.send("hiserver") assert data_received_at_server.wait(1) bts.send("hiclient") assert data_received_at_server.wait(1) btc.disconnect() bts.stop()
subject_images_names) #, folder_label #number of the image in the path #Def of showface function: def show_face(text, face): cv2.imshow(text, face) cv2.waitKey(1000) cv2.destroyAllWindows() #---------------------------------------------------------------------------- #Main function: #Starting Bluetooth Serial Client: c = BluetoothClient(mac2NAME(MAC_BL), data_received) last_package = b'' if (first_conn == 1): print('Hola serial: ' + SERIAL) BLUEcryptosend(bytes(SERIAL + HOUR, 'utf-8')) time.sleep(5) face_recognizer = cv2.face.LBPHFaceRecognizer_create() config_folders() folder_label = -1
import os def data_received(data): with open(file_name, mode='a+') as latency_file: latency_writer = csv.writer(latency_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) latency_writer.writerow([datetime.now(), data]) print(data) print("Connecting to bluetooth server.") client = BluetoothClient("raspberrypi", data_received) count = 0 file = 'bluetooth_client_latency' file_name = f"{file}_{count}.csv" if os.path.isfile(file_name): while os.path.isfile(file_name): if not os.path.isfile(file_name): break count = count + 1 file_name = f"{file}_{count}.csv" print("Sending") try: while True:
class MqttConnector(threading.Thread, IResponseWriter, IPackageReceiver): _logger = logging.getLogger('Main') _mqtt_address: str _is_mqtt_connected: bool _bluetooth_client: BluetoothClient = None _response_mutex = threading.Lock() def __init__(self, config: Config, request_transmitter: 'Queue[Request]'): threading.Thread.__init__(self) self._config = config if not config.mqtt_enabled: self._logger.fatal('Mqtt is disabled but is trying to create') raise Exception('Mqtt is disabled but is trying to create') self._request_transmitter = request_transmitter self._mqtt_address = config.mqtt_address self._is_mqtt_connected = False self._protocol_parser = ProtocolParser(self) @property def connected(self) -> bool: if self._bluetooth_client is not None: return self._bluetooth_client.connected else: return False def run(self): self._logger.info('Mqtt running start') self._bluetooth_client = BluetoothClient(server=self._mqtt_address, data_received_callback=self.data_received_handler, auto_connect=False, power_up_device=True, encoding=None) self._logger.info('Mqtt client created') while True: self._logger.info('Mqtt client try to connect') try: self._bluetooth_client.connect() except OSError as e: self._logger.info(f'Mqtt client connection error: {e}') time.sleep(30) continue except Exception as e: self._logger.exception(e) raise e self._is_mqtt_connected = True self._logger.info('Mqtt client connected') while True: if not self._bluetooth_client.connected: self._logger.info('Mqtt client disconnected') self._is_mqtt_connected = False break self._is_mqtt_connected = False time.sleep(10) def data_received_handler(self, data): self._logger.debug(f'MQTT receive {len(data)} bytes') self._protocol_parser.update(data) def write_response(self, response: Response): self._response_mutex.acquire() payload_length = 0 if response.payload is not None: payload_length = {len(response.payload)} if response.command_type is not CommandType.Telemetry: self._logger.info( f'MQTT try to send response with type {response.command_type} and payload length {payload_length}') package = self._protocol_parser.create_package(response.command_type, response.payload) self.send(self._protocol_parser.serialize_package(package)) self._response_mutex.release() def receive_package(self, package: PackageDto): self._logger.info(f'MQTT receive new package {package.command_type} with size {package.payload_size} bytes') new_request = Request(package.command_type, package.payload, self) self._request_transmitter.put(new_request) def send(self, payload: bytes): if self._bluetooth_client is None: self._logger.critical('MQTT not running, but send invoke') raise ConnectionError('MQTT not running, but send invoke') self._bluetooth_client.send(payload)
device = "B8:27:EB:2A:46:91" #other bluetooth device to pair #device = "7C:B0:C2:AC:16:7D" #Xiaoyu's computer result = subprocess.run('hostname -I', stdout=subprocess.PIPE, shell=True) result = result.stdout.decode('utf-8') client_IP = re.split(' |\n', result)[0] print("client_IP: " + client_IP) num = 0 adapter = BluetoothAdapter() print("Powered = {}".format(adapter.powered)) print(adapter.paired_devices) def data_recieved(data): global host_IP global flag host_IP = data flag = False flag = True c = BluetoothClient(device, data_recieved, power_up_device=True) while flag: c.send(client_IP) time.sleep(1) c.disconnect
def __init__(self): super().__init__("pharaon_service") self.srv = self.create_service(Trigger, "/pharaon/deploy", self.activate_callback) self.bt = BluetoothClient("00:14:03:06:61:BA", self.data_received) self.get_logger().info("Pharaon has been started")
from bluedot.btcomm import BluetoothClient from datetime import datetime from time import sleep from signal import pause def data_received(data): print("recv - {}".format(data)) print("Connecting") c = BluetoothClient("devpi", data_received) print("Sending") try: while True: c.send("hi {} \n".format(str(datetime.now()))) sleep(1) finally: c.disconnect()
oy = y oz = z #print('moving to False') moving = False #@skywriter.touch() def touch(position): print('Touch!', position) bdx, bdy = direction[position] if position == sky_centre: command(bd_release, bdx, bdy) else: command(bd_press, bdx, bdy) try: print("Connecting to {}".format(bd_server)) c = BluetoothClient(bd_server, data_received) print(" Connected to {}".format(bd_server)) with SenseHAT() as hat: for m in movements(hat.imu): #hat.screen.array = arrays(m) move(m[0], m[1], m[2]) #move(m[0], m[1], m[2]) #pause() finally: command(bd_release, 0, 0) c.disconnect()
from bluedot.btcomm import BluetoothClient from signal import pause def data_received(data): print(data) c = BluetoothClient("j2controller", data_received) c.send("helloworld") pause() # from bluedot.btcomm import BluetoothServer # from signal import pause # def data_received(data): # print(data) # s.send(data) #s = BluetoothServer(data_received) # pause()
bd_command = '{},{:.3f},{:.3f}\n' print('op={} x={:.3f} y={:.3f}'.format(operation, bdx, bdy)) if operation == bd_release: if not pressed: return pressed = False print('op={} x={:.3f} y={:.3f}'.format(operation, bdx, bdy)) c.send(bd_command.format(operation, bdx, bdy)) def data_received(data): print("recv - {}".format(data)) print("Connecting to {}".format(bd_server)) c = BluetoothClient(bd_server, data_received) print("Sending protocol version") c.send("3,{},BlueSky\n".format(BD_PROTOCOL_VERSION)) print(" Connected to {}".format(bd_server)) #print("Sending") #try: # while True: # c.send("hi {} \n".format(str(datetime.now()))) # sleep(1) #finally: # c.disconnect() #pause() some_value = 5000
from bluedot.btcomm import BluetoothClient from time import sleep forward = Button(20) def print_bt_error(): print ("Error - Check BT connection!") def print_bt_error2(): print ("Error 2- Check BT connection!") def data_received(data): print (data) c = BluetoothClient("baxbotserver", data_received) #try: # c = BluetoothClient("baxbotserver", data_received) #except: # print_bt_error() while True: forward.wait_for_press() try: c.send("forward") except: print_bt_error2() forward.wait_for_stop()