The code I have attached bellow is a Python plugin to get json data from a Sorel solar controller and sent to Domoticz server via HTTP get. Instead the nabto P2P protocol (*), plugin implement an HTTP client to go to device website and get json data.
My question is, with Dzvents would be possible to implement the nabto P2P protocol instead the HTTP client? What I understand it is possible to create a Nabto TCP tunneling.
(*)Nabto’s P2P plataform made possible to connect selected SOREL products to the internet and to enable direct remote access to the devices. More info 5.3 TCP Tunneling
Code: Select all
import requests
from time import sleep
from datetime import datetime, timedelta
from urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
import urllib.request
import re
domourl = "http://192.168.1.50:8080/json.htm?type=command¶m=udevice&nvalue=0&idx="
baseurl = "https://***MAC***.sorel-connect.net"
urlsensors = "sensors.json"
urlrelais = "relays.json"
loginurl = "https://***MAC***.sorel-connect.net/nabto/hosted_plugin/login/execute?email={email}&password={password}"
acquisitionstep = 10 # in minutes
sensors = {1: "Deposito 1 AQS",
2: "Deposito 2 AQS",
3: "Temperatura",
4: "Temperatura",
5: "Permutador circuito 1",
7: "Temperatura coletor A",
8: "Temperatura coletor B",
9: "Temperatura retorno A",
10: "Caudal Instantaneo A",
11: "Temperatura retorno B",
12: "Caudal Instantaneo B"}
idx = {1: 520, 2: 521, 3: 522,4: 523, 5: 524, 7: 594,
8: 526, 9: 595, 10: 596,
11: 529, 12: 530}
# podiamos haber creado una lista en el diccionario sensors en lugar de crear el diccionario idx
# relais = [1, 2, 3, 4, 5]
s2 = requests.session()
response = s2.get(baseurl, verify=False)
response.close()
results = []
if (response.status_code == 200):
formdata = {'email': 'your_mail',
'password': 'your_pass'}
response = s2.get(loginurl.format(**formdata), verify=False, cookies=s2.cookies)
sessionkeys = eval(response.content)
response.close()
if "session_key" in sessionkeys:
response = s2.get(baseurl + "?session_key=%s" % sessionkeys["session_key"], verify=False, cookies=s2.cookies)
response.close()
#A timedelta object represents a duration, the difference between two dates or times
starttimeobj = (datetime.utcnow() + timedelta(minutes=1)).replace(second=0, microsecond=0)
starttime = starttimeobj.timestamp()
sleeptimetosync = (starttimeobj - datetime.utcnow()).total_seconds()
sleep(sleeptimetosync)
while True:
try:
curinstant = datetime.utcnow()#This call is returning datetime en formato utc
tmp_results = {}
tmp_results.update({'instant': curinstant})
founderror = False
for x in sensors.keys():
response = s2.get("%s/%s?id=%d" % (baseurl, urlsensors, x), verify=False, cookies=s2.cookies)
data = response.json()
response.close()
if 'error' not in data:
tmp_results.update({"sensor_%d" % x: data['val']})
else:
founderror = True
print("Error: sensor %s - %s" % (x, data['error']['body']))
sleep(2)
# for x in relais:
# response = s2.get("%s/%s?id=%d" % (baseurl, urlrelais, x), verify=False, cookies=s2.cookies)
# data = response.json()
# response.close()
# if 'error' not in data:
# tmp_results.update({"relay_%d" % x: data['val']})
# else:
# founderror = True
# print("Error: relay %s - %s" % (x, data['error']['body']))
# sleep(0.1)
results.insert(len(results), tmp_results)
if founderror:
print("Errors in comunication detected. leave the program")
break
except KeyboardInterrupt:
print('Keyboard interrupt, Terminar')
break
except Exception as ex:
print("Some error happens - %s" % str(ex))
break
for x in tmp_results:
if not x == 'instant':
print(sensors[int(x.split('_')[-1])], tmp_results[x])#divide la variable x, elimina 'sensor_', lo convierte en integrer y busca el valor en el diccionario sensors[]
idxvalue = (''.join(map(str,(re.findall('\d+',tmp_results[x])))))#extrae solo numeros del diccionario tmp_results y transforma su valor en string
response = urllib.request.urlopen("%s%d&svalue=%s" % (domourl,idx[int(x.split('_')[-1])], idxvalue))
else:
print(tmp_results[x])
sleep(0.2)
# print("current results", tmp_results)
delta = datetime.utcnow().timestamp() - starttime
sleeptime = ((acquisitionstep * 60) - (delta % (acquisitionstep * 60)))
sleep(sleeptime)
print("all reseults", results)
s2.close()