def test_asyncio(self):
        TEXT = b'hello world\n'
        received = []
        actions = []

        class Output(asyncio.Protocol):
            def connection_made(self, transport):
                self.transport = transport
                actions.append('open')
                transport.serial.rts = False
                transport.write(TEXT)

            def data_received(self, data):
                #~ print('data received', repr(data))
                received.append(data)
                if b'\n' in data:
                    self.transport.close()

            def connection_lost(self, exc):
                actions.append('close')
                asyncio.get_event_loop().stop()

            def pause_writing(self):
                actions.append('pause')
                print(self.transport.get_write_buffer_size())

            def resume_writing(self):
                actions.append('resume')
                print(self.transport.get_write_buffer_size())

        coro = serial_asyncio.create_serial_connection(self.loop, Output, PORT, baudrate=115200)
        self.loop.run_until_complete(coro)
        self.loop.run_forever()
        self.assertEqual(b''.join(received), TEXT)
        self.assertEqual(actions, ['open', 'close'])
Beispiel #2
0
def open(port):
    global transport
    loop = asyncio.get_event_loop()
    reader = asyncio.StreamReader()
    proto = asyncio.StreamReaderProtocol(reader)
    transport, _ = yield from serial_asyncio.create_serial_connection(
        loop, lambda: proto, url=port, baudrate=115200)
    return transport
    def test_asyncio(self):
        TEXT = b'Hello, World!\n'
        received = []
        actions = []

        class Input(asyncio.Protocol):

            def __init__(self):
                super().__init__()
                self._transport = None

            def connection_made(self, transport):
                self._transport = transport

            def data_received(self, data):
                self._transport.write(data)

        class Output(asyncio.Protocol):

            def __init__(self):
                super().__init__()
                self._transport = None

            def connection_made(self, transport):
                self._transport = transport
                actions.append('open')
                transport.write(TEXT)

            def data_received(self, data):
                received.append(data)
                if b'\n' in data:
                    self._transport.close()

            def connection_lost(self, exc):
                actions.append('close')
                self._transport.loop.stop()

            def pause_writing(self):
                actions.append('pause')
                print(self._transport.get_write_buffer_size())

            def resume_writing(self):
                actions.append('resume')
                print(self._transport.get_write_buffer_size())

        if PORT.startswith('socket://'):
            coro = self.loop.create_server(Input, HOST, _PORT)
            self.loop.run_until_complete(coro)

        client = serial_asyncio.create_serial_connection(self.loop, Output, PORT)
        self.loop.run_until_complete(client)
        self.loop.run_forever()
        self.assertEqual(b''.join(received), TEXT)
        self.assertEqual(actions, ['open', 'close'])
Beispiel #4
0
def main():
    application = tornado.web.Application([
        (r'/ws', WSHandler),
        (r"/static/(.*)", tornado.web.StaticFileHandler, dict(path=SCRIPT_PATH)),
        (r'/(.*)', MainHandler),
    ])

    tornado.platform.asyncio.AsyncIOMainLoop().install()
    loop = asyncio.get_event_loop()

    config = json.load(open(os.path.join(SCRIPT_PATH, 'server.json')))
    if 'serial' in config:
        # TODO: Ugly fugly, please fix
        Denon.connected  = asyncio.Event(loop=loop)
        asyncio.ensure_future(
                serial_asyncio.create_serial_connection(
                    loop, Denon, config['serial'], baudrate=9600))
        loop.run_until_complete(Denon.connected.wait())
        denon = Denon.instance

        mqtt_client = MQTTClient(
                denon, config['mqtt_host'], config['mqtt_user'], config['mqtt_pass'])
        loop.run_until_complete(mqtt_client.start())
    else:
        denon = MQTTDenon(config['mqtt_host'], config['mqtt_user'], config['mqtt_pass'])

    MainHandler.denon = denon
    MainHandler.config = config

    loop.run_until_complete(denon.start())
    loop.run_until_complete(denon.request_status())

    http_server = tornado.httpserver.HTTPServer(application)
    if 'http_addr' in config:
        http_server.listen(config['http_port'], address=config['http_addr'])
    else:
        http_server.listen(config['http_port'])

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass

    print("Stopping")
    loop.run_until_complete(denon.stop())
    if 'serial' in config:
        loop.run_until_complete(mqtt_client.stop())
    loop.stop()
Beispiel #5
0
    def connect(self):
        """
        Connect Async client
        :return:
        """
        _logger.debug('Connecting.')
        try:
            from serial_asyncio import create_serial_connection

            yield from create_serial_connection(
                self.loop, self._create_protocol, self.port, baudrate=self.baudrate,
                bytesize=self.bytesize, stopbits=self.stopbits
            )
            yield from self._connected_event.wait()
            _logger.info('Connected to %s', self.port)
        except Exception as ex:
            _logger.warning('Failed to connect: %s', ex)
Beispiel #6
0
    for avatar_conf in conf['avatars']:
        name = avatar_conf['name']

        if name in avatars:
            raise Error('Cannot have two Avatars with the same name: ' +
                        str(avatar_conf['name']))

        callbacks = []
        callbacks.append(
            lambda x: log.debug("Status from[%s]: %s", name, repr(x)))
        callbacks.append(
            lambda x: datawriter.writerow(status_to_list(name, x)))
        callbacks.append(functools.partial(fastrack_emitter.emit, name))

        avatar_obj = avatar.AvatarProtocol(name, callbacks)
        avatar_coro = serial_asyncio.create_serial_connection(
            loop, lambda: avatar_obj, '/dev/ttyUSB0', baudrate=9600)
        avatar_task = loop.run_until_complete(avatar_coro)

        avatars[name] = avatar_obj

    # Create web server.
    web_handler = web.WabatarServer(avatars).new_handler()
    web_task = loop.run_until_complete(
        loop.create_server(web_handler, '0.0.0.0', 8080))

    try:
        loop.run_forever()
    finally:
        web_task.close()
        loop.run_until_complete(fastrack_emitter.stop())
        loop.run_until_complete(web_task.wait_closed())
Beispiel #7
0
    def connection_lost(self, exc):
        print('Writer closed')

    async def send(self):
        """Send four newline-terminated messages, one byte at a time.
        """
        message = b'foo\nbar\nbaz\nqux\n'
        for b in message:
            await asyncio.sleep(0.5)
            self.transport.serial.write(bytes([b]))
            print(f'Writer sent: {bytes([b])}')
        self.transport.close()


loop = asyncio.get_event_loop()
reader = serial_asyncio.create_serial_connection(loop,
                                                 Reader,
                                                 'reader',
                                                 baudrate=115200)
writer = serial_asyncio.create_serial_connection(loop,
                                                 Writer,
                                                 'writer',
                                                 baudrate=115200)
