########### Dev : Baurin Leza ############
# Cliente MQTT de pruebas
import paho.mqtt.client as mqtt
import sys
import random
import requests
import threading
import json
class StationDiY():
def __init__(self, host="stationdiy.eu", username = "", port = 80, password = "", device = "", actioner = "", data_actioner = "", sensor = "", data = "", longitud = "", latitud = ""):
self.host = host
self.device = device
self.sensor = sensor
self.data = data
self.actioner = actioner
self.data_actioner = data_actioner
self.longitud = longitud
self.latitud = latitud
self.max_value = ""
self.min_value = ""
self.type_data = ""
self.user_hash = ""
self.port = port
self.url = "http://%s:%s/api/"%(self.host, self.port)
def login(self, username, password):
""" Save auth credentials to objects return """
self.action = "authenticate"
payload = {'password': password, 'username': username}
response = requests.post(self.url+"login/", data=payload)
if response.status_code == 200 :
self.username = username
self.password = password
self.authenticated = True
self.user_hash = response.json()["user_hash"]
else :
self.authenticated = False
def register(self, username, password):
""" Save auth credentials to objects return """
self.action = "authenticate"
payload = {'password': password, 'username': username}
response = requests.post(self.url+"register/", data=payload)
if response.status_code == 200 :
self.username = username
self.password = password
self.authenticated = True
self.user_hash = response.json()["user_hash"]
else :
self.authenticated = False
def subscribe_actioner(self, device, actioner, on_message):
"""
Subscribe to concrete actioner
"""
def on_publish(mqttc, userdata, mid):
mqttc.disconnect()
client = mqtt.Client()
client.on_message = on_message
client.connect(host=self.host, port=1883, keepalive=60, bind_address="")
print ("Subscribe to ---> %s - %s"%(device,actioner))
def worker():
client.loop_forever()
return
t = threading.Thread(target=worker)
t.daemon = True
t.start()
client.subscribe("%s/%s/%s"%(self.user_hash,device,actioner))
def subscribe_sensor(self, device, sensor, on_message):
"""
Subscribe to concrete actioner
"""
def on_publish(mqttc, userdata, mid):
mqttc.disconnect()
client = mqtt.Client()
client.on_message = on_message
client.connect(host=self.host, port=1883, keepalive=60, bind_address="")
print ("Subscribe to ---> %s - %s"%(device,sensor))
def worker():
client.loop_forever()
return
t = threading.Thread(target=worker)
t.daemon = True
t.start()
client.subscribe("%s/%s/%s"%(self.user_hash,device,sensor))
def sendMQTT(self):
""" Send message """
def on_connect(mqttc, userdata, flags, rc):
mqttc.publish(topic='StationDiy/', payload='{"user_hash":"%s", "action":"%s","username":"%s","password":"%s","device":"%s","sensor":"%s","data":"%s", "actioner":"%s", "data_actioner":"%s", "longitud":"%s", "latitud": "%s","description":"Lorem Ipsium Dev2...", "max_value":"%s", "min_value":"%s", "type_data":"%s"}'%(self.user_hash, self.action, self.username, self.password, self.device, self.sensor, self.data, self.actioner, self.data_actioner, self.longitud, self.latitud, self.max_value, self.min_value, self.type_data), qos=0)
def on_disconnect(mqttc, userdata, rc):
pass
# print('Disconnect...rc=' + str(rc))
def on_subscribe(mqttc, userdata, mid, granted_qos):
print('subscribed (qos=' + str(granted_qos) + ')')
def on_unsubscribe(mqttc, userdata, mid, granted_qos):
print('unsubscribed (qos=' + str(granted_qos) + ')')
def on_message(mqttc, userdata, msg):
print('message received...')
print ("-->%s"%userdata)
print('topic: ' + msg.topic + ', qos: ' +
str(msg.qos) + ', message: ' + str(msg.payload))
def on_publish(mqttc, userdata, mid):
mqttc.disconnect()
self.mqttc = mqtt.Client()
self.mqttc.on_connect = on_connect
self.mqttc.on_disconnect = on_disconnect
self.mqttc.on_message = on_message
self.mqttc.on_publish = on_publish
self.mqttc.connect(host=self.host, port=1883, keepalive=60, bind_address="")
self.mqttc.loop_forever()
def setSensor(self, device, sensor, data, type = "string", max_value = "", min_value = "", type_ = ""):
""" Set sensor by mqtt """
self.device = device
self.sensor = sensor
self.data = data
self.max_value = max_value
self.min_value = min_value
self.type_data = type_
if self.authenticated == True : self.sendMQTT()
else: print ("No authenticated request api" )
self.clear()
def clear(self):
self.device = ""
self.sensor = ""
self.actioner = ""
self.max_value, self.min_value, self.type_data = "", "", ""
def getSensorData(self,device,sensor):
""" Get sensor by http method """
# Get data
if self.authenticated == False :
return -1
payload = {'password': self.password, 'username': self.username, 'sensor':sensor, 'device':device}
response = requests.post(self.url+"getsensordata/", data=payload)
if response.status_code == 200 : return response.text
else : return -1
def getSensors(self, device):
""" Get Actioner data by http method """
if self.authenticated == False :
return -1
payload = {'password': self.password, 'username': self.username, 'device':device}
response = requests.post(self.url+"getsensors/", data=payload)
if response.status_code == 200 : return response.text
else : return -1
def setActioner(self, device, actioner, data, max_value = "", min_value = "", type_ = ""):
""" Set actioner data by mqtt """
self.device = device
self.actioner = actioner
self.data_actioner = data
self.max_value = max_value
self.min_value = min_value
self.type_data = type_
if self.authenticated == True : self.sendMQTT()
else: print ("No authenticated request api" )
self.clear()
def getActionerData(self, device, actioner):
""" Get Actioner data by http method """
if self.authenticated == False :
return -1
payload = {'password': self.password, 'username': self.username, 'actioner':actioner, 'device':device}
response = requests.post(self.url+"getactionerdata/", data=payload)
if response.status_code == 200 : return response.text
else : return -1
def getActioners(self, device):
""" Get Actioner data by http method """
if self.authenticated == False :
return -1
payload = {'password': self.password, 'username': self.username, 'device':device}
response = requests.post(self.url+"getactioners/", data=payload)
if response.status_code == 200 : return response.text
else : return -1
def getDevices(self):
""" Get Actioner data by http method """
if self.authenticated == False :
return -1
payload = {'password': self.password, 'username': self.username}
response = requests.post(self.url+"getdevices/", data=payload)