Ejemplo n.º 1
0
def main():
    # Parse CLI args
    args = setup_cli_args(cli.grpc_host, cli.log_level)

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

    http = Flask(__name__)

    @http.route("/count")
    def val_count():
        global count
        return "Read {0} values".format(count)

    def read_values():
        global count
        while True:
            print("Got location: {0}".format(client.get_xy()))
            count += 1

    # Start client
    with LocationClient(args[GRPC_HOST]) as client:

        # Run read_values in a thread
        count = 0
        Thread(target=read_values).start()

        # Run HTTP server in a thread
        Thread(target=http.run, kwargs={"port": 8080}).start()

        sleep()
def main():
    # Parse CLI args
    args = setup_cli_args(cli.grpc_host, cli.mqtt_host, cli.camera_name,
                          cli.log_level)

    # 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...")
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-s", "--serial", default="ttyACM0", type=str,
                        help="Arduino serial port [ttyACM0] (OSX is cu.usbmodemXXXX)")
    cli.grpc_host(parser)
    parser.add_argument("-x", "--xservo", default=5, type=int, help="X servo PWM pin [5]")
    parser.add_argument("-y", "--yservo", default=6, type=int, help="Y servo PWM pin [6]")
    cli.alternate(parser)
    cli.calib(parser)
    cli.log_level(parser)
    args = vars(parser.parse_args())

    alternate = args["alternate"]
    calib = args["calib"]
    xservo = args["xservo"]
    yservo = args["yservo"]

    setup_logging(level=args[LOG_LEVEL])

    # Setup firmata client
    port = ("" if is_windows() else "/dev/") + args["serial"]
    try:
        board = Arduino(port)
        logger.info("Connected to Arduino at: {0}".format(port))
    except OSError as e:
        logger.error("Failed to connect to Arduino at {0} - [{1}]".format(port, e))
        sys.exit(0)

    with LocationClient(args[GRPC_HOST]) as client:
        # Create servos
        servo_x = FirmataServo("Pan", alternate, board, "d:{0}:s".format(xservo), 1.0, 8)
        servo_y = FirmataServo("Tilt", alternate, board, "d:{0}:s".format(yservo), 1.0, 8)

        try:
            if calib:
                try:
                    calib_t = Thread(target=calibrate_servo.calibrate, args=(client, servo_x, servo_y))
                    calib_t.start()
                    calib_t.join()
                except KeyboardInterrupt:
                    pass
            else:
                if alternate:
                    # Set servo X to go first
                    servo_x.ready_event.set()
                try:
                    servo_x.start(True, lambda: client.get_x(), servo_y.ready_event if not calib else None)
                    servo_y.start(False, lambda: client.get_y(), servo_x.ready_event if not calib else None)
                    servo_x.join()
                    servo_y.join()
                except KeyboardInterrupt:
                    pass
                finally:
                    servo_x.stop()
                    servo_y.stop()
        finally:
            board.exit()

    logger.info("Exiting...")
Ejemplo n.º 4
0
def main():
    # Parse CLI args
    args = setup_cli_args(cli.grpc_host, cli.log_level)

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

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

        stream_ids = tls.get_credentials_file()['stream_ids']
        stream_id = stream_ids[0]

        # Declare graph
        graph = go.Scatter(x=[],
                           y=[],
                           mode='lines+markers',
                           stream=dict(token=stream_id, maxpoints=80))
        data = go.Data([graph])
        layout = go.Layout(title='Target Locations',
                           xaxis=go.XAxis(range=[0, 800]),
                           yaxis=go.YAxis(range=[0, 450]))
        fig = go.Figure(data=data, layout=layout)
        py.plot(fig, filename='plot-locations')

        # Write data
        stream = py.Stream(stream_id)
        stream.open()

        logger.info("Opening plot.ly tab")
        time.sleep(5)

        try:
            while True:
                x_val, y_val = client.get_xy()

                if x_val[0] == -1 or y_val[0] == -1:
                    continue

                x = x_val[1] - abs(x_val[1] - x_val[0])
                y = abs(y_val[1] - y_val[0])

                stream.write(dict(x=x, y=y))
                time.sleep(.10)
        except KeyboardInterrupt:
            pass
        finally:
            stream.close()

    logger.info("Exiting...")
def main():
    # Parse CLI args
    args = setup_cli_args(cli.grpc_host, cli.log_level)

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

    with LocationClient(args[GRPC_HOST]) as client:
        try:
            while True:
                print("Got location: {0}".format(client.get_xy()))
        except KeyboardInterrupt:
            pass

    logger.info("Exiting...")
Ejemplo n.º 6
0
def main():
    # Parse CLI args
    args = setup_cli_args(cli.grpc_host, cli.log_level)

    setup_logging(level=args[LOG_LEVEL])

    with LocationClient(args[GRPC_HOST]) as client:
        init_w, init_h = 800, 450

        root = tk.Tk()

        canvas = tk.Canvas(root, bg="white", width=init_w, height=init_h)
        canvas.pack()

        sketch = LocationSketch(canvas)

        b = tk.Button(root, text="Clear", command=sketch.clear_canvas)
        b.pack(side=tk.LEFT)

        lb_var = tk.IntVar()
        lb_var.set(1)
        lb = tk.Checkbutton(root,
                            text="Lines",
                            variable=lb_var,
                            command=sketch.toggle_lines)
        lb.pack(side=tk.LEFT)

        pb_var = tk.IntVar()
        pb_var.set(1)
        pb = tk.Checkbutton(root,
                            text="Points",
                            variable=pb_var,
                            command=sketch.toggle_points)
        pb.pack(side=tk.LEFT)

        Thread(target=sketch.plot_vals, args=(client, init_w, init_h)).start()

        root.mainloop()
#!/usr/bin/env python

import logging

import cli_args as cli
from cli_args import LOG_LEVEL, GRPC_HOST
from cli_args import setup_cli_args
from location_client import LocationClient
from utils import setup_logging

logger = logging.getLogger(__name__)

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

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

    with LocationClient(args[GRPC_HOST]) as client:
        try:
            while True:
                print("Got location: {0}".format(client.get_xy()))
        except KeyboardInterrupt:
            pass

    logger.info("Exiting...")
Ejemplo n.º 8
0
from common_constants import CAMERA_NAME
from common_constants import LOGGING_ARGS
from common_utils import mqtt_broker_info
from common_utils import sleep
from location_client import LocationClient
from mqtt_connection import MqttConnection

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

    # Setup logging
    logging.basicConfig(**LOGGING_ARGS)

    # Start location reader
    locations = LocationClient(args["grpc"]).start()

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

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

    def on_publish(client, userdata, mid):
        print("Published message id: {0}".format(mid))

    def publish_locations(client, userdata):
        while True:
            x_loc = locations.get_x()