Interfacing Nabto with Dzvents?

Easy to use, 100% Lua-based event scripting framework.

Moderator: leecollings

Post Reply
javalin
Posts: 71
Joined: Tuesday 30 April 2019 16:06
Target OS: Raspberry Pi / ODroid
Domoticz version: 4.10717
Location: Portugal
Contact:

Interfacing Nabto with Dzvents?

Post by javalin »

Hello, may be this is a strange question but I would like you to help me solve

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&param=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()
Any help would be appreciated.
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Interfacing Nabto with Dzvents?

Post by waaren »

javalin wrote: Friday 19 March 2021 15:02 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.
How would this translate into openURL statements and how would the return values look like?
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
javalin
Posts: 71
Joined: Tuesday 30 April 2019 16:06
Target OS: Raspberry Pi / ODroid
Domoticz version: 4.10717
Location: Portugal
Contact:

Re: Interfacing Nabto with Dzvents?

Post by javalin »

I don't know if I have understood the question correctly.

Once you have the session open with your login, if you type:

Code: Select all

https://***MAC***.sorel-connect.net/state.json?id=sensor1
You get value for sensor 1:

Code: Select all

{ "val": "66°C" }

For sensor2 just change last number to 2.
I have not written the Python code, just domoticz HTTP get, but what I understand is that this plugin keeps a session open constantly pretending to be a browser.
User avatar
waaren
Posts: 6028
Joined: Tuesday 03 January 2017 14:18
Target OS: Linux
Domoticz version: Beta
Location: Netherlands
Contact:

Re: Interfacing Nabto with Dzvents?

Post by waaren »

javalin wrote: Friday 19 March 2021 16:19 this plugin keeps a session open constantly pretending to be a browser.
This is something a dzVents script (or any other event script) can never do. As the name already implies, a script is triggered by an event, -does its job and finish. In domoticz this has to be done within 10 seconds to prevent blocking the complete event system for too long.
As you might already know the event system is single threaded which means that no other scripts can be active if another one is still busy.
Debian buster, bullseye on RPI-4, Intel NUC.
dz Beta, Z-Wave, RFLink, RFXtrx433e, P1, Youless, Hue, Yeelight, Xiaomi, MQTT
==>> dzVents wiki
javalin
Posts: 71
Joined: Tuesday 30 April 2019 16:06
Target OS: Raspberry Pi / ODroid
Domoticz version: 4.10717
Location: Portugal
Contact:

Re: Interfacing Nabto with Dzvents?

Post by javalin »

Thank you very much for the clarification waaren, in the best case scenario I could create a script that would run every 5 minutes blocking the rest of the system until it is finished. Python script is running well, I have no need to complicate what works well.
Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 1 guest