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 build(self): # 빈창 띄우는 범인: flask - 어케 해결하지? # self.que = Manager().Queue() # self.que_to_flask = Manager().Queue() # self.flask_proc = Process(target=flaskRun, args=(self.que, self.que_to_flask)) # self.flask_proc.start() f = [] f.append(open("layout/main.kv", encoding='utf8')) f.append(open("layout/aprow.kv", encoding='utf8')) f.append(open("layout/btrow.kv", encoding='utf8')) f.append(open("layout/home.kv", encoding='utf8')) f.append(open("layout/menu.kv", encoding='utf8')) f.append(open("layout/ether.kv", encoding='utf8')) f.append(open("layout/bluetooth.kv", encoding='utf8')) f.append(open("layout/disp.kv", encoding='utf8')) content = '' for i in f: content += i.read() + "\r\n" i.close() Builder.load_string(content) self.scm = ScreenManagement() self.scm.transition = NoTransition() self.triggerThreads() if sys.platform == 'win32': pass elif sys.platform.startswith('linux'): self.s = BluetoothServer(self.data_received) return self.scm
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 run(self): self._logger.info('RFCC running start') self._bluetooth_server = BluetoothServer( data_received_callback=self._data_received_handler, auto_start=False, power_up_device=True, encoding=None, when_client_connects=self._client_connect_handler, when_client_disconnects=self._client_disconnect_handler) self._logger.info('RFCC server created') while True: self._logger.info('RFCC server try to start') try: self._bluetooth_server.start() except OSError as e: self._logger.info(f'RFCC server start error: {e}') time.sleep(30) continue except Exception as e: self._logger.exception(e) raise e self._logger.info('RFCC started') break
def bluetooth_client(done_event): def data_received(data): print(data) # adds data to the queue and leaves s = BluetoothServer(data_received) #starts RFCOMM Server while not (done_event.wait(0.00001)): pass s.stop()
def run(event): def data_received(data): updated_data.append(data) # adds data to the queue and leaves s = BluetoothServer(data_received) #starts RFCOMM Server while True: event_set = event.wait(0.0001) if event_set: s.close() break pass
def __init__(self, isDebug=False): self.__debug = isDebug self.joystick_action = JoystickAction(self.__debug) self.cannon_action = CannonAction(self.__debug) self.__bt_server = BluetoothServer(self.data_received, self.__debug) self.__bt_server.when_client_connects = self.bt_client_connected self.__bt_server.when_client_disconnects = self.bt_client_disconnected self.__bt_server.start() self.__cruncher_menu = CruncherMenu(self.__debug) self.__joystick_input = JoystickInput(self.__debug) self.__joystick_input.init_joystick() atexit.register(self.cleanup) if (self.__debug): print("Bluetooth Adapter Address:" + self.__bt_server.adapter.address)
def test_server_default_values(): def data_received(data): pass bts = BluetoothServer(data_received) assert bts.data_received_callback == data_received assert bts.device == "hci0" assert bts.server_address == bta0.address assert bts.running assert bts.port == 1 assert bts.encoding == "utf-8" assert bts.when_client_connects == None assert bts.when_client_disconnects == None bts.stop()
def test_server_alt_values(): def data_received(data): pass def when_client_connects(): pass def when_client_disconnects(): pass bts = BluetoothServer( data_received, device = "hci1", auto_start = False, port = 2, encoding = None, when_client_connects = when_client_connects, when_client_disconnects = when_client_disconnects) assert bts.data_received_callback == data_received assert bts.device == "hci1" assert bts.server_address == bta1.address assert not bts.running assert bts.port == 2 assert bts.encoding == None assert bts.when_client_connects == when_client_connects assert bts.when_client_disconnects == when_client_disconnects
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 get_ip(): """ Receives sender IP through bluetooth Relays its IP back to the sender using send's IP that was received Also generates pygame GUI to inform user that we are looking for bluetooth. Blocks until one robot connects """ global flag blue = BluetoothServer(data_received, power_up_device=True) flag = True i = 0 while flag: screen.fill((0, 0, 0)) mytext = "Connecting to Bluetooth" if (i == 0): mytext = mytext + '.' elif (i == 1): mytext = mytext + '..' elif (i == 2): mytext = mytext + '...' else: i = -1 i += 1 text_surface = my_font.render(mytext, True, (255, 255, 255)) text_surface = pygame.transform.rotate(text_surface, 180) rect = text_surface.get_rect(center=(160, 120)) screen.blit(text_surface, rect) time.sleep(1) pygame.display.flip() blue.send(host_IP) blue.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()
def get_ip(): global flag blue = BluetoothServer(data_recieved, power_up_device=True) flag = True while flag: time.sleep(1) blue.send(host_IP) blue.stop()
def test_server_start_stop(): bts = BluetoothServer(None, auto_start = False) bts.start() assert bts.running bts.stop() assert not bts.running
def __init__(self): super(Ui, self).__init__() uic.loadUi(strLocal + '/UI/MatChinh.ui', self) self.TimeTxt = self.findChild(QtWidgets.QLabel, 'Time') self.DateTxt = self.findChild(QtWidgets.QLabel, 'Ngay') timer = QTimer(self) timer.timeout.connect(self.showTime) timer.start(1000) self.btn_count = 0 self.led_status = 0 self.led = LED("GPIO17") self.cutRun = LED("GPIO26") self.screen_btn = Button("BOARD7") clock_time = QTimer(self) clock_time.timeout.connect(self.actions) clock_time.start(100) def data_received(data): print(data) self.TimeTxt.setText(data) s.send(data) s = BluetoothServer(data_received)
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()
if GPIO.input(ECHO) == GPIO.HIGH: break while True: pulso_fin = time.time() if GPIO.input(ECHO) == GPIO.LOW: break duracion = pulso_fin - pulso_inicio #cm distancia = (34300 * duracion) / 2 if distancia > 200: distancia = 200 print("Distancia: %.2f cm" % distancia) s.send(str(round(distancia, 2))) GPIO.cleanup() s = BluetoothServer(data_received_handler, port=1, when_client_connects=connect_handler, when_client_disconnects=disconnect_handler) print('Listening...') pause()
class AppMain(App): th_obj = "" def build(self): # 빈창 띄우는 범인: flask - 어케 해결하지? # self.que = Manager().Queue() # self.que_to_flask = Manager().Queue() # self.flask_proc = Process(target=flaskRun, args=(self.que, self.que_to_flask)) # self.flask_proc.start() f = [] f.append(open("layout/main.kv", encoding='utf8')) f.append(open("layout/aprow.kv", encoding='utf8')) f.append(open("layout/btrow.kv", encoding='utf8')) f.append(open("layout/home.kv", encoding='utf8')) f.append(open("layout/menu.kv", encoding='utf8')) f.append(open("layout/ether.kv", encoding='utf8')) f.append(open("layout/bluetooth.kv", encoding='utf8')) f.append(open("layout/disp.kv", encoding='utf8')) content = '' for i in f: content += i.read() + "\r\n" i.close() Builder.load_string(content) self.scm = ScreenManagement() self.scm.transition = NoTransition() self.triggerThreads() if sys.platform == 'win32': pass elif sys.platform.startswith('linux'): self.s = BluetoothServer(self.data_received) return self.scm def on_stop(self): # 종료시 쓰레드 종료 self.th_obj.is_running = False # 종료시 플라스크 종료 # self.flask_proc.terminate() # self.flask_proc.join() def triggerThreads(self, mode="none"): if self.th_obj != "": self.th_obj.threadDateTime("stop") self.th_obj.queueToDevice("stop") self.th_obj = ThreadKivy() self.th_obj.is_running = True self.th_obj.threadDateTime("start") self.th_obj.queueToDevice("start") def openMenu(self): # 메뉴 current_screen = self.scm.children[0] menu_cavity = current_screen.ids.menu menu = menu_cavity.children[0] menu.pos = (0, 0) menu.ids.menu_btn.pos = [-1000, -1000] def closeMenu(self): # 메뉴 current_screen = self.scm.children[0] menu_cavity = current_screen.ids.menu menu = menu_cavity.children[0] menu.pos = (800, 0) def data_received(self, data): if (data != "\n"): # print(data.strip()) self.que.put(data.strip()) self.s.send(data.strip() + " hahahaha" + "\n")
sc.close() surf = pygame.image.load("test.png") # Load local image for piTFT buff = surf.get_rect() buff.left = 0 buff.top = 0 if state == 2: # If in camera display mode server.send('d') # When client connects, send ip def when_client_connects(): temp = check_output(['hostname', '-I']) server.send(re.sub('\n', '', temp)) server = BluetoothServer(data_received_callback=data_received, when_client_connects=when_client_connects) #WHILE PROGRAM IS RUNNING while isRunning: clockvar.tick(framerate) #manual framerate control so we can edit it screen.fill(LIGHTBLUE) #erase the work space if state == 0 or state == 1: screen.blit(chikin, chikinrect) if state == 0: #start screen # render start button text_surface = my_font.render("Start", True, WHITE) rect = text_surface.get_rect(center=center_button_loc) bkgd_rect = pygame.draw.rect(screen, YOLK, (rect.left - 15, rect.top - 15,
class RFCCConnector(threading.Thread, IResponseWriter, IPackageReceiver): _logger = logging.getLogger('Main') _bluetooth_server: BluetoothServer = None _response_mutex = threading.Lock() _count_connected: int def __init__(self, config: Config, request_transmitter: 'Queue[Request]'): threading.Thread.__init__(self) self._config = config if not config.rfcomm_enabled: self._logger.fatal('RFCC is disabled but is trying to create') raise Exception('RFCC is disabled but is trying to create') self._count_connected = 0 self._request_transmitter = request_transmitter self._protocol_parser = ProtocolParser(self) @property def connected(self) -> bool: if self._bluetooth_server is not None: return self._count_connected > 0 else: return False def run(self): self._logger.info('RFCC running start') self._bluetooth_server = BluetoothServer( data_received_callback=self._data_received_handler, auto_start=False, power_up_device=True, encoding=None, when_client_connects=self._client_connect_handler, when_client_disconnects=self._client_disconnect_handler) self._logger.info('RFCC server created') while True: self._logger.info('RFCC server try to start') try: self._bluetooth_server.start() except OSError as e: self._logger.info(f'RFCC server start error: {e}') time.sleep(30) continue except Exception as e: self._logger.exception(e) raise e self._logger.info('RFCC started') break def _client_connect_handler(self): self._logger.info('New device connected') self._count_connected = self._count_connected + 1 def _client_disconnect_handler(self): self._logger.info('Device disconnected') self._count_connected = self._count_connected - 1 if self._count_connected < 0: self._count_connected = 0 def _data_received_handler(self, data): self._logger.debug(f'RFCC 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'RFCC 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'RFCC 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_server is None: self._logger.critical('RFCC not running, but send invoke') raise ConnectionError('RFCC not running, but send invoke') self._bluetooth_server.send(payload)
class J2Cruncher: __bt_server = None __cruncher_menu = None __joystick_input = None __looper = True __debug = False steeringPositions = SteeringPositions() joystick_action = None cannon_action = None def __init__(self, isDebug=False): self.__debug = isDebug self.joystick_action = JoystickAction(self.__debug) self.cannon_action = CannonAction(self.__debug) self.__bt_server = BluetoothServer(self.data_received, self.__debug) self.__bt_server.when_client_connects = self.bt_client_connected self.__bt_server.when_client_disconnects = self.bt_client_disconnected self.__bt_server.start() self.__cruncher_menu = CruncherMenu(self.__debug) self.__joystick_input = JoystickInput(self.__debug) self.__joystick_input.init_joystick() atexit.register(self.cleanup) if (self.__debug): print("Bluetooth Adapter Address:" + self.__bt_server.adapter.address) async def run(self): self.__cruncher_menu.init_screen() while self.__looper: try: self.__cruncher_menu.paint_screen() if (self.__cruncher_menu.previous_menu_name != self.__cruncher_menu.current_menu_name): self.process_menu() await asyncio.sleep(1.0 / 60) except KeyboardInterrupt: self.__looper = False self.cleanup() def process_menu(self): if (self.__cruncher_menu.current_menu_name == "ev_pi_noon"): self.__joystick_input.poll_joystick_events() self.__joystick_input.enabled = True self.__joystick_input.speedMultiplier = 0.8 self.update_j2_controller() if (self.__cruncher_menu.current_menu_name == "ev_spirit"): self.__joystick_input.poll_joystick_events() self.__joystick_input.enabled = True self.__joystick_input.speedMultiplier = 0.7 self.update_j2_controller() if (self.__cruncher_menu.current_menu_name == "ev_obstacles"): self.__joystick_input.poll_joystick_events() self.__joystick_input.enabled = True self.__joystick_input.speedMultiplier = 0.7 self.update_j2_controller() elif (self.__cruncher_menu.current_menu_name == "ev_space_invaders"): self.__joystick_input.poll_joystick_events() self.__joystick_input.enabled = True self.__joystick_input.speedMultiplier = 0.3 self.update_j2_controller() self.update_cannon_shooter() # self.update_suspension() elif (self.__cruncher_menu.current_menu_name == "ev_blastoff"): self.update_straight_line_speed() else: self.__joystick_input.enabled = False # else: #print("Previous {}, Current {}".format(self.__cruncher_menu.previous_menu_name, self.__cruncher_menu.current_menu_name)) def update_straight_line_speed(self): pass def update_suspension(self): pass def update_cannon_shooter(self): cannonCommand = self.cannon_action.get_command( self.__joystick_input.steeringPosition) if (cannonCommand != ""): self.__bt_server.send(cannonCommand) def update_j2_controller(self): steerCommand, driveCommand = self.joystick_action.get_commands( self.__joystick_input.steeringPosition, self.__joystick_input.directionLeft, self.__joystick_input.driveLeft, self.__joystick_input.directionRight, self.__joystick_input.driveRight) if (steerCommand != ""): self.__bt_server.send(steerCommand) if (driveCommand != ""): self.__bt_server.send(driveCommand) def data_received(self, data): if (self.__debug): print(data) self.__bt_server.send(data) def bt_client_connected(self): print("Client Connected: ") def bt_client_disconnected(self): print("Client Disconnected:") def cleanup(self): self.__bt_server = None
# sleep(0.1) # reset_display() def client_connected(): print("client connected") def client_disconnected(): print("client disconnected") print("init") server = BluetoothServer(data_received, auto_start=False, when_client_connects=client_connected(), when_client_disconnects=client_disconnected()) server.start() def run(): running = True button_down = False reset_display() try: while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN and button_down == False:
from bluedot.btcomm import BluetoothServer def data_received(data): print(data) s = BluetoothServer(data_received) _= input("Press Enter to quit...") s.stop()
#print(result) time.sleep(3) result = read_all_data_from_arduino() #print(result) result = do_stop() #print(result) result = read_all_data_from_arduino() #print(result) try: print('===> CREATING BLUETOOTH SERVER <===') s = BluetoothServer(data_received_callback=data_received, when_client_connects=client_connect, when_client_disconnects=client_disconnect) print('---> waiting for connection <---') pause() except ConnectionAbortedError as ex: print("*** ERROR ***: got connection request for closed socket: ex=" + str(ex)) sys.exit(5) except OSError as ex: print("*** ERROR ***: got mysterious OSError: ex=" + str(ex)) sys.exit(6) except Exception as ex: print("*** PROGRAM ERROR ***: ex=" + str(ex)) sys.exit(7)
#detection.detect('Jordan','8329300230','9152273680', int(tmax), int(tmin)) # return detection.detect(primaryName, primaryNumber, secondaryNumber, int(tmax), int(tmin)) return detection.detect(primaryName, primaryNumber, secondaryNumber, int(tmax)) def stop(data): print("here2") print(thread.toString()) stringCmd = 'Command: ' + data[0] print(stringCmd) s.send(stringCmd) #detection.stop() thread.exit() def client_connects(): print('Client Connected!') def client_disconnects(): print('Client Disconnected!') s = BluetoothServer(data_received, True, 'hci0', 1, 'utf-8', False, client_connects, client_disconnects) print(s.client_address) pause()
#!/usr/bin/python3 from bluedot.btcomm import BluetoothServer from signal import pause import time def data_received(data): print(data) s.send(data) while True: try: s = BluetoothServer(data_received) pause() except Exception as e: print("ERROR: e=" + str(e)) time.sleep(2)
host_mac = re.split(' |\n|\t', result)[2] print("host_mac: " + host_mac) adapter = BluetoothAdapter() print("Powered = {}".format(adapter.powered)) print(adapter.paired_devices) num = 0 Connection = True conn = True def data_recieved(data): global num, conn print("received data #" + str(num)) print(data) c.send(host_IP) num += 1 conn = True c = BluetoothServer(data_recieved, power_up_device=True) while Connection: if (c.client_connected and conn): print("connection from: " + str(c.client_address)) conn = False try: time.sleep(1) except KeyboardInterrupt: print("disconnected by keyboard") Connection = False