Page 1 of 1

Python/Domoticz User Variable no update

Posted: Friday 19 April 2024 18:25
by boggiz
Hello all,

How to modify a User Variable with Python/domoticz ?

Code: Select all

# Callback - reception d'un message du broker
def on_message(client, userdata, msg):
    import DomoticzEvents as Dz   # global DE  pour mettre a jour ma User Variable NE FONCTIONNE PAS!
    print('[RECEPTION] Ancienne valeur: ' + Dz.user_variables["NewCodePG"])
    RecMess = str(msg.payload)
    print("[RECEPTION] du topic: " + msg.topic + " : NewCodePG: " + RecMess)
    Dz.user_variables["NewCodePG"] = RecMess 
Python.png
Python.png (4.27 KiB) Viewed 996 times
Dz.user_variables["NewCodePG"] do not takes the DZandPython value
Can someone tell me why ?

Re: Python/Domoticz User Variable no update

Posted: Friday 19 April 2024 19:24
by habahabahaba

Code: Select all

import requests

#  URL API Domoticz
url = 'http://<user>:<password>@<Domoticz IP>:<port number>/json.htm?type=command&param=updateuservariable&vname=USERVARIABLENAME&vtype=USERVARIABLETYPE&vvalue=USERVARIABLEVALUE'

# updating user variable
response = requests.get(url)

# server response
print(response.text)
Wiki

Re: Python/Domoticz User Variable no update

Posted: Saturday 20 April 2024 0:51
by waltervl
Or switch to DVents, much more functionality and better documentation.

There is a memory leak with python event scripts so don't use a lot of them.

Re: Python/Domoticz User Variable no update

Posted: Sunday 21 April 2024 16:36
by boggiz
Hello, thx for your responses.

For some time I have been trying to develop a DIY Rolling Code to secure the opening of my garage door. I send it a code to MQTT which retransmits it to an ESP on standby. If the code received is correct, the ESP opens the door and transmits a new code to MQTT via a Python script which saves it in a Domoticz User variable etc.

Domoticz 2023.1, Python 3.9.2 and MQTT 1.6.1 brocker are installed in Docker
In the Dz environment I also installed the Python modules Paho.mqtt and Requests

I have 2 python scripts MQTTpublishPG and MQTTsubscribPG, the first works perfectly, but the second does not. The cause is that I cannot update my User Variable as indicated in the Python Events doc:
This python event system has limited functionality, it can only switch devices On/Off, no other update parameters are available

moreover I can't tinker with a device because it will only be able to take on/off values (I tried).

The solution proposed by @habahabahaba to use JSON does not work from the Domoticz IDE either.
The User Variable is never updated! On the other hand the same JSON sent from the Docker Terminal or Firefox works.

The problem seems to come from the implementation of the Requests module in the domoticz embedded Python. Perhaps this has been corrected in subsequent versions of Dz otherwise I will have to go through a file saved on disk, the old fashioned way!

Other concerns:
DE, the Domoticz instance declared in the main of the script is not visible from a function so it must be re-declared each time. And this is true, whatever the types of variables!

I haven't tried but I don't think it is possible to add the DE parameter in the header of a CallBack function in paho.mqtt.

In the Domoticz IDE, Import paho.mqtt does not work, you must use import mqtt and modify the Path. This does not seem to affect the functioning of the interpreter which is really basic like not rewinding the line in question during a syntax error!

Unfortunately, using an external Python IDE like Pycharm is not possible: the domoticz module only exists in the Domoticz install.

Code: Select all

#!/usr/bin/python3

# Ce code déclanche sur une demande d'overture de la Porte du Garage
# il attend l'arrivée du Nouveau code porte a utiliser la prochaine fois.

import sys 
sys.path.append('/usr/local/lib/python3.9/dist-packages/paho/')

import DomoticzEvents as DE
import time as time


from mqtt import client as mqtt   # paho.mqtt imperatif en mode TERMINAL

# Definitions: 
Broker            = "192.168.0.45"
#username          = "mosquitto"
#password          = "mqtt"
PortaBroker       = 11883
KeepAliveBroker   = 60
clientID          = "BGz"

# Callback - connexion du broker OK
def on_connect(client, userdata, flags, rc):
    print("[STATUS] Connection au Broker. Resultat de la Connection: " + str(rc))
    client.subscribe("home/domoticz/PG/PG2Dz")

# Callback - reception d'un message du broker
def on_message(client, userdata, msg):
    import DomoticzEvents as Dz   # global DE  pour mettre a jour ma User Variable NE FONCTIONNE PAS!
    print('[RECEPTION] Ancienne valeur: ' + Dz.user_variables["NewCodePG"])
    RecMess = str(msg.payload)
    print("[RECEPTION] du topic: " + msg.topic + " : NewCodePG: " + RecMess)
    Dz.user_variables["NewCodePG"] = RecMess # ne fonctionne pas utiliser Python/requests
    Dz.Devices["Test Python"].s_value = RecMess  # marche pas dommage !
    import requests
    from requests.auth import HTTPBasicAuth
    url="http://192.168.0.45:18080/json.htm?type=command&param=updateuservariable&vname=NewCodePG&vtype=string&vvalue=" + RecMess + ", auth('Boggiz, '************')"
    response = requests.get(url)
    print(response.text)

if DE.changed_device_name == "Test Python" and DE.Devices["Test Python"].n_value_string == "On":
    print("[STATUS] Initialisation de MQTT ...")
    client = mqtt.Client(clientID)
    #client.username_pw_set(username, password)
    #client.on_disconnect  = on_disconnect
    client.on_connect = on_connect
    client.on_message = on_message  
    
    client.connect(Broker, PortaBroker, KeepAliveBroker)
    
    client.loop_start()
    time.sleep(30)                         # a régler ..
    #client.loop_forever()
    client.loop_stop()
    client.disconnect()
In short, I'm struggling..

Re: Python/Domoticz User Variable no update

Posted: Sunday 21 April 2024 16:49
by habahabahaba
It works.
I 've tested it befor posting on Dz 2024.4

Re: Python/Domoticz User Variable no update

Posted: Sunday 21 April 2024 16:56
by habahabahaba
As i remember in 2023 version another way of authentication

Try

Code: Select all

http://<Domoticz IP>:<port number>/json.htm?username=<username>&password=<password>&type=command&param=updateuservariable&vname=USERVARIABLENAME&vtype=USERVARIABLETYPE&vvalue=USERVARIABLEVALUE
username and password are base64 encoded.

Re: Python/Domoticz User Variable no update

Posted: Sunday 21 April 2024 18:19
by boggiz
@habahabahaba Thank you for the info.
I will test this quickly

Re: Python/Domoticz User Variable no update

Posted: Sunday 21 April 2024 18:29
by RonkA
Could it be that you try to acces a value that lives inside a Docker-container using an outside Docker-container ip adress?

Re: Python/Domoticz User Variable no update

Posted: Monday 22 April 2024 12:00
by habahabahaba
habahabahaba wrote: Friday 19 April 2024 19:24

Code: Select all

import requests

#  URL API Domoticz
url = 'http://<user>:<password>@<Domoticz IP>:<port number>/json.htm?type=command&param=updateuservariable&vname=USERVARIABLENAME&vtype=USERVARIABLETYPE&vvalue=USERVARIABLEVALUE'

# updating user variable
response = requests.get(url)

# server response
print(response.text)
Wiki
Ah, and the lib 'requests' needed. Its not installed by default

pip install requests