asyncio.ensure_future(reader)
print('Reader scheduled')
asyncio.ensure_future(writer)
print('Writer scheduled')
loop.call_later(10, loop.stop)
loop.run_forever()
print('Done')
Beispiel #8
0
    async def initLink(self, strconnection: str):
        """Try initialising a connection. returns True if connection
        was successful, False otherwise"""
        constr = strconnection.split(":")
        newlink = None
        try:
            if constr[0] == "udpserver":
                newlink = UDPConnection(rxcallback=self.incomingPacket,
                                        clcallback=self.closelinkcallback,
                                        dialect=self.dialect,
                                        mavversion=self.mavversion,
                                        server=True,
                                        srcsystem=self.sourceSystem,
                                        srccomp=self.sourceComponent,
                                        name=strconnection)
                trans = self.loop.create_datagram_endpoint(
                    lambda: newlink, local_addr=(constr[1], constr[2]))
                await asyncio.wait_for(trans, timeout=0.2)
            elif constr[0] == "udpclient":
                newlink = UDPConnection(rxcallback=self.incomingPacket,
                                        clcallback=self.closelinkcallback,
                                        dialect=self.dialect,
                                        mavversion=self.mavversion,
                                        server=False,
                                        srcsystem=self.sourceSystem,
                                        srccomp=self.sourceComponent,
                                        name=strconnection)
                trans = self.loop.create_datagram_endpoint(
                    lambda: newlink, remote_addr=(constr[1], constr[2]))
                await asyncio.wait_for(trans, timeout=0.2)
            elif constr[0] == "serial":
                newlink = SerialConnection(rxcallback=self.incomingPacket,
                                           clcallback=self.closelinkcallback,
                                           dialect=self.dialect,
                                           mavversion=self.mavversion,
                                           srcsystem=self.sourceSystem,
                                           srccomp=self.sourceComponent,
                                           name=strconnection)
                trans = serial_asyncio.create_serial_connection(self.loop, lambda: newlink,
                                                                constr[1], int(constr[2]))
                await asyncio.wait_for(trans, timeout=0.2)
            elif constr[0] == "tcpclient":
                newlink = TCPConnection(rxcallback=self.incomingPacket,
                                        clcallback=self.closelinkcallback,
                                        dialect=self.dialect,
                                        mavversion=self.mavversion,
                                        server=False,
                                        srcsystem=self.sourceSystem,
                                        srccomp=self.sourceComponent,
                                        name=strconnection)
                trans = self.loop.create_connection(
                    lambda: newlink, constr[1], int(constr[2]))
                await asyncio.wait_for(trans, timeout=0.2)
            elif constr[0] == "tcpserver":
                newlink = TCPConnection(rxcallback=self.incomingPacket,
                                        clcallback=self.closelinkcallback,
                                        dialect=self.dialect,
                                        mavversion=self.mavversion,
                                        server=True,
                                        srcsystem=self.sourceSystem,
                                        srccomp=self.sourceComponent,
                                        name=strconnection)

                await self.loop.create_server(lambda: newlink, constr[1], int(constr[2]))
            else:
                logging.debug("Bad link type: %s", constr)
                return False
            # ok, we've got a link
            self.linkdict[strconnection] = newlink
            logging.debug("Added link - %s", strconnection)
            return True
        except(OSError, asyncio.TimeoutError):
            logging.debug("Can't connect - %s", strconnection)
            self.linkdict[strconnection] = None
            return False
Beispiel #9
0
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software Foundation,
#   Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA

import asyncio
import logging

import serial_asyncio

from pyduofern.duofern_stick import DuofernStickAsync

logging.basicConfig(level=logging.DEBUG)
loop = asyncio.get_event_loop()

coro = serial_asyncio.create_serial_connection(loop,
                                               lambda: DuofernStickAsync(loop),
                                               '/dev/ttyUSB0',
                                               baudrate=115200)
f, proto = loop.run_until_complete(coro)
# proto.handshake()

initialization = asyncio. async (proto.handshake())
asyncio.wait(initialization)


def cb(a):
    logging.info(a)
    asyncio. async (proto.command("409882", "position", 10))


proto.available.add_done_callback(cb)
Beispiel #10
0
        print(self.transport.get_write_buffer_size())
        print('resume writing')


# https://docs.python.org/3/library/asyncio-eventloop.html
# asyncio.get_event_loop() :
# Function: get the current event loop OR create a new event loop and set it as the current one
# IF there is no current event loop set in the current OS thread,
# AND set_event_loop() has not yet been called
# THEN asyncio will create a new event loop and set it as the current one
loop = asyncio.get_event_loop()

# serial_asyncio.create_serial_connection(loop, protocol_factory, *args, **kwargs)
#   Function: Get a connection making coroutine
# Parameters:
#           loop - The event handler
#           protocol_factory - Factory function(asyncio.coroutine) for a asyncio.Protocol
#           args, kwargs - Passed to the serial.Serial init function
coro = serial_asyncio.create_serial_connection(loop,
                                               Output,
                                               '/dev/ttyAMA0',
                                               baudrate=2000000)

# loop.run_until_complete(future)
# Function: run until the future(an instance of Future) has completed
#           If the argument is a coroutine object it is implicitly scheduled to run as a asyncio.Task
loop.run_until_complete(coro)

loop.run_forever()
loop.close()
Beispiel #11
0
        self._transport = transport
        print('port opened', self._transport)
        self._transport.serial.rts = False
        self._transport.write(b'Hello, World!\n')

    def data_received(self, data):
        print('data received', repr(data))
        if b'\n' in data:
            self._transport.close()

    def connection_lost(self, exc):
        print('port closed')
        self._transport.loop.stop()

    def pause_writing(self):
        print('pause writing')
        print(self._transport.get_write_buffer_size())

    def resume_writing(self):
        print(self._transport.get_write_buffer_size())
        print('resume writing')


loop = asyncio.get_event_loop()
coro = create_serial_connection(loop,
                                Output,
                                '/dev/tty.usbmodem1424421',
                                baudrate=115200)
loop.run_until_complete(coro)
loop.run_forever()
loop.close()
            ports = ['COM%s' % (i + 1) for i in range(256)]
        elif sys.platform.startswith('linux') or \
                sys.platform.startswith('cygwin'):
            # this excludes your current terminal "/dev/tty"
            # ports = glob.glob('/dev/tty[A-Za-z]*')
            # modification to show ONLY Arduinos
            ports = glob.glob('/dev/tty[A-Z]*')
        elif sys.platform.startswith('darwin'):
            ports = glob.glob('/dev/tty.*')
        else:
            raise EnvironmentError('Unsupported platform')

        result = []
        for port in ports:
            try:
                s = serial.Serial(port)
                s.close()
                result.append(port)
            except (OSError, serial.SerialException):
                pass
        return result


port = Output.list_serial_ports().pop()
loop = asyncio.get_event_loop()
coro = serial_asyncio.create_serial_connection(loop, Output, port,
                                               baudrate=9600)
