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 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()
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
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 @skywriter.move()
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 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() try: c.send("stop") except: print_bt_error2() ''' # Create lights lights = TrafficLights(18, 15, 14) # Start Listing to Distance Sensor sensor = DistanceSensor(echo=12, trigger=11)
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()
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()
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: now = datetime.now() current_time = now.strftime('%H:%M:%S.%f')[:-3] print(current_time) client.send("{time} {payload}".format( time=current_time, payload="{\"enabled\": true, \"direction\": \"west\"}")) sleep(1) finally: c.disconnect()