Example #1
0
def to_protobuf(in_packet):
    """ Transform a json packet to a protobuf equivalent

        Args:
            in_packet (str): json string
        Returns:
            a protobuf object or None if unable to transform the input packet.
            If return None the packet is silently discarded


    """
    LOG.debug("to_protobuf - input: %s, msg: %s", type(in_packet), in_packet)

    obj = json.loads(in_packet.decode())

    packet = None

    # check if the received json packet is a profile command
    if 'uid' in obj and 'pwd' in obj:
        packet = ns.marshall(ns.msg.Profile(obj['uid'], obj['pwd']))

    # check if json packet is a led command
    elif 'leds' in obj:
        if obj['leds'] == 'get':
            packet = ns.marshall(cmd.Leds())
        elif obj['leds'] == 'set':
            packet = ns.marshall(
                cmd.Leds(red=obj['red'] if 'red' in obj else None,
                         yellow=obj['yellow'] if 'yellow' in obj else None))
    else:
        LOG.info("to_protobuf - unable to convert message %s", in_packet)
    return packet
Example #2
0
async def test_switch_led():
    """switch on and off the red led
    """
    broker = await start_broker()

    msg_on = ns.marshall(cmd.Leds(red='on'))
    msg_off = ns.marshall(cmd.Leds(red='off'))

    cli = mqtt.MQTTClient()
    await cli.connect(tc.broker)

    await cli.subscribe([('hb/{}/{}'.format(tc.network, tc.board), QOS_0)])

    await cli.publish('{}/{}'.format(tc.network, tc.board), msg_on, qos=QOS_0)
    await asyncio.sleep(1)
    await cli.publish('{}/{}'.format(tc.network, tc.board), msg_off, qos=QOS_0)

    try:
        for _ in range(2):
            # wait for the ack
            message = await cli.deliver_message(timeout=3)
            packet = message.publish_packet
            LOG.debug("%s => %s", packet.variable_header.topic_name,
                      str(packet.payload.data))
    except asyncio.TimeoutError:
        assert 0
    finally:
        # wait before shutting down the broker, otherwise the pub packets get lost
        await asyncio.sleep(1)
        await cli.disconnect()
        await broker.shutdown()
        tc.cancel_tasks()
Example #3
0
def test_print_commands():
    config = ns.msg.Config()
    print(config)

    config.alive_period = 100
    ns.marshall(config)

    profile = ns.msg.Profile()
    print(profile)

    with pytest.raises(ns.InvalidObjectId):
        print(ns.msg.Ack(id=100))
Example #4
0
async def test_junction_protobuf(event_loop, shutdown, init_tcp_junction):
    origins = [
        cmd.Leds(red='on'),
        ns.msg.Config(host=ns.my_ip_address()),
        ns.msg.Profile('pippo', 'pluto'),
        ns.msg.Ack(1)
    ]

    port1, port2 = await init_tcp_junction()

    #start the clients
    reader1, writer1 = await asyncio.open_connection('0.0.0.0', port1)
    reader2, writer2 = await asyncio.open_connection('0.0.0.0', port2)

    for origin in origins:

        proto_msg = ns.marshall(origin)

        writer1.write(proto_msg)

        recv_msg = await ns.msg_receive(ns.Channel(reader2, writer2))

        LOG.debug("msg delivered!: %s", recv_msg)

        received = ns.unmarshall(recv_msg)

    await shutdown()
Example #5
0
async def test_add_profile():
    """add a wlan profile
    """
    broker = await start_broker()

    profile = ns.msg.Profile(uid='baba', pwd='there_is_no_secret_for_me')
    msg = ns.marshall(profile)

    cli = mqtt.MQTTClient()
    await cli.connect(tc.broker)

    await cli.publish('{}/{}'.format(tc.network, tc.board), msg, qos=QOS_0)

    await cli.subscribe([('hb/{}/{}'.format(tc.network, tc.board), QOS_0)])

    try:
        # wait for the ack
        message = await cli.deliver_message(timeout=3)
        packet = message.publish_packet
        payload = packet.payload.data
        print("%s => %s" %
              (packet.variable_header.topic_name, str(payload)))

        ack = ns.unmarshall(payload)
        print(ack)
    except asyncio.TimeoutError:
        assert 0
    finally:
        await cli.disconnect()
        await broker.shutdown()
        tc.cancel_tasks()