loop.run_until_complete(coro)
loop.run_forever()
loop.close()
Beispiel #13
0
    async def connect(self):
        if self.ev_connected.is_set():
            log.warning("already connected")
            return False
        self.ack_queue = asyncio.Queue(self.firmware.max_buffer_lenght)
        self.tx_queue = asyncio.Queue(1)
        rx_queue = asyncio.Queue()
        is_alive = asyncio.Event()

        await self.store('idle', True)

        self.ev_resume = asyncio.Event()
        self.ev_resume.set()
        self.panic_mode = False

        port_spec = re.compile("^(.+)://(.+)[@:]([0-9]+)$")
        port = self.cfg["port"].strip()
        if not port_spec.match(port):
            log.error("port property in configuration not parsable.")
            return False

        def connect_cb(ev_done, ev_connected, future):
            try:
                r = future.result()
            except concurrent.futures._base.CancelledError:
                log.debug('Connect task cancelled')
            except FileNotFoundError as e:
                log.error(str(e))
            except serial.serialutil.SerialException as e:
                log.error(str(e))
            except OSError as e:
                log.error(str(e))
            except Exception as e:
                log.critical("Unhandled exception: {}".format(str(e)))
                log.critical(traceback.format_exc())
            else:
                ev_connected.set()
            finally:
                ev_done.set()

        log.info("device '{}' trying to connect...".format(self.get_name()))
        ## the result must have three groups exactly"
        proto, addr, param = port_spec.findall(port)[
            0]  ## we can only have one
        ev_done = asyncio.Event()
        loop = self.gctx['loop']
        if proto == 'dummy':
            DummySerialConnection(self, rx_queue)
            ev_done.set()
            self.ev_connected.set()
        elif proto == 'serial':
            coro = serial_asyncio.create_serial_connection(loop,
                                                           functools.partial(
                                                               CncConnection,
                                                               self, rx_queue),
                                                           addr,
                                                           baudrate=param)
            self.tx_task = asyncio.ensure_future(coro)
            self.tx_task.add_done_callback(
                functools.partial(connect_cb, ev_done, self.ev_connected))
        elif proto == 'tcp':
            coro = loop.create_connection(
                functools.partial(CncConnection, self, rx_queue), addr, param)
            self.tx_task = asyncio.ensure_future(coro)
            self.tx_task.add_done_callback(
                functools.partial(connect_cb, ev_done, self.ev_connected))
        else:
            log.error("can't understand portspec")
            return False

        await ev_done.wait()
        if not self.ev_connected.is_set():
            log.error("Failed to connect.")
            return False
        await self.store('connected', True)

        self.tx_task = asyncio.ensure_future(
            self.sender(self.tx_queue, self.ack_queue, is_alive))
        self.tx_task.add_done_callback(self.task_done)
        self.rx_task = asyncio.ensure_future(
            self.receiver(rx_queue, self.ack_queue, is_alive))
        self.rx_task.add_done_callback(self.task_done)
        return True
Beispiel #14
0
    def start_message(self):
        self.reply = bytearray()

    def feed_message(self, byte):
        self.reply.append(byte)

    def end_message(self):
        print('\n<- {}'.format(bytes(self.reply)), flush=True)
        self.prompt()

    def prompt(self):
        print('?? ', end='', flush=True)


loop = asyncio.get_event_loop()
coro = serial_asyncio.create_serial_connection(
    loop,
    WJMx50,
    '/dev/ttyUSB0',  # or whatever yr comport is
    bytesize=serial.EIGHTBITS,  #.SEVENBITS, - EIGHTBITS for extron
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE)
loop.run_until_complete(coro)
loop.run_forever()
loop.close()
'''
PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE = 'N', 'E', 'O', 'M', 'S'
STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO = (1, 1.5, 2)
FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS = (5, 6, 7, 8)
'''
Beispiel #15
0
        print("port opened", transport)
        # transport.serial.rts = False  # You can manipulate Serial object via transport
        transport.write(b"Hello, World!\n")  # Write serial data via transport

    def data_received(self, data):
        print("data received", repr(data))
        if b"\n" in data:
            self.transport.close()

    def connection_lost(self, exc):
        print("port closed")
        self.transport.loop.stop()

    def pause_writing(self):
        print("pause writing")
        print(self.transport.get_write_buffer_size())

    def resume_writing(self):
        print(self.transport.get_write_buffer_size())
        print("resume writing")


loop = asyncio.get_event_loop()
coro = serial_asyncio.create_serial_connection(loop,
                                               Output,
                                               "/dev/ttyACM0",
                                               baudrate=115200)
loop.run_until_complete(coro)
loop.run_forever()
loop.close()
Beispiel #16
0
def async_setup(hass, config):
    """ Setup the ZiGate platform """
    import serial_asyncio
    from .zigate2hass import ZiGateProtocol, ZiGate2HASS
    from pyzigate.interface import ZiGate

    _LOGGER.debug('ZIGATE : Starting')

    # device interpreter
    zigate = ZiGate2HASS(hass)

    # Go through config and find all addresses of zigate devices
    _LOGGER.debug('ZIGATE : Finding zigate addresses')
    for domain_config in config.keys():
        if domain_config in COMPONENT_TYPES:
            for platform_config in config[domain_config]:
                if platform_config['platform'] == DOMAIN:
                    if 'address' in platform_config.keys():
                        zigate.add_known_device(
                            str(platform_config['address'])[:6])
    _LOGGER.debug('ZIGATE : All known addresses added')

    # Commands available as HASS services
    def permit_join(call):
        """Put ZiGate in Permit Join mode and register new devices"""
        zigate.permit_join()

    def raw_command(call):
        """send a raw command to ZiGate"""
        cmd = call.data.get('cmd', '')
        data = call.data.get('data', '')
        zigate.send_data(cmd, data)

    def zigate_init(call):
        channel = call.data.get('channel', DEFAULT_CHANNEL)
        zigate.send_data('0021', '0000%02x00' % int(channel))  # Channel
        zigate.send_data('0023', '00')  # Coordinator
        zigate.send_data('0024', '')  # Start network

    hass.services.async_register(DOMAIN, 'permit_join', permit_join)
    hass.services.async_register(DOMAIN, 'raw_command', raw_command)
    hass.services.async_register(DOMAIN, 'init', zigate_init)

    # Asyncio serial connection to the device
    # If HOST is configured, then connection is WiFi
    if config[DOMAIN].get(CONF_HOST) is "":
        # Serial
        coro = serial_asyncio.create_serial_connection(
            hass.loop,
            ZiGateProtocol,
            config[DOMAIN].get(CONF_SERIAL_PORT),
            baudrate=config[DOMAIN].get(CONF_BAUDRATE))
    else:
        # WiFi
        coro = hass.loop.create_connection(ZiGateProtocol,
                                           host=config[DOMAIN].get(CONF_HOST),
                                           port=config[DOMAIN].get(CONF_PORT))

    future = hasync.run_coroutine_threadsafe(coro, hass.loop)
    # bind connection to the device interpreter
    future.add_done_callback(partial(bind_transport_to_device, zigate))
    return True
Beispiel #17
0
        #await asyncio.sleep(random.randint(0, 6))
        await asyncio.sleep(3)
        queue.task_done()


async def main():
    loop = asyncio.get_event_loop()
    queue = asyncio.Queue(loop=loop)
    produce = partial(Reader, queue)
    producer_coro = serial_asyncio.create_serial_connection(
        loop, produce, com, baudrate)
    consumer_coro = consume(queue)
    await producer_coro
    await consumer_coro
    #await asyncio.gather(producer_coro, consumer_coro)


#asyncio.run(main()) # after 3.7.0

# before 3.7.0
loop = asyncio.get_event_loop()
queue = asyncio.Queue(loop=loop)

produce = partial(Reader, queue)
producer_coro = serial_asyncio.create_serial_connection(
    loop, produce, com, baudrate)
print(producer_coro)
consumer_coro = consume(queue)
loop.run_until_complete(asyncio.gather(producer_coro, consumer_coro))
loop.close()
                data = yield from self.send_queue.get()
                self.transport.write(data)
            except asyncio.CancelledError:
                logger.info("Got CancelledError, stopping send loop")
                break
            logger.debug("sending {}".format(data))

    def connection_lost(self, exc):
        print('The server closed the connection')
        print('Stop the event loop')

        self.loop.stop()


