86 lines
2.7 KiB
Python
86 lines
2.7 KiB
Python
#!/usr/bin/python
|
|
#Bosch Home Automation <> MQTT Gateway
|
|
|
|
import requests, json, time
|
|
import paho.mqtt.client as mqtt
|
|
|
|
class Mqtt2ThingBoard:
|
|
|
|
#Mosquitto Settings
|
|
client_name = "Mqtt2ThingBoardGateWay"
|
|
host_name = "192.168.178.36"
|
|
host_port = 1884
|
|
|
|
mqtt_client = mqtt.Client(client_name)
|
|
|
|
tb_gateway_user = "K9iW4T5E7tVeP4ZyapxB"
|
|
tb_port = 1883
|
|
tb_client = mqtt.Client(tb_gateway_user)
|
|
tb_client.username_pw_set(tb_gateway_user,None)
|
|
|
|
#Sent MQTT Debugging Message
|
|
def publishDebugMsg(self,msg):
|
|
self.mqtt_client.publish("Mqtt2ThingBoardGateWay/debug",msg,0,True)
|
|
print(msg)
|
|
|
|
#Sent message to MQTT ThingsBoard Gateway
|
|
def publishTelemetryMsg(self,msg):
|
|
#TODO: USE Python SDK from Github ThingsBoard !!!!!
|
|
if not self.tb_client.is_connected:
|
|
ret2 = self.tb_client.connect(self.host_name,self.tb_port)
|
|
self.tb_client.publish("v1/gateway/telemetry",msg,0,True)
|
|
|
|
|
|
def handleMobileAlertsStatus(self,topics,msg):
|
|
device = topics[1]+"_"+topics[2]
|
|
msg = {
|
|
device: [
|
|
{
|
|
topics[3]: msg
|
|
}
|
|
]
|
|
}
|
|
print(f"{device}: {json.dumps(msg)}")
|
|
self.publishTelemetryMsg(json.dumps(msg))
|
|
|
|
#react to MQTT incoming message
|
|
def onMqttMessage(self, client, userdata, message):
|
|
msg = str(message.payload.decode("utf-8"))
|
|
topics = message.topic.split("/")
|
|
#print(f"{message.topic}: {msg}")
|
|
if (topics[0]=="stat" and topics[2]=="MA"):
|
|
self.handleMobileAlertsStatus(topics,msg)
|
|
|
|
|
|
#subscribe to message to trigger scenarios
|
|
def subscribeToMqttInputs(self):
|
|
self.mqtt_client.subscribe('#')
|
|
self.mqtt_client.on_message = self.onMqttMessage
|
|
|
|
|
|
#set up the system: login to MQTT + get all needed data from the BSH
|
|
def __init__(self):
|
|
self.publishDebugMsg("Connecting to MQTT Server")
|
|
ret1 = self.mqtt_client.connect(self.host_name,self.host_port)
|
|
|
|
self.publishDebugMsg("Connecting to ThingsBoard Mqtt Gateway")
|
|
ret2 = self.tb_client.connect(self.host_name,self.tb_port)
|
|
|
|
self.publishDebugMsg("Setting up the Environment...")
|
|
|
|
self.publishDebugMsg("Subscribe to MQTT Messages")
|
|
self.subscribeToMqttInputs()
|
|
|
|
|
|
def loop(self):
|
|
#Restart Long Polling every second
|
|
while True:
|
|
self.mqtt_client.loop_start()
|
|
time.sleep(1)
|
|
self.mqtt_client.loop_stop()
|
|
|
|
|
|
|
|
Mqtt2ThingBoardGateWay = Mqtt2ThingBoard()
|
|
Mqtt2ThingBoardGateWay.loop()
|