Exemple #1
0
def average_publisher(mqtt_client, userdata):
    while True:
        try:
            time.sleep(1)
            payload = str(userdata[MESSAGES]).encode("utf-8")
            mqtt_client.publish("metrics/msg_rate", payload=payload, qos=0)
            mqtt_client.publish("logging/metrics/msg_rate", payload=payload, qos=0)
            with userdata[LOCK]:
                userdata[MESSAGES] = 0
        except BaseException as e:
            logger.error("Failure in publish averages() [%s]", e, exc_info=True)
            time.sleep(1)


if __name__ == "__main__":
    # Parse CLI args
    parser = argparse.ArgumentParser()
    cli.mqtt_host(parser)
    args = vars(parser.parse_args())

    # Setup MQTT client
    with MqttConnection(args[MQTT_HOST],
                        userdata={LOCK: Lock(),
                                  MESSAGES: 0},
                        on_connect=on_connect,
                        on_message=on_message):
        waitForKeyboardInterrupt()

    logger.info("Exiting...")
Exemple #2
0
    # Define MQTT callbacks
    def on_connect(client, userdata, flags, rc):
        info("Connected with result code: {0}".format(rc))
        client.subscribe("{0}/#".format(userdata[CAMERA_NAME]))

    def on_disconnect(client, userdata, rc):
        info("Disconnected with result code: {0}".format(rc))

    def on_message(client, userdata, msg):
        print("{0} {1}".format(msg.topic, msg.payload))

    # Setup MQTT client
    hostname, port = mqtt_broker_info(args["mqtt"])
    mqtt_conn = MqttConnection(hostname,
                               port,
                               userdata={CAMERA_NAME: args["camera"]})
    mqtt_conn.client.on_connect = on_connect
    mqtt_conn.client.on_disconnect = on_disconnect
    mqtt_conn.client.on_message = on_message
    mqtt_conn.connect()

    try:
        sleep()
    except KeyboardInterrupt:
        pass
    finally:
        mqtt_conn.disconnect()

    print("Exiting...")
Exemple #3
0
        for n in range(8):
            blinkt.set_pixel(n, 0, 0, 0, intensity)
        blinkt.show()
        time.sleep(duration * (1 - duty_cycle))


if __name__ == "__main__":
    # Parse CLI args
    args = setup_cli_args(cli.mqtt)

    # Setup logging
    logging.basicConfig(**LOGGING_ARGS)

    # Create MQTT connection
    hostname, port = mqtt_broker_info(args["mqtt"])
    mqtt_conn = MqttConnection(hostname, port, userdata={HOSTNAME: hostname, PORT: port})
    mqtt_conn.client.on_connect = on_connect
    mqtt_conn.client.on_disconnect = on_disconnect
    mqtt_conn.client.on_subscribe = on_subscribe
    mqtt_conn.client.on_message = on_message
    mqtt_conn.connect()

    try:
        run_display()
    except KeyboardInterrupt:
        pass
    finally:
        mqtt_conn.disconnect()

    print("Exiting...")
    # Subscribe to all broker messages
    topic = userdata[TOPIC]
    mqtt_client.subscribe(topic)
    setup_logging(filename=args[LOG_FILE],
                  format="%(asctime)s %(levelname)-6s %(message)s",
                  level=logging.DEBUG)
    logger.info("Connected, subscribing to topic %s", topic)
    # print("Connected, subscribing to topic {0}".format(topic))


def on_message(mqtt_client, userdata, msg):
    logger.info("%s : %s", msg.topic, msg.payload)
    # print("{0} : {1}".format(msg.topic, msg.payload))


if __name__ == "__main__":
    # Parse CLI args
    parser = argparse.ArgumentParser()
    cli.mqtt_host(parser)
    cli.log_file(parser)
    cli.mqtt_topic(parser)
    args = vars(parser.parse_args())

    with MqttConnection(args[MQTT_HOST],
                        userdata={TOPIC: args[MQTT_TOPIC]},
                        on_connect=on_connect,
                        on_message=on_message):
        waitForKeyboardInterrupt()

    logger.info("Exiting...")
