Skip to content

Commit

Permalink
Merge pull request #39 from sparks-baird/public-mqtt
Browse files Browse the repository at this point in the history
use mqtt by default
  • Loading branch information
sgbaird committed Sep 10, 2022
2 parents 5f43025 + 84a2d08 commit 25b44e9
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 19 deletions.
22 changes: 3 additions & 19 deletions src/self_driving_lab_demo/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,18 @@
- https://setuptools.pypa.io/en/latest/userguide/entry_point.html
- https://pip.pypa.io/en/stable/reference/pip_install
"""

import ast
import logging
from importlib.resources import open_text
from time import sleep

import numpy as np
import pandas as pd
import requests
from scipy.interpolate import interp1d
from similaritymeasures import frechet_dist
from sklearn.metrics import mean_absolute_error, mean_squared_error

from self_driving_lab_demo import data as data_module
from self_driving_lab_demo.utils.observe import mqtt_observe_sensor_data

__author__ = "sgbaird"
__copyright__ = "sgbaird"
Expand Down Expand Up @@ -84,20 +82,6 @@
intensity_lbl = "relative_intensity" # (uW/cm^2)/nm


def pico_server_observe_sensor_data(
R: int, G: int, B: int, url="http://192.168.0.111/"
):
payload = {
"control_led": "Send+command+to+LED",
"red": str(R),
"green": str(G),
"blue": str(B),
}
r = requests.post(url, data=payload)
sensor_data_cookie = r.cookies["sensor_data"]
return ast.literal_eval(sensor_data_cookie)


class SensorSimulator(object):
def __init__(self):
self.red_interp = self.create_interpolator("neopixel_red.csv")
Expand Down Expand Up @@ -163,8 +147,8 @@ def __init__(
max_brightness=0.35,
autoload=False,
simulation=False,
observe_sensor_data_fn=pico_server_observe_sensor_data,
observe_sensor_data_kwargs=dict(url="http://192.168.0.111/"),
observe_sensor_data_fn=mqtt_observe_sensor_data,
observe_sensor_data_kwargs={}, # dict(PICO_ID="a123b456")
):
self.random_rng = random_rng
self.target_seed = target_seed
Expand Down
69 changes: 69 additions & 0 deletions src/self_driving_lab_demo/utils/observe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
"""Based on the following resource:
https://www.steves-internet-guide.com/receiving-messages-mqtt-python-clientq=Queue() # noqa: E501
"""
import ast
import json
import logging
from queue import Queue
from time import time

import paho.mqtt.client as mqtt
import requests

sensor_data_queue = Queue()
timeout = 30

_logger = logging.getLogger(__name__)


def on_message(client, userdata, msg):
sensor_data_queue.put(json.loads(msg.payload))


def mqtt_observe_sensor_data(R, G, B, pico_id=None, hostname="test.mosquitto.org"):
if pico_id is None:
_logger.warning(
"No pico_id provided, but should be provided. On Pico, run the following to get your pico_id. from machine import unique_id; from ubinascii import hexlify; print(hexlify(unique_id()).decode()). Or change pico_id to whatever you want, but make it match between the Pico main.py and this mqtt_observe_sensor_data kwarg." # noqa: E501
)
prefix = f"sdl-demo/picow/{pico_id}/"
neopixel_topic = prefix + "GPIO/28"
sensor_topic = prefix + "as7341/"

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
if rc != 0:
print("Connected with result code " + str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe(sensor_topic)

client = mqtt.Client() # create new instance
client.on_connect = on_connect
client.on_message = on_message
client.connect(hostname) # connect to broker
client.subscribe(sensor_topic)

# ensures double quotes for JSON compatiblity
payload = json.dumps(dict(R=R, G=G, B=B))
client.publish(neopixel_topic, payload)

t = time()
while sensor_data_queue.empty():
client.loop()
if t - time() > 30:
raise ValueError("Failed to retrieve message within timeout period")
return sensor_data_queue.get()


def pico_server_observe_sensor_data(
R: int, G: int, B: int, url="http://192.168.0.111/"
):
payload = {
"control_led": "Send+command+to+LED",
"red": str(R),
"green": str(G),
"blue": str(B),
}
r = requests.post(url, data=payload)
sensor_data_cookie = r.cookies["sensor_data"]
return ast.literal_eval(sensor_data_cookie)

0 comments on commit 25b44e9

Please sign in to comment.