示例#1
0
 async def async_serial_init(self, n=1):
     """
     Asynchronous function for initializing serial connection
     """
     try:
         self.serial = aioserial.AioSerial(
             loop=self.loop,
             port=self.config.get("interface",
                                  {}).get("port", "/dev/serial0"),
             baudrate=self.config.get("interface",
                                      {}).get("baudrate", 115200),
         )
     except aioserial.serialutil.SerialException as e:
         if n <= 20:
             self.logger.info(
                 "unable to connect to serial, trying again in 2 seconds. Exception: %s",
                 str(e),
             )
         elif n == 21:
             self.logger.warning(
                 "unable to connect to serial for more than 40 seconds, logging for this issue stopped until the attempts to connect are successful. Exception: %s",
                 str(e),
             )
         await asyncio.sleep(1 + (n * (n < 25) or 24))
         await self.async_serial_init(n + 1)
示例#2
0
 def __init__(self, port):
     self.tx_lock = asyncio.Lock()
     self.rx_lock = asyncio.Lock()
     self.rx_buffer = bytearray(264)
     if not isinstance(port, str):
         port = port.device
     self.port = aioserial.AioSerial(port, 230400)
示例#3
0
    def __init__(self, core: "Core", config: Dict):
        self.core = core

        self.instances = {}

        self.config = config

        for name, port in self.config.items():
            try:
                instance = aioserial.AioSerial()
                if isinstance(port, str):
                    instance.port = port
                    conn = Connection(instance, port, name, self.core)
                else:
                    instance.port = port["port"]
                    conn = Connection(
                        instance,
                        port["port"],
                        name,
                        self.core,
                        reconnect=port.get("reconnect", False),
                        reconnect_time=port.get("reconnect_time", 5),
                        silent=port.get("silent", True),
                    )
                self.instances[name] = conn
            except:
                pass
 def __init__(self, port, handle_fn):
     self.serial = aioserial.AioSerial(port, baudrate=115200)
     self.handle_fn = handle_fn
     self.tags = self.get_session_tags()
     self.line_queue = asyncio.Queue()
     self.parser = TextProtocolParser()
     self.last_point_datetime = None
示例#5
0
    def initPort(self,
                 serialSettings: SerialCommSettings,
                 raiseException: bool = True) -> bool:
        """
        Initialize serial port with a given settings and return True on success, False otherwise.
            @param raiseException: if True, raise exception if port is not open.
        """
        try:
            self.closePort()

            self._portHandle = aioserial.AioSerial(
                port=serialSettings.port,
                baudrate=serialSettings.baudrate,
                bytesize=serialSettings.dataSize,
                parity=serialSettings.parity,
                stopbits=serialSettings.stopbits,
                xonxoff=serialSettings.swFlowControl,
                rtscts=serialSettings.hwFlowControl,
                dsrdtr=False,  # disable hardware (DSR/DTR) flow control
                timeout=serialSettings.readTimeoutMs / 1000,
                write_timeout=serialSettings.writeTimeoutMs / 1000)

            self.portSettings = serialSettings

            return True

        except Exception as err:
            if raiseException:
                errorMsg = f"Unable to init serial port with following settings: {serialSettings}"
                errorMsg += f"\nError:\n{err}"
                raise Exception

        return False
示例#6
0
    async def connect(self, product):
        """Creates connection to server at given address.

        Arguments:
            product (str):
                USB product string to search for
        """
        port = None
        devices = list_ports.comports()
        for dev in devices:
            # FIXME: Generalize for cross platform
            if dev.product == product or (
                    dev.pid == 0x5740 and dev.vid == 0x0483) or (
                        dev.vid == 0x0694
                        and dev.pid == 0x0010) or (dev.vid == 0x0694
                                                   and dev.pid == 0x0009):
                port = dev.device
                break

        if port is None:
            raise ValueError("Could not find hub.")

        print("Connecting to {0}".format(port))
        self.ser = aioserial.AioSerial(port)
        self.connected = True
        self.task = asyncio.create_task(self._read_loop())
        await asyncio.sleep(0.5)
示例#7
0
 def __init__(self, serial_device=SERIAL_DEVICE, baud=BAUD_RATE):
     self.ser = aioserial.AioSerial(serial_device, baud)  # open serial port
     logging.info('Attached to serial port: {}'.format(self.ser.name))
     # Bypass an go into raw serial mode.
     self.ser.write(BYPASS_COMMAND)
     logging.info('Entered Bypass mode')
     self.raw_message = ''
     self.parser = MessageParser()