loop = asyncio.get_event_loop()
coro = serial_asyncio.create_serial_connection(loop, lambda: Output(loop), '/dev/ttyUSB0', baudrate=115200)

running = True


def one_time_callback(protocol, _message, name, future):
    logger.info("{} answer for {}".format(_message, name))
    if not future.cancelled():
        future.set_result(_message)
        protocol.callback = None

@asyncio.coroutine
def send_and_await_reply(protocol, message, message_identifier):
    future = asyncio.Future()
    protocol.callback = lambda message: one_time_callback(protocol, message, message_identifier, future)
    yield from protocol.send_message(message.encode("utf-8"))
Beispiel #19
0
        
    client.on_message = on_message

    lwtPublish = client.publish(mqtt_topicBase + "/LWT", 'ON')
    await lwtPublish.wait_for_publish()
    print("MQTT LWT published!")

    while True:
        msg = await mqttTxQueue.get()
        try:
            msgPublish = client.publish(mqtt_topicBase + msg[0], msg[1], retain=msg[2])
            await msgPublish.wait_for_publish()
            print("MQTT publish - Retain: " + str(msg[2]) + " Topic: " + mqtt_topicBase + msg[0] + " - Message: " + str(msg[1]))
        except IndexError:
            print("MQTT publish failed: ")
            print(msg)

canRxQueue = asyncio.Queue()
canTxQueue = asyncio.Queue()
mqttTxQueue = asyncio.Queue()
canPartial = partial(canRxTx, canRxQueue, canTxQueue)

loop = asyncio.get_event_loop()
canAIO = serial_asyncio.create_serial_connection(loop, canPartial, port, baudrate=baud)
asyncio.ensure_future(canAIO)
asyncio.ensure_future(procCANRx(canRxQueue, mqttTxQueue))
asyncio.ensure_future(mqtt(mqttTxQueue, canTxQueue, mqtt_server, mqtt_port, mqtt_topicBase, mqtt_user, mqtt_pass, mqtt_ca))

loop.run_forever()
loop.close()
def get_async_blackbird2(port_url, loop):
    """
    Return asynchronous version of Blackbird2 interface
    :param port_url: serial port, i.e. '/dev/ttyUSB0'
    :return: asynchronous implementation of blackbird2 interface
    """

    lock = asyncio.Lock()

    def locked_coro(coro):
        @asyncio.coroutine
        @wraps(coro)
        def wrapper(*args, **kwargs):
            with (yield from lock):
                return (yield from coro(*args, **kwargs))

        return wrapper

    class blackbird2Async(blackbird2):
        def __init__(self, blackbird2_protocol):
            self._protocol = blackbird2_protocol

        @locked_coro
        @asyncio.coroutine
        def zone_status(self, zone: int):
            string = yield from self._protocol.send(
                _format_zone_status_request(zone), skip=15)
            return ZoneStatus.from_string(zone, string)

        @locked_coro
        @asyncio.coroutine
        def set_zone_power(self, zone: int, power: bool):
            yield from self._protocol.send(_format_set_zone_power(zone, power))

        @locked_coro
        @asyncio.coroutine
        def set_zone_source(self, zone: int, source: int):
            yield from self._protocol.send(
                _format_set_zone_source(zone, source))

        @locked_coro
        @asyncio.coroutine
        def set_zone_source_no_ir(self, zone: int, source: int):
            yield from self._protocol.send(
                _format_set_zone_source_no_ir(zone, source))

        @locked_coro
        @asyncio.coroutine
        def set_all_zone_source(self, source: int):
            yield from self._protocol.send(_format_set_all_zone_source(source))

        @locked_coro
        @asyncio.coroutine
        def lock_front_buttons(self):
            yield from self._protocol.send(_format_lock_front_buttons())

        @locked_coro
        @asyncio.coroutine
        def unlock_front_buttons(self):
            yield from self._protocol.send(_format_unlock_front_buttons())

        @locked_coro
        @asyncio.coroutine
        def lock_status(self):
            string = yield from self._protocol.send(_format_lock_status())
            return LockStatus.from_string(string)

    class blackbird2Protocol(asyncio.Protocol):
        def __init__(self, loop):
            super().__init__()
            self._loop = loop
            self._lock = asyncio.Lock()
            self._transport = None
            self._connected = asyncio.Event(loop=loop)
            self.q = asyncio.Queue(loop=loop)

        def connection_made(self, transport):
            self._transport = transport
            self._connected.set()
            _LOGGER.debug('port opened %s', self._transport)

        def data_received(self, data):
            asyncio.ensure_future(self.q.put(data), loop=self._loop)

        @asyncio.coroutine
        def send(self, request: bytes, skip=0):
            yield from self._connected.wait()
            result = bytearray()
            # Only one transaction at a time
            with (yield from self._lock):
                self._transport.serial.reset_output_buffer()
                self._transport.serial.reset_input_buffer()
                while not self.q.empty():
                    self.q.get_nowait()
                self._transport.write(request)
                try:
                    while True:
                        result += yield from asyncio.wait_for(self.q.get(),
                                                              TIMEOUT,
                                                              loop=self._loop)
                        if len(result) > skip and result[-LEN_EOL:] == EOL:
                            ret = bytes(result)
                            _LOGGER.debug('Received "%s"', ret)
                            return ret.decode('ascii')
                except asyncio.TimeoutError:
                    _LOGGER.error(
                        "Timeout during receiving response for command '%s', received='%s'",
                        request, result)
                    raise

    _, protocol = yield from create_serial_connection(loop,
                                                      functools.partial(
                                                          blackbird2Protocol,
                                                          loop),
                                                      port_url,
                                                      baudrate=9600)

    return blackbird2Async(protocol)
Beispiel #21
0
    }
    async with session.post(config.endpoint, json=post_data) as resp:
        print("hitting endpoint")
        print(resp.status)
        print(await resp.text())


class Output(asyncio.Protocol):
    def connection_made(self, transport):
        self.transport = transport
        print("port opened", transport)

    def data_received(self, data):
        print("data received", repr(data))
        loop.create_task(post_data(data))
        if b"\n" in data:
            self.transport.close()

    def connection_lost(self, exc):
        print("port closed")
        self.transport.loop.stop()


serial_monitor = serial_asyncio.create_serial_connection(loop,
                                                         Output,
                                                         config.serial_port,
                                                         baudrate=config.baud)