Example #6
0
def test_ack():
    src = ns.msg.Profile(uid='pippo', pwd='secret')
    target = ns.ack(src)

    msg = ns.marshall(src)

    assert (ns.is_ack(target, msg))
Example #7
0
async def main(color, value, topic):
    """Starter
    """
    sub_topic = 'hb/{}'.format(topic)

    mqtt = MQTTClient()
    await mqtt.connect('mqtt://localhost')
    await mqtt.subscribe([(sub_topic, QOS_1)])

    leds = cmd.Leds()
    setattr(leds, color, value)
    await mqtt.publish(topic, ns.marshall(leds))

    try:
        while True:
            message = await mqtt.deliver_message()
            payload = message.publish_packet.payload.data
            if ns.is_protobuf(payload):
                obj = ns.unmarshall(payload)
                if ns.is_ack(obj):
                    break
            else:
                LOG.debug(">> %s", payload)

        await mqtt.unsubscribe([sub_topic])
        await mqtt.disconnect()

    except ClientException as cli_exc:
        LOG.error("Client exception: %s", cli_exc)
Example #8
0
def test_add_protobuf():
    pobj = pb2.TMsg()
    pobj.name = "pino"
    pobj.rank = 1
    ns.add_protobuf_model(51, pb2.TMsg, DemoMsg)

    packet = ns.marshall(DemoMsg("bonzo", 1))

    assert (ns.is_protobuf(packet))
Example #9
0
def handle_event(event, uart):
    """manage events from board
    """
    if (event.name == 'BOARD_INIT'):
        profile = ns.msg.Profile(
            os.environ['TEST_UID'], pwd=os.environ['TEST_PWD'])
        uart.write(ns.marshall(profile))

        board_cfg = ns.msg.Config(host=ns.my_ip_address(),
                                  network=tc.network, board=tc.board)
        uart.write(ns.marshall(board_cfg))

        return 1

    if (event.name == 'BOARD_READY'):
        return 1

    if (event.name == 'SERIAL_TIMEOUT'):
        assert 0
Example #10
0
def handle_event(event, uart):
    """react to board events
    """

    if (event.name == 'CONN_FAILED_OK'):
        # configure the board with the bocia settings
        host_ip = ns.my_ip_address()
        cfg = ns.msg.Config(network=tc.network, board=tc.board, host=host_ip)
        uart.write(ns.marshall(cfg))

    if event.name == 'CONN_FAILED_ERR':
        return 0

    if event.name == 'TEST_OK':
        return 1

    if event.name == 'IP_ACQUIRED':
        return 1

    if (event.name == 'BOARD_READY'):
        # WLAN uid/password setup
        profile = ns.msg.Profile(os.environ['TEST_UID'],
                                 pwd=os.environ['TEST_PWD'])
        uart.write(ns.marshall(profile))

    if (event.name == 'TEST_RESULT'):
        print("event received: {} - arg1: {}".format(event.name, event.arg1))
        # arg2 contains the number of test failures
        #assert(event.arg2 == 1)

    if (event.name == 'PROTOBUF'):
        print("handle_event: {}".format(event.obj))

        # time to end successfully the test
        # return 1

    if (event.name == 'SERIAL_TIMEOUT'):
        assert (0)
Example #11
0
def ack_response(msg):
    ack = ns.msg.Ack(id=MyCmd.ID)
    ack.sts = 0
    return ns.marshall(ack)
Example #12
0
def test_long_message():
    cmd = MyCmd()

    m = ns.marshall(cmd)
    print(m)
    um = ns.unmarshall(m)
Example #13
0
def main_serial(dev, server_address):
    """Connect directly to serial port
    """
    with serial.Serial(dev, 115200, timeout=1) as ser:
        ser.write(ns.marshall(server_address))