示例#8
0
def get_serial(port: str = default_port,
               baud: int = default_baud) -> aioserial.AioSerial:
    ''' Opens a new serial connection
    params:
        port - the logical port on your computer for the microbit
        baud - the serial baud rate of the connect, defaults to 115200
    '''
    s: aioserial.AioSerial = aioserial.AioSerial(port=port, baudrate=baud)
    return s
示例#9
0
 def __init__(self, port):
     self.counter = 1
     self.aioserial_instance = aioserial.AioSerial(port)
     self.loop = asyncio.get_event_loop()
     try:
         self.loop.run_until_complete(self.receive_measurements())
     finally:
         self.loop.run_until_complete(
             self.loop.shutdown_asyncgens())  # Python 3.6 only
         self.loop.close()
示例#10
0
    def connect(self, deviceName):
        if deviceName not in self.configDut:
            raise AssertionError(
                'Device {} is not found, please check config file for it'.
                format(deviceName))

        dut = self.configDut[deviceName]
        dut['serialport'] = aioserial.AioSerial(port=dut['com'],
                                                baudrate=dut['baudrate'])
        print('Serial port {} opened successfully'.format(dut['com']))
示例#11
0
    def __init__(self, port: str, ipc_tunnel_address: str = ''):
        self.port: str = port
        self.baud: int = 115200
        self.serial_instance: aioserial.AioSerial = aioserial.AioSerial(self.port, self.baud)
        self.hooks: List[Tuple[Callable, str]] = []
        self.hook_repeat_count: int = 0

        self.load_buffer = StringIOQueue(4000)
        self.send_buffer = None

        self.progress_notifier: ProgressNotifier = ProgressNotifier(ipc_tunnel_address)
示例#12
0
    def __init__(self, serial_port=None, unit_id=0):
        import aioserial

        self.ser = aioserial.AioSerial(serial_port,
                                       baudrate=19200,
                                       parity="E",
                                       stopbits=1,
                                       timeout=0.02)

        # Unit id encoding is offset by 128 per GSIOC specification
        self.gsioc_id = 0x80 + unit_id
示例#13
0
def main():
    loop = asyncio.get_event_loop()
    signal.signal(signal.SIGINT, signal_handler)
    while True:
        try:
            global central_serial
            central_serial = aioserial.AioSerial(
                port=os.path.realpath('/dev/serial/by-id/usb-ZEPHYR_N39_BLE_KEYKEEPER_0.01-if00'))
            loop.run_until_complete(manage_serial(central_serial))
        except serial.serialutil.SerialException:
            print("LOST CONNECTION. RECONNECTING...", file=sys.stderr)
            loop.run_until_complete(asyncio.sleep(5))
示例#14
0
    def _open_stream(self, port, speed, homing):
        if self.dry_run:
            print("#DRY _open_stream: port=%s" % port)
            return

        self.s = aioserial.AioSerial(port=port, baudrate=speed)
        self.flush()
        # Go through homing or unlock
        if homing:
            self.send("$H")
        else:
            self.send("$X")
示例#15
0
    def __enter__(self):
        import aioserial

        self.ser = aioserial.AioSerial(
            self.serial_port, 115200, parity=aioserial.PARITY_NONE, stopbits=1
        )

        # Listen to sensor's self-introduction
        # (gives it time for internal init)
        self.ser.readline()

        return self
示例#16
0
 def __try_open_port(port):
     new_connection = aioserial.AioSerial()
     new_connection.port = port.device
     i = 0
     while not new_connection.is_open and i < 5:  # Make multiple attempts in case device is busy
         i += 1
         try:
             new_connection.open()
         except SerialException as e:
             time.sleep(1)
     if not new_connection.is_open:  # Failed to connect
         return False, None
     return True, new_connection
示例#17
0
    def __enter__(self):
        import aioserial

        self._ser = aioserial.AioSerial(
            self.serial_port,
            9600,
            parity=aioserial.PARITY_NONE,
            stopbits=1,
            timeout=0.1,
            write_timeout=0.1,
        )

        return self
