Page 1 sur 1

Switch plugin python

Publié : 03 oct. 2022, 20:59
par skarab22
Bonjour,

Pour m'exercer et surtout pour gagner un peu de temps quand j'ajoute des nouveaux esp en mode relais dans mon installation électrique j'ai tenté de développer un plugin python.

Malheureusement, j'ai pas mal d'erreur dans mon script, est ce que l'un d'entre vous (ou plusieurs) serait ok pour me filer un petit coup de main pour m'aider à progresser ?

Pour le moment, mon plugin doit :
- ajouter un nouveau selector switch à la création
- contrôler les deux relais sur les esp pour contrôler mes radiateurs

Problème actuel :
- j'ai une erreur : "
- mes switch envoie bien la requête http mais ne change pas d'état sur Domoticz.

J'ai tenté de chercher des exemples sur d'autres plugin mais j'ai du mal à trouver. J'ai mis mon code ci dessous mais si besoin, je peux le mettre sur github

Code : Tout sélectionner

# Python Plugin ModeChauffage
#
# Created: 10-aug-2022
# Author: Skarab22
#
"""
<plugin key="ModeChauffage" name="ModeChauffage" author="Skarab22" version="1.0.0" externallink="https://github.com/skarab22/Update_timer">
    <params>
	    <param field="Address" label="Device IP" width="250px" required="true" default="127.0.0.1"/>
	    <param field="Port" label="Port" width="100px" required="true" default="80"/>
	    <param field="Mode1" label="Idx Domoticz" width="100px" required="true"/>
        <param field="Mode6" label="Debug" width="75px">
            <options>
                <option label="True" value="Debug"/>
                <option label="False" value="Normal"  default="true" />
            </options>
        </param>
    </params>
</plugin>
"""
import Domoticz
import requests

class BasePlugin:
    __UNIT = 1

    def url(self, cmd):
        return 'http://' + self.IP + cmd

    def command (self,sLevel):

        if(sLevel == "Off"):
            gpiopos = '0'
            gpioneg = '1'
        if(sLevel == "HG"):
            gpiopos = '1'
            gpioneg = '0'
        if(sLevel == "Eco"):
            gpiopos = '1'
            gpioneg = '1'
        if(sLevel == "Confort"):
            gpiopos = '0'
            gpioneg = '0'

        cmdPos = '/control?cmd=gpio,4,' + gpiopos
        cmdNeg = '/control?cmd=gpio,5,' + gpioneg        

        return cmdPos, cmdNeg

    def sendCommand(self, ip, level):
        self.IP = ip
        
        cmd = self.command(level)
        url1 = self.url(cmd[0])
        url2 = self.url(cmd[1])
        
        
        Domoticz.Log(f"url:{url1}")
        Domoticz.Log(f"url:{url2}")
        
        requests.get(url1)
        requests.get(url2)

         
    def onStart(self):
        if Parameters["Mode6"] == "Debug":
            Domoticz.Debugging(1)

        if (len(Devices) == 0):
            #selector switch for heating mode
            PowerSelectorOptions = {"LevelActions": "|||||",
                                    "LevelNames": "Off|HG|Eco|Confort",
                                    "LevelOffHidden": "false",
                                    "SelectorStyle": "0"}
            Domoticz.Device(Name="Mode Chauffage", Unit=self.__UNIT, TypeName="Selector Switch", Image=15, Options=PowerSelectorOptions, Used=1).Create()

        Domoticz.Heartbeat(10)
        DumpConfigToLog()

    def onStop(self):
        Domoticz.Log("Plugin is stopping.")
   
    def onHeartbeat(self):     
        Domoticz.Debug("onHeartbeat")

    def onCommand(self, Unit, Command, Level, Hue):
        Domoticz.Debug(f"Unit:{Unit}, Command:{Command}")
        
        if (int(Level) == 0):
            ModeChauffage = "Off"
            UpdateDevice(self.__UNIT,0, 0)
        elif(int(Level == 10)):
            ModeChauffage = "HG"
            UpdateDevice(self.__UNIT, 0, 10)
        elif(int(Level == 20)):
            ModeChauffage = "Eco"
            UpdateDevice(self.__UNIT, 0, 20)
        elif(int(Level == 30)):
            ModeChauffage = "Confort"
            UpdateDevice(self.__UNIT, 0, 30)

        self.sendCommand(Parameters["Address"], ModeChauffage)
       
    def onDisconnect(self, Connection):
        Domoticz.Log("Device has disconnected")



global _plugin
_plugin = BasePlugin()


def onStart():
    global _plugin
    _plugin.onStart()

def onStop():
    global _plugin
    _plugin.onStop()

#def onConnect(Connection, Status, Description):
#    global _plugin
#    _plugin.onConnect(Connection, Status, Description)

#def onMessage(Connection, Data):
#    global _plugin
#    _plugin.onMessage(Connection, Data)

def onCommand(Unit, Command, Level, Hue):
    global _plugin
    _plugin.onCommand(Unit, Command, Level, Hue)

def onHeartbeat():
    global _plugin
    _plugin.onHeartbeat()

def onDisconnect(Connection):
    global _plugin
    _plugin.onDisconnect(Connection)

# Generic helper functions
def DumpConfigToLog():
    for x in Parameters:
        if Parameters[x] != "":
            Domoticz.Debug( "'" + x + "':'" + str(Parameters[x]) + "'")
            
    Domoticz.Debug("Device count: " + str(len(Devices)))
    for x in Devices:
        Domoticz.Debug("Device:           " + str(x) + " - " + str(Devices[x]))
        Domoticz.Debug("Device ID:       '" + str(Devices[x].ID) + "'")
        Domoticz.Debug("Device Name:     '" + Devices[x].Name + "'")
        Domoticz.Debug("Device nValue:    " + str(Devices[x].nValue))
        Domoticz.Debug("Device sValue:   '" + Devices[x].sValue + "'")
        Domoticz.Debug("Device LastLevel: " + str(Devices[x].LastLevel))
                
    return

def UpdateDevice(Unit, nValue, sValue):
    # Make sure that the Domoticz device still exists (they can be deleted) before updating it 
    if (Unit in Devices):
        if (Devices[Unit].nValue != nValue):
            Devices[Unit].Update(nValue=nValue, sValue=str(sValue))
            Domoticz.Debug("Update "+str(nValue)+":'"+str(sValue)+"' ("+Devices[Unit].Name+") due to different in nValue")
        elif ( str(Devices[Unit].sValue) != str(sValue) ):
            Devices[Unit].Update(nValue=nValue, sValue=str(sValue))
            Domoticz.Debug("Update "+str(nValue)+":'"+str(sValue)+"' ("+Devices[Unit].Name+") due to different in sValue")
    return