def UpdateDeviceState(self, d): foundHotWaterDevice = False foundOutsideDevice = False Domoticz.Debug('Getting Temperatures') thermostats = self.GetThermostat(d, 'Heating') if thermostats: for node in thermostats: # TODO: add schedule switch to change toggle scheduled or off (chrelay switch toggles manual or off) # TODO: add switch for boost mode (fix time to half an hour) foundInsideDevice = False foundTargetDevice = False foundHeatingDevice = False foundThermostatDevice = False # get the temperature and heating states temp = node["attributes"]["temperature"]["reportedValue"] Domoticz.Debug('Temp = ' + str(temp)) targetTemp = node["attributes"]["targetHeatTemperature"]["reportedValue"] if targetTemp < 7.0: targetTemp = 7.0 Domoticz.Debug('Target = ' + str(targetTemp)) heating = node["attributes"]["stateHeatingRelay"]["reportedValue"] Domoticz.Debug('Heating = ' + heating) Domoticz.Debug('Getting Battery Status') thermostatui = self.GetThermostatUI(d, node["parentNodeId"]) if (thermostatui): # get the battery and rssi values thermostat_battery = thermostatui["attributes"]["batteryLevel"]["reportedValue"] Domoticz.Debug('Battery = ' + str(thermostat_battery)) thermostat_rssi = 12*((0 - thermostatui["attributes"]["RSSI"]["reportedValue"])/100) Domoticz.Debug('RSSI = ' + str(thermostat_rssi)) # Loop through the devices and update temperatures Domoticz.Debug('Updating Devices') for unit in Devices: if Devices[unit].DeviceID == node["name"]+"_Current": Devices[unit].Update(nValue=int(temp), sValue=str(temp)) foundInsideDevice = True if Devices[unit].DeviceID == node["name"]+"_Target": Devices[unit].Update(nValue=int(targetTemp), sValue=str(targetTemp)) foundTargetDevice = True if Devices[unit].DeviceID == node["id"] and Devices[unit].Type == 244: #if CH Switch device foundHeatingDevice = True if unit not in set(self.chrelaySet): self.chrelaySet.add(unit) if (thermostatui): if thermostatui["attributes"]["presence"]["reportedValue"] == "ABSENT": if self.TimedOutAvailable: if Devices[unit].TimedOut == 0: Devices[unit].Update(nValue=Devices[unit].nValue, sValue=Devices[unit].sValue, TimedOut=1) else: Domoticz.Log("Device Offline : " + Devices[unit].Name) else: if heating == 'ON': if Devices[unit].nValue == 0: if self.TimedOutAvailable: Devices[unit].Update(nValue=1, sValue='On', TimedOut=0) else: Devices[unit].Update(nValue=1, sValue='On') else: if Devices[unit].nValue == 1: if self.TimedOutAvailable: Devices[unit].Update(nValue=0, sValue='Off', TimedOut=0) else: Devices[unit].Update(nValue=0, sValue='Off') if Devices[unit].DeviceID == node['id'] and Devices[unit].Type == 242: #Thermostat foundThermostatDevice = True Devices[unit].Update(nValue = int(targetTemp), sValue = str(targetTemp), BatteryLevel = int(thermostat_battery), SignalLevel = int(thermostat_rssi)) if foundInsideDevice == False and thermostatui: Domoticz.Device(Name = thermostatui["name"] + ' - Current', Unit = self.GetNextUnit(False), TypeName = 'Temperature', DeviceID = node["name"]+'_Current').Create() self.counter = self.multiplier if foundTargetDevice == False and thermostatui: Domoticz.Device(Name = thermostatui["name"] + ' - Target', Unit = self.GetNextUnit(False), TypeName = 'Temperature', DeviceID = node["name"]+'_Target').Create() self.counter = self.multiplier if foundHeatingDevice == False and thermostatui: Domoticz.Device(Name = thermostatui["name"] + ' - Heating', Unit = self.GetNextUnit(False), TypeName = 'Switch', Switchtype = 0, DeviceID = node['id']).Create() self.counter = self.multiplier if foundThermostatDevice == False and thermostatui: Domoticz.Device(Name = thermostatui["name"] + ' - Thermostat', Unit = self.GetNextUnit(False), Type = 242, Subtype = 1, DeviceID = node['id']).Create() self.counter = self.multiplier else: Domoticz.Debug('No heating thermostat found') thermostatsW = self.GetThermostat(d, 'HotWater') if thermostatsW: # HotWater too... thermostatW = thermostatsW[0] hotwater = thermostatW["attributes"]["stateHotWaterRelay"]["reportedValue"] for unit in Devices: if Devices[unit].DeviceID == thermostatW["id"]: foundHotWaterDevice = True if unit not in set(self.hwrelaySet): self.hwrelaySet.add(unit) if (thermostatui): if thermostatui["attributes"]["presence"]["reportedValue"] == "ABSENT": if self.TimedOutAvailable: if Devices[unit].TimedOut == 0: Devices[unit].Update(nValue=Devices[unit].nValue, sValue=Devices[unit].sValue, TimedOut=1) else: Domoticz.Log("Device Offline : " + Devices[unit].Name) else: if hotwater == 'ON': if Devices[unit].nValue == 0: if self.TimedOutAvailable: Devices[unit].Update(nValue=1, sValue='On', TimedOut=0) else: Devices[unit].Update(nValue=1, sValue='On') else: if Devices[unit].nValue == 1: if self.TimedOutAvailable: Devices[unit].Update(nValue=0, sValue='Off', TimedOut=0) else: Devices[unit].Update(nValue=0, sValue='Off') if foundHotWaterDevice == False: Domoticz.Device(Name = 'HotWater - Relay', Unit = self.GetNextUnit(False), TypeName = 'Switch', Switchtype = 0, DeviceID = thermostatW["id"]).Create() self.counter = self.multiplier else: Domoticz.Debug('No hot water thermostat/relay found') lights = self.GetLights(d) tunablelights = self.GetTunableLights(d) colourlights = self.GetColourLights(d) if lights: Domoticz.Debug("Found Standard Light(s)") if colourlights: Domoticz.Debug("Found Colour Light(s)") lights += colourlights if tunablelights: Domoticz.Debug("Found Tunable Light(s)") lights += tunablelights else: if tunablelights: Domoticz.Debug("Found Tunable Light(s)") lights += tunablelights else: if colourlights: Domoticz.Debug("Found Colour Light(s)") lights = colourlights if tunablelights: Domoticz.Debug("Found Tunable Light(s)") lights += tunablelights else: if tunablelights: Domoticz.Debug("Found Tunable Light(s)") lights = tunablelights if lights: for node in lights: Domoticz.Debug("Light detected " + node["name"]) if "RSSI" in node["attributes"]: rssi = 12*((0 - node["attributes"]["RSSI"]["reportedValue"])/100) else: rssi = 0 found = False for unit in Devices: if node['id'] == Devices[unit].DeviceID: if unit not in set(self.lightsSet): self.lightsSet.add(unit) Domoticz.Debug(Devices[unit].Name + ": " + node["attributes"]["presence"]["reportedValue"]) if node["attributes"]["presence"]["reportedValue"] == "ABSENT": if self.TimedOutAvailable: if Devices[unit].TimedOut == 0: Devices[unit].Update(nValue=0, sValue='Off', TimedOut=1, SignalLevel=0) else: Domoticz.Log("Device Offline : " + Devices[unit].Name) else: # Work on targetValues (allows to update devices on the return of an update posted but not yet executed) if "state" not in node["attributes"]: node["attributes"]["state"] = {} node["attributes"]["state"]["targetValue"] = "OFF" node["attributes"]["state"]["reportedValue"] = "OFF" if ("targetValue" in node["attributes"]["state"] and node["attributes"]["state"]["targetValue"] == "OFF") or \ ("targetValue" not in node["attributes"]["state"] and node["attributes"]["state"]["reportedValue"] == "OFF"): if Devices[unit].nValue != 0: # Device not already off if self.TimedOutAvailable: Devices[unit].Update(nValue=0, sValue='Off', TimedOut=0, SignalLevel=int(rssi)) else: Devices[unit].Update(nValue=0, sValue='Off', SignalLevel=int(rssi)) else: # Device is already off but could have been timed out if self.TimedOutAvailable: if Devices[unit].TimedOut: Devices[unit].Update(nValue=0, sValue='Off', TimedOut=0, SignalLevel=int(rssi)) else: if "targetValue" not in node["attributes"]["brightness"]: node["attributes"]["brightness"]["targetValue"] = node["attributes"]["brightness"]["reportedValue"] Domoticz.Debug("Brightness Target: " + str(Devices[unit].LastLevel)) Domoticz.Debug("Brightness: " + str(node["attributes"]["brightness"]["targetValue"])) if Devices[unit].LastLevel != int(node["attributes"]["brightness"]["targetValue"]) or Devices[unit].sValue == 'Off': if self.TimedOutAvailable: if node["attributes"]["model"]["reportedValue"] == "RGBBulb01UK": # Don't bother with colours as there is currently nowhere in domoticz to store these # 1 = Set Level for rgbww dimmer Devices[unit].Update(nValue=1, sValue=str(node["attributes"]["brightness"]["targetValue"]), TimedOut=0, SignalLevel=int(rssi)) elif node["attributes"]["model"]["reportedValue"] == "TWBulb01UK" \ or node["attributes"]["model"]["reportedValue"] == "TWBulb01US" \ or node["attributes"]["model"]["reportedValue"] == "TWGU10Bulb01UK" \ or node["attributes"]["model"]["reportedValue"] == "FWCLBulb01UK": # 1 = Set Level for ww dimmer Devices[unit].Update(nValue=1, sValue=str(node["attributes"]["brightness"]["targetValue"]), TimedOut=0, SignalLevel=int(rssi)) elif node["attributes"]["model"]["reportedValue"] == "FWBulb01" \ or node["attributes"]["model"]["reportedValue"] == "FWBulb02UK": # 2 = Set Level Devices[unit].Update(nValue=2, sValue=str(node["attributes"]["brightness"]["targetValue"]), TimedOut=0, SignalLevel=int(rssi)) else: Domoticz.Debug("Unknown Light") else: # 2 = Set Level Devices[unit].Update(nValue=2, sValue=str(node["attributes"]["brightness"]["targetValue"]), SignalLevel=int(rssi)) found = True Domoticz.Debug("Light finished " + node["name"]) break if not found: Domoticz.Log("Light not found " + node["name"]) created = False newUnit = self.GetNextUnit(False) if node["attributes"]["model"]["reportedValue"] == "RGBBulb01UK": # RGB WW CW Bulb Domoticz.Device(Name = node["name"], Unit = newUnit, Type=241, Subtype=4, Switchtype=7, DeviceID = node['id']).Create() created = True elif node["attributes"]["model"]["reportedValue"] == "TWBulb01UK" \ or node["attributes"]["model"]["reportedValue"] == "TWBulb01US" \ or node["attributes"]["model"]["reportedValue"] == "TWGU10Bulb01UK": # TW CW Bulb Domoticz.Device(Name = node["name"], Unit = newUnit, Type=241, Subtype=8, Switchtype=7, DeviceID = node['id']).Create() created = True elif node["attributes"]["model"]["reportedValue"] == "FWBulb01" \ or node["attributes"]["model"]["reportedValue"] == "FWBulb02UK" \ or node["attributes"]["model"]["reportedValue"] == "FWCLBulb01UK": # Standard dimmable light Domoticz.Device(Name = node["name"], Unit = newUnit, Type=244, Subtype=73, Switchtype=7, DeviceID = node['id']).Create() created = True else: Domoticz.Debug("Unknown Light") if created: if "state" in node["attributes"]: if node["attributes"]["state"]["reportedValue"] == "OFF": Domoticz.Debug("New Device Off") Devices[newUnit].Update(nValue=0, sValue='Off', SignalLevel=int(rssi)) else: Domoticz.Debug("New Device On") Devices[newUnit].Update(nValue=2, sValue=str(node["attributes"]["brightness"]["reportedValue"]), SignalLevel=int(rssi)) # 2 = Set Level else: Devices[newUnit].Update(nValue=0, sValue='Off', SignalLevel=int(rssi)) activeplugs = self.GetActivePlugs(d) if activeplugs: for node in activeplugs: for unit in Devices: # Active plugs also have internalTemperature, energyConsumed and powerConsumption if "RSSI" in node["attributes"]: rssi = 12*((0 - node["attributes"]["RSSI"]["reportedValue"])/100) else: rssi = 0 if node['id'] == Devices[unit].DeviceID and Devices[unit].Type == 244: if unit not in set(self.activeplugsSet): self.activeplugsSet.add(unit) if node["attributes"]["presence"]["reportedValue"] == "ABSENT": if self.TimedOutAvailable: if Devices[unit].TimedOut == 0: Devices[unit].Update(nValue=Devices[unit].nValue, sValue=Devices[unit].sValue, TimedOut=1, SignalLevel=0) else: Domoticz.Log("Device Offline : " + Devices[unit].Name) else: if node["attributes"]["state"]["reportedValue"] == "OFF": if Devices[unit].nValue != 0: if self.TimedOutAvailable: Devices[unit].Update(nValue=0, sValue='Off', TimedOut=0, SignalLevel=int(rssi)) else: Devices[unit].Update(nValue=0, sValue='Off', SignalLevel=int(rssi)) else: Domoticz.Debug("State: " + Devices[unit].sValue) if Devices[unit].nValue != 1: if self.TimedOutAvailable: Devices[unit].Update(nValue=1, sValue='On', TimedOut=0, SignalLevel=int(rssi)) else: Devices[unit].Update(nValue=1, sValue='On', SignalLevel=int(rssi)) for unit1 in Devices: if node['id'] == Devices[unit1].DeviceID and Devices[unit1].Type == 80: if "internalTemperature" in node["attributes"]: Domoticz.Debug("ActivePlug Temperature found " + node["name"]) Devices[unit1].Update(nValue = 0, sValue = str(node["attributes"]["internalTemperature"]["reportedValue"])) break else: # Create a temperature device to go with the plug Domoticz.Debug("ActivePlug Temperature not found " + node["name"]) newUnit = self.GetNextUnit(False) Domoticz.Device(Name = node["name"]+" - Temperature", Unit = newUnit, TypeName = "Temperature", DeviceID = node['id']).Create() Devices[newUnit].Update(nValue = 0, sValue = str(node["attributes"]["internalTemperature"]["reportedValue"])) break else: Domoticz.Log("ActivePlug not found " + node["name"]) newUnit = self.GetNextUnit(False) Domoticz.Device(Name = node["name"], Unit = newUnit, TypeName = "Switch", Switchtype = 0, DeviceID = node['id']).Create() if "state" in node["attributes"]: if node["attributes"]["state"]["reportedValue"] == "OFF": Devices[newUnit].Update(nValue=0, sValue='Off', SignalLevel=int(rssi)) else: Devices[unit].Update(nValue=1, sValue='On', SignalLevel=int(rssi)) else: Devices[newUnit].Update(nValue=0, sValue='Off', SignalLevel=int(rssi)) # Create a temperature device to go with the plug newUnit = self.GetNextUnit(False) Domoticz.Device(Name = node["name"]+" - Temperature", Unit = newUnit, TypeName = "Temperature", DeviceID = node['id']).Create() if "internalTemperature" in node["attributes"]: Devices[newUnit].Update(nValue = 0, sValue = str(node["attributes"]["internalTemperature"]["reportedValue"])) else: Devices[newUnit].Update(nValue = 0, sValue = "0")
def onMessage(self, Connection, Data): self.DumpVariable(Data, "OnMessage Data") self.readBytes.extend(Data) if len(self.readBytes) > 3: if (self.readBytes[0] != 0x68 or self.readBytes[1] != 0x73 or self.readBytes[2] != 0x41): # incorrect message, purge it self.outstandingMessages = self.outstandingMessages - 1 if not self.errorIncorrectStartReported: self.DumpVariable(self.readBytes, "Incorrect start message purge it", Level=4) self.nofIncorrectMessages = self.nofIncorrectMessages + 1 self.lastIncorrectStart = datetime.datetime.now() self.Log( "Incorrect message received. Occurrences: " + str(self.nofIncorrectMessages), 3, 3) self.errorIncorrectStartReported = True self.readBytes.clear() if len(self.readBytes) > 155: self.outstandingMessages = self.outstandingMessages - 1 if (self.readBytes[154] == 0x4F and self.readBytes[155] == 0x4B): if self.errorIncorrectStartReported: self.errorIncorrectStartReported = False endtime = datetime.datetime.now() self.Log( "First correct message received, duration: " + str(endtime - self.lastIncorrectStart), 3, 2) vac = [] vdc = [] pac = [] vac.append(self.GetValue(self.readBytes, 51, 2, 10)) # volt vac.append(self.GetValue(self.readBytes, 53, 2, 10)) vac.append(self.GetValue(self.readBytes, 55, 2, 10)) vdc.append(self.GetValue(self.readBytes, 33, 2, 10)) # Volt vdc.append(self.GetValue(self.readBytes, 35, 2, 10)) vdc.append(self.GetValue(self.readBytes, 37, 2, 10)) pac.append(self.GetValue(self.readBytes, 59, 2, 1)) # watt pac.append(self.GetValue(self.readBytes, 63, 2, 1)) pac.append(self.GetValue(self.readBytes, 67, 2, 1)) temperature = self.GetValue(self.readBytes, 31, 2, 10) #Celcius self.totalEnergy = self.GetValue(self.readBytes, 71, 4, 0.01) # wh 0.01 #self.outstandingMessages = self.outstandingMessages - 1 self.Log( "VAC: " + str(vac) + " VDC: " + str(vdc) + " PAC: " + str(pac) + " Total: " + str(self.totalEnergy) + " Temperature: " + str(temperature), 5, 2) # add / update devices if needed for i in range(3): if (vac[i] > 0 or vdc[i] > 0 or pac[i] > 0): unt = 2 + i * 3 if (unt not in Devices): Domoticz.Device(Name=("VAC " + str(i + 1)), Unit=unt, Type=243, Subtype=8, Switchtype=0, Image=0).Create() self.UpdateDevice(unt, 0, vac[i]) unt = unt + 1 if (unt not in Devices): Domoticz.Device(Name=("VDC " + str(i + 1)), Unit=unt, Type=243, Subtype=8, Switchtype=0, Image=0).Create() self.UpdateDevice(unt, 0, vdc[i]) unt = unt + 1 if (unt not in Devices): Domoticz.Device(Name=("Power " + str(i + 1)), Unit=unt, Type=243, Subtype=29, Switchtype=4, Image=0).Create() self.UpdateDevice(unt, 0, pac[i], self.totalEnergy) self.UpdateDevice(1, 0, temperature) self.DumpVariable(self.readBytes, "Correct messsage", Level=8) self.readBytes.clear() else: self.DumpVariable(self.readBytes, "Incorrect messsage", Level=4) self.readBytes.clear() return
def onStart(self): Domoticz.Debug("onStart called") try: self.freeboxURL = Parameters["Address"] + ":" + Parameters["Port"] if Parameters["Mode6"] == "Debug": Domoticz.Debugging(1) DumpConfigToLog() if Parameters["Mode1"] == "": # Le Token Domoticz.Log( "C'est votre première connexion, le token n'est pas renseigné." ) Domoticz.Log( "Vous avez 30 secondes pour autoriser le plugin sur l'écran de la Freebox." ) Domoticz.Log( "Une fois autorisé sur la Freebox, le token s'affichera ici." ) Token = freebox.FbxCnx(self.freeboxURL).register( "idPluginDomoticz", "Plugin Freebox", "1", "Domoticz") if Token: Domoticz.Log( "------------------------------------------------------------------------------" ) Domoticz.Log( "Veuillez copier ce token dans la configuration du plugin Reglages > Matériel" ) Domoticz.Log(Token) Domoticz.Log( "------------------------------------------------------------------------------" ) else: Domoticz.Log( "Vous avez été trop long (ou avez refusé), veuillez désactiver et réactiver le matériel Reglages > Matériel." ) else: self.token = Parameters["Mode1"] Domoticz.Log("Token déjà présent. OK.") f = freebox.FbxApp("idPluginDomoticz", self.token, host=self.freeboxURL) #Pour trouver le pb avec la FreeBox Delta, on affiche le json #if Parameters["Mode6"] == "Debug": # jsonUsageDisk = f.diskinfoRaw() # Domoticz.Debug(jsonUsageDisk) #Creation des device Disque Dur de la Freebox usageDisk = f.diskinfo() for disk in usageDisk: keyunit = self.getOrCreateUnitIdForDevice( self.DeviceType.deviceTypeDisk, disk) if (keyunit not in Devices): v_dev = Domoticz.Device(Unit=keyunit, Name="Utilisation " + disk, TypeName="Percentage") v_dev.Create() Domoticz.Log("Création du dispositif " + "Utilisation " + disk) # Unfortunately the image in the Percentage device can not be changed. Use Custom device! # Domoticz.Device(Unit=_UNIT_USAGE, Name=Parameters["Address"], TypeName="Custom", Options={"Custom": "1;%"}, Image=3, Used=1).Create() #Creation des device infos systeme de la Freebox sysinfo = f.sysinfo() for info in sysinfo: keyunit = self.getOrCreateUnitIdForDevice( self.DeviceType.deviceSystemInfo, info) if (keyunit not in Devices): v_dev = Domoticz.Device(Unit=keyunit, Name="System " + info, TypeName="Temperature") v_dev.Create() Domoticz.Log("Création du dispositif " + "System " + info) #Creation des device presence de la Freebox listeMacString = Parameters["Mode2"] if (listeMacString != ""): listeMac = listeMacString.split(";") for macAdresse in listeMac: name = f.getNameByMacAdresse(macAdresse) if (name != None): keyunit = self.getOrCreateUnitIdForDevice( self.DeviceType.devicePresence, macAdresse) if (keyunit not in Devices): v_dev = Domoticz.Device(Unit=keyunit, Name="Presence " + name, TypeName="Switch") v_dev.Create() Domoticz.Log("Création du dispositif " + "Presence " + name) else: Domoticz.Log( "La mac adresse " + macAdresse + " est inconnu de la freebox, on ne crée aucun dispositif." ) #Creation du device d'activation/désactivation du WIFI v_etatWIFI = f.isOnWIFI() Domoticz.Log("Etat WIFI : " + str(v_etatWIFI)) keyunit = self.getOrCreateUnitIdForDevice( self.DeviceType.deviceCommande, "WIFI") if (keyunit not in Devices): v_dev = Domoticz.Device(Unit=keyunit, Name="WIFI On/Off", TypeName="Switch") v_dev.Create() Domoticz.Log("Création du dispositif " + "WIFI On/Off") self.updateDeviceIfExist(self.DeviceType.deviceCommande, "WIFI", v_etatWIFI, str(v_etatWIFI)) #Creation du device de reboot du Freebox server #f.reboot() keyunit = self.getOrCreateUnitIdForDevice( self.DeviceType.deviceCommande, "REBOOT") if (keyunit not in Devices): v_dev = Domoticz.Device(Unit=keyunit, Name="Reboot Server", TypeName="Switch") v_dev.Create() Domoticz.Log("Création du dispositif " + "Reboot Server") DumpConfigToLog() except Exception as e: Domoticz.Log("OnStart error: " + str(e))
def onStart(self): global _tv if Parameters["Mode6"] == "Debug": Domoticz.Debugging(1) self.debug = True #TODO: get number of inputs and apps to build list self.SourceOptions3 = { "LevelActions": "||||||", "LevelNames": "Off|TV|HDMI1|HDMI2|HDMI3|Hulu|Netflix", "LevelOffHidden": "true", "SelectorStyle": "0" } if (len(Devices) == 0): Domoticz.Device(Name="Status", Unit=1, Type=17, Image=2, Switchtype=17).Create() if Parameters["Mode3"] == "Volume": Domoticz.Device(Name="Volume", Unit=2, Type=244, Subtype=73, Switchtype=7, Image=8).Create() Domoticz.Device(Name="Source", Unit=3, TypeName="Selector Switch", Switchtype=18, Image=2, Options=self.SourceOptions3).Create() Domoticz.Log("Devices created") elif (Parameters["Mode3"] == "Volume" and 2 not in Devices): Domoticz.Device(Name="Volume", Unit=2, Type=244, Subtype=73, Switchtype=7, Image=8).Create() Domoticz.Log("Volume device created") elif (Parameters["Mode3"] != "Volume" and 2 in Devices): Devices[2].Delete() Domoticz.Log("Volume device deleted") elif 1 not in Devices: Domoticz.Device(Name="Status", Unit=1, Type=17, Image=2, Switchtype=17).Create() Domoticz.Log("TV device created") elif 3 not in Devices: Domoticz.Device(Name="Source", Unit=3, TypeName="Selector Switch", Switchtype=18, Image=2, Options=self.SourceOptions3).Create() Domoticz.Log("Source device created") else: if (1 in Devices): self.tvState = Devices[1].nValue #--> of sValue if (2 in Devices): self.tvVolume = Devices[2].nValue #--> of sValue if (3 in Devices): self.tvSource = Devices[3].sValue # Set update interval, values below 10 seconds are not allowed due to timeout of 5 seconds in bravia.py script updateInterval = int(Parameters["Mode5"]) if updateInterval < 30: if updateInterval < 10: updateInterval == 10 Domoticz.Log("Update interval set to " + str(updateInterval) + " (minimum is 10 seconds)") Domoticz.Heartbeat(updateInterval) else: Domoticz.Heartbeat(30) if self.debug == True: DumpConfigToLog() return #--> return True
def onStart(self): Domoticz.Log("onStart called") Domoticz.Heartbeat(30) if Parameters["Mode6"] == "Debug": Domoticz.Debugging(1) #Login to ZoneMinder self.api.login() #Get all existing monitors from ZoneMinder cmd = '/api/monitors.json' monitors = self.api.call(cmd) Domoticz.Debug("Number of found monitors: " + str(len(monitors['monitors']))) Domoticz.Debug(str(len(monitors['monitors']))) Domoticz.Debug(str(monitors)) #Create Devices for each monitor that was found if len(Devices) == 0: if (len(monitors) > 0): Options = { "LevelActions": "||||", "LevelNames": "Start|Stop|Restart", "LevelOffHidden": "True", "SelectorStyle": "0" } Domoticz.Device(Name="State", Unit=1, TypeName="Selector Switch", Switchtype=18, Image=12, Options=Options).Create() Domoticz.Log("Device State with id 1 was created.") for monitor in monitors['monitors']: Id = monitor['Monitor']['Id'] Name = monitor['Monitor']['Name'] Options = { "LevelActions": "|||||||", "LevelNames": "None|Monitor|Modect|Record|Mocord|Nodect", "LevelOffHidden": "True", "SelectorStyle": "0" } Domoticz.Device(Name="Monitor " + str(Name) + " Function", Unit=int(Id + "1"), TypeName="Selector Switch", Switchtype=18, Image=12, Options=Options).Create() Domoticz.Log("Device Monitor " + str(Name) + " Function with id " + str(Id) + "1 was created.") Domoticz.Device(Name="Monitor " + str(Name) + " Status", Unit=int(Id + "2"), Type=17, Switchtype=0).Create() Domoticz.Log("Device Monitor " + str(Name) + " Status with id " + str(Id) + "2 was created.")
def onMessage(self, Data, Status, Extra): self.dataIntervalCount += self.pluginInterval self.switchIntervalCount += self.pluginInterval if (self.dataIntervalCount >= self.dataInterval or self.switchIntervalCount >= self.switchInterval): try: self.smr_version = Data['smr_version'] self.meter_model = Data['meter_model'] self.wifi_ssid = Data['wifi_ssid'] self.wifi_strength = Data['wifi_strength'] self.total_power_import_t1_kwh = int( Data['total_power_import_t1_kwh'] * 1000) self.total_power_import_t2_kwh = int( Data['total_power_import_t2_kwh'] * 1000) self.total_power_export_t1_kwh = int( Data['total_power_export_t1_kwh'] * 1000) self.total_power_export_t2_kwh = int( Data['total_power_export_t2_kwh'] * 1000) self.active_power_w = Data['active_power_w'] self.active_power_l1_w = Data['active_power_l1_w'] self.active_power_l2_w = Data['active_power_l2_w'] self.active_power_l3_w = Data['active_power_l3_w'] self.total_gas_m3 = int(Data['total_gas_m3'] * 1000) self.gas_timestamp = Data['gas_timestamp'] if (self.active_power_w >= 0): self.import_active_power_w = self.active_power_w self.export_active_power_w = 0 else: self.import_active_power_w = 0 self.export_active_power_w = self.active_power_w * -1 except: Domoticz.Error("Failed to read response data") return if (self.dataIntervalCount >= self.dataInterval): self.dataIntervalCount = 0 try: if (self.active_power_id not in Devices): Domoticz.Device(Name="Current usage", Unit=self.active_power_id, Type=243, Subtype=29).Create() UpdateDevice(self.active_power_id, 0, numStr(self.active_power_w) + ";0", True) except: Domoticz.Error("Failed to update device id " + str(self.active_power_id)) try: if (self.total_power_id not in Devices): Domoticz.Device(Name="Total electricity", Unit=self.total_power_id, Type=250, Subtype=1).Create() UpdateDevice( self.total_power_id, 0, numStr(self.total_power_import_t1_kwh) + ";" + numStr(self.total_power_import_t2_kwh) + ";" + numStr(self.total_power_export_t1_kwh) + ";" + numStr(self.total_power_export_t2_kwh) + ";" + numStr(self.import_active_power_w) + ";" + numStr(self.export_active_power_w), True) except: Domoticz.Error("Failed to update device id " + str(self.total_power_id)) try: if (self.total_gas_id not in Devices): Domoticz.Device(Name="Total gas", Unit=self.total_gas_id, TypeName="Gas").Create() UpdateDevice(self.total_gas_id, 0, numStr(self.total_gas_m3), True) except: Domoticz.Error("Failed to update device id " + str(self.total_gas_id)) try: if (self.wifi_signal_id not in Devices): Domoticz.Device(Name="Wifi signal", Unit=self.wifi_signal_id, TypeName="Percentage").Create() UpdateDevice(self.wifi_signal_id, 0, numStr(self.wifi_strength), True) except: Domoticz.Error("Failed to update device id " + str(self.wifi_signal_id)) if (self.switchIntervalCount >= self.switchInterval): self.switchIntervalCount = 0 try: if (self.switch_export_id not in Devices): Domoticz.Device(Name="Production switch", Unit=self.switch_export_id, TypeName="Switch").Create() if (self.export_active_power_w > 0): UpdateDevice(self.switch_export_id, 1, "On") else: UpdateDevice(self.switch_export_id, 0, "Off") except: Domoticz.Error("Failed to update device id " + str(self.switch_export_id)) if (self.productionSwitchValue > 0): try: if (self.switch_export_value_id not in Devices): Domoticz.Device(Name="Production value switch", Unit=self.switch_export_value_id, TypeName="Switch").Create() if (self.export_active_power_w >= self.productionSwitchValue): UpdateDevice(self.switch_export_value_id, 1, "On") else: UpdateDevice(self.switch_export_value_id, 0, "Off") except: Domoticz.Error("Failed to update device id " + str(self.switch_export_value_id)) if (self.usageSwitchValue > 0): try: if (self.switch_import_value_id not in Devices): Domoticz.Device(Name="Usage value switch", Unit=self.switch_import_value_id, TypeName="Switch").Create() if (self.import_active_power_w >= self.usageSwitchValue): UpdateDevice(self.switch_import_value_id, 1, "On") else: UpdateDevice(self.switch_import_value_id, 0, "Off") except: Domoticz.Error("Failed to update device id " + str(self.switch_import_value_id)) return True
def onStart(self): if (int(Parameters["Mode2"]) >= 30): self.pollinterval = int(Parameters["Mode2"]) # Create valve device iUnit = -1 for Device in Devices: try: if (Devices[Device].DeviceID.strip() == "cometblue-" + str(Parameters["Address"])): iUnit = Device break except: pass if iUnit < 0: # if device does not exists in Domoticz, than create it try: iUnit = 0 for x in range(1, 256): if x not in Devices: iUnit = x break if iUnit == 0: iUnit = len(Devices) + 1 Domoticz.Device(Name="cometblue-" + str(Parameters["Address"]), Unit=iUnit, DeviceID="cometblue-" + str(Parameters["Address"]), Type=242, Subtype=1, Used=1).Create() except Exception as e: Domoticz.Debug(str(e)) return False # Create temperature device iUnit = -1 for Device in Devices: try: if (Devices[Device].DeviceID.strip() == "cometblue-" + str(Parameters["Address"]) + "-temp"): iUnit = Device break except: pass if iUnit < 0: # if device does not exists in Domoticz, than create it try: iUnit = 0 for x in range(1, 256): if x not in Devices: iUnit = x break if iUnit == 0: iUnit = len(Devices) + 1 Domoticz.Device( Name="cometblue-" + str(Parameters["Address"]) + "-temp", Unit=iUnit, DeviceID="cometblue-" + str(Parameters["Address"]) + "-temp", TypeName="Temperature", Used=1).Create() except Exception as e: Domoticz.Debug(str(e)) return False
def onStart(self): if Parameters["Mode6"] == "Debug": Domoticz.Debugging(1) DumpAllToLog() # Do not change below UNIT constants! self.UNIT_STATUS_REMOTE = 1 self.UNIT_POWER_CONTROL = 2 try: "parse" in dir(xmltodict) self.isXmltodict = True except Exception as e: print(e) self.isXmltodict = False pass if (len(Devices) == 0): Domoticz.Device(Name="Status", Unit=self.UNIT_STATUS_REMOTE, Type=17, Image=2, Switchtype=17).Create() Options = { "LevelActions": "||||", "LevelNames": "Off|Standby|Reboot|RestartE2|On", "LevelOffHidden": "true", "SelectorStyle": "0" } Domoticz.Device(Name="Source", Unit=self.UNIT_POWER_CONTROL, TypeName="Selector Switch", Switchtype=18, Image=12, Options=Options).Create() Domoticz.Log("Devices created.") self.pollPeriod = int(Parameters["Mode3"]) self.pollCount = self.pollPeriod - 1 Domoticz.Heartbeat(10) self.config = { "description": "Domoticz", "user": Parameters["Mode1"], "password": Parameters["Mode2"], "host": Parameters["Address"], "port": int(Parameters["Port"]), } Domoticz.Log("Connecting to: " + Parameters["Address"] + ":" + Parameters["Port"]) self.isAlive() if (self.isConnected == True): if Parameters["Mode6"] == "Debug": Domoticz.Log("Devices are connected - Initialisation") UpdateDevice(self.UNIT_STATUS_REMOTE, 1, 'Enigma2 ON') self.EnigmaDetails() UpdateDevice(self.UNIT_POWER_CONTROL, 40, '40') return True
def onStart(self): # setup the appropriate logging level try: debuglevel = int(Parameters["Mode6"]) except ValueError: debuglevel = 0 self.loglevel = Parameters["Mode6"] if debuglevel != 0: self.debug = True Domoticz.Debugging(debuglevel) DumpConfigToLog() self.loglevel = "Verbose" else: self.debug = False Domoticz.Debugging(0) # check if the host domoticz version supports the Domoticz.Status() python framework function try: Domoticz.Status( "This version of domoticz allows status logging by the plugin (in verbose mode)" ) except Exception: self.statussupported = False # create the child devices if these do not exist yet devicecreated = [] if 1 not in Devices: Options = { "LevelActions": "||", "LevelNames": "Off|Auto|Forced", "LevelOffHidden": "false", "SelectorStyle": "0" } Domoticz.Device(Name="Thermostat Control", Unit=1, TypeName="Selector Switch", Switchtype=18, Image=15, Options=Options, Used=1).Create() devicecreated.append(deviceparam(1, 0, "0")) # default is Off state if 2 not in Devices: Options = { "LevelActions": "||", "LevelNames": "Off|Normal|Economy", "LevelOffHidden": "true", "SelectorStyle": "0" } Domoticz.Device(Name="Thermostat Mode", Unit=2, TypeName="Selector Switch", Switchtype=18, Image=15, Options=Options, Used=1).Create() devicecreated.append(deviceparam(2, 0, "10")) # default is normal mode if 3 not in Devices: Domoticz.Device(Name="Thermostat Pause", Unit=3, TypeName="Switch", Image=9, Used=1).Create() devicecreated.append(deviceparam(3, 0, "")) # default is Off if 4 not in Devices: Domoticz.Device(Name="Setpoint Normal", Unit=4, Type=242, Subtype=1, Used=1).Create() devicecreated.append(deviceparam(4, 0, "20")) # default is 20 degrees if 5 not in Devices: Domoticz.Device(Name="Setpoint Economy", Unit=5, Type=242, Subtype=1, Used=1).Create() devicecreated.append(deviceparam(5, 0, "17")) # default is 17 degrees if 6 not in Devices: Domoticz.Device(Name="Thermostat temp", Unit=6, TypeName="Temperature").Create() devicecreated.append(deviceparam(6, 0, "20")) # default is 20 degrees # if any device has been created in onStart(), now is time to update its defaults for device in devicecreated: Devices[device.unit].Update(nValue=device.nvalue, sValue=device.svalue) # build lists of sensors and switches self.InTempSensors = parseCSV(Parameters["Mode1"]) self.WriteLog( "Inside Temperature sensors = {}".format(self.InTempSensors), "Verbose") self.OutTempSensors = parseCSV(Parameters["Mode2"]) self.WriteLog( "Outside Temperature sensors = {}".format(self.OutTempSensors), "Verbose") self.Heaters = parseCSV(Parameters["Mode3"]) self.WriteLog("Heaters = {}".format(self.Heaters), "Verbose") # build dict of status of all temp sensors to be used when handling timeouts for sensor in itertools.chain(self.InTempSensors, self.OutTempSensors): self.ActiveSensors[sensor] = True # splits additional parameters params = parseCSV(Parameters["Mode5"]) if len(params) == 5 or len(params) == 6: self.calculate_period = CheckParam("Calculation Period", params[0], 30) if self.calculate_period < 5: Domoticz.Error( "Invalid calculation period parameter. Using minimum of 5 minutes !" ) self.calculate_period = 5 self.minheatpower = CheckParam("Minimum Heating (%)", params[1], 0) if self.minheatpower > 100: Domoticz.Error( "Invalid minimum heating parameter. Using maximum of 100% !" ) self.minheatpower = 100 self.pauseondelay = CheckParam("Pause On Delay", params[2], 2) self.pauseoffdelay = CheckParam("Pause Off Delay", params[3], 0) self.forcedduration = CheckParam("Forced Mode Duration", params[4], 60) if self.forcedduration < 15: Domoticz.Error( "Invalid forced mode duration parameter. Using minimum of 15 minutes !" ) self.forcedduration = 15 if len(params) > 5: self.deltamax = CheckParam("Delta max", params[5], 0.2) else: Domoticz.Error( "Delta max missing in parameters. Add the field in the plugin configuration (default value=0.2)" ) else: Domoticz.Error("Error reading Mode5 parameters") # loads persistent variables from dedicated user variable # note: to reset the thermostat to default values (i.e. ignore all past learning), # just delete the relevant "<plugin name>-InternalVariables" user variable Domoticz GUI and restart plugin self.getUserVar() # if mode = off then make sure actual heating is off just in case if was manually set to on if Devices[1].sValue == "0": self.switchHeat(False)
def handle_hwstatus(self, data): # Get partition for status update part = int(data[4:6]) # Get overall status status = int(data[7:11], 16) # check armed status if status & 0x8000 > 0: # armed stay (3=with zero delay) self.alarmState['partition'][part]['status'].update( evl_ArmModes['3' if status & 0x80 > 0 else '1']['status']) elif status & 0x4 > 0: # armed away (2=with zero delay) self.alarmState['partition'][part]['status'].update( evl_ArmModes['2' if status & 0x80 > 0 else '0']['status']) else: # disarmed, but is it 'ready' or not if status & 0x1000 > 0: # Ready self.alarmState['partition'][part]['status'].update( evl_ResponseTypes['650']['status']) # zones bypassed ? if status & 0x80 > 0: self.alarmState['partition'][part]['status'][ 'alpha'] = "Ready with zones bypassed" else: # Not ready self.alarmState['partition'][part]['status'].update( evl_ResponseTypes['651']['status']) # Read zone number and mark it as open and save last fault time zone = int(data[12:14]) self.alarmState['zone'][zone]['partition'] = part self.alarmState['zone'][zone]['last_fault'] = time() self.alarmState['zone'][zone]['status']['open'] = True # If we don't have a device for it if (not ZONE_BASE + zone in Devices): Domoticz.Device(Name="Zone " + str(ZONE_BASE + zone), Unit=ZONE_BASE + zone, Type=244, Subtype=73, Switchtype=11).Create() # Make sure device has initial state UpdateDevice(ZONE_BASE + zone, 1, 'Open', self.alarmState['zone'][zone]['status']['bypass']) # Get AC status if status & 0x8: self.alarmState['partition'][part]['status']['ac_present'] = True UpdateDevice(ACIDX, 1, "ON", False) else: self.alarmState['partition'][part]['status']['ac_present'] = False UpdateDevice(ACIDX, 0, "OFF", False) # Get Chime status if status & 0x20: self.alarmState['partition'][part]['status']['chime'] = True UpdateDevice(CHIMEIDX, 1, "ON", False) else: self.alarmState['partition'][part]['status']['chime'] = False UpdateDevice(CHIMEIDX, 0, "OFF", False) self.updateDomoticz()
def updateDomoticz(self): # Sync Devices to Alarm state for zone in self.alarmState['zone']: # For DSC Always check/add zones as devices, For Honeywell they're added on auto-detection (during zone timer dump) if self.HWTYPE == 0 and (not ZONE_BASE + zone in Devices): Domoticz.Device(Name="Zone " + str(ZONE_BASE + zone), Unit=ZONE_BASE + zone, Type=244, Subtype=73, Switchtype=2).Create() sValue = 'Closed' if self.alarmState['zone'][zone]['status']['open']: sValue = 'Open' if self.alarmState['zone'][zone]['status']['bypass']: sValue = 'Bypass' if self.alarmState['zone'][zone]['status']['tamper']: sValue = 'Tamper' UpdateDevice(ZONE_BASE+zone, \ 1 if self.alarmState['zone'][zone]['status']['open'] else 0, \ sValue, \ self.alarmState['zone'][zone]['status']['bypass']) for part in self.alarmState['partition']: if (not PARTITION_BASE + part in Devices): Domoticz.Device(Name="Partition " + str(part), Unit=PARTITION_BASE + part, TypeName='Alert').Create() nValue = 1 if self.alarmState['partition'][part]['status'][ 'ready'] else 2 if self.alarmState['partition'][part]['status']['trouble']: nValue = 2 if self.alarmState['partition'][part]['status']['alarm']: nValue = 3 UpdateDevice(PARTITION_BASE+part, nValue, \ self.alarmState['partition'][part]['status']['alpha'], \ self.alarmState['partition'][part]['status']['trouble']) if Parameters["Mode3"] != "False": if (not SECURITY_PANEL in Devices): #Domoticz.Device(Name="Security Panel", Unit=SECURITY_PANEL, TypeName="Security Panel").Create() Domoticz.Device(Name="Security Panel", Unit=SECURITY_PANEL, Type=32, Subtype=131).Create() Domoticz.Log( "Created Domoticz integrated Security Panel device for partition 1." ) nValue = 0 # sStatusNormal if self.alarmState['partition'][1]['status']['alarm']: nValue = 2 # sStatusAlarm if self.alarmState['partition'][1]['status']['armed_away']: nValue = 9 # sStatusArmAway if self.alarmState['partition'][1]['status']['armed_stay']: nValue = 11 # sStatusArmHome if self.alarmState['partition'][1]['status']['trouble']: nValue = nValue + 128 # sStatusNormalTamper or sStatusAlarmTamper UpdateDevice(SECURITY_PANEL, nValue, "", self.alarmState['partition'][1]['status']['trouble']) if self.HWTYPE == 1: sText = '0' if self.alarmState['partition'][1]['status'][ 'armed_zero_entry_delay']: if self.alarmState['partition'][1]['status']['armed_away']: sText = '30' if self.alarmState['partition'][1]['status']['armed_stay']: sText = '40' else: if self.alarmState['partition'][1]['status']['armed_away']: sText = '10' if self.alarmState['partition'][1]['status']['armed_stay']: sText = '20' UpdateDevice(ARMIDX, 2, sText, self.alarmState['partition'][1]['status']['trouble'])
def onStart(self): # setup the appropriate logging level try: debuglevel = int(Parameters["Mode6"]) except ValueError: debuglevel = 0 self.loglevel = Parameters["Mode6"] if debuglevel != 0: self.debug = True Domoticz.Debugging(debuglevel) DumpConfigToLog() self.loglevel = "Verbose" else: self.debug = False Domoticz.Debugging(0) # create the child devices if these do not exist yet devicecreated = [] if 1 not in Devices: Domoticz.Device(Name="Surveillance", Unit=1, TypeName="Switch", Image=9, Used=1).Create() devicecreated.append(deviceparam(1, 0, "")) # default is Off if 2 not in Devices: Domoticz.Device(Name="Detection", Unit=2, TypeName="Switch", Image=9, Used=1).Create() devicecreated.append(deviceparam(2, 0, "")) # default is Off if 3 not in Devices: Domoticz.Device(Name="Intrusion Detected", Unit=3, TypeName="Switch", Image=13, Used=1).Create() devicecreated.append(deviceparam(3, 0, "")) # default is Off if 4 not in Devices: Domoticz.Device(Name="Zone Alarm", Unit=4, TypeName="Switch", Image=13, Used=1).Create() devicecreated.append(deviceparam(4, 0, "")) # default is Off # if any device has been created in onStart(), now is time to update its defaults for device in devicecreated: Devices[device.unit].Update(nValue=device.nvalue, sValue=device.svalue) # build lists of alarm sensors self.DTAlarm = parseCSV(Parameters["Mode1"]) Domoticz.Debug("Alarm Sensors for this Zone = {}".format(self.DTAlarm)) # splits additional parameters params = parseCSV(Parameters["Mode5"]) if len(params) == 3: self.Detectiondelay = CheckParam( "delay before detection validation)", params[0], 0) self.Alarmondelay = CheckParam("Alarm On Delay", params[1], 0) self.Alarmoffdelay = CheckParam("Alarm Off Delay", params[2], 60) else: Domoticz.Error("Error reading Mode5 parameters")
def onStart(self): global icons Domoticz.Debug("onStart called") if Parameters["Mode6"] == 'Debug': self.debug = True Domoticz.Debugging(1) DumpConfigToLog() else: Domoticz.Debugging(0) if Parameters["Mode3"] == 'Yes': self.shutdown = True if Parameters["Mode4"] == '1.0': self.address = 0x36 self.v_constant = 78.125 elif Parameters["Mode4"] == 'UPSPIco': self.address = 0x69 self.isPico = True else: self.address = 0x62 self.v_constant = 305 ## load custom battery images for key, value in icons.items(): if key not in Images: Domoticz.Image(value).Create() Domoticz.Debug("Added icon: " + key + " from file " + value) Domoticz.Debug(">>>>>>>>>Number of icons loaded = " + str(len(Images))) for image in Images: Domoticz.Debug(">>>>>>>>>>>>>Icon " + str(Images[image].ID) + " " + Images[image].Name) # check polling interval parameter try: temp = int(Parameters["Mode1"]) except: Domoticz.Error("Invalid polling interval parameter") else: if temp < 2: temp = 2 # minimum polling interval Domoticz.Error( "Specified polling interval too short: changed to 2 minutes" ) elif temp > 60: temp = 60 # maximum polling interval is 60 minutes Domoticz.Error( "Specified polling interval too long: changed to 60 minutes" ) self.pollinterval = temp Domoticz.Log("Using polling interval of {} minutes".format( str(self.pollinterval))) # check log param if Parameters["Mode6"] == 'Debug': self.myLog = True logFile = str(Parameters["HomeFolder"]) + "ups.log" if (len(Devices) == 0): Domoticz.Device(Name="UPSPers", Unit=1, TypeName="Custom", Options={ "Custom": "1;%" }).Create() Domoticz.Device(Name="UPSVolts", Unit=2, TypeName="Voltage").Create() if (self.isPico): Domoticz.Device(Name="RasVolts", Unit=3, TypeName="Voltage").Create() Domoticz.Device(Name="PicoTemperature", Unit=4, TypeName="Temperature").Create()
def onStart(self): Domoticz.Debug("onStart called") if Parameters["Mode6"] == "Debug": Domoticz.Debugging(1) else: Domoticz.Debugging(0) # Images # Check if images are in database if "xfr_pihole" not in Images: Domoticz.Image("xfr_pihole.zip").Create() image = Images["xfr_pihole"].ID # Get id from database Domoticz.Log("Image created. ID: " + str(image)) # Create devices if len(Devices) == 0: # Following devices are set on used by default Domoticz.Device(Unit=self._UNITS["DOMAINS_BLOCKED"], Name="Blocked domains", TypeName="Custom", Options={ "Custom": "1;" }, Used=1, Image=image).Create() Domoticz.Device(Unit=self._UNITS["DNS_QUERIES"], Name="DNS queries", TypeName="Custom", Options={ "Custom": "1;" }, Used=1, Image=image).Create() Domoticz.Device(Unit=self._UNITS["ADS_BLOCKED"], Name="Ads blocked", TypeName="Custom", Options={ "Custom": "1;" }, Used=1, Image=image).Create() Domoticz.Device(Unit=self._UNITS["ADS_PERCENTAGE"], Name="Ads percentage", TypeName="Custom", Options={ "Custom": "1;%" }, Used=1, Image=image).Create() # Image not working :( Domoticz.Device(Unit=self._UNITS["RECENTBLOCKED"], Name="Recent blocked", TypeName="Text", Used=1, Image=image).Create() # Following devices are NOT set on used. Can be done by user Domoticz.Device(Unit=self._UNITS["UNIQUE_DOMAINS"], Name="Unique domains", TypeName="Custom", Options={ "Custom": "1;" }, Image=image).Create() Domoticz.Device(Unit=self._UNITS["QUERIES_FORWARDED"], Name="Queries forwarded", TypeName="Custom", Options={ "Custom": "1;" }, Image=image).Create() Domoticz.Device(Unit=self._UNITS["QUERIES_CACHED"], Name="Queries cached", TypeName="Custom", Options={ "Custom": "1;" }, Image=image).Create() Domoticz.Device(Unit=self._UNITS["CLIENTS_EVER_SEEN"], Name="Clients ever seen", TypeName="Custom", Options={ "Custom": "1;" }, Image=image).Create() Domoticz.Device(Unit=self._UNITS["UNIQUE_CLIENTS"], Name="Unique clients", TypeName="Custom", Options={ "Custom": "1;" }, Image=image).Create() # Create On/Off switch when API Token is defined if Parameters["Mode1"]: Domoticz.Device(Unit=self._UNITS["SWITCH"], Name="Status", TypeName="Switch", Used=1, Image=image).Create() else: if not Parameters["Mode1"] and self._UNITS["SWITCH"] in Devices: # No API Token, so no reason for an On/Off switch Domoticz.Device(Unit=self._UNITS["SWITCH"]).Delete() if Parameters["Mode1"] and self._UNITS["SWITCH"] not in Devices: Domoticz.Device(Unit=self._UNITS["SWITCH"], Name="Status", TypeName="Switch", Used=1, Image=image).Create() Domoticz.Log("Devices created.") DumpConfigToLog() # Create connections self.__jsonConn = Domoticz.Connection(Name="Summary", Transport="TCP/IP", Protocol="HTTP", Address=Parameters["Address"], Port=Parameters["Port"]) self.__textConn = Domoticz.Connection(Name="RecentBlocked", Transport="TCP/IP", Protocol="HTTP", Address=Parameters["Address"], Port=Parameters["Port"]) self.__headers = {"Content-Type": "text/xml; charset=utf-8",\ "Connection": "keep-alive",\ "Accept": "Content-Type: text/html; charset=UTF-8",\ "Host": Parameters["Address"] + ":" + Parameters["Port"],\ "User-Agent": "Domoticz/1.0" }
def onStart(self): Domoticz.Log("onStart called") if Parameters["Mode2"] == "Debug": Domoticz.Debugging(1) if (len(Devices) == 0): Domoticz.Device(Name="Power", Unit=1, Image=16, TypeName="Switch", Used=1).Create() Domoticz.Device(Name="Temp IN", Unit=2, TypeName="Temperature", Used=1).Create() Domoticz.Device(Name="Temp OUT", Unit=3, TypeName="Temperature", Used=1).Create() Options = { "LevelActions": "|||||", "LevelNames": "|Auto|Cool|Heat|Fan|Dry", "LevelOffHidden": "true", "SelectorStyle": "1" } Domoticz.Device(Name="Mode", Unit=4, TypeName="Selector Switch", Image=16, Options=Options, Used=1).Create() Options = { "LevelActions": "|||||||", "LevelNames": "|Auto|Silent|L1|L2|L3|L4|L5", "LevelOffHidden": "true", "SelectorStyle": "1" } Domoticz.Device(Name="Fan Rate", Unit=5, TypeName="Selector Switch", Image=7, Options=Options, Used=1).Create() Domoticz.Device(Name="Temp TARGET", Unit=6, Type=242, Subtype=1, Image=16, Used=1).Create() Domoticz.Log("Device created.") DumpConfigToLog() Domoticz.Heartbeat(10) self.httpConnSensorInfo = Domoticz.Connection( Name="Sensor Info", Transport="TCP/IP", Protocol="HTTP", Address=Parameters["Address"], Port=Parameters["Port"]) self.httpConnSensorInfo.Connect() self.httpConnControlInfo = Domoticz.Connection( Name="Control Info", Transport="TCP/IP", Protocol="HTTP", Address=Parameters["Address"], Port=Parameters["Port"]) self.httpConnControlInfo.Connect() self.httpConnSetControl = Domoticz.Connection( Name="Set Control", Transport="TCP/IP", Protocol="HTTP", Address=Parameters["Address"], Port=Parameters["Port"]) self.runCounter = int(Parameters["Mode1"])
def onStart(self): # Debug mode Domoticz.Debugging(int(Parameters["Mode6"])) Domoticz.Debug("onStart called") #get parameters self.__address = Parameters["Address"] self.__devID = Parameters["Mode1"] self.__localKey = Parameters["Mode2"] #set the next heartbeat self.__runAgain = self.__HB_BASE_FREQ #build internal maps (__unit2dps_id_list and __plugs) self.__unit2dps_id_list = {} self.__plugs = {} max_unit = 0 max_dps = 0 for val in sorted(Parameters["Mode3"].split(";")): self.__unit2dps_id_list[int(val)]=[int(val),] self.__plugs[int(val)]=Plug(int(val)) if(int(val)>max_unit): max_unit=int(val) max_dps = max_unit #groups management: #syntax: 1;2 : 3;4 max_unit = max_unit + 1 if(Parameters["Mode4"]!="None"): groups = Parameters["Mode4"].split(":") for group in groups: self.__unit2dps_id_list[max_unit]=[] for val in sorted(group.split(";")): self.__unit2dps_id_list[max_unit].append(int(val)) max_unit = max_unit + 1 #create domoticz devices if(len(Devices) == 0): for val in self.__unit2dps_id_list: if(val <= max_dps): #single socket dps # Image #15 - heating, use <domo>/json.htm?type=custom_light_icons to get ID Domoticz.Device(Name="Thermostat Control #" + str(val), Unit=val, Image=15, TypeName="Switch", Used=1).Create() Domoticz.Log("Tuya Thermostat Control #" + str(val) +" created.") Domoticz.Device(Name="Thermostat #" + str(val), Unit=(256-val), Type=242, Subtype=1, Used=1).Create() Domoticz.Log("Tuya Thermostat #" + str(val) +" created.") else: #group: selector switch Options = {"LevelActions": "|", "LevelNames": "Off|On", "LevelOffHidden": "false", "SelectorStyle": "0"} Domoticz.Device(Name="Tuya Thermostat #" + str(val), Unit=val, TypeName="Selector Switch", Options=Options).Create() Domoticz.Log("Tuya Thermostat Device #" + str(val) +" created.") #manage always on if(Parameters["Mode5"]!="None"): for val in sorted(Parameters["Mode5"].split(";")): self.__plugs[int(val)].set_alwaysON() #create the pytuya object self.__device = pytuya.OutletDevice(self.__devID, self.__address, self.__localKey) #state machine self.__state_machine = 0 #start the connection self.__connection = Domoticz.Connection(Name="Tuya", Transport="TCP/IP", Address=self.__address, Port="6668") self.__connection.Connect()
def onStart(self): try: self.logLevel = int(Parameters["Mode6"]) except: self.LogError("Debuglevel '" + Parameters["Mode6"] + "' is not an integer") if self.logLevel == 10: Domoticz.Debugging(1) self.LogMessage("onStart called", 9) self.connection = Domoticz.Connection(Name="LG_TCP", Transport="TCP/IP", Protocol="HTTP", Address=Parameters["Address"], Port=Parameters["Port"]) if (self.regexIp.match(Parameters["Address"])): self.ip = Parameters["Address"] else: self.LogError("'" + Parameters["Address"] + "' is not a valid IP address.") self.tempFile = Parameters["Mode5"] + "ping_" + Parameters["Address"] self.LogMessage("Temp file: " + self.tempFile, 3) try: self.port = int(Parameters["Port"]) except Exception as e: self.LogError("Port is not a number: " + Parameters["Port"]) try: Domoticz.Heartbeat(int(Parameters["Mode2"])) except: pass self.key = Parameters["Mode4"] # initial cleanup if (os.path.isfile(self.tempFile)): subprocess.call('sudo chmod +wr ' + self.tempFile, shell=True) os.remove(self.tempFile) #ICONS if ("LGtvchanneldown" not in Images): Domoticz.Image('LGtvchanneldown.zip').Create() if ("LGtvchannelup" not in Images): Domoticz.Image('LGtvchannelup.zip').Create() if ("LGtvplasma_tv" not in Images): Domoticz.Image('LGtvplasma_tv.zip').Create() if ("LGtvsatellite_dish" not in Images): Domoticz.Image('LGtvsatellite_dish.zip').Create() if ("LGtvexit" not in Images): Domoticz.Image('LGtvexit.zip').Create() if ("LGtvvolmin" not in Images): Domoticz.Image('LGtvvolmin.zip').Create() if ("LGtvvolplus" not in Images): Domoticz.Image('LGtvvolplus.zip').Create() if ("LGtvsystem" not in Images): Domoticz.Image('LGtvsystem.zip').Create() if ("LGtvok" not in Images): Domoticz.Image('LGtvok.zip').Create() if ("LGtvmute" not in Images): Domoticz.Image('LGtvmute.zip').Create() # create buttons if (1 not in Devices): Domoticz.Device(Name="Power", Unit=1, TypeName="Switch", Image=Images["LGtvplasma_tv"].ID).Create() if (2 not in Devices): Domoticz.Device(Name="Volume up", Unit=2, TypeName="Switch", Image=Images["LGtvvolplus"].ID).Create() if (3 not in Devices): Domoticz.Device(Name="Volume down", Unit=3, TypeName="Switch", Image=Images["LGtvvolmin"].ID).Create() if (4 not in Devices): Domoticz.Device(Name="Channel up", Unit=4, TypeName="Switch", Image=Images["LGtvchannelup"].ID).Create() if (5 not in Devices): Domoticz.Device(Name="Channel down", Unit=5, TypeName="Switch", Image=Images["LGtvchanneldown"].ID).Create() if (6 not in Devices): Domoticz.Device(Name="HDMI", Unit=6, TypeName="Switch", Image=Images["LGtvsystem"].ID).Create() if (7 not in Devices): Domoticz.Device(Name="TV/Radio", Unit=7, TypeName="Switch", Image=Images["LGtvsatellite_dish"].ID).Create() if (8 not in Devices): Domoticz.Device(Name="Mute", Unit=8, TypeName="Switch", Image=Images["LGtvmute"].ID).Create() if (9 not in Devices): Domoticz.Device(Name="Exit", Unit=9, TypeName="Switch", Image=Images["LGtvexit"].ID).Create() self.lastState = Devices[1].nValue != 0 # was on/off self.DumpConfigToLog() return
def CS_2_DZ_decoder(self, topic, message): success = 0 Domoticz.Debug("CS_Decoder") EUI = str(topic.split("device/")[1].split("/")[0]) Domoticz.Debug("EUI : " + EUI) ############ ## Devices payload = json.loads(message) Domoticz.Debug("Payload:\n" + str(payload)) if not 'loRaSNR' in str(payload): Domoticz.Log( "Decoding LoRa message problem. Check ChirpStack application.") return success RSSI = payload['rxInfo'][0]['loRaSNR'] RSSI = int(round(mapFromTo(int(RSSI), -20, 0, 0, 10), 0)) #Domoticz : between 0 and 10 Domoticz.Debug("RSSI : " + str(RSSI)) CS_objects = json.loads(payload['objectJSON']) if (len(CS_objects) == 0): Domoticz.Log( "Decoding cayenne message problem. Check ChirpStack application." ) return success #Domoticz.Debug(str(CS_objects))#{'temperatureSensor': {'1': 12}, 'humiditySensor': {'1': 80}} #Reorganize data data = [] for obj in CS_objects: if (str(obj) in CS_cayenne_to_DZ): for channel in CS_objects[str(obj)]: #Get the value of the sensor value = str(CS_objects[str(obj)][str(channel)]) #build DATA : [Channel, value, [Corresp.DZ_TypeName, Corresp.DZ_pType,DZ_sType, Corresp.FancyName, Corresp.UNIT_ID] ] data.append([channel, value, CS_cayenne_to_DZ[str(obj)]]) else: Domoticz.Log("Unfound/Unproccessable Cayenne Data Type : " + str(obj)) Domoticz.Debug("DATA structure:" + str(data)) #[['1', '12', ['Temperature', 243, 17, 'temp']], ['2', '14', ['Temperature', 243, 17, 'temp']], ['3', '15', ['Temperature', 243, 17, 'temp']], ['1', '80', ['Humidity', 243, 3, 'hum']]] # #aggregate several sensor types into one sensor. Decide whi one is nvalue, which one is svalue # # TODO data_ag = data #Devices ID d_ids = [] d_units = [] for x in Devices: d_ids.append([ str(x), str(Devices[x].ID), str(Devices[x].Name), str(Devices[x].DeviceID) ]) d_units.append(int(x)) Domoticz.Debug(str(d_ids)) Domoticz.Debug(str(d_units)) #Device for d in range(0, len(data_ag)): # Case there is Type_Name assigned if data_ag[d][2][0] != "": #Shape the values device_fancyname = str(data_ag[d][2][3]) device_id = "eui-" + EUI + "-" + str( data_ag[d] [0]) + "-" + device_fancyname #eui-a8d4fdf51239f322-1-hum device_Name = "Unknown " + device_fancyname device_TypeName = str(data_ag[d][2][0]) Domoticz.Debug("===================") Domoticz.Debug("device_id: " + str(device_id)) #If not exist, create if (device_id not in str(d_ids)): #Find a new unit ID device_Unit = 0 for u in range(1, 255): if u not in d_units: device_Unit = u d_units.append(u) break if device_Unit == 0: Domoticz.Log( "ERROR - No more UNIT ID to allocate. Device not created" ) return 0 Domoticz.Debug("device_Name: " + str(device_Name)) Domoticz.Debug("device_TypeName: " + str(device_TypeName)) if self.create_new_devices == "True": Domoticz.Log( "ChirpStack Plugin - Create NEW device with ID=" + str(device_id) + ", Name=" + str(device_Name) + ", Type=" + str(device_TypeName)) #Create Domoticz.Device(Name=device_Name, TypeName=device_TypeName, Unit=device_Unit, DeviceID=device_id).Create() else: Domoticz.Log( "ChirpStack Plugin - DISBALED [Create device " + str(device_id) + "]") for x in Devices: #Check if now exists, and update if (str(Devices[x].DeviceID) == device_id): device_svalue = str(data_ag[d][1]) #Update Domoticz.Log("Chirpstack Plugin - Update device (ID=" + str(Devices[x].ID) + ") value =" + data_ag[d][1]) Devices[x].Update(nValue=int(device_svalue), sValue=str(device_svalue), SignalLevel=RSSI) Domoticz.Debug("===================") return success
def onStart(self): self.debug = int(Parameters["Mode6"]) Domoticz.Debugging(self.debug) b.log.logstate = self.debug & 3 Domoticz.Log("Start DL485 Loop Plugin with Debug: {}".format( self.debug)) for board_id in b.mapiotype: # Iterazione di tutte le board su config.json self.devicesUpdate( ) # Aggiorna dizionario con i device di domoticz # Creazione dispositivi TEXT per ciascuna Board per inserire le caratteristiche del nodo DeviceID = "{}-0".format(board_id) board_enable = b.config['BOARD{}'.format( board_id)]['GENERAL_BOARD'].get('enable', 1) if DeviceID not in self.devices['DeviceID2Unit'].keys(): """ Create Devices 0 con le caratteristiche della scheda """ # print("Crea il device TEXT con le caratteristiche della BOARD: {}".format(board_id)) unit_present = list(self.devices['Unit2DeviceID'].keys()) Unit = self.unitPresent(unit_present) dtype = 'Text' name = 'BOARD{} CHARACTERISTICS'.format(board_id) description = "Caratteristiche Board {}".format(board_id) Domoticz.Device(DeviceID=DeviceID, Name=name, Unit=Unit, Type=self.typeNameDict[dtype]['Type'], Subtype=self.typeNameDict[dtype]['SubType'], \ Description=description, Switchtype=self.typeNameDict[dtype]['Switchtype'], Image=0, Options={}, Used=board_enable).Create() self.devices['Unit2DeviceID'][Unit] = DeviceID self.devices['DeviceID2Unit'][DeviceID] = Unit else: # print("Update device TEXT con le caratteristiche della BOARD: {}".format(board_id)) Unit = self.devices['DeviceID2Unit'][DeviceID] board_enable = b.config['BOARD{}'.format( board_id)]['GENERAL_BOARD'].get('enable', 1) Devices[Unit].Update(Used=board_enable, nValue=0, sValue='') for logic_io in b.mapiotype[ board_id]: # iterazione per ogni logic_io self.devicesUpdate( ) # Aggiorna dizionario con i device di domoticz description = b.mapiotype[board_id][logic_io]['description'] device_enable = b.mapiotype[board_id][logic_io][ 'enable'] and b.mapiotype[board_id][logic_io][ 'board_enable'] # Abilita il device se sulla configurazione sono abilitati device_type = b.mapiotype[board_id][logic_io]['device_type'] dtype = b.mapiotype[board_id][logic_io]['dtype'] DeviceID = "{}-{}".format(board_id, logic_io) # print("----- board_id: {}, logic_io: {}, board_enable: {}, device_type: {}".format(board_id, logic_io, board_enable, device_type)) if device_type in ['DIGITAL_IN_PULLUP', 'DIGITAL_IN']: image = 9 elif device_type in ['DIGITAL_OUT']: image = 0 else: image = 0 name = "[{}] {}".format( DeviceID, b.mapiotype[board_id][logic_io]['name']) # print("*** BoardID:{:>2} LogiIO:{:>3} Device_enable:{:>3} DeviceID:{:>6}".format(board_id, logic_io, device_enable, DeviceID)) if dtype not in self.typeNameDict: Domoticz.Log( " ==>> ERROR DEVICE dtype: {} on board_id:{} logic_io:{} is NOT CORRECT!!!" .format(dtype, board_id, logic_io)) sys.exit() # continue if dtype == "None": # Domoticz.Log(" ==>> ERROR DEVICE dtype NON IMPOSTATO: None => Board_id:{} Logic_io: {}".format(board_id, logic_io)) # sys.exit() continue Type = self.typeNameDict[dtype]['Type'] SubType = self.typeNameDict[dtype]['SubType'] SwitchType = self.typeNameDict[dtype]['SwitchType'] options = '' # value = 0 if dtype == 'switch': pass elif dtype == 'Temp+Hum': sValue = "0;0;0" elif dtype == 'Temp+Hum+Baro': sValue = "0;0;0;0;0" elif dtype == 'kWh': sValue = "0;0" elif dtype == 'Custom Sensor': options = { 'Custom': '1;{}'.format(b.mapiotype[board_id][logic_io]['dunit']) } sValue = "0" elif dtype == 'Counter Incremental': # mostra i Watt/ora sValue = "0" elif dtype == 'None': # print("Device che non deve essere aggiunto a Domoticz") continue # print("====>>>>> Device: Unit:{:<3} Dtype: {:20} nValue: {:<3} sValue: {:<5} Used: {} OPTIONS: {} Name: {:30}".format(Unit, dtype, value, sValue, device_enable, options, name)) # print(DeviceID, self.devices['DeviceID2Unit'].keys()) if DeviceID not in self.devices['DeviceID2Unit'].keys(): """ Crea Device """ unit_present = list(self.devices['Unit2DeviceID'].keys()) Unit = self.unitPresent(unit_present) ### Domoticz.Device(Name=name, Unit=Unit, TypeName=dtype, Description=description, DeviceID=DeviceID, Used=device_enable, Image=image).Create() Domoticz.Device(DeviceID=DeviceID, Name=name, Unit=Unit, Type=Type, Subtype=SubType, Switchtype=SwitchType, Description=description, Image=0, \ Options={}, Used=device_enable).Create() self.devices['Unit2DeviceID'][Unit] = DeviceID self.devices['DeviceID2Unit'][DeviceID] = Unit Domoticz.Log( "====>>>>> Create Device: Unit:{:5} DeviceID:{:>5} Dtype: {:20} Used: {} OPTIONS: {} Name: {:30}" .format(Unit, DeviceID, dtype, device_enable, options, name)) Unit = self.devices['DeviceID2Unit'][DeviceID] if not b.overwrite_text and Devices[ Unit].Description != description: # check if Domoticz description is equal to config description description = Devices[Unit].Description if not b.overwrite_text and Devices[ Unit].Name != name: # check if Domoticz description is equal to config description name = Devices[Unit].Name Domoticz.Log( "=> Update Dev: Un:{:3} DevID:{:>4} T:{:>3} SubT:{:>3} SwitchT:{:>3} Dtype: {:20} nVal: {:<1} sVal: {:>4} Used: {} opt: {:<10} Name: {:30}" .format(Unit, DeviceID, Type, SubType, SwitchType, dtype, Devices[Unit].nValue, Devices[Unit].sValue, device_enable, str(options), name)) Devices[Unit].Update(Name=name, Type=Type, Subtype=SubType, Switchtype=SwitchType, Description=description, nValue=Devices[Unit].nValue, sValue=Devices[Unit].sValue, Used=device_enable, Options=options) b.Connection = Domoticz.Connection(Name="DL485", Transport="Serial", Address=b.bus_port, Baud=b.bus_baudrate) b.Connection.Connect()
def registerDevices(self): unitIds = self.indexRegisteredDevices() if self.hasTimedOut: return ikeaIds = [] # Add unregistred lights try: if self.includeGroups: tradfriDevices = get_devices(groups=True) else: tradfriDevices = get_devices() if tradfriDevices == None: Domoticz.Log("Failed to get Tradfri-devices") return for aLight in tradfriDevices: devID = str(aLight.DeviceID) ikeaIds.append(devID) if not devID in unitIds: Domoticz.Debug("Processing: {0} - {1}".format( aLight.Description, aLight.Type)) new_unit_id = firstFree() if aLight.Type == "Plug": Domoticz.Device( Name=aLight.Name, Unit=new_unit_id, Type=244, Subtype=73, Switchtype=0, Image=1, DeviceID=devID, ).Create() self.updateDevice(new_unit_id, devID) if aLight.Type == "Remote": Domoticz.Device( Name=aLight.Name + " - Battery level", Unit=new_unit_id, Type=243, Subtype=6, DeviceID=devID, ).Create() if aLight.Type == "Blind": deviceType = 244 subType = 73 switchType = 13 Domoticz.Device( Name=aLight.Name, Unit=new_unit_id, Type=deviceType, Subtype=subType, Switchtype=switchType, DeviceID=devID, ).Create() self.updateDevice(new_unit_id, devID) if aLight.Type == "Light" or aLight.Type == "Group": deviceType = 244 subType = 73 switchType = 7 # Basic device Domoticz.Device( Name=aLight.Name, Unit=new_unit_id, Type=deviceType, Subtype=subType, Switchtype=switchType, DeviceID=devID, ).Create() self.updateDevice(new_unit_id, devID) if aLight.Color_space == "W": continue if self.monitorBatteries: if aLight.Battery_level is not None and devID + ":Battery" not in unitIds: new_unit_id = firstFree() Domoticz.Debug("Registering: {0}:Battery".format( aLight.DeviceID)) Domoticz.Device(Name=aLight.Name + " - Battery", Unit=new_unit_id, TypeName="Custom", Options={ "Custom": "1;%" }, DeviceID=devID + ":Battery").Create() self.updateDevice(new_unit_id, devID) if aLight.Color_space == "CWS" and devID + ":CWS" not in unitIds: new_unit_id = firstFree() Domoticz.Debug("Registering: {0}:CWS".format( aLight.DeviceID)) Domoticz.Device( Name=aLight.Name + " - Color", Unit=new_unit_id, TypeName="Selector Switch", Switchtype=18, Options=colorOptions, DeviceID=devID + ":CWS", ).Create() self.updateDevice(new_unit_id, devID) if aLight.Color_space == "WS" and devID + ":WS" not in unitIds: new_unit_id = firstFree() Domoticz.Debug("Registering: {0}:WS".format( aLight.DeviceID)) Domoticz.Device( Name=aLight.Name + " - Color", Unit=new_unit_id, TypeName="Selector Switch", Switchtype=18, Options=WhiteOptions, DeviceID=devID + ":WS", ).Create() self.updateDevice(new_unit_id, devID) # Remove registered lights no longer found on the gateway for aUnit in list(Devices.keys()): devID = str(Devices[aUnit].DeviceID).split(":") if not devID[0] in ikeaIds: Devices[aUnit].Delete() if not self.monitorBatteries and len(devID) == 2: if devID[1] == "Battery": Devices[aUnit].Delete() self.hasTimedOut = False except (HandshakeError, ReadTimeoutError, WriteTimeoutError): Domoticz.Debug("Connection to gateway timed out") self.hasTimedOut = True
def createDevices(): # Are there any devices? ###if len(Devices) != 0: # Could be the user deleted some devices, so do nothing ###return # Give the devices a unique unit number. This makes updating them more easy. # UpdateDevice() checks if the device exists before trying to update it. # Add the temperature and humidity device(s) if Parameters["Mode4"] == "True": if 3 not in Devices: Domoticz.Device(Name="Temperature", Unit=3, TypeName="Temp+Hum", Used=1).Create() else: if 1 and 2 not in Devices: Domoticz.Device(Name="Temperature", Unit=1, TypeName="Temperature", Used=1).Create() Domoticz.Device(Name="Humidity", Unit=2, TypeName="Humidity", Used=1).Create() # Add the barometer device if 4 not in Devices: Domoticz.Device(Name="Barometer", Unit=4, TypeName="Barometer", Used=1).Create() # Add the wind (and wind chill?) device if Parameters["Mode5"] == "True": if 6 not in Devices: Domoticz.Device(Name="Wind", Unit=6, TypeName="Wind+Temp+Chill", Used=1).Create() else: if 5 not in Devices: Domoticz.Device(Name="Wind", Unit=5, TypeName="Wind", Used=1).Create() if 7 not in Devices: Domoticz.Device(Name="Visibility", Unit=7, TypeName="Visibility", Used=1).Create() if 8 not in Devices: Domoticz.Device(Name="Solar Radiation", Unit=8, TypeName="Solar Radiation", Used=1).Create() if 9 not in Devices: Domoticz.Device(Name="Rain rate", Unit=9, TypeName="Custom", Options={ "Custom": "1;mm/h" }, Used=1).Create() UpdateImage(9, 'BuienradarRainLogo') if 10 not in Devices: Domoticz.Device(Name="Rain forecast [0-255]", Unit=10, TypeName="Custom", Used=1).Create() UpdateImage(10, 'BuienradarRainLogo') if 11 not in Devices: Domoticz.Device(Name="Rain forecast", Unit=11, TypeName="Custom", Options={ "Custom": "1;mm/h" }, Used=1).Create() UpdateImage(11, 'BuienradarRainLogo') if 12 not in Devices: Domoticz.Device(Name="Weather forecast", Unit=12, TypeName="Text", Used=1).Create() #UpdateImage(12, 'BuienradarLogo') # Logo update doesn't work for text device if 9 in Devices: UpdateImage(9, 'BuienradarRainLogo') if 10 in Devices: UpdateImage(10, 'BuienradarRainLogo') if 11 in Devices: UpdateImage(11, 'BuienradarRainLogo') Domoticz.Log("Devices checked and created/updated if necessary")
def createDevices(self, unitname): OptionsSensor = {"Custom": "1;Hz"} OptionsSensorAVG = {"Custom": "1;w"} iUnit = -1 for Device in Devices: try: if (Devices[Device].DeviceID.strip() == unitname): iUnit = Device break except: pass if iUnit < 0: # if device does not exists in Domoticz, than create it try: iUnit = 0 for x in range(1, 256): if x not in Devices: iUnit = x break Domoticz.Debug("Creating: " + unitname) if iUnit == 0: iUnit = len(Devices) + 1 #Fronius3 if (Parameters["Mode3"].strip() == "Fronius3"): if (unitname == "F_IDC"): #amper Domoticz.Device(Name=unitname, Unit=iUnit, Type=243, Subtype=23, Switchtype=0, Used=1, DeviceID=unitname).Create() if (unitname == "F_IAC"): #amper Domoticz.Device(Name=unitname, Unit=iUnit, Type=243, Subtype=23, Switchtype=0, Used=1, DeviceID=unitname).Create() if (unitname == "F_FAC"): #custom Domoticz.Device(Name=unitname, Unit=iUnit, Type=243, Subtype=31, Switchtype=0, Used=1, DeviceID=unitname).Create() if (unitname == "F_UAC"): #voltage Domoticz.Device(Name=unitname, Unit=iUnit, Type=243, Subtype=8, Switchtype=0, Used=1, DeviceID=unitname).Create() if (unitname == "F_UDC"): #voltage Domoticz.Device(Name=unitname, Unit=iUnit, Type=243, Subtype=8, Switchtype=0, Used=1, DeviceID=unitname).Create() if (unitname == "F_PAC"): Domoticz.Device(Name=unitname, Unit=iUnit, Type=243, Subtype=29, Switchtype=0, Used=1, DeviceID=unitname).Create() if (Parameters["Mode3"].strip() == "Fronius6"): if (unitname == "FROM_GRID"): Domoticz.Device(Name=unitname, Unit=iUnit, Type=243, Subtype=29, Switchtype=0, Used=1, DeviceID=unitname).Create() if (unitname == "TO_GRID"): Domoticz.Device(Name=unitname, Unit=iUnit, Type=243, Subtype=29, Switchtype=0, Used=1, DeviceID=unitname).Create() if (unitname == "HOME_LOAD"): Domoticz.Device(Name=unitname, Unit=iUnit, Type=243, Subtype=29, Switchtype=0, Used=1, DeviceID=unitname).Create() if (unitname == "FV_POWER"): Domoticz.Device(Name=unitname, Unit=iUnit, Type=243, Subtype=29, Switchtype=0, Used=1, DeviceID=unitname).Create() if (unitname == "AVGGRID"): Domoticz.Device(Name=unitname, Unit=iUnit, TypeName='Custom', Options=OptionsSensorAVG, Used=1, DeviceID=unitname).Create() #Fronius3 except Exception as e: Domoticz.Debug(str(e)) return False return
def checkDevices(self): # self.SM10 = Parameters["SM10"] if 1 not in Devices: Domoticz.Debug("Create Temperature Device") Domoticz.Device(Name="EMS thermostat current temp", Unit=1, Type=80, Subtype=5).Create() if 2 not in Devices: Domoticz.Debug("Create System Pressure Device") Domoticz.Device(Name="Boiler system pressure", Unit=2, Type=243, Subtype=9).Create() if 3 not in Devices: Domoticz.Debug("Create Thermostat Setpoint Device") Domoticz.Device(Name="EMS thermostat setpoint", Unit=3, Type=242, Subtype=1).Create() if 4 not in Devices: Domoticz.Debug("Create on/off switch (burnGas)") Domoticz.Device(Name="Boiler gas", Unit=4, Type=244, Subtype=73, Switchtype=0).Create() if 5 not in Devices: Domoticz.Debug("Create on/off switch (fanWork)") Domoticz.Device(Name="Boiler fan", Unit=5, Type=244, Subtype=73, Switchtype=0).Create() if 6 not in Devices: Domoticz.Debug("Create on/off switch (ignWork)") Domoticz.Device(Name="Boiler ingnition", Unit=6, Type=244, Subtype=73, Switchtype=0).Create() if 7 not in Devices: Domoticz.Debug("Create on/off switch (heatPmp)") Domoticz.Device(Name="Boiler heating pump", Unit=7, Type=244, Subtype=73, Switchtype=0).Create() if 8 not in Devices: Domoticz.Debug("Create on/off switch (wWActivated)") Domoticz.Device(Name="Boiler warm water", Unit=8, Type=244, Subtype=73, Switchtype=0).Create() if 9 not in Devices: Domoticz.Debug("Create on/off switch (wWHeat)") Domoticz.Device(Name="Boiler warm water heating", Unit=9, Type=244, Subtype=73, Switchtype=0).Create() if 10 not in Devices: Domoticz.Debug("Create on/off switch (wWCirc)") Domoticz.Device(Name="Boiler warm water circulation", Unit=10, Type=244, Subtype=73, Switchtype=0).Create() if 11 not in Devices: Domoticz.Debug("Create temperature device (selFlowTemp)") Domoticz.Device(Name="Boiler selected flow temperate", Unit=11, Type=80, Subtype=5).Create() if 12 not in Devices: Domoticz.Debug("Create temperature device (outdoorTemp)") Domoticz.Device(Name="Boiler connected outdoor temperature", Unit=12, Type=80, Subtype=5).Create() if 13 not in Devices: Domoticz.Debug("Create temperature device (wWCurTmp)") Domoticz.Device(Name="Boiler warm water current temperate", Unit=13, Type=80, Subtype=5).Create() if 14 not in Devices: Domoticz.Debug("Create temperature device (curFlowTemp)") Domoticz.Device(Name="Boiler current flow temperate", Unit=14, Type=80, Subtype=5).Create() if 15 not in Devices: Domoticz.Debug("Create temperature device (retTemp)") Domoticz.Device(Name="Boiler return temperate", Unit=15, Type=80, Subtype=5).Create() if 16 not in Devices: Domoticz.Debug("Create temperature device (boilTemp)") Domoticz.Device(Name="Boiler temperate", Unit=16, Type=80, Subtype=5).Create() if 17 not in Devices: Domoticz.Debug("Create text device (wWComfort)") Domoticz.Device(Name="Boiler warm water comfort setting", Unit=17, Type=243, Subtype=19).Create() if 18 not in Devices: Domoticz.Debug("Create text device (ServiceCode)") Domoticz.Device(Name="Boiler Service code", Unit=18, Type=243, Subtype=19).Create() if 19 not in Devices: Domoticz.Debug("Create text device (ServiceCodeNumber)") Domoticz.Device(Name="Boiler Service code number", Unit=19, Type=243, Subtype=19).Create() if 20 not in Devices: Domoticz.Debug("Create text device (THERMOSTAT_MODE)") Domoticz.Device(Name="EMS thermostat mode", Unit=20, Type=243, Subtype=19).Create() if 21 not in Devices: Domoticz.Debug("Create percentage device (selBurnPow)") Domoticz.Device(Name="Boiler selected power", Unit=21, Type=243, Subtype=6).Create() if 22 not in Devices: Domoticz.Debug("Create percentage device (curBurnPow)") Domoticz.Device(Name="Boiler current power", Unit=22, Type=243, Subtype=6).Create() if 23 not in Devices: Domoticz.Debug("Create percentage device (pumpMod)") Domoticz.Device(Name="Boiler pump modulation", Unit=23, Type=243, Subtype=6).Create() if 24 not in Devices: Domoticz.Debug("Create percentage device (wWCurFlow)") Domoticz.Device(Name="Boiler warm water flow", Unit=24, Type=243, Subtype=6).Create()
def onStart(self): Domoticz.Debug("onStart called") if Parameters["Mode6"] == "Debug": Domoticz.Debugging(1) InputSelections = 'Off' for a in self.InputIdx: InputSelections = InputSelections + '|' + pioneerapi.INPUT_MODES[a] Domoticz.Debug('LIST:' + InputSelections) SourceOptions = { 'LevelActions': '|' * InputSelections.count('|'), 'LevelNames': InputSelections, 'LevelOffHidden': 'false', 'SelectorStyle': '1' } if self.UNITS['power'] not in Devices: Domoticz.Device(Name="Power", Unit=self.UNITS['power'], TypeName="Switch", Image=5, Used=1).Create() if self.UNITS['input'] not in Devices: Domoticz.Device(Name="Input", Unit=self.UNITS['input'], TypeName="Selector Switch", Switchtype=18, Image=5, Options=SourceOptions, Used=1).Create() if self.UNITS['display'] not in Devices: Domoticz.Device(Name="Display", Unit=self.UNITS['display'], TypeName="Text", Image=5, Used=1).Create() if self.UNITS['listening_mode'] not in Devices: Domoticz.Device(Name="Listening Mode", Unit=self.UNITS['listening_mode'], TypeName="Text", Used=1).Create() if self.UNITS['playing_mode'] not in Devices: Domoticz.Device(Name="Playing Mode", Unit=self.UNITS['playing_mode'], TypeName="Text", Used=1).Create() if self.UNITS['main_volume'] not in Devices: Domoticz.Device(Name="Volume Main Zone", Unit=self.UNITS['main_volume'], Type=244, Subtype=73, Switchtype=7, Image=8, Used=1).Create() DumpConfigToLog() self.SyncDevices(1) self.PioneerConn = Domoticz.Connection(Name="Telnet", Transport="TCP/IP", Protocol="Line", Address=Parameters["Address"], Port=Parameters["Port"]) self.PioneerConn.Connect() Domoticz.Heartbeat(30)
def onStart(self): # Debug debug = 0 if (Parameters["Mode1"] != "none"): Domoticz.Debugging(1) debug = 1 if (Parameters["Mode1"] == "ptvsd"): Domoticz.Log("Debugger ptvsd started, use 0.0.0.0:5678 to attach") import ptvsd # signal error on raspberry ptvsd.enable_attach() ptvsd.wait_for_attach() elif (Parameters["Mode1"] == "rpdb"): Domoticz.Log( "Debugger rpdb started, use 'telnet 0.0.0.0 4444' to connect") import rpdb rpdb.set_trace() # signal error on raspberry # rpdb.handle_trap("0.0.0.0", 4444) # Heartbeat self.heartbeat = Heartbeat(int(Parameters["Mode2"])) self.heartbeat.setHeartbeat(self.UpdateStatus) # Create miio ip = Parameters["Address"] token = Parameters["Mode3"] mode = Parameters["Mode4"] price = Parameters["Mode5"] self.miio = miio.powerstrip.PowerStrip(ip, token, 0, debug, True, mode) Domoticz.Debug("Xiaomi Miio PowerStrip created with address '" + ip + "' and token '" + token + "' and mode '" + mode + "'") if (price != ''): self.miio.set_power_price(int(price)) # Read function self.UpdateStatus(False) # Create devices for unit in self.__UNITS: field = unit["bindingStatusField"] value = getattr(self.status, field) if value is not None and unit["_Unit"] not in Devices: if "_Switchtype" in unit and unit["_Switchtype"] != None: Domoticz.Device(Name=unit["_Name"], Unit=unit["_Unit"], TypeName=unit["_TypeName"], Switchtype=unit["_Switchtype"], Image=unit["_Image"], Options=unit["_Options"]).Create() else: Domoticz.Device(Name=unit["_Name"], Unit=unit["_Unit"], TypeName=unit["_TypeName"], Options=unit["_Options"]).Create() # Read initial state self.UpdateStatus() DumpConfigToLog() return
def onStart(self): Domoticz.Debug("onStart called") self.hvac_device = Domoticz_AehW4a1(Parameters["Address"]) if Parameters["Mode2"] == "Debug": Domoticz.Debugging(1) if (len(Devices) == 0): Domoticz.Device(Name="Power", Unit=1, Image=9, TypeName="Switch", Used=1).Create() Domoticz.Device(Name="Temp IN", Unit=2, TypeName="Temperature", Used=1).Create() Domoticz.Device(Name="Temp OUT", Unit=3, TypeName="Temperature", Used=1).Create() Domoticz.Device(Name="Temp TARGET", Unit=4, Type=242, Subtype=1, Image=16, Used=1).Create() Options = { "LevelActions": "||||", "LevelNames": "|Heat|Cool|Dry|Fan", "LevelOffHidden": "true", "SelectorStyle": "1" } Domoticz.Device(Name="Mode", Unit=5, TypeName="Selector Switch", Image=16, Options=Options, Used=1).Create() Options = { "LevelActions": "||||||", "LevelNames": "|AutoHeat|Auto|Mute|Low|Medium|High", "LevelOffHidden": "true", "SelectorStyle": "1" } Domoticz.Device(Name="Fan Rate", Unit=6, TypeName="Selector Switch", Image=7, Options=Options, Used=1).Create() Options = { "LevelActions": "|||", "LevelNames": "Off|Vertical|Horizontal|Both", "LevelOffHidden": "false", "SelectorStyle": "1" } Domoticz.Device(Name="Swing", Unit=7, TypeName="Selector Switch", Image=7, Options=Options, Used=1).Create() Options = { "LevelActions": "|||||||", "LevelNames": "|Normal|Eco|Boost|Sleep1|Sleep2|Sleep3|Sleep4", "LevelOffHidden": "true", "SelectorStyle": "1" } Domoticz.Device(Name="Preset", Unit=8, TypeName="Selector Switch", Image=9, Options=Options, Used=1).Create() Domoticz.Device(Name="Display", Unit=9, Image=9, TypeName="Switch", Used=1).Create() Domoticz.Debug("Device created.") DumpConfigToLog() Domoticz.Heartbeat(10) self.DataUpdate()
def CreateDomoDevice(nbrdevices, Addr, Ep, Type): DeviceID = Addr #int(Addr,16) Domoticz.Debug("CreateDomoDevice - Device ID : " + str(DeviceID) + " Device EP : " + str(Ep) + " Type : " + str(Type)) if Type == "lumi.weather": # Detecteur temp/hum/baro xiaomi (v2) typename = "Temp+Hum+Baro" Domoticz.Device(DeviceID=str(DeviceID), Name=str(typename) + " - " + str(DeviceID), Unit=nbrdevices, TypeName=typename, Options={ "EP": str(Ep), "devices_type": str(Type), "typename": str(typename) }).Create() typename = "Temp+Hum" Domoticz.Device(DeviceID=str(DeviceID), Name=str(typename) + " - " + str(DeviceID), Unit=nbrdevices + 1, TypeName=typename, Options={ "EP": str(Ep), "devices_type": str(Type), "typename": str(typename) }).Create() typename = "Temperature" Domoticz.Device(DeviceID=str(DeviceID), Name=str(typename) + " - " + str(DeviceID), Unit=nbrdevices + 2, TypeName=typename, Options={ "EP": str(Ep), "devices_type": str(Type), "typename": str(typename) }).Create() typename = "Humidity" Domoticz.Device(DeviceID=str(DeviceID), Name=str(typename) + " - " + str(DeviceID), Unit=nbrdevices + 3, TypeName=typename, Options={ "EP": str(Ep), "devices_type": str(Type), "typename": str(typename) }).Create() typename = "Barometer" Domoticz.Device(DeviceID=str(DeviceID), Name=str(typename) + " - " + str(DeviceID), Unit=nbrdevices + 4, TypeName=typename, Options={ "EP": str(Ep), "devices_type": str(Type), "typename": str(typename) }).Create() if Type == "lumi.sensor_ht": # Detecteur temp/humi xiaomi (v1) typename = "Temp+Hum" Domoticz.Device(DeviceID=str(DeviceID), Name=str(typename) + " - " + str(DeviceID), Unit=nbrdevices, TypeName=typename, Options={ "EP": str(Ep), "devices_type": str(Type), "typename": str(typename) }).Create() typename = "Temperature" Domoticz.Device(DeviceID=str(DeviceID), Name=str(typename) + " - " + str(DeviceID), Unit=nbrdevices + 1, TypeName=typename, Options={ "EP": str(Ep), "devices_type": str(Type), "typename": str(typename) }).Create() typename = "Humidity" Domoticz.Device(DeviceID=str(DeviceID), Name=str(typename) + " - " + str(DeviceID), Unit=nbrdevices + 2, TypeName=typename, Options={ "EP": str(Ep), "devices_type": str(Type), "typename": str(typename) }).Create() if Type == "lumi.sensor_magnet.aq2" or Type == "lumi.sensor_magnet": # capteur ouverture/fermeture xiaomi (v1 et v2) typename = "Switch" Domoticz.Device(DeviceID=str(DeviceID), Name=str(typename) + " - " + str(DeviceID), Unit=nbrdevices, Type=244, Subtype=73, Switchtype=2, Options={ "EP": str(Ep), "devices_type": str(Type), "typename": str(typename) }).Create() if Type == "lumi.sensor_motion": # detecteur de presence (v1) xiaomi typename = "Switch" Domoticz.Device(DeviceID=str(DeviceID), Name=str(typename) + " - " + str(DeviceID), Unit=nbrdevices, Type=244, Subtype=73, Switchtype=8, Options={ "EP": str(Ep), "devices_type": str(Type), "typename": str(typename) }).Create() if Type == "lumi.sensor_switch.aq2" or Type == "lumi.sensor_switch": # petit inter rond ou carre (v1) typename = "Switch" Domoticz.Device(DeviceID=str(DeviceID), Name=str(typename) + " - " + str(DeviceID), Unit=nbrdevices, TypeName=typename, Options={ "EP": str(Ep), "devices_type": str(Type), "typename": str(typename) }).Create() if Type == "lumi.sensor_smoke": # detecteur de fumee (v1) xiaomi typename = "Switch" Domoticz.Device(DeviceID=str(DeviceID), Name=str(typename) + " - " + str(DeviceID), Unit=nbrdevices, Type=244, Subtype=73, Switchtype=5, Options={ "EP": str(Ep), "devices_type": str(Type), "typename": str(typename) }).Create() if Type == "lumi.sensor_motion.aq2": # Lux sensors + detecteur xiaomi v2 typename = "Lux" Domoticz.Device(DeviceID=str(DeviceID), Name=str(typename) + " - " + str(DeviceID), Unit=nbrdevices, Type=246, Subtype=1, Switchtype=0, Options={ "EP": str(Ep), "devices_type": str(Type), "typename": str(typename) }).Create() typename = "Switch" Domoticz.Device(DeviceID=str(DeviceID), Name=str(typename) + " - " + str(DeviceID), Unit=nbrdevices + 1, Type=244, Subtype=73, Switchtype=8, Options={ "EP": str(Ep), "devices_type": str(Type), "typename": str(typename) }).Create() if Type == "lumi.sensor_86sw1": # inter sans fils 1 touche 86sw1 xiaomi typename = "Switch" Domoticz.Device(DeviceID=str(DeviceID), Name=str(typename) + " - " + str(DeviceID), Unit=nbrdevices, Type=244, Subtype=73, Switchtype=9, Options={ "EP": str(Ep), "devices_type": str(Type), "typename": str(typename) }).Create()
def onStart(self): Domoticz.Debug("onStart called") #read out parameters for local connection self.ip_address = Parameters["Address"].strip() self.port_number = Parameters["Port"].strip() self.otp_code = Parameters['Mode1'] self.runCounter = int(Parameters['Mode2']) self.log_level = Parameters['Mode4'] self.account_password = Parameters['Mode3'] self.account_email = Parameters['Mode5'] self.machine_name = Parameters['Mode6'] if self.log_level == 'Debug': Domoticz.Debugging(2) DumpConfigToLog() if self.log_level == 'Verbose': Domoticz.Debugging(1 + 2 + 4 + 8 + 16 + 64) DumpConfigToLog() if self.log_level == 'Reset': Domoticz.Log( "Plugin config will be erased to retreive new cloud account data" ) Config = {} Config = Domoticz.Configuration(Config) #PureLink needs polling, get from config Domoticz.Heartbeat(10) self.checkVersion(self.version) mqtt_client_id = "" #create a Dyson account deviceList = self.get_device_names() if deviceList != None and len(deviceList) > 0: Domoticz.Debug( "Number of devices found in plugin configuration: '" + str(len(deviceList)) + "'") else: Domoticz.Log( "No devices found in plugin configuration, request from Dyson cloud account" ) #new authentication Domoticz.Debug( "=== start making connection to Dyson account, new method as of 2021 ===" ) dysonAccount2 = DysonAccount() challenge_id = getConfigItem(Key="challenge_id", Default="") setConfigItem(Key="challenge_id", Value="") #clear after use if challenge_id == "": #request otp code via email when no code entered challenge_id = dysonAccount2.login_email_otp( self.account_email, "NL") setConfigItem(Key="challenge_id", Value=challenge_id) Domoticz.Log( '==== An OTP verification code had been requested, please check email and paste code into plugin=====' ) return else: #verify the received code if len(self.otp_code) < 6: Domoticz.Error("invalid verification code supplied") return dysonAccount2.verify(self.otp_code, self.account_email, self.account_password, challenge_id) setConfigItem( Key="challenge_id", Value="") #reset challenge id as it is no longer valid Parameters['Mode1'] = "0" #reset the stored otp code #get list of devices info's deviceList = dysonAccount2.devices() deviceNames = list(deviceList.keys()) Domoticz.Log("Received new devices: " + str(deviceNames) + ", they will be stored in plugin configuration") i = 0 for device in deviceList: setConfigItem( Key="{0}.name".format(i), Value=deviceNames[i]) #store the name of the machine Domoticz.Debug('Key="{0}.name", Value = {1}'.format( i, deviceNames[i])) #store the name of the machine setConfigItem( Key="{0}.credential".format( deviceList[deviceNames[i]].name), Value=deviceList[ deviceNames[i]].credential) #store the credential Domoticz.Debug('Key="{0}.credential", Value = {1}'.format( deviceList[deviceNames[i]].name, deviceList[ deviceNames[i]].credential)) #store the credential setConfigItem( Key="{0}.serial".format( deviceList[deviceNames[i]].name), Value=deviceList[ deviceNames[i]].serial) #store the serial Domoticz.Debug('Key="{0}.serial", Value = {1}'.format( deviceList[deviceNames[i]].name, deviceList[deviceNames[i]].serial)) #store the serial setConfigItem(Key="{0}.product_type".format( deviceList[deviceNames[i]].name), Value=deviceList[deviceNames[i]].product_type ) #store the product_type Domoticz.Debug( 'Key="{0}.product_type" , Value = {1}'.format( deviceList[deviceNames[i]].name, deviceList[deviceNames[i]].product_type) ) #store the product_type i = i + 1 if deviceList == None or len(deviceList) < 1: Domoticz.Error( "No devices found in plugin configuration or Dyson cloud account" ) return else: Domoticz.Debug("Number of devices in plugin: '" + str(len(deviceList)) + "'") if deviceList != None and len(deviceList) > 0: if len(self.machine_name) > 0: if self.machine_name in deviceList: password, serialNumber, deviceType = self.get_device_config( self.machine_name) Domoticz.Debug( "password: {0}, serialNumber: {1}, deviceType: {2}". format(password, serialNumber, deviceType)) self.myDevice = DysonPureLinkDevice( password, serialNumber, deviceType, self.machine_name) else: Domoticz.Error( "The configured device name '" + self.machine_name + "' was not found in the cloud account. Available options: " + str(list(deviceList))) return elif len(deviceList) == 1: self.myDevice = deviceList[list(deviceList)[0]] Domoticz.Log( "1 device found in plugin, none configured, assuming we need this one: '" + self.myDevice.name + "'") else: #more than 1 device returned in cloud and no name configured, which the the plugin can't handle Domoticz.Error( "More than 1 device found in cloud account but no device name given to select. Select and filter one from available options: " + str(list(deviceList))) return #the Domoticz connection object takes username and pwd from the Parameters so write them back Parameters[ 'Username'] = self.myDevice.serial #take username from account Parameters[ 'Password'] = self.myDevice.password #override the default password with the one returned from the cloud else: Domoticz.Error("No usable credentials found") return #check, per device, if it is created. If not,create it Options = { "LevelActions": "|||", "LevelNames": "|OFF|ON|AUTO", "LevelOffHidden": "true", "SelectorStyle": "1" } if self.fanModeUnit not in Devices: Domoticz.Device(Name='Fan mode', Unit=self.fanModeUnit, TypeName="Selector Switch", Image=7, Options=Options).Create() if self.fanStateUnit not in Devices: Domoticz.Device(Name='Fan state', Unit=self.fanStateUnit, Type=244, Subtype=62, Image=7, Switchtype=0).Create() if self.heatStateUnit not in Devices: Domoticz.Device(Name='Heating state', Unit=self.heatStateUnit, Type=244, Subtype=62, Image=7, Switchtype=0).Create() if self.nightModeUnit not in Devices: Domoticz.Device(Name='Night mode', Unit=self.nightModeUnit, Type=244, Subtype=62, Switchtype=0, Image=9).Create() Options = { "LevelActions": "|||||||||||", "LevelNames": "OFF|1|2|3|4|5|6|7|8|9|10|AUTO", "LevelOffHidden": "false", "SelectorStyle": "1" } if self.fanSpeedUnit not in Devices: Domoticz.Device(Name='Fan speed', Unit=self.fanSpeedUnit, TypeName="Selector Switch", Image=7, Options=Options).Create() if self.fanOscillationUnit not in Devices: Domoticz.Device(Name='Oscilation mode', Unit=self.fanOscillationUnit, Type=244, Subtype=62, Image=7, Switchtype=0).Create() if self.standbyMonitoringUnit not in Devices: Domoticz.Device(Name='Standby monitor', Unit=self.standbyMonitoringUnit, Type=244, Subtype=62, Image=7, Switchtype=0).Create() if self.filterLifeUnit not in Devices: Options: {'Custom': '1;hrs'} Domoticz.Device(Name='Remaining filter life', Unit=self.filterLifeUnit, TypeName="Custom", Options=Options).Create() if self.resetFilterLifeUnit not in Devices: Domoticz.Device(Name='Reset filter: 0 hrs', Unit=self.resetFilterLifeUnit, TypeName="Switch", Image=9).Create() if self.tempHumUnit not in Devices: Domoticz.Device(Name='Temperature and Humidity', Unit=self.tempHumUnit, TypeName="Temp+Hum").Create() if self.volatileUnit not in Devices: Domoticz.Device(Name='Volatile organic', Unit=self.volatileUnit, TypeName="Air Quality").Create() if self.sleepTimeUnit not in Devices: Domoticz.Device(Name='Sleep timer', Unit=self.sleepTimeUnit, TypeName="Custom").Create() if self.particlesUnit not in Devices: Domoticz.Device(Name='Dust', Unit=self.particlesUnit, TypeName="Air Quality").Create() if self.qualityTargetUnit not in Devices: Options = { "LevelActions": "|||", "LevelNames": "|Normal|Sensitive (Medium)|Very Sensitive (High)|Off", "LevelOffHidden": "true", "SelectorStyle": "1" } Domoticz.Device(Name='Air quality setpoint', Unit=self.qualityTargetUnit, TypeName="Selector Switch", Image=7, Options=Options).Create() if self.particles2_5Unit not in Devices: Domoticz.Device(Name='Dust (PM 2,5)', Unit=self.particles2_5Unit, TypeName="Air Quality").Create() if self.particles10Unit not in Devices: Domoticz.Device(Name='Dust (PM 10)', Unit=self.particles10Unit, TypeName="Air Quality").Create() if self.particlesMatter25Unit not in Devices: Domoticz.Device(Name='Particles (PM 25)', Unit=self.particlesMatter25Unit, TypeName="Air Quality").Create() if self.particlesMatter10Unit not in Devices: Domoticz.Device(Name='Particles (PM 10)', Unit=self.particlesMatter10Unit, TypeName="Air Quality").Create() if self.fanModeAutoUnit not in Devices: Domoticz.Device(Name='Fan mode auto', Unit=self.fanModeAutoUnit, Type=244, Subtype=62, Image=7, Switchtype=0).Create() if self.fanFocusUnit not in Devices: Domoticz.Device(Name='Fan focus mode', Unit=self.fanFocusUnit, Type=244, Subtype=62, Image=7, Switchtype=0).Create() if self.nitrogenDioxideDensityUnit not in Devices: Domoticz.Device(Name='Nitrogen Dioxide Density (NOx)', Unit=self.nitrogenDioxideDensityUnit, TypeName="Air Quality").Create() if self.heatModeUnit not in Devices: Options = { "LevelActions": "||", "LevelNames": "|Off|Heating", "LevelOffHidden": "true", "SelectorStyle": "1" } Domoticz.Device(Name='Heat mode', Unit=self.heatModeUnit, TypeName="Selector Switch", Image=7, Options=Options).Create() if self.heatTargetUnit not in Devices: Domoticz.Device(Name='Heat target', Unit=self.heatTargetUnit, Type=242, Subtype=1).Create() if self.deviceStatusUnit not in Devices: Domoticz.Device(Name='Machine status', Unit=self.deviceStatusUnit, TypeName="Text", Image=7).Create() Domoticz.Log("Device instance created: " + str(self.myDevice)) self.base_topic = self.myDevice.device_base_topic Domoticz.Debug("base topic defined: '" + self.base_topic + "'") #create the connection if self.myDevice != None: self.mqttClient = MqttClient(self.ip_address, self.port_number, mqtt_client_id, self.onMQTTConnected, self.onMQTTDisconnected, self.onMQTTPublish, self.onMQTTSubscribed)
def onMessage(self, Connection, Data): #DumpHTTPResponseToLog(Data) # expect strData like [{"id":"100017aec6","state":"on","model":"PSA-B01-GL","version":"1.5.5"},{"id":"100017aec6","state":"on","model":"PSA-B01-GL","version":"1.5.5"}] strData = Data["Data"].decode("utf-8", "ignore") Status = int(Data["Status"]) #LogMessage(strData) if (Status == 200): # success Domoticz.Log("Response from local Sonoff server."+str(strData)) self.httpConn.Disconnect() else: # problem Domoticz.Error("Local Sonoff server returned a status: "+str(Status)) # convert strData string to a python dictionary using eval strData_structure=eval(strData) # handle all switches provided by the local Sonoff server Domoticz.Log("loop strData_structure") for Switch in strData_structure: sw_id=Switch["id"] sw_state=Switch["state"] sw_model=Switch["model"] sw_version=Switch["version"] Domoticz.Log("Sonoff switch: id=" + str(sw_id) + " state=" + str(sw_state) + " model=" + str(sw_model) + " version=" + str(sw_version)) # compose name off switch in Domoticz, can later be changed in GUI sw_name="Sonoff"+str(sw_id) # Domoticz.Debug("Existing Devices:" + str(Devices)) DumpConfigToLog() # check the Sonoff id (like 100017aec6) with the sValue of existing Domoticz devices deviceFound = False for Device in Devices: if (Devices[Device].sValue == sw_id): deviceFound = True sw_unit=Device if (deviceFound == True): # existing device Domoticz.Debug("Sonoff " + sw_id + " is existing as Unit " + str(sw_unit)) Domoticz.Debug("Existing Sonoff switch updated from : id=" + str(sw_id) + " state=" + str(sw_state) + " model=" + str(sw_model) + " version=" + str(sw_version)) else: # unknown device Domoticz.Debug("Sonoff-" + sw_id + "is NOT existing") #if NO devices defined yet, set unitnumber to 1, else set new unit number as currently max unit number + 1 if ( len(Devices) == 0 ): sw_unit=1 else: sw_unit=max(Devices)+1 # create new device device, unit to sw_unit, nvalue to 0, sValue to sw_id of Sonoff (like 100017aec6), unit to sw_unit, Used=1 Domoticz.Device(Name=sw_name, Unit=sw_unit, TypeName="Switch", Used=1).Create() UpdateDevice(sw_unit, 0 , str(sw_id)) Domoticz.Debug("New Sonoff switch created from : id=" + str(sw_id) + " state=" + str(sw_state) + " model=" + str(sw_model) + " version=" + str(sw_version)) Domoticz.Debug("New Sonoff switch created as unit " + str(sw_unit) + "and sValue " + str(Devices[sw_unit].sValue)) if ( str(sw_state).lower() == "on" ): # command is "on", set nValue to 1 UpdateDevice(sw_unit, 1 ,Devices[sw_unit].sValue) Domoticz.Debug("Existing Sonoff switch updated as unit " + str(sw_unit) + " and sValue " + str(Devices[sw_unit].sValue) + " with nValue=1") else: # command is NOT "on" so it must be "off", set nValue to 0 UpdateDevice(sw_unit, 0 ,Devices[sw_unit].sValue) Domoticz.Debug("Existing Sonoff switch updated as unit " + str(sw_unit) + " and sValue " + str(Devices[sw_unit].sValue) + " with nValue=0")
def onStart(): global mainSource, mainVolume1, zone2Source, zone2Volume, zone3Source, zone3Volume if Parameters["Mode6"] == "Debug": Domoticz.Debugging(1) LevelActions = '|' * Parameters["Mode3"].count('|') # if Zone 3 required make sure at least themain device exists, otherwise suppress polling for it if (Parameters["Mode1"] > "2"): if (5 not in Devices): Domoticz.Device(Name="Zone 3", Unit=5, TypeName="Selector Switch", Switchtype=18, Image=5, \ Options="LevelActions:"+stringToBase64(LevelActions)+";LevelNames:"+stringToBase64(Parameters["Mode3"])+";LevelOffHidden:ZmFsc2U=;SelectorStyle:MQ==").Create() if (6 not in Devices): Domoticz.Device(Name="Volume 3", Unit=6, Type=244, Subtype=73, Switchtype=7, Image=8).Create() Domoticz.Log( "Created Zone 3 device(s) because zone requested in hardware setup but device not found." ) else: zone3Source = Devices[5].nValue if (6 in Devices): zone3Volume = int(Devices[6].sValue) else: pollingDict.pop("Z3") pollingDict["Z2"] = "PW?\r" # if Zone 2 required make sure at least themain device exists, otherwise suppress polling for it if (Parameters["Mode1"] > "1"): if (3 not in Devices): Domoticz.Device(Name="Zone 2", Unit=3, TypeName="Selector Switch", Switchtype=18, Image=5, \ Options="LevelActions:"+stringToBase64(LevelActions)+";LevelNames:"+stringToBase64(Parameters["Mode3"])+";LevelOffHidden:ZmFsc2U=;SelectorStyle:MQ==").Create() if (4 not in Devices): Domoticz.Device(Name="Volume 2", Unit=4, Type=244, Subtype=73, Switchtype=7, Image=8).Create() Domoticz.Log( "Created Zone 2 device(s) because zone requested in hardware setup but device not found." ) else: zone2Source = Devices[3].nValue if (4 in Devices): zone2Volume = int(Devices[4].sValue) else: pollingDict.pop("Z2") pollingDict["MU"] = "PW?\r" if (1 not in Devices): Domoticz.Device(Name="Main Zone", Unit=1, TypeName="Selector Switch", Switchtype=18, Image=5, \ Options="LevelActions:"+stringToBase64(LevelActions)+";LevelNames:"+stringToBase64(Parameters["Mode3"])+";LevelOffHidden:ZmFsc2U=;SelectorStyle:MQ==").Create() Domoticz.Device(Name="Main Volume", Unit=2, Type=244, Subtype=73, Switchtype=7, Image=8).Create() Domoticz.Log("Created Main Zone devices because they were not found.") else: mainSource = Devices[1].nValue if (2 in Devices): mainVolume1 = int(Devices[2].sValue) DumpConfigToLog() dictValue = 0 for item in Parameters["Mode3"].split('|'): selectorMap[dictValue] = item dictValue = dictValue + 10 Domoticz.Log(str(selectorMap)) Domoticz.Transport("TCP/IP", Parameters["Address"], Parameters["Port"]) Domoticz.Protocol("Line") Domoticz.Connect() return