Domoticz crashes because of my script

Python and python framework

Moderator: leecollings

Post Reply
User avatar
Luxtux
Posts: 31
Joined: Monday 14 August 2017 15:16
Target OS: Linux
Domoticz version: 2021.1 β
Location: Luxembourg
Contact:

Domoticz crashes because of my script

Post by Luxtux »

Hello,

i'm teaching myself python and thought it would be a good learning experience to create a domoticz event script. The idea is when i update my phone's alarm settings, it automatically changes my Hue sunrise routine and change the timer on my bedroom shutter. My phone updates a uservariable (AlarmTime) in domoticz via tasker as epoch(linux time) or if i cancel the alarm it updates it to a string 'next'. the script is triggered on updated uservariables. I convert the epoch time to the time format the hue api understands and to the timeformat domoticz understands. basically HUE sunrise routine needs to start 30 min before the alarm and the shutter should open 10 min after the alarm.

My issue is that as soon as my alarm of today has rang, it updates the uservariable to tomorrows alarm and the shutter timer is overwritten with tomorrows timer. basically it never opens automatically. to get around this issue i thought it would be a good idea to save today's alam time in another uservariable (lastalarmtime) and compare the two. if the new alarm is in 24 hours don't delete the old one. this all seems to work as i would expect but as soon as i update the lastalarmtime uservariable domoticz crashes. i honestly dont see where the issue is. any ideas or suggestions are more than welcome. :)

Code: Select all

import Domoticz , DomoticzEvents as DEVS

if '/home/domoticz/.local/lib/python3.7/site-packages' not in sys.path :
    DEVS.Log('Site packages path not found')
    sys.path.append( '/home/domoticz/.local/lib/python3.7/site-packages' )

from datetime import datetime , requests, json, urllib

def isint(value):
  try:
    int(value)
    return True
  except ValueError:
    return False


DomoticzIP = '192.168.10.51'
ShutterIDX = '151'
HueIP = '192.168.10.52'
HueUsername = '0000000000000-000000000-0000000000000000000000000000'


for name, value in DEVS.user_variables.items():
    
    res = isinstance(value, str)
    
    if name == 'LastAlarmTime':
        LastAlarm = value
    
    if name == 'AlarmTime':
        
        # Get Hue schedules
        response = requests.get(f"http://{HueIP}/api/{HueUsername}/schedules")
        data =  json.loads(response.text)
        
        # Get the ID of the Schedule called Wake Up Sunrise
        for i in data.keys():
            if data[i].get('name') == 'Wake up Sunrise':
                Schedule = i
            
    
        if isint(value) :
        
            DEVS.Log('New Alarm')
            
            # Take 30 min of for Hue sunrise
            HueAlarm = int(value) - 1800
            
            # add 10 min for opening shutter
            ShutterAlarm = int(value) + 600
            
            # Create JSON Post for Hue schedule
            TimeAlarm = datetime.utcfromtimestamp(HueAlarm).strftime('/T%H:%M:%S')
            DayAlarm = datetime.utcfromtimestamp(HueAlarm).weekday()
            TimeFormated = {0 : f'W064{TimeAlarm}',1 : f'W032{TimeAlarm}',2 : f'W016{TimeAlarm}',3 : f'W008{TimeAlarm}',4 : f'W004{TimeAlarm}',5 : f'W002{TimeAlarm}',6 : f'W001{TimeAlarm}',}
            JsonPutAlarm = { "time": TimeFormated[DayAlarm], "status": "enabled"}
            
            # Create url elements for shutter opening
            HourAlarm = datetime.fromtimestamp(ShutterAlarm).strftime('%H')
            MinuteAlarm = datetime.fromtimestamp(ShutterAlarm).strftime('%M')
            DateAlarm = datetime.fromtimestamp(ShutterAlarm).strftime('%Y-%m-%d')
            
            if LastAlarm == value :
                break
            
            # calculate if the new alarm is in 24 hours
            TwentyFourHours = int(LastAlarm) + 86400 - int(value)
            
            if TwentyFourHours != 0 :
                DEVS.Log('not 24 hours difference')
                # remove shutter timers if alarm is not in 24 hours
                ClearShutter = requests.get(f'http://{DomoticzIP}/json.htm?type=command&param=cleartimers&idx={ShutterIDX}')
                
            # set shutter opening
            SetShutter = requests.get(f'http://{DomoticzIP}/json.htm?active=true&command=1&date={DateAlarm}&days=0&hour={HourAlarm}&idx={ShutterIDX}&level=1&min={MinuteAlarm}&param=addtimer&randomness=false&timertype=5&type=command')
            
            # save alarm to LastAlarm
            SetLastAlarm = requests.get(f'http://{DomoticzIP}/json.htm?type=command&param=updateuservariable&vname=LastAlarmTime&vtype=0&vvalue={value}')
            
        elif str(res):
        
            DEVS.Log('Cancel Alarm')
             
            # Create JSON Post for Hue schedule
            JsonPutAlarm = { "status": "disabled"}
            
            # remove shutter timers if alarm is not in 24 hours
            requestShutter = requests.get(f'http://{DomoticzIP}/json.htm?type=command&param=cleartimers&idx={ShutterIDX}')
    
        # post sunrise
        putHue = requests.put(f"http://{HueIP}/api/{HueUsername}/schedules/{Schedule}", json=JsonPutAlarm)
        
        