loop.run_until_complete(serial_monitor)
loop.run_forever()
loop.close()
def get_async_monoprice(port_url, loop):
    """
    Return asynchronous version of Monoprice interface
    :param port_url: serial port, i.e. '/dev/ttyUSB0'
    :return: asynchronous implementation of Monoprice interface
    """

    lock = asyncio.Lock()

    def locked_coro(coro):
        @asyncio.coroutine
        @wraps(coro)
        def wrapper(*args, **kwargs):
            with (yield from lock):
                return (yield from coro(*args, **kwargs))

        return wrapper

    class MonopriceAsync(Monoprice):
        def __init__(self, monoprice_protocol):
            self._protocol = monoprice_protocol

        @locked_coro
        @asyncio.coroutine
        def zone_status(self, zone: int):
            # Ignore first 6 bytes as they will contain 3 byte command and 3 bytes of EOL
            string = yield from self._protocol.send(
                _format_zone_status_request(zone), skip=6)
            return ZoneStatus.from_string(string)

        @locked_coro
        @asyncio.coroutine
        def set_power(self, zone: int, power: bool):
            yield from self._protocol.send(_format_set_power(zone, power))

        @locked_coro
        @asyncio.coroutine
        def set_mute(self, zone: int, mute: bool):
            yield from self._protocol.send(_format_set_mute(zone, mute))

        @locked_coro
        @asyncio.coroutine
        def set_volume(self, zone: int, volume: int):
            yield from self._protocol.send(_format_set_volume(zone, volume))

        @locked_coro
        @asyncio.coroutine
        def set_treble(self, zone: int, treble: int):
            yield from self._protocol.send(_format_set_treble(zone, treble))

        @locked_coro
        @asyncio.coroutine
        def set_bass(self, zone: int, bass: int):
            yield from self._protocol.send(_format_set_bass(zone, bass))

        @locked_coro
        @asyncio.coroutine
        def set_balance(self, zone: int, balance: int):
            yield from self._protocol.send(_format_set_balance(zone, balance))

        @locked_coro
        @asyncio.coroutine
        def set_source(self, zone: int, source: int):
            yield from self._protocol.send(_format_set_source(zone, source))

        @locked_coro
        @asyncio.coroutine
        def restore_zone(self, status: ZoneStatus):
            yield from self._protocol.send(
                _format_set_power(status.zone, status.power))
            yield from self._protocol.send(
                _format_set_mute(status.zone, status.mute))
            yield from self._protocol.send(
                _format_set_volume(status.zone, status.volume))
            yield from self._protocol.send(
                _format_set_treble(status.zone, status.treble))
            yield from self._protocol.send(
                _format_set_bass(status.zone, status.bass))
            yield from self._protocol.send(
                _format_set_balance(status.zone, status.balance))
            yield from self._protocol.send(
                _format_set_source(status.zone, status.source))

    class MonopriceProtocol(asyncio.Protocol):
        def __init__(self, loop):
            super().__init__()
            self._loop = loop
            self._lock = asyncio.Lock()
            self._transport = None
            self._connected = asyncio.Event(loop=loop)
            self.q = asyncio.Queue(loop=loop)

        def connection_made(self, transport):
            self._transport = transport
            self._connected.set()
            _LOGGER.debug('port opened %s', self._transport)

        def data_received(self, data):
            asyncio.ensure_future(self.q.put(data), loop=self._loop)

        @asyncio.coroutine
        def send(self, request: bytes, skip=0):
            yield from self._connected.wait()
            result = bytearray()
            # Only one transaction at a time
            with (yield from self._lock):
                self._transport.serial.reset_output_buffer()
                self._transport.serial.reset_input_buffer()
                while not self.q.empty():
                    self.q.get_nowait()
                self._transport.write(request)
                try:
                    while True:
                        result += yield from asyncio.wait_for(self.q.get(),
                                                              TIMEOUT,
                                                              loop=self._loop)
                        if len(result) > skip and result[-LEN_EOL:] == EOL:
                            ret = bytes(result)
                            _LOGGER.debug('Received "%s"', ret)
                            return ret.decode('ascii')
                except asyncio.TimeoutError:
                    _LOGGER.error(
                        "Timeout during receiving response for command '%s', received='%s'",
                        request, result)
                    raise

    _, protocol = yield from create_serial_connection(loop,
                                                      functools.partial(
                                                          MonopriceProtocol,
                                                          loop),
                                                      port_url,
                                                      baudrate=9600)
    return MonopriceAsync(protocol)
                        metavar='WAMP_REALM',
                        default=os.getenv("NERDRAGE_WAMP_REALM"))
    parser.add_argument('--port',
                        metavar='SERIAL_PORT',
                        default=os.getenv("NERDRAGE_SERIAL_PORT"))

    args = parser.parse_args()
    print(f'WAMP server address: {args.address}')
    print(f'WAMP realm:          {args.realm}')
    print(f'Serial port:         {args.port}')

    loop = asyncio.get_event_loop()

    serial_coro = serial_asyncio.create_serial_connection(
        loop,
        nerdrage_controller_bridge.NerdRageControllerSerialProtocol,
        args.port,
        baudrate=115200)
    loop.run_until_complete(serial_coro)

    runner = autobahn.asyncio.wamp.ApplicationRunner(args.address, args.realm)
    wamp_session_coro = runner.run(
        nerdrage_controller_bridge.NerdRageControllerBridgeWampSession,
        start_loop=False)
    loop.run_until_complete(wamp_session_coro)

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        print("exit")
    finally:
Beispiel #24
0
        self.transport = transport
        print('port opened', transport)
        transport.serial.rts = False  # You can manipulate Serial object via transport
        transport.write(b'Hello, World!\n')  # Write serial data via transport

    def data_received(self, data):
        print('data received', repr(data))
        if b'\n' in data:
            self.transport.close()

    def connection_lost(self, exc):
        print('port closed')
        self.transport.loop.stop()

    def pause_writing(self):
        print('pause writing')
        print(self.transport.get_write_buffer_size())

    def resume_writing(self):
        print(self.transport.get_write_buffer_size())
        print('resume writing')


loop = asyncio.get_event_loop()
coro = serial_asyncio.create_serial_connection(loop,
                                               Output,
                                               '/dev/ttyUSB0',
                                               baudrate="external_parameters")
loop.run_until_complete(coro)
loop.run_forever()
loop.close()
Beispiel #25
0
            print('Received: {!r}'.format(command_raw))
        try:
            packet_ascii = self.interface.process_command(tokens)
            if tokens[-1] not in skip_print:
                print('Sending: {!r}'.format(packet_ascii))
            self.transport.write(packet_ascii.encode())
        except Exception:
            print("INVALID")
        fut = asyncio.ensure_future(cmd_queue.get())
        fut.add_done_callback(self.process_user_input)


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.add_reader(sys.stdin, process_stdin_data, cmd_queue)
    coroutine0 = serial_asyncio.create_serial_connection(
        loop, CANUartServer, '/dev/tty232-0', 115200)
    loop.run_until_complete(coroutine0)
    coroutine1 = serial_asyncio.create_serial_connection(
        loop, EncoderUartServer, '/dev/ttyJ1', 115200)
    loop.run_until_complete(coroutine1)
    coroutine2 = loop.create_server(IOServer, '127.0.0.1', 1978)
    server = loop.run_until_complete(coroutine2)
    coroutine3 = loop.create_task(periodic_polling())
    coroutine4 = loop.create_task(process_response())
    loop.run_until_complete(asyncio.gather(coroutine3, coroutine4))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass

    # Close the server
Beispiel #26
0
        try:
            msgPublish = client.publish(mqtt_topicBase + msg[0],
                                        msg[1],
                                        retain=msg[2])
            await msgPublish.wait_for_publish()
            print("MQTT publish - Retain: " + str(msg[2]) + " Topic: " +
                  mqtt_topicBase + msg[0] + " - Message: " + str(msg[1]))
        except IndexError:
            print("MQTT publish failed: ")
            print(msg)


canRxQueue = asyncio.Queue()
canTxQueue = asyncio.Queue()
mqttTxQueue = asyncio.Queue()
canPartial = partial(canRxTx, canRxQueue, canTxQueue)