示例#18
0
async def main(device: str):
    serial_port = aioserial.AioSerial(port=device, baudrate=115200)

    print("Talking with your device")
    meas = await get_measurement(serial_port)
    print(meas)
    if not meas:
        return
    print(
        "OK - Please rotate thru the range of brightnesses to determine the limits. Press enter when done"
    )
    brightness_extrema = RunningExtrema()
    input_task = asyncio.create_task(aioconsole.ainput())
    while True:
        meas = await get_measurement_or_enter(input_task, serial_port)
        if not meas:
            # they hit enter
            break
        if brightness_extrema.process(meas.brightness):
            print(brightness_extrema.min_val, brightness_extrema.max_val)
            if brightness_extrema.min_val == 0:
                print("Got a brightness of zero, not OK. Is your sensor connected right?")
                return

    print("OK, limits found.")
    if brightness_extrema.get_range() < 200:
        print(
            "Range not large enough: improve sensitivity of sensor or connection to display"
        )
        return

    print("OK, recording to disk, enter to stop.")
    with open(FILENAME, "w") as fp:
        # header row
        fp.write("us,drx,dry,drz,brightness\n")
        base_meas = await get_measurement(serial_port)
        if not base_meas:
            raise RuntimeError("Could not get our baseline timestamp")
        zero_time = base_meas.us
        # the task watching for the enter press
        input_task = asyncio.create_task(aioconsole.ainput())
        while True:
            meas = await get_measurement_or_enter(input_task, serial_port)
            if not meas:
                # they hit enter
                break

            # Offset the timestamp for ease of use.
            meas.us -= zero_time
            fp.write(meas.get_csv_line())
    print(f"All done! Go move/rename {FILENAME} and analyze it!")
示例#19
0
    def setup_connection(self):

        try:
            self.serialConection = aioserial.AioSerial(
                port=self.SERIAL_PORT,
                baudrate=self.BAUDRATE,
                bytesize=serial.EIGHTBITS,
                parity=serial.PARITY_NONE,
                stopbits=serial.STOPBITS_ONE,
                timeout=2,
                write_timeout=2)
            return self.serialConection
        except Exception as e:
            print(e)
示例#20
0
 async def connect_serial(self, websocket):
     print("Tentando conexão com a serial...")
     try:
         self.aio_instance = aioserial.AioSerial(port=self.port,
                                                 baudrate=self.baudrate)
         self.aio_instance.flush()
         print("Conexão estabelecida")
         self.is_connected = True
         await websocket.send(json.dumps(self.connected_json))
     except serial.serialutil.SerialException:
         self.is_connected = False
         await websocket.send(json.dumps(self.handshake_json))
         if self.logger_except != None:
             self.logger_except.exception('')
示例#21
0
    def __init__(self, device: str, timeout: int = 30, callback=None):
        """
        A connection to one or more Acmeda hubs on the given RS485 device.
        Timeout is how long to wait for any single response.
        A callback, if given, will be called as a task with parameters
        (hub, motor) when an update is detected.
        """
        self.device = device
        self.ser = aioserial.AioSerial(port=device,
                                       baudrate=9600,
                                       timeout=timeout)
        self.hubs: Dict[str, Hub] = {}
        self.callback = callback

        # Start a watcher
        asyncio.create_task(self.monitor_updates())
async def init_all(port=8001):
    # Open serial port
    ser = aioserial.AioSerial(port='/dev/ttyUSB1', baudrate=9600, timeout=2)
    print('Port opened')

    # Open socket
    reader, writer = await asyncio.open_connection('127.0.0.1', port)
    print('Socket opened')

    # Create queues
    from_serial = asyncio.Queue()
    to_serial = asyncio.Queue()

    # Run everything
    await asyncio.gather(serial_reader(ser, from_serial),
                         serial_writer(ser, to_serial),
                         socket_reader(reader, to_serial),
                         socket_writer(writer, from_serial))
示例#23
0
 async def serialConnect(self):
     # init serial
     self.serialIsConnecting = True
     self.serialIsConnected = False
     while self.serialIsConnected == False:
         try:
             print("... Waiting for serial Connection to {}".format(
                 self.serialData['path']))
             self.serial = aioserial.AioSerial(
                 port=self.serialData['path'],
                 baudrate=self.serialData['option']['baudRate'])
             self.serialIsConnected = True
             self.serialIsConnecting = False
             print("... Serial Connected")
         except:
             print("Serial Connection Failed")
             self.serialIsConnected = False
             await asyncio.sleep(2)
     return
示例#24
0
 def serial_init(self):
     """
     Synchronous function for initializing serial connection - deprecated as of 0.7
     """
     try:
         self.serial = aioserial.AioSerial(
             loop=self.loop,
             port=self.config.get("interface",
                                  {}).get("port", "/dev/serial0"),
             baudrate=self.config.get("interface",
                                      {}).get("baudrate", 115200),
         )
     except aioserial.serialutil.SerialException as e:
         self.logger.debug(
             "unable to connect to serial, trying again in 2 seconds. Exception: %s",
             str(e),
         )
         sleep(2)
         self.serial_init()