Exemple #5
0
        def publish_locations(mqtt_client, userdata):
            prev_value = -1
            while True:
                try:
                    x_loc = loc_client.get_x()

                    if not userdata[ENABLED]:
                        continue

                    if x_loc is not None and abs(x_loc[0] - prev_value) > 1:
                        result, mid = mqtt_client.publish("{0}/x".format(userdata[TOPIC]),
                                                          payload="{0}:{1}".format(x_loc[0], x_loc[1]).encode('utf-8'))
                        prev_value = x_loc[0]

                except BaseException as e:
                    logger.error("Failure in publish_locations() [%s]", e, exc_info=True)
                    time.sleep(1)


        # Setup MQTT client
        with MqttConnection(args[MQTT_HOST],
                            userdata={TOPIC: args[MQTT_TOPIC],
                                      COMMAND: args[MQTT_TOPIC] + "/command",
                                      ENABLED: True},
                            on_connect=on_connect,
                            on_message=frc_utils.on_message):
            waitForKeyboardInterrupt()

    logger.info("Exiting...")
Exemple #6
0
def on_message(mqtt_client, userdata, msg):
    # Payload is a string byte array
    val = bytes.decode(msg.payload)
    print("{0} : {1}".format(msg.topic, val))
    # If payload is an int byte array, use: int.from_bytes(msg.payload, byteorder="big"))
    # int.from_bytes() requires python3: https://docs.python.org/3/library/stdtypes.html#int.from_bytes


if __name__ == "__main__":
    # Parse CLI args
    parser = argparse.ArgumentParser()
    parser.add_argument("-m",
                        "--mqtt",
                        required=True,
                        help="MQTT broker hostname")
    parser.add_argument("-t", "--topic", required=True, help="MQTT topic")
    args = vars(parser.parse_args())

    # Setup logging
    setup_logging()

    # Setup MQTT client
    with MqttConnection(args["mqtt"],
                        userdata={TOPIC: args["topic"]},
                        on_connect=on_connect,
                        on_subscribe=on_subscribe,
                        on_message=on_message):
        waitForKeyboardInterrupt()

    print("Exiting...")
                        help="Device ('left' or 'right'")
    cli.verbose(parser)
    args = vars(parser.parse_args())

    # Setup logging
    setup_logging(level=args[LOG_LEVEL])

    userdata = {
        TOPIC: "lidar/{0}/mm".format(args[DEVICE]),
        COMMAND: "lidar/{0}/command".format(args[DEVICE]),
        ENABLED: True,
        MOVING_AVERAGE: MovingAverage(size=3),
        OOR_VALUES: OutOfRangeValues(size=args[OOR_SIZE]),
        OOR_TIME: args[OOR_TIME],
        OOR_UPPER: args[OOR_UPPER]
    }

    with SerialReader(func=fetch_data,
                      userdata=userdata,
                      port=SerialReader.lookup_port(args[DEVICE_ID])
                      if args.get(DEVICE_ID) else args[SERIAL_PORT],
                      baudrate=args[BAUD_RATE],
                      debug=True):
        with MqttConnection(hostname=args[MQTT_HOST],
                            userdata=userdata,
                            on_connect=on_connect,
                            on_message=frc_utils.on_message):
            waitForKeyboardInterrupt()

    logger.info("Exiting...")
@nav.on(nav.UP)
def handle_up_button(ch, evt):
    item_deque.rotate(1)
    assign_selected_sensor()


@nav.on(nav.DOWN)
def handle_down_button(ch, evt):
    item_deque.rotate(-1)
    assign_selected_sensor()


if __name__ == "__main__":
    # Parse CLI args
    args = cli.setup_cli_args(cli.mqtt_host, cli.verbose)

    # Setup logging
    setup_logging(level=args[LOG_LEVEL])

    Thread(target=lcd_display, args=(item_dict, 0.1)).start()

    # Setup MQTT client
    with MqttConnection(args[MQTT_HOST],
                        userdata={ITEM_DICT: item_dict},
                        on_connect=on_connect,
                        on_message=on_message):
        waitForKeyboardInterrupt()

    logger.info("Exiting...")