loop = asyncio.get_event_loop()
canAIO = serial_asyncio.create_serial_connection(loop,
                                                 canPartial,
                                                 port,
                                                 baudrate=baud)
asyncio.ensure_future(canAIO)
asyncio.ensure_future(procCANRx(canRxQueue, mqttTxQueue))
asyncio.ensure_future(
    mqtt(mqttTxQueue, canTxQueue, mqtt_server, mqtt_port, mqtt_topicBase,
         mqtt_user, mqtt_pass, mqtt_ca))

loop.run_forever()
loop.close()
Beispiel #27
0
def handle_sighup():
    logger.info("Received SIGHUP, reopening log file")
    log_file_handler.close()
    logger.info("Received SIGHUP, log file reopened")


loop.add_signal_handler(signal.SIGHUP, handle_sighup)

# Connect to serial port
serial_transport, serial_protocol = loop.run_until_complete(
    serial_asyncio.create_serial_connection(
        loop,
        VelbusSerialProtocol,
        args.serial_port,
        baudrate=38400,
        bytesize=serial.EIGHTBITS,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
    ))
try:
    logger.debug("Old DTR/RTS: {}/{}".format(serial_transport._serial.dtr,
                                             serial_transport._serial.rts))
    serial_transport._serial.dtr = False  # low
    serial_transport._serial.rts = True  # high
    logger.debug("New DTR/RTS: {}/{}".format(serial_transport._serial.dtr,
                                             serial_transport._serial.rts))
except OSError as e:
    logger.warning(
        "Could not set DTR/RTS status, trying anyway... ({})".format(str(e)))
    arguments = {
        'read_address': 1,
        'read_count': 8,
        'write_address': 1,
        'write_registers': [20] * 8,
    }
    log.debug("Read write registeres simulataneously")
    rq = await client.readwrite_registers(unit=UNIT, **arguments)
    rr = await client.read_holding_registers(1, 8, unit=UNIT)
    assert (rq.function_code < 0x80)  # test that we are not an error
    assert (rq.registers == [20] * 8)  # test the expected value
    assert (rr.registers == [20] * 8)  # test the expected value


# create_serial_connection doesn't allow to pass arguments
# to protocol so that this is kind of workaround
def make_protocol():
    return ModbusClientProtocol(framer=ModbusRtuFramer(ClientDecoder()))


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    coro = create_serial_connection(loop,
                                    make_protocol,
                                    '/dev/ptyp0',
                                    baudrate=9600)
    transport, protocol = loop.run_until_complete(asyncio.gather(coro))[0]
    loop.run_until_complete(start_async_test(protocol))
    loop.close()
Beispiel #29
0
    def connection_made(self, transport: serial_asyncio.SerialTransport):
        self.transport = transport
        print('UartServer serial port opened')
        self.transport.serial.rts = False


    def connection_lost(self, exc: Optional[Exception]):
        print('port closed')
        self.transport.loop.stop()

    def data_received(self, data: bytes):
        self.buffer.append(data.decode())
        contents = "".join(self.buffer)
        if '\n' in contents:
            # print(contents)
            if contents.startswith("f 0"):
                print("fbk0")
                self.transport.write("111111.111 0.0\n".encode())
            elif contents.startswith("f 1"):
                print("fbk1")
                self.transport.write("222222.222 0.0\n".encode())
            else:
                print(contents)
            self.buffer = []


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    coroutine1 = serial_asyncio.create_serial_connection(loop, UartServer, '/dev/ttyJ1', 921600)
    loop.run_until_complete(coroutine1)
    loop.run_forever()
        """
        if b'\n' in data:
            self.transport.close()
        """

    def connection_lost(self, exc):
        print('port closed')
        self.transport.loop.stop()

    def pause_writing(self):
        print('pause writing')
        print(self.transport.get_write_buffer_size())

    def resume_writing(self):
        print(self.transport.get_write_buffer_size())
        print('resume writing')


if __name__ == '__main__':
    # 创建事件循环
    loop = asyncio.get_event_loop()
    # 创建协程
    coro = serial_asyncio.create_serial_connection(loop,
                                                   Controller,
                                                   'COM5',
                                                   baudrate=9600)
    # 事件循环运行
    loop.run_until_complete(coro)
    loop.run_forever()
    loop.close()
Beispiel #31
0
    def thread_worker_func(self, port, function_class):
        # Utility functions
        def writeOutToUI(message):
            # NOTE: The following should do a deep copy which is needed 'cause
            #       another thread will be accessing this data later
            # NOTE: Tkinter textbox uses '\n' for newline regardless of OS
            message = message + '\n'

            # We push serial data from controller to a queue which will be
            # accessed by GUI thread later to write text safely to GUI text control
            self.gui_dispatcher_queue.append(
                lambda: self.txt_serialoutput.insert(tk.END, message))

            return message

        # This thread:
        # 1. Reads and shows incoming data from slave Arduino.
        # 2. If 'COMPLETED' message is received from LED controller, next set of frames are written out.
        try:
            # Start async serial read write
            class ControllerSerialHandler(asyncio.Protocol):
                END_OF_MESSAGE_BYTE = ord(
                    '\n'
                )  # In CRLF line ending of a message, LF signifies end-of-message

                def _handle_message(self, message):
                    if not self.is_daemon:
                        writeOutToUI(message)

                    if not self.controller_ready and message == settings.CONTROLLER_READY_MESSAGE:
                        # LED controller is now ready after soft reset
                        self.controller_ready = True

                        self.next_frame = self.compressor.feed(
                            self.function.get_frame())

                    elif self.controller_ready:
                        if message.startswith(
                                settings.CONTROLLER_SYNC_MESSAGE):
                            self.get_serial().write(self.next_frame)
                            self.next_frame = self.compressor.feed(
                                self.function.get_frame())

                        elif message.startswith(
                                settings.CONTROLLER_ERROR_MESSAGE):
                            raise Exception(message)

                def __init__(self, is_daemon, function, event_loop,
                             compressor):
                    self.controller_ready = False
                    self.read_buffer = bytearray()
                    self.transport = None

                    self.is_daemon = is_daemon
                    self.function = function
                    self.event_loop = event_loop
                    self.compressor = compressor
                    self.next_frame = None

                def __enter__(self):
                    return self

                def __exit__(self, exc_type, exc_value, exc_traceback):
                    if self.transport:
                        self.get_serial().write(
                            makeResetCommand(IntervalEnum.MSECS_1000))
                        self.get_serial().flush()

                def get_serial(self):
                    return self.transport.serial

                def connection_made(self, transport):
                    self.transport = transport
                    self.get_serial().rts = False

                    self.get_serial().set_buffer_size(rx_size=256,
                                                      tx_size=2048)

                    self.get_serial().reset_input_buffer()
                    self.get_serial().reset_output_buffer()

                    time.sleep(.1)
                    while self.get_serial().in_waiting:
                        self.get_serial().read(self.get_serial().in_waiting)

                    # Ask controller to reset
                    self.get_serial().write(
                        makeResetCommand(self.function.get_interval()))
                    self.get_serial().flush()

                def data_received(self, data):
                    for data_byte in data:
                        self.read_buffer.append(data_byte)

                        if data_byte == self.END_OF_MESSAGE_BYTE:
                            message = self.read_buffer.decode(
                                'utf-8'
                            )[:-len(settings.
                                    CONTROLLER_MESSAGE_END_SEQUENCE_BYTES)]
                            self.read_buffer.clear()

                            # Determine the kind of message received and perform actions accordingly
                            self._handle_message(message)

                def connection_lost(self, exc):
                    self.transport = None
                    self.event_loop.stop()

            with function_class(
                    os.path.join(settings.FUNCTIONS_DIRECTORY,
                                 function_class.__name__)) as function:
                self.event_loop = asyncio.new_event_loop()
                with ControllerSerialHandler(
                        self.is_daemon, function, self.event_loop,
                        Compressor()) as controller_serialhandler:
                    conn = serial_asyncio.create_serial_connection(
                        self.event_loop, lambda: controller_serialhandler,
                        port, **settings.CONTROLLER_COM_PORT_CONFIG)
                    self.event_loop.run_until_complete(conn)
                    self.event_loop.run_forever()
                self.event_loop.close()
                self.event_loop = None

        except Exception as ex:
            if not self.is_daemon:
                ex_str = str(
                    ex
                )  # CAUTION: Needs to be outside separately as 'ex' will be out of scope outside this block
                self.gui_dispatcher_queue.append(
                    lambda: self.lbl_status.configure(text=ex_str))