def main():
    SERIAL_PORT = 'COM4'
    BAUDRATE = 115200
    global result
    #
    serialConection = aioserial.AioSerial(port=SERIAL_PORT,
                                          baudrate=BAUDRATE,
                                          bytesize=serial.EIGHTBITS,
                                          parity=serial.PARITY_NONE,
                                          stopbits=serial.STOPBITS_ONE,
                                          timeout=2,
                                          write_timeout=2)
    #
    send = asyncio.run(write_serial(serialConection))
    print(send)
    #
    data = asyncio.run(read_and_print_serial(serialConection))
    #
    print("######################## RESULT ######################## ")
    print(data)
示例#26
0
async def main():
    parser = create_parser()
    args = parser.parse_args()
    counter = 0

    serial = aioserial.AioSerial(port=args.device.name, baudrate=BAUD_RATE)
    initialized = False
    running = True
    player = SoundPlayer()
    sounds_db = SoundsDB(args.greeting_dir, args.bye_dir, args.random_dir)

    while running:
        msg = (await serial.readline_async(-1)).decode(errors="ignore")
        eye_pos, closed, sound = unpack_msg(msg)

        #        print(f"sound {sound} player: {player.is_playing}")
        valid_sound = sound is not None and len(sound.strip()) > 0
        if valid_sound and not player.is_playing:
            sound_path = sounds_db.get_sound_file(sound)
            player.start_playing(sound_path)
示例#27
0
    async def run_async(self):
        self.current_coin = Coin()

        first_start = True
        while True:
            try:
                self.central_serial = aioserial.AioSerial(port=os.path.realpath(
                    '/dev/serial/by-id/usb-ZEPHYR_N39_BLE_KEYKEEPER_0.01-if00')
                                                          )
                self.central_serial.write(b'\r\n\r\n')
                if first_start:
                    self.central_serial.write(b'reboot\r\n')
                    first_start = False
                    await self._wait_until_done()

                else:
                    await self._manage_serial()
            except serial.serialutil.SerialException:
                os.write(self.status_pipe,
                         str("status: connecting to central").encode('utf8'))
                await asyncio.sleep(1)
示例#28
0
async def main():
    s = aioserial.AioSerial('/dev/cu.usbmodem3341731', baudrate=1000000)
    r = CobsReader(s)

    def handler(data):
        i, = struct.unpack_from("<I", data)
        print("Got {}".format(i))
        if i == 100:
            r.close()
            asyncio.get_event_loop().call_soon(
                lambda: asyncio.get_event_loop().stop())
        else:
            r.write(struct.pack("<I", i + 1))

    r.set_receiver(handler)
    r.run()

    # Kick off
    r.write(struct.pack("<I", 1))

    await asyncio.sleep(1)
示例#29
0
async def task_main(port, baudrate, client):
    inst = aioserial.AioSerial(port=port, baudrate=baudrate, rtscts=True)
    # Make sure app is running
    inst.send_break(.5)
    await cmd(inst, APP_CMD)
    # App doesn't respond until first input
    await cmd(inst, '')
    # Configure S-registers
    for srec in SREGISTER_VALUES:
        await cmd(inst, SREG_SET_CMD.format(srec[0], srec[1]))
    await cmd(inst, SREG_STORE_CMD)
    # Reset (no response)
    await inst.write_async(RESET_CMD.encode())
    # Wait for module to reboot
    time.sleep(2)
    # Start app again
    await cmd(inst, APP_CMD)
    await cmd(inst, '')
    # Start the scanning task
    asyncio.create_task(scan_and_filter(inst, client))
    while True:
        ## this will allow developers to have a responsive ctr-C
        await asyncio.sleep(1)
    )
    ch.setFormatter(formatter)
    logger.addHandler(ch)
    logger.setLevel(logging.DEBUG)

    hwid = "VID:PID=04D8:FD92"
    # https://stackoverflow.com/questions/24683987/executable-out-of-script-containing-serial-for-url/24688413#24688413
    # __import__('serial.urlhandler.protocol_hwgrep')
    # self.port = sys.modules['serial.urlhandler.protocol_hwgrep'].Serial(f'hwgrep://{hwid}')
    read_version()

    # port =
    # asyncio.run(read_and_print(aioserial.serial_for_url(f'hwgrep://{hwid}')))
    # port = aioserial.AioSerial(port="COM5")
    port = aioserial.serial_for_url(f"hwgrep://{hwid}")
    port_com = port.name
    logger.debug(f"name: {port_com}")
    port.close()

    port = aioserial.AioSerial(port=port_com)
    # # port = serial.serial_for_url(f'hwgrep://{hwid}')
    # port.write("V".encode('ascii')+b'\r')
    # time.sleep(0.05)
    # b = port.in_waiting
    # print(port.read(size=b))
    # port.close()
    start_time = time.time()
    asyncio.run(write_and_read(port))
    duration = time.time() - start_time
    logger.debug(f"duration: {duration}")