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
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()
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()
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)
async def test_socket_tc2(event_loop, init_tcp2_junction, run_receiver_and_shutdown): port1, port2 = await init_tcp2_junction() leds = cmd.Leds(red='on') with ns.create_connection(('127.0.0.1', port1)) as sock: sock.ascii_send(b'a') await run_receiver_and_shutdown(port2, receiver_tc2)
def to_json(in_packet): """Convert a protobuf into a json message """ LOG.debug("to_json - input: %s, msg: %s", type(in_packet), in_packet) # from protobuf to json is just a matter of unmarshalling if ns.is_protobuf(in_packet): obj = ns.unmarshall(in_packet) if ns.is_ack(obj, command_type=cmd.Leds): mask = obj.sts obj = cmd.Leds() obj.set_status(mask) return obj else: LOG.debug("to_json - |%r| > /dev/null", in_packet) # do not send the message return None