Skip to content

Instantly share code, notes, and snippets.

@aschmidt75
Created July 16, 2018 11:59
Show Gist options
  • Save aschmidt75/b341a90c507b861c7b73b7b919b50b38 to your computer and use it in GitHub Desktop.
Save aschmidt75/b341a90c507b861c7b73b7b919b50b38 to your computer and use it in GitHub Desktop.
Micropython binding class between MQTT client and WebThing API Thing class
import json
from action import Action
from event import Event
from property import Property
from thing import Thing
from value import Value
class ThingMQTTBinding:
def __init__(self,client, thing):
self.client = client
self.thing = thing
self.topic = thing.ws_href
self.client.set_callback(self.handle_web_thing_message)
self.client.subscribe(self.topic)
# set self as listener for all events
for e in self.thing.available_events:
self.thing.add_event_subscriber(e, self)
def handle_announce(self):
# announce thing on topic
self.client.publish(self.topic, json.dumps({
"messageType": "announce",
"data": self.thing.as_thing_description(),
}))
def update_property_status(self):
msg = {
"messageType": "propertyStatus",
"data": {}
}
for name in self.thing.properties:
msg["data"][name] = self.thing.get_property(name)
self.SendText(json.dumps(msg))
def handle_set_property(self, obj):
for property in list(obj):
#print("set_property")
#print(obj)
if self.thing.has_property(property):
self.thing.set_property(property,obj[property])
else:
raise Exception("No such property", property)
def handle_request_action(self,obj):
for actionName in list(obj):
#print("request_action")
#print(obj)
action = self.thing.perform_action(actionName,obj[actionName])
if action != None:
action.start()
else:
raise Exception("No such action", actionName)
def SendText(self, message):
self.client.publish(self.topic, message)
def handle_web_thing_message(self, topic, msg):
try:
obj = json.loads(msg)
if not("action" in obj):
return
if obj["action"] == "setProperty":
del obj["action"]
self.handle_set_property(obj)
return
if obj["action"] == "requestAction":
del obj["action"]
data = None
if obj["data"]:
data = obj["data"]
self.handle_request_action(data)
return
except Exception as e:
print(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment