コード例 #1
0
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()
コード例 #2
0
ファイル: mainserver.py プロジェクト: xy97cornell/ece5725
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()
コード例 #3
0
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()
コード例 #4
0
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")
コード例 #5
0
ファイル: j2_cruncher.py プロジェクト: piofthings/piwars-2019
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
コード例 #6
0
                 screen, YOLK, (rect.left - 15, rect.top - 15,
                                rect.width + 30, rect.height + 30))
             screen.blit(text_surface, rect)
         for event in pygame.event.get():  # event handling
             if ((event.type is MOUSEBUTTONDOWN)):
                 pos = pygame.mouse.get_pos()
                 i, j = pos
                 state = 1
                 print("touch at " + str((i, j)))
             elif (event.type is MOUSEBUTTONUP):
                 pos = pygame.mouse.get_pos()
                 x, y = pos
                 if y > 35 and y < 75:  #{'Friend':(80, 60), 'Camera':(160,60), 'Drive':(240,60)}
                     if x > 50 and x < 110:  # friend
                         print "heart"
                         server.send('h')
                     elif x > 130 and x < 190:  # camera
                         print "camera"
                         server.send('c')
                         state = 2
                     elif x > 210 and x < 270:  # drive
                         print "drive"
                         server.send('r')
                         state = 3
 if state == 2:  # Camera display mode
     if surf != None:
         screen.blit(surf, buff)  # Load new image to screen
     text_surface = my_font.render("Back", True, WHITE)
     rect = text_surface.get_rect(center=(30, 30))
     bkgd_rect = pygame.draw.rect(
         screen, YOLK,
コード例 #7
0
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)