def test_server_start_stop(): bts = BluetoothServer(None, auto_start = False) bts.start() assert bts.running bts.stop() assert not bts.running
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: if event.key == pygame.K_UP: # send start_motor() forward command print("forward")
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
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)