User avatar
Luxtux
Posts: 31
Joined: Monday 14 August 2017 15:16
Target OS: Linux
Domoticz version: 2021.1 β
Location: Luxembourg
Contact:

Re: Domoticz crashes because of my script

Post by Luxtux »

Hey,

i changed my approach and now just put a timer on scene which resolves the issue for me. If anybody feel like telling me what i actually did wrong in the origninal idea; it would be appriciated.

Code: Select all

import Domoticz, DomoticzEvents as DEVS
from datetime import datetime

if '/home/domoticz/.local/lib/python3.7/site-packages' not in sys.path :
    DEVS.Log('Path not found')
    sys.path.append( '/home/domoticz/.local/lib/python3.7/site-packages' )


import requests,json,urllib

def isint(value):
  try:
    int(value)
    return True
  except ValueError:
    return False


DomoticzIP ='192.168.10.51'
ShutterSceneIDX = '9'
HueIP = '192.168.10.52'
HueUsername = '0000000000000-000000000-0000000000000000000000000000'


for name, value in DEVS.user_variables.items():
    
    res = isinstance(value, str)
    
    if name == 'AlarmTime':
        
        # Get Hue schedule
        response = requests.get(f"http://{HueIP}/api/{HueUsername}/schedules")
        data =  json.loads(response.text)
        
        # Get the ID of the Schedule called Wake Up  :)
        for i in data.keys():
            if data[i].get('name') == 'Wake up' :
                Schedule = i
            
    
        if isint(value) :
        
            DEVS.Log('Set Alarm')
            
            # Take 30 min of for Hue sunrise
            HueAlarm = int(value) - 1800
            
            
            # Create JSON Post for Hue schedule
            TimeAlarm = datetime.utcfromtimestamp(HueAlarm).strftime('/T%H:%M:%S')
            DayAlarm = datetime.utcfromtimestamp(HueAlarm).weekday()
            TimeFormated = {0 : f'W064{TimeAlarm}',1 : f'W032{TimeAlarm}',2 : f'W016{TimeAlarm}',3 : f'W008{TimeAlarm}',4 : f'W004{TimeAlarm}',5 : f'W002{TimeAlarm}',6 : f'W001{TimeAlarm}',}
            JsonPutAlarm = { "time": TimeFormated[DayAlarm], "status": "enabled"}
            
            # Create url elements for shutter opening
            HourAlarm = datetime.fromtimestamp(int(value)).strftime('%H')
            MinuteAlarm = datetime.fromtimestamp(int(value)).strftime('%M')
            DateAlarm = datetime.fromtimestamp(int(value)).strftime('%Y-%m-%d')
            #DateAlarm = DateAlarm.replace("/","%2F")

            # remove shutter timers
            ClearShutterAlarm = requests.get('http://{DomoticzIP}/json.htm?idx={ShutterSceneIDX}&param=clearscenetimers&type=command')
            
            # set shutter opening
            requestShutter = requests.get(f'http://{DomoticzIP}/json.htm?active=true&command=0&date={DateAlarm}&days=0&hour={HourAlarm}&idx={ShutterSceneIDX}&min={MinuteAlarm}&param=addscenetimer&randomness=false&timertype=5&type=command')
            
        elif str(res):
        
            DEVS.Log('Cancel Alarm')
             
            # Create JSON Post for Hue schedule
            JsonPutAlarm = { "status": "disabled"}
            
            # remove shutter timers
            ClearShutterAlarm = requests.get('http://{DomoticzIP}/json.htm?idx={ShutterSceneIDX}&param=clearscenetimers&type=command')
            
    
        # post sunrise
        putHue = requests.put(f"http://{HueIP}/api/{HueUsername}/schedules/{Schedule}", json=JsonPutAlarm)
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest