You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

117 lines
4.1 KiB
Python

2 years ago
#!/usr/bin/python
from waggle.plugin import Plugin
import time
#import paho.mqtt.client as paho
import logging
import asyncio
import os
from amqtt.broker import Broker
import yaml
from amqtt.client import MQTTClient, ClientException
from amqtt.mqtt.constants import QOS_1, QOS_2
2 years ago
import json
2 years ago
import base64
import numpy as np
import cv2 as cv
2 years ago
sublist = []
sensorlist = []
devicelist = []
2 years ago
showData = True # debug print
2 years ago
async def broker_coro(brokerconfig):
broker = Broker(config=brokerconfig)
await broker.start()
async def uptime_coro():
C = MQTTClient()
await C.connect('mqtt://127.0.0.1:1883/') # connect to my own broker
# Subscribe to '$SYS/broker/uptime' with QOS=1
# Subscribe to '$SYS/broker/load/#' with QOS=2
2 years ago
#await C.subscribe([
# ('a/b', QOS_1),
# ])
await C.subscribe(sublist)
try:
2 years ago
count = 0
while True:
count = count + 1
message = await C.deliver_message()
packet = message.publish_packet
2 years ago
dictout = decoder(packet.payload.data)
print("%d: %s => %s" % (count, packet.variable_header.topic_name, dictout))
2 years ago
if packet.variable_header.topic_name.split("/")[-1] == "camera": # trigger image loading
print(len(dictout["data"]))
img = np.frombuffer(base64.b64decode(dictout["data"]), np.uint8)
cv.imwrite('./output.jpg', img)
2 years ago
else:
publishData(str(dictout["data"]), str(dictout["sensorID"]), str(packet.variable_header.topic_name.split("/")[-1]), dictout["timestamp"])
2 years ago
#await C.unsubscribe(['a/b'])
#await C.disconnect()
except ClientException as ce:
logger.error("Client exception: %s" % ce)
2 years ago
def publishData(data, sensorID, sensorType, dataTimestamp):
with Plugin() as plugin:
if showData is True:
2 years ago
print("publishing network.bridge.sensor." + sensorType + " with metadata:", {"sensorID": sensorID, "sensorType": sensorType}, "and timestamp:", dataTimestamp, "and data:", data)
2 years ago
else:
print("publishing network.bridge.sensor." + sensorType + "with metadata", {"sensorID": sensorID, "sensorType": sensorType})
# send data to waggle:
2 years ago
plugin.publish("network.bridge.sensor." + sensorType, data, meta={"sensorID": str(sensorID), "sensorType": str(sensorType)}, timestamp=dataTimestamp)
sensorcount = 0
devicecount = 0
2 years ago
2 years ago
def subdict(d, header):
# coordinate mqtt topic names and waggle topics / sensor names
global sensorcount
global devicecount
for k,v in d.items():
if isinstance(v, dict):
if header is not None:
subdict(v, header + k + "/") # recurse further
else:
subdict(v, k + "/")
else:
for sensor in v:
sublist.append((header + k + "/" + sensor, QOS_2))
sensorlist.append((header + k + "/" + sensor, sensorcount))
sensorcount = sensorcount + 1
if (header + k + "/", devicecount) not in devicelist:
devicelist.append((header + k + "/", devicecount))
devicecount = devicecount + 1
#print (((header + k + "/" + sensor, QOS_2), sensorcount))
2 years ago
def decoder(data):
print (data)
return json.loads(data.decode("utf-8"))
2 years ago
if __name__ == "__main__":
2 years ago
# mqtt broker config
with open('broker.yaml', 'r') as fileread:
brokerconfig = yaml.safe_load(fileread)
2 years ago
# clients config
with open('subscribe.yaml', 'r') as fileread:
clientconfig = yaml.safe_load(fileread)
subdict(clientconfig, None)
print("sublist:", sublist)
print("sensors:", sensorlist)
print("devices:", devicelist)
2 years ago
formatter = "[%(asctime)s] :: %(levelname)s :: %(name)s :: %(message)s"
2 years ago
logging.basicConfig(level=logging.ERROR, format=formatter)
asyncio.get_event_loop().run_until_complete(broker_coro(brokerconfig))
asyncio.get_event_loop().run_until_complete(uptime_coro())
asyncio.get_event_loop().run_forever()
2 years ago
#publishData(1, "0", sensortypes[0], time.time_ns())