Beispiel #32
0
    def run_async_loop(self):
        ''' called by connect in a new thread to setup and start the asyncio loop '''
        global async_main_loop

        if async_main_loop:
            self.log.error("Comms: Already running cannot connect again")
            self.app.main_window.async_display(
                '>>> Already running cannot connect again')
            return

        newloop = asyncio.new_event_loop()
        asyncio.set_event_loop(newloop)
        loop = asyncio.get_event_loop()
        async_main_loop = loop
        f = asyncio.Future()

        # if tcp connection port will be net://ipaddress[:port]
        # otherwise it will be serial:///dev/ttyACM0 or serial://COM2:
        if self.port.startswith('net://'):
            sc_factory = functools.partial(
                SerialConnection, cb=self, f=f,
                is_net=True)  # uses partial so we can pass a parameter
            self.net_connection = True
            ip = self.port[6:]
            ip = ip.split(':')
            if len(ip) == 1:
                self.port = 23
            else:
                self.port = ip[1]

            self.ipaddress = ip[0]
            self.log.info('Comms: Connecting to Network at {} port {}'.format(
                self.ipaddress, self.port))
            serial_conn = loop.create_connection(sc_factory, self.ipaddress,
                                                 self.port)
            if self.app.fast_stream:  # optional do not use ping pong for network connections
                self.ping_pong = False

        elif self.port.startswith('serial://'):
            sc_factory = functools.partial(
                SerialConnection, cb=self,
                f=f)  # uses partial so we can pass a parameter
            self.net_connection = False
            self.port = self.port[9:]
            serial_conn = serial_asyncio.create_serial_connection(
                loop, sc_factory, self.port, baudrate=115200)

        else:
            loop.close()
            self.log.error('Comms: Not a valid connection port: {}'.format(
                self.port))
            self.app.main_window.async_display(
                '>>> Connect failed: unknown connection type, use "serial://" or "net://"'
                .format(self.port))
            self.app.main_window.disconnected()
            loop.close()
            async_main_loop = None
            return

        try:
            transport, self.proto = loop.run_until_complete(
                serial_conn
            )  # sets up connection returning transport and protocol handler
            self.log.debug('Comms: serial connection task completed')

            # this is when we are really setup and ready to go, notify upstream
            self.app.main_window.connected()

            # issue a M115 command to get things started
            self._write('\n')
            self._write('M115\n')

            if self.report_rate > 0:
                # start a timer to get the reports
                self.timer = loop.call_later(self.report_rate,
                                             self._get_reports)

            # wait until we are disconnected
            self.log.debug('Comms: waiting until disconnection')
            loop.run_until_complete(f)

            # clean up and notify upstream we have been disconnected
            self.proto = None  # no proto now
            self._stream_pause(False,
                               True)  # abort the stream if one is running
            if self.timer:  # stop the timer if we have one
                self.timer.cancel()
                self.timer = None

            self.app.main_window.disconnected(
            )  # tell upstream we disconnected

            # we wait until all tasks are complete
            pending = asyncio.Task.all_tasks()
            self.log.debug(
                'Comms: waiting for all tasks to complete: {}'.format(pending))
            loop.run_until_complete(asyncio.gather(*pending))
            # loop.run_forever()

        except asyncio.CancelledError:
            pass

        except Exception as err:
            # self.log.error('Comms: {}'.format(traceback.format_exc()))
            self.log.error(
                "Comms: Got serial error opening port: {0}".format(err))
            self.app.main_window.async_display(
                ">>> Connect failed: {0}".format(err))
            self.app.main_window.disconnected()

        finally:
            loop.close()
            async_main_loop = None
            self.log.info('Comms: comms thread Exiting...')
Beispiel #33
0
    # asyncio.Protocol
    def pause_writing(self):
        Log.info('pause writing')
        print(self.transport.get_write_buffer_size())

    # asyncio.Protocol
    def resume_writing(self):
        Log.info(self.transport.get_write_buffer_size())
        Log.info('resume writing')


if __name__ == '__main__':
    # Test with debug tracing
    logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)s %(levelname)s:%(name)s:%(message)s',
        datefmt='%m-%d-%Y %H:%M:%S')

    loop = asyncio.get_event_loop()
    # Include asyncio debug tracing
    loop.set_debug(True)

    coro = serial_asyncio.create_serial_connection(loop,
                                                   ZigbeeAsyncSerialBase,
                                                   "/dev/ttyUSB0",
                                                   baudrate=115200)

    loop.run_until_complete(coro)
    loop.run_forever()
    loop.close()
Beispiel #34
0
        log.info("%d %s", len(data), repr(data))
        if data[0] != 0x42 or data[1] != 0x4d:
            log.info("skipping %s %s %s", repr(data), data[0], data[1])
            return
        frame_len = (data[2] << 8) + data[3]
        data = data[4:frame_len]

        higher = data[::2]
        lower = data[1::2]
        proc_data = [(d1 << 8) + d2 for d1, d2 in zip(higher, lower)]
        if len(proc_data) != 12:
            log.info("aaa  %s", repr(data))
        log.info("%d %s", len(proc_data), proc_data)
        rrdtool.update("pm_2_5_ct.rrd", "N:%d" % (proc_data[9]))

    def connection_lost(self, exc):
        log.info('port closed')
        asyncio.get_event_loop().stop()


loop = asyncio.get_event_loop()
coro = serial_asyncio.create_serial_connection(loop,
                                               Monitor,
                                               '/dev/serial0',
                                               baudrate=9600)
transport, protocol = loop.run_until_complete(coro)
loop.run_forever()
loop.close()

# asyncio.run(main())
        transport.serial.rts = False  # You can manipulate Serial object via transport
        transport.write(b'Hello, World!\n')  # Write serial data via transport

    def data_received(self, data):
        print('data received', repr(data))
        if b'\n' in data:
            self.transport.close()

    def connection_lost(self, exc):
        print('port closed')
        self.transport.loop.stop()

    def pause_writing(self):
        print('pause writing')
        print(self.transport.get_write_buffer_size())

    def resume_writing(self):
        print(self.transport.get_write_buffer_size())
        print('resume writing')


