MQTT Library
Library
The mqtt library exposes three things that should be used to send sensor data to Stemi's datastore. These are:
mqtt(of typeStemiMqtt)SensorDataSensorPacket
mqtt.py
mqtt = None # variable that will hold the mqtt client instance instance
class SensorData:
SENSOR_TYPES = ["Light", "Pressure", "AirHumidity",
"SoilHumidity", "AirTemperature", "SoilTemperature"]
def __init__(self, type: str, value: float):
...
class SensorPacket:
def __init__(self, init=None):
...
def add(self, packet: SensorData):
...
class StemiMqtt:
def publish(self, topic: str, packet: SensorPacket):
...
def reconnect(self):
...
Explanations
| Returns | Description | |
|---|---|---|
SensorData | A class that holds a sensor's type information and it's value, a data point | |
SensorData.SENSOR_TYPES | Preferred types of sensor data, this information will be used later in data analysis, if the user enters some other value, it will be overridden to Other | |
SensorData.__init__() | An instance of SensorData | Creates a sensor data point that can be sent to the datastore |
SensorPacket | A class that hold multiple sensor data points | |
SensorPacket.__init__() | An instance of SensorPacket | Creates an instance of SensorPacket and sets the inital data points if the variable init is passed, which should be a list of type SensorData |
SensorPacket.add() | Adds another SensorData instance to the packet | |
StemiMqtt | A class that sends multiple data points to Stemi's datastore, should used through mqtt instance | |
StemiMqtt.publish() | Sends a SensorPacket to Stemi's datastore | |
StemiMqtt.reconnect() | Reconnects the internal mqtt client in case of a network error |
Structured data example
main.py
from stemi.mqtt import mqtt, SensorPacket, SensorData
...
mqtt_topic = "stream/cl1npjxh20000t4xz5fyi42u9"
try:
s = SensorPacket()
s.add(SensorData('Light', ldr.value))
s.add(SensorData('AirHumidity', aht.relative_humidity))
s.add(SensorData('AirTemperature', aht.temperature))
mqtt.publish(mqtt_topic, s)
except RuntimeError as e:
mqtt.reconnect()
Unstructured data example
main.py
from stemi.mqtt import mqtt, MqttPacket
...
mqtt_topic = "stream/cl1npjxh20000t4xz5fyi42u9"
try:
m = MqttPacket()
m.add("This is a raw, unstructured value")
mqtt.publish(mqtt_topic, m)
except RuntimeError as e:
mqtt.reconnect()