Exemple #9
0
    # Parse CLI args
    args = setup_cli_args(cli.grpc_host, cli.mqtt_host, cli.camera_name, cli.verbose)

    # Setup logging
    setup_logging(level=args[LOG_LEVEL])

    # Start location reader
    with LocationClient(args[GRPC_HOST]) as loc_client:

        # Define MQTT callbacks
        def on_connect(mqtt_client, userdata, flags, rc):
            logger.info("Connected with result code: {0}".format(rc))
            Thread(target=publish_locations, args=(mqtt_client, userdata)).start()


        def publish_locations(mqtt_client, userdata):
            while True:
                x_loc, y_loc = loc_client.get_xy()
                if x_loc is not None and y_loc is not None:
                    result, mid = mqtt_client.publish("{0}/x".format(userdata[CAMERA_NAME]), payload=x_loc[0])
                    result, mid = mqtt_client.publish("{0}/y".format(userdata[CAMERA_NAME]), payload=y_loc[0])


        # Setup MQTT client
        with MqttConnection(args[MQTT_HOST],
                            userdata={CAMERA_NAME: args[CAMERA_NAME]},
                            on_connect=on_connect):
            waitForKeyboardInterrupt()

    logger.info("Exiting...")
Exemple #10
0
    "lidar/rear/command", "heading/command", "camera/gear/command"
]

if __name__ == "__main__":

    def on_connect(mqtt_client, userdata, flags, rc):
        logger.info("Connected with result code: %s", rc)
        Thread(target=enable_disable, args=(mqtt_client, )).start()

    def enable_disable(client):
        while True:
            for i in cmds:
                client.publish(i, payload="OFF", qos=0)
            time.sleep(3)
            for i in cmds:
                client.publish(i, payload="ON", qos=0)
            time.sleep(10)

    # Parse CLI args
    parser = argparse.ArgumentParser()
    cli.mqtt_host(parser)
    cli.verbose(parser)
    args = vars(parser.parse_args())

    with MqttConnection(hostname=args[MQTT_HOST],
                        userdata={},
                        on_connect=on_connect):
        waitForKeyboardInterrupt()

    logger.info("Exiting...")
    for val in range(int(userdata["count"])):
        # Write a string byte array
        bval = str(val).encode('utf-8')
        result, mid = mqtt_client.publish(userdata[TOPIC], payload=bval, qos=0)
        # To write an int byte array, use: bval = val.to_bytes(4, byteorder="big"):
        # int.to_bytes() requires python3: https://docs.python.org/3/library/stdtypes.html#int.to_bytes
        time.sleep(1)
    userdata["paho.client"].disconnect()


if __name__ == "__main__":
    # Parse CLI args
    parser = argparse.ArgumentParser()
    parser.add_argument("-m", "--mqtt", required=True, help="MQTT broker hostname")
    parser.add_argument("-t", "--topic", required=True, help="MQTT topic")
    parser.add_argument("-c", "--count", default="1000", help="Number of messages to publish")
    args = vars(parser.parse_args())

    # Setup logging
    setup_logging()

    # Setup MQTT client
    with MqttConnection(args["mqtt"],
                        userdata={TOPIC: args["topic"], "count": args["count"]},
                        on_connect=on_connect,
                        on_disconnect=on_disconnect,
                        on_publish=on_publish):
        waitForKeyboardInterrupt()

    print("Exiting...")
Exemple #12
0

def on_message(mqtt_client, userdata, msg):
    print("{0} : {1}".format(msg.topic, msg.payload))


if __name__ == "__main__":
    # Parse CLI args
    parser = argparse.ArgumentParser()
    parser.add_argument("-m", "--mqtt", required=True, help="MQTT broker hostname")
    args = vars(parser.parse_args())

    # Setup logging
    setup_logging()

    # Setup MQTT client
    mqtt_conn = MqttConnection(args["mqtt"],
                               on_connect=on_connect,
                               on_disconnect=on_disconnect,
                               on_message=on_message)
    mqtt_conn.connect()

    try:
        sleep()
    except KeyboardInterrupt:
        pass
    finally:
        mqtt_conn.disconnect()

    print("Exiting...")