port = 'COM3'
baudrate = 57600

eventloop = asyncio.get_event_loop()
AsyncSerial = serial_asyncio.create_serial_connection(eventloop, Output, port,
                                                      baudrate)
eventloop.run_until_complete(AsyncSerial)
eventloop.run_forever()
eventloop.close()
Beispiel #36
0
def main() :
    import argparse
    import logging

    parser = argparse.ArgumentParser(description='''
py_tsip_proxy is a proxy for the Trimble Standard Interface Protocol
(TSIP). It allows several clients to connect to one single TSIP capable
device. Assuming the TSIP capable device is a GPS controlled clock (e.g.
timing standard, GPSDO (GPS disciplined oscillator), a logfile can be
written to disk for monitoring purposes.

This software lives at https://github.com/vogelchr/py_tsip_proxy and has
been tested with a Trimbe Thunderbolt http://www.leapsecond.com/tbolt-faq.htm.
''')

    parser.add_argument('-d', '--debug', action='store_true', default=False,
            help='''Write packets sent/received by each client. (def: don't)''')

    grp = parser.add_argument_group('Serial or Network Connection to GPS Device')

    grp.add_argument('-t', '--tcp', metavar='PORT', dest='tcp_port',
        type=int, action='store', default=None,
        help='Use TCP connection and specify port number. (def: use serial)')

    grp.add_argument('-b', '--baud', dest='baud',
        type=int, action='store', default=9600,
        help='Baudrate to use on serial device (def: 9600)')

    grp.add_argument('tty_or_host', metavar='TTY|HOST',
        type=str, action='store', default=None,
        help='Serial device or hostname when using TCP connection.')

    grp = parser.add_argument_group('Listening Sockets')

    grp.add_argument('-l', '--listen', dest='listen',
        type=int, action='store', default=4321, metavar='PORT',
        help='''Listen for local connections on tcp port whose
packets will be forwarded to the device (def: 4321).''')

    grp.add_argument('-m', '--listen-mute', dest='listen_mute',
        type=int, action='store', default=None, metavar='PORT',
        help='''Listen for local connections on tcp port whose
packets will not be forwarded to the device (def: None).''')

    grp = parser.add_argument_group('Logging to ASCII Files')

    grp.add_argument('-o', '--logfile', dest='logfile',
        type=str, action='store', default=None, metavar='BASE',
        help='''Write GPS stats (primary and supplemental timing
        information and GPS satellite data) to logfile, files will be
        named BASE_YYYYmmdd.txt and reopened at midnight local time.
        (def: no logfile)''')

    grp.add_argument('-f', '--flush', action='store_true',
            default=False, help='''Flush logfiles after each line. Useful
            if you are watching with "tail -f", but wears out storage
            faster as the file will fsync() after every single line. (def:
            no flush)''')

    args = parser.parse_args()

    logging.basicConfig(
        format='%(asctime)-15s %(message)s',
        level=logging.DEBUG if args.debug else logging.INFO)

    loop = asyncio.get_event_loop()

    if args.tcp_port :
        conn_future = loop.create_connection(TSIP_Protocol_Master,
                args.tty_or_host, args.tcp_port)
    else :
        conn_future = serial_asyncio.create_serial_connection(loop,
            TSIP_Protocol_Master, args.tty_or_host, baudrate=args.baud)

    transport, protocol_master = loop.run_until_complete(conn_future)
    slave = TSIP_Protocol_Slave(protocol_master)

    ###
    # listen socket
    ###
    bind_future = loop.create_server(
        lambda: TSIP_Protocol_Slave(protocol_master, True), port=args.listen)
    loop.run_until_complete(bind_future)

    if args.listen_mute :
        bind_future = loop.create_server(
            lambda: TSIP_Protocol_Slave(protocol_master, False),
            port=args.listen_mute)
        loop.run_until_complete(bind_future)

    if args.logfile :
        logger = TSIP_Logger(args.logfile, protocol_master, args.flush)

    loop.run_forever()
Beispiel #37
0
                    print('land')
                if(((msg)[2])==53):#5
                    drone.add_action( PercisionLand( 1.0,   np.array([1, 1])   )  )
                    print('percision_land')
                if(((msg)[2])==54):#6
                    drone.add_action(FlyToPoint(np.array([0,0,-10]),tolerance =1))
                    print('FlyToPoint0,0,-10')
                if(((msg)[2])==55):#7
                    drone.add_action(Circle(velocity=2.0,radius=8.0,angle=0.0))
                    print('circle')
                if(((msg)[2])==56):#8
                    drone.add_action(Spin())
                    print('Spin')
                if(((msg)[2])==57):#9
                    drone.override_action(Killing())
                    print('Killing!')
        except Exception as E:
            print(E)
    def connection_lost(self, exc):
        print('port closed')
        asyncio.get_event_loop().stop()

# drone = Craft("drone1","serial:///dev/serial0:1000000")
drone = Craft('drone0',"udp://:14540")
drone.start()
loop = asyncio.get_event_loop()
# coro = serial_asyncio.create_serial_connection(loop, Output, '/dev/ttyUSB0', baudrate=57600)
coro = serial_asyncio.create_serial_connection(loop, Output, '/dev/serial0', baudrate=1000000)
loop.run_until_complete(coro)
loop.run_forever()
loop.close()
Beispiel #38
0
        self.transport = transport
        print("port opened", transport)
        # transport.serial.rts = False  # You can manipulate Serial object via transport
        transport.write(b"Hello, World!\n")  # Write serial data via transport

    def data_received(self, data):
        print("data received", repr(data))
        if b"\n" in data:
            self.transport.close()

    def connection_lost(self, exc):
        print("port closed")
        self.transport.loop.stop()

    def pause_writing(self):
        print("pause writing")
        print(self.transport.get_write_buffer_size())

    def resume_writing(self):
        print(self.transport.get_write_buffer_size())
        print("resume writing")


loop = asyncio.get_event_loop()
coro = serial_asyncio.create_serial_connection(
    loop, Output, "/dev/ttyACM0", baudrate=115200
)
loop.run_until_complete(coro)
loop.run_forever()
loop.close()
    rr = await client.read_input_registers(1, 8, unit=UNIT)
    assert(rq.function_code < 0x80)     # test that we are not an error

    arguments = {
        'read_address':    1,
        'read_count':      8,
        'write_address':   1,
        'write_registers': [20]*8,
    }
    log.debug("Read write registeres simulataneously")
    rq = await client.readwrite_registers(unit=UNIT, **arguments)
    rr = await client.read_holding_registers(1, 8, unit=UNIT)
    assert(rq.function_code < 0x80)     # test that we are not an error
    assert(rq.registers == [20]*8)      # test the expected value
    assert(rr.registers == [20]*8)      # test the expected value


# create_serial_connection doesn't allow to pass arguments
# to protocol so that this is kind of workaround
def make_protocol():
    return ModbusClientProtocol(framer=ModbusRtuFramer(ClientDecoder()))


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    coro = create_serial_connection(loop, make_protocol, '/dev/ptyp0',
                                    baudrate=9600)
    transport, protocol = loop.run_until_complete(asyncio.gather(coro))[0]
    loop.run_until_complete(start_async_test(protocol))
    loop.close()