def logList(): qString = request.query_string.strip() logSys("/logs >>" + qString + "<<") # selectedDay = qString.strip() now = datetime.now() today = now.strftime("%A") if selectedDay == "": selectedDay = today fLog = logFile(selectedDay) output = [] try: logss = open(fLog, 'r') for line in logss: output.append('<li>' + line.replace("\n","") + '</li>') output.sort(reverse=True) output = '<ul>' + str(output) + '</ul>' output = str(output).replace("', '","").replace("']","").replace("['","") except: msg = " +++ " + xS("piMain.piLogFile") + " "+ fLog + " " + xS("piSchedule.notFound") logSys(msg) rv = {'logList':output, 'today':today} page = templateSetup('piLogs', rv) return page.replace("&¤tDay&&",xS("piLogs."+selectedDay))
def home(): qString = request.query_string.strip() logSys("/home >>" + qString + "<<") # # build 'ini' file menu fileList = iniFileMenu('edit') fileList += "</li><li role='presentation'><a href='/edit?newSchedule'>" + xS('piMain.newSchedule') + "</a></li>" fileList1 = iniFileMenu1('weekScheduleSet') rv = combineKeys(xP.prefs, {'pilight':'http://'+xP.prefs['server']+':'+ str(xP.prefs['pilightPort']), 'Monday': xS("piLogs.Monday"), 'schedule1': getSchedule4Day('Monday'), 'Tuesday': xS("piLogs.Tuesday"), 'schedule2': getSchedule4Day('Tuesday'), 'Wednesday': xS("piLogs.Wednesday"), 'schedule3': getSchedule4Day('Wednesday'), 'Thursday': xS("piLogs.Thursday"), 'schedule4': getSchedule4Day('Thursday'), 'Friday': xS("piLogs.Friday"), 'schedule5': getSchedule4Day('Friday'), 'Saturday': xS("piLogs.Saturday"), 'schedule6': getSchedule4Day('Saturday'), 'Sunday': xS("piLogs.Sunday"), 'schedule0': getSchedule4Day('Sunday') }) page = templateSetup('piMain', rv) page = page.replace('&&iniFileList&&',fileList) page = page.replace('&&iniFileList1&&',fileList1) return page.replace('&&localeList&&',localesMenu())
def refreshSchedule(): global xP caller = request.fullpath[1:] qString = request.query_string.strip() logSys(" /" + caller + " >>" + qString + "<<") tab = scheduleActive() fileList = iniFileMenu('schedule') newsSchedule, newsStatus, newsDate = getNews(xP.prefs) if newsDate != "": xP.prefs['newsDate'] = newsDate rv = combineKeys(xP.prefs, {'pilight':'http://'+xP.prefs['server']+':'+ str(xP.prefs['pilightPort']), 'newsDisplay': newsStatus}) page = templateSetup('piSchedule', rv) page = page.replace('&&iniFileList&&',fileList) hString = str(datetime.now())[:19] page = page.replace('&&datetime&&', hString) page = page.replace('&&timeTable&&', tab) page = page.replace('&&newsDate&&', newsDate) return page.replace('&&news&&', newsSchedule)
def control(): caller = request.fullpath[1:] qString = request.query_string.strip() logSys(" /" + caller + " >>\n" + str(qString) + "\n<<") jobs2Schedule([qString]) tab = scheduleActive() return "<br> >>" + caller + "::" + str(qString) + "<<<br><br>"
def updateWeekdaySchedule(): qString = request.query_string.strip(' ,') schedules = qString.split(',') logSys("/setWeekdaySchedule >>" + str(schedules) + "<<") wDays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] for day in range(0,7): xP.prefs['weekSchedule'][wDays[day]] = schedules[day] prefsSaveJSON(None, None)
def listPrefs(): caller = request.fullpath[1:] qString = request.query_string.strip() logSys(" /"+caller + " >>" + qString + "<<", '36') #36mCyan" prefsRead() showPrefs = (json.dumps(xP.prefs, sort_keys=True, indent=3).decode('unicode_escape')) showPrefs = showPrefs.replace(",",",<br>") return [showPrefs]
def getSchedule(): caller = request.fullpath[1:] if caller != 'schedule': qString = "" else: qString = request.query_string.strip() logSys("/schedule >>" + qString + "<<") sched.remove_all_jobs() if qString != "": aSchedule = qString else: aSchedule = "Select INI " if 'iniFile' in xP.prefs: aSchedule = xP.prefs['iniFile'] renew = True xP.switchTime = datetime.now().replace(hour=0,minute=0,second=0,microsecond=0) + timedelta(hours=24) #log2DayFile(False, ' .. activated Schedule .. ' + str(xP.switchTime)) prefsSaveJSON('iniFile', aSchedule) jobLines = jobsRead(aSchedule) jobs2Schedule(jobLines) cJob = sched.add_job(renewSchedule, 'date', run_date=str(xP.switchTime), id="renew") tab = scheduleActive() msg = " next SwitchTime :: " + str(xP.switchTime) #print("activated Schedule " + msg) #log2DayFile(False, msg) fileList = iniFileMenu('schedule') newsSchedule, newsStatus, newsDate = getNews(xP.prefs) if newsDate != "": xP.prefs['newsDate'] = newsDate rv = combineKeys(xP.prefs, {'pilight':'http://'+xP.prefs['server']+':'+ str(xP.prefs['pilightPort']), 'newsDisplay': newsStatus}) page = templateSetup('piSchedule', rv) page = page.replace('&&iniFileList&&',fileList) hString = str(datetime.now())[:19] page = page.replace('&&datetime&&', hString) page = page.replace('&&timeTable&&', tab) page = page.replace('&&newsDate&&', newsDate) return page.replace('&&news&&', newsSchedule)
def gMapsApi(address, **geo_args): geo_args.update({ 'address': address }) gPrefs = {} if (address == ""): gPrefs["status"] = " *** piGeoDetails 'gmaps' needs a location string!" return gPrefs url = GEOCODE_BASE_URL + '?' + urllib.urlencode(geo_args) with closing(urlopen(url)) as response: rv = json.loads(response.read()) #logInfo("\n" + str(rv).replace("u'", "'")) logSys("\n" + str(rv).encode('utf-8').replace("u'", "'")) ''' #19498 19:13:01 - piGeoDetails gMapsApi #69 {'status': 'ZERO_RESULTS', 'results': []} ''' if (type(rv) is dict): status = rv['status'] if status != "OK": gPrefs['status'] = (" *** Request failed for %s with %s. (HTTP code %s)" % (str(geo_args), status, response.getcode())) gPrefs['location'] = 'Location :: ' + str(status) return gPrefs gPrefs['latitude'] = rv['results'][0]['geometry']['location']['lat'] gPrefs['longitude'] = rv['results'][0]['geometry']['location']['lng'] gPrefs['address'] = rv['results'][0]['formatted_address'].encode('utf-8') for s in rv['results'][0]['address_components']: for d in s: if s[d][0] == 'locality': #gPrefs ["location"] = s['short_name'] gPrefs ["location"] = s['long_name'].encode('utf-8') if s[d][0] == 'country': gPrefs ["locale"] = s['short_name'].encode('utf-8') gPrefs['geo'] = 'gmaps' gPrefs['status'] = response.getcode() #"200" else: #&&---- print (" *** piGeoDetails (gmaps) failed to deliver location for >>%s<<" % (str(address))) gPrefs['status'] = " *** gmaps ERROR ***" return gPrefs
def removeJob(): caller = request.fullpath[1:] qString = request.query_string.strip() logSys(" /" + caller + " >>" + qString + "<<") try : sched.remove_job(qString) except: logInfo("Job may have been removed already") page = refreshSchedule() return page #.replace('&&language&&', piStrings.getLocale())
def xDelete(): caller = request.fullpath[1:] qString = request.query_string.strip() logSys(" /" + caller + " >>\n" + str(qString) + "\n<<") qString = json.loads(urllib2.unquote(qString)) fName = qString[0]['fName'] #file name pName = qString[1]['pName'] #placeholder file name if fName == "": fName = pName os.remove(fName)
def fire_pilight(arg): #--------------------------------- global xP message = arg['message'] info = arg['info'] url = ('http://' + xP.prefs['server'] + ':' + str(xP.prefs['pilightPort']) + message) request = urllib2.Request(url) response = urllib2.urlopen(request) logSys ("url " + url) logInfo ("\n " + "\033[1m" + "pilight control >" + info + "<" + "\033[0m") log2DayFile(False, info)
def iniRead(): caller = request.fullpath[1:] qString = request.query_string.strip() logSys(" /" + caller + " >>" + qString + "<<") jobLines = jobsRead(qString) jobs2Schedule(jobLines) output = '<table class="table table-striped table-bordered"><tbody>' for job in aJobs: #logSys("out: " + str(job)) if job != []: output += "<tr><td> " + str(job[0]) + "</td><td> " + str(job[1]) + "</td><td> " + str(job[2]) + "</td></tr> " output += '</tbody></table>' return output
def jobsRead(cIniFile = 'piSchedule.ini'): if cIniFile == "": cIniFile = 'piSchedule.ini' jobLines = "" try: msg = "read INI Jobs file >> " + cIniFile + "<<" jobLines = jobsReadFile(cIniFile) logSys (msg + "\n" + str(jobLines)) logInfo (msg) except: pass #if fails get 'piSchedule.ini' or initialize it logERR(True) return jobLines
def geoPrefs(xPrefs): info = " ** Geolocation details." cLocation = "" if 'location' in xPrefs: cLocation = xPrefs['location'].encode('utf-8') rv = {} if 'geo' not in xPrefs: xPrefs['geo'] = 'ip' if xPrefs['geo'] == 'fix': rv['latitude'] = xPrefs['latitude'] rv['longitude'] = xPrefs['longitude'] info += " GeoCoordinates fixed!" if (xPrefs['geo'] == "-ip") or (xPrefs['geo'] == "ip"): rv = ipApi() # testing purpose only #print ("ipApi " + str(rv)) #rv['location'] = "" #rv = {} if (('location' in rv) == False) or (rv['location'] == ""): #logInfo(" *** piGeoDetails (ip) failed, try (gmaps) *** \n", '31') # red logSys(" *** piGeoDetails (ip) failed, try (gmaps) *** \n", '31') # red xPrefs['geo'] = "-gmaps" if (xPrefs['geo'] == "-gmaps") or (xPrefs['geo'] == "gmaps"): rv = gMapsApi(cLocation) logSys(" geo gmaps status: " + str(rv['status'])) if rv['status'] != 200: return rv rvS = sunrise_sunset.getSunrise_Sunset(rv['latitude'], rv['longitude']) rv['sunset'] = rvS['sunset'] rv['sunrise'] = rvS['sunrise'] rv['status'] = rvS['status'] #print(" ***&&& GeoDetails: " + str(rv)) return rv
def setPrefs(): caller = request.fullpath[1:] qString = request.query_string.strip() logSys(" /"+caller + " >>" + qString + "<<") if qString != "": xP.prefs[caller] = qString prefsSaveJSON(caller, qString) prefsSetup() #if caller == 'newsDate': # qString = caller + "::" + xP.prefs[caller] if caller in xP.prefs: qString = caller + "::" + xP.prefs[caller] return getSchedule()
def suntime(): #--------------------------------- # support Sunrise/Sunset with time values # time is calculated for actual day! if ('latitude' in xP.prefs) and ('longitude' in xP.prefs): rvS = sunrise_sunset.getSunrise_Sunset(xP.prefs['latitude'], xP.prefs['longitude']) xP.prefs['sunrise'] = rvS['sunrise'] xP.prefs['sunset'] = rvS['sunset'] logSys("&& check suntime sunrise: " + str(xP.prefs['sunrise'])) logSys("&& check suntime sunset: " + str(xP.prefs['sunset'])) prefsSaveJSON(None, None) else: pass
def onoff(): caller = request.fullpath[1:] message = request.query_string.strip() logSys(caller + " >>\n" + message + "\n<<") device = message.split(",")[0] state = message.split(",")[1] logSys(" on/off for device: " + device + " with " + state) # http://192.168.178.16:5001/send?{"action":"control","code":{"device":"Bad","state": "on"}} message = '/send?{"action":"control","code":{"device":"' + device \ + '","state":"' + state + '"}}' arg = {} arg['info'] = ' timeline on/off ' + device + ' state ' +state arg['message'] = message fire_pilight(arg)
def send(): caller = request.fullpath[1:] message = request.query_string.strip() logSys(caller + " >>\n" + message + "\n<<") arg = {} arg['message'] = "/send?" + message # {%22action%22:%22control%22,%22code%22:{%22device%22:%22Bad%22,%22state%22:%22off%22}} # {"action":"control","code":{"device":"Bad","state":"off"}} info = message info = info.replace('%22', '"').replace('/send?','') info = info.replace('{"action":"control","code":', '') info = info.replace('{', '').replace('}', '').replace('"', '') arg['info'] = "/send " + info fire_pilight(arg) return [info]
def about(): caller = request.fullpath[1:] message = request.query_string.strip() logSys(str(caller) + " >>" + str(platform.uname()) + "<<") rv = {'about': xS("piMain.about"), 'gotoMain': xS("piPrefs.gotoMain"), 'back': xS("piEdit.back"), 'version': xP.prefs['version'], 'pilightVersion': xP.prefs['pilightVersion'], 'server': xP.prefs['server'], 'port': xP.prefs['port'], 'iniFile': xP.prefs['iniFile'], 'locale': xP.prefs['locale'], 'geo': xP.prefs['geo'], 'platform': str(platform.platform()).replace("'","") } return templateSetup('piAbout', rv)
def main(): global xP, piPortDelta try: logInfo('\n________Started piSchedule (cMain)________') logSys ('\n________Started piSchedule (cMain)________') debug(mode=False) # Bottle debug mode <<<<<<<<<<<<<<<<< xP.switchTime = datetime.now().replace(hour=0,minute=0,second=0,microsecond=0)+ timedelta(hours=24) prefsRead() xP.prefs = prefsSetup() # includes geoDetails, suntime info = logPrefsDetails(xP.prefs) print(info) logInfo(info) if xP.prefs['ssdp'] != "OK": print ("\n ** NO 'ssdp' connection! **") return xP.prefs['ssdp'] if (len(sys.argv) == 2) and sys.argv[1] == "-prefs": return 0 #x= 1/0 # logERR Testing only sched.start() # start the scheduler renewSchedule() # if iniFile is set, load jobList of it # starting bottle with web page app.run(host = xP.prefs['server'], port = xP.prefs['port'], reloader=False) except: logERR(True) logInfo('Finished Main\n') logSys('Finished Main\n')
def main(): #if len(sys.argv) == 1: # return # Initialized only try: calling = sys.argv[1] except: calling = "-ip" if (calling == "-help"): print (""" --- piGeoDetails Help piGeoDetails returns the geolocation (city, locale code, latitude, longitude) based on the current IP or a given location. Call: piGeoDetails.py [argument] arguments are: -ip uses IP based search -gmaps uses Google Maps, needs location data -help Note: With using IP based search (-ip) and the return string for 'city' is empty, an alternative Google Maps search will run if the 'location' was passed also. """) exit() location = "" if (len(sys.argv) == 3): location = (sys.argv[2]).encode('utf-8') # address="San+Francisco" rv = geoPrefs(calling, location) if rv['status'] != 200: logInfo (json.dumps(rv, sort_keys=True, indent=3).decode('unicode_escape'), color) else: logSys (json.dumps(rv, sort_keys=True, indent=3).decode('unicode_escape'), color) return rv
def fSave(): caller = request.fullpath[1:] qString = request.query_string.strip() logSys(" /" + caller + " >>\n" + str(qString) + "\n<<") qString = json.loads(urllib2.unquote(qString)) fName = qString[0]['fName'] #file name pName = qString[1]['pName'] #placeholder file name if fName == "": fName = pName iniFiles = glob.glob("*.ini") fileList = "" for x in iniFiles: if fName == x: shutil.copy2(fName, fName + '.bak') logSys(" Make .bak Copy of >>" +fName + "<<") xjobs = qString[2]['jobs'].replace('|','\n') f = open(fName, 'w') f.write(xjobs) f.close()
def getWeekDaySchedule(): weekSchedule = {} newSchedule = "--" if 'weekSchedule' in xP.prefs: weekSchedule = xP.prefs['weekSchedule'] currentDay = (datetime.now().strftime("%A")) logSys(" weekday schedule currentDay >>" + currentDay + "<<") if currentDay in weekSchedule: newSchedule = weekSchedule[currentDay] logSys(" weekday schedule newSchedule >>" + newSchedule + "<<") #check if file for 'newSchedule' exists try: dummy = open(newSchedule, 'r') except: newSchedule = "--" logSys(" weekday schedule is >>" + newSchedule + "<<") return newSchedule
def getNews(xpPrefs): # --------------------------- global xP response = "" newsStatus = "" newsDate = "" try: global xP url = xpPrefs['news'] request = urllib2.Request(url) response = urllib2.urlopen(request).read() newsStatus = "color: gray;" #'display:none' nLine = 0 lines = response.split('\n') for line in lines: if nLine == 0: # first line holds 'newsDate', compare with 'newsDate' in prefs # and enable news link if news date newer logSys(" .. getNews >>" + lines[nLine].strip() + "<<") newsDate = lines[nLine].strip() if 'newsDate' in xpPrefs and newsDate > xpPrefs['newsDate']: newsStatus = "color: blue;" #'display:block' else: xP.prefs['newsDate'] = newsDate newsDate = "" lines[nLine] = "<div align='right' style=\'margin-bottom:-5px;padding-right: 100px;\'> \ <b>" + lines[nLine] + "</b></div><p style='margin:0;padding-left: 50px;padding-right: 100px;'>" if lines[nLine][0:3] == "** " : lines[nLine] = "<b> " + lines[nLine][3:] + "</b>" if lines[nLine][0:3] == " " : lines[nLine] = "<span style='margin-left:20px;'>" + lines[nLine][3:] + "</span>" if lines[nLine][0:3] == "|| " : lines[nLine] = "<blockquote style='margin-top:-10px;margin-left:35px;'><small><tt>" + lines[nLine][3:] + "</tt></small></blockquote>" if lines[nLine][0:3] == "__ ": lines[nLine] = "<u> " + lines[nLine][3:] + "</u>" if lines[nLine][0:3] == "===": lines[nLine] = "</p><hr style='margin-top: -5px; margin-bottom: 0px;'><p style='padding-left: 50px;padding-right: 100px;'>" cLine = lines[nLine] linkA = cLine.find(" [") if linkA != -1: linkM = cLine.find("](", linkA) if linkM != -1: linkE = cLine.find(")", linkM) if linkE != -1: linkDesc = cLine[(linkA+2):linkM] link = cLine[(linkM+2):linkE] cLink = "<a href='" + link + "'>" + linkDesc + "</a>" lines[nLine] = lines[nLine].replace(lines[nLine][(linkA+1):(linkE+1)], cLink) lines[nLine] = lines[nLine].replace(" ", " ") nLine = nLine +1 response = "<br>".join(lines) except: logSys ("--- getNews failed from: " + url) response = [] return response, newsStatus, newsDate
def edit(): caller = request.fullpath[1:] qString = request.query_string.strip() logSys(" /" + caller + " >>" + qString + "<<") page = templateSetup('piEdit', xP.prefs) addJob = False fileName = request.query_string if fileName == 'addJob': addJob = True # build the html list of devices devices = pilightConfig('devices') #<a role="menuitem" onclick="changeDevice(this)">Haustuer</a> deviceList = "" for d in devices: deviceList += '<a role="menuitem" onclick="changeDevice(this)">'+d+'</a>' page = page.replace('&&deviceList&&', deviceList) # replace date/time string hString = str(datetime.now())[:19] page = page.replace('&&datetime&&', hString) if addJob == True: page = page.replace('&&JOBS&&',"") page = page.replace('&&FILE&&',"") page = page.replace('&&jobDefEdit&&','display:none') page = page.replace('&&jobDefExec&&','display:block') page = page.replace('&&displaySchedule&&','display:none') page = page.replace('&&jobAdd&&','display:none') page = page.replace('&&jobExec&&','display:block') else: page = page.replace('&&jobDefEdit&&','display:block') page = page.replace('&&jobDefExec&&','display:none') page = page.replace('&&displaySchedule&&','display:block') page = page.replace('&&jobAdd&&','display:block') page = page.replace('&&jobExec&&','display:none') # newSchedule if fileName == 'newSchedule': fileName = 'newDaySchedule.ini' f = open(fileName, 'w') f.write(' * Define new Schedule') f.close() if fileName == "" or fileName == None: fileName = 'piSchedule.ini' # read the selected 'ini' file to textbox jobFile = jobsReadFile(fileName, setName=False) #logSys("\n$$\n" + str(jobFile) + "\n$$\n") jobList = "" for line in jobFile: jobList = jobList + '<option>' + line +'</option>' page = page.replace('&&JOBS&&',str(jobList)) # set the 'ini' file name page = page.replace('&&FILE&&',str(fileName)) return (page)
def timelineSchedule(): caller = request.fullpath[1:] qString = request.query_string.strip() logSys(" /" + caller + " >>\n" + str(qString) + "\n<<") rv = combineKeys(xP.prefs, {'editJob': xS("piEdit.editJob"), 'editJobs': xS("piEdit.editJobs"), 'edit': xS("piEdit.edit"), 'insert': xS("piEdit.insert"), 'delete': xS("piEdit.delete"), 'change': xS("piEdit.change"), 'close': xS("piEdit.close"), 'changeRow': xS("piEdit.changeRow"), 'insertRow': xS("piEdit.insertRow"), 'help': xS("piEdit.help"), 'toggleHelp': xS("piEdit.toggleHelp"), 'advanceEditHelp': xS("piEdit.advanceEditHelp"), 'timelineEditHelp': xS("piEdit.timelineEditHelp"), 'legend': xS("piEdit.legend"), 'scheduleFile': xS("piEdit.scheduleFile")}) page = templateSetup('piTimeLine', rv) fileName = xP.prefs['iniFile'] jobsList = jobsRead(fileName) jobs = "" nJ = len(jobsList) ni=0 while ni < nJ: if jobsList[ni] != "\n": jobs += jobsList[ni] + "||" ni += 1 page = page.replace('&&FILE&&',str(fileName)) page = page.replace("&&jobLines&&", jobs.replace("\n","")) # build the html list of devices #<a role="menuitem" onclick="changeDevice(this)">Haustuer</a> devices = pilightConfig('devices') deviceList = "" firstDevice = "" for d in devices: if deviceList == "": firstDevice = d deviceList += '<a role="menuitem" onclick="changeDevice(this)">'+d+'</a>' if qString != "": firstDevice = qString firstDeviceStatus = str(devices[firstDevice]['state']) logSys(" device details: "+ firstDevice + " " + str(devices[firstDevice]['state'])) page = page.replace('&&firstDevice&&', firstDevice) page = page.replace('&&firstDeviceStatus&&', firstDeviceStatus) page = page.replace('&&deviceList&&', deviceList) page = page.replace('&&sunrise&&',(xP.prefs['sunrise'])[11:]) page = page.replace('&&sunset&&',(xP.prefs['sunset'])[11:]) startTime = "10:00:00" if 'timelineStart' in xP.prefs : startTime = xP.prefs['timelineStart'] endTime = "24:00:00" if 'timelineEnd' in xP.prefs : endTime = xP.prefs['timelineEnd'] page = page.replace('&&endTime&&', endTime) page = page.replace('&&startTime&&', startTime) return page
def piDiscover(service, timeout=2, retries=1): #--------------------------------- global xP try: prefsFile = open(xP.prefsJSONfile, 'r') fPrefs = json.loads(prefsFile.read()) except: fPrefs = {} group = ("239.255.255.250", 1900) message = "\r\n".join([ 'M-SEARCH * HTTP/1.1', 'HOST: {0}:{1}'.format(*group), 'MAN: "ssdp:discover"', 'ST: {st}','MX: 3','','']) responses = {} try: server = str(fPrefs['server']) except: server = "" port = '' error = 'OK' i = 0; for _ in range(retries): i += 1 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, struct.pack('LL', 0, 10000)); sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) sock.sendto(message.format(st=service), group) while True: try: responses[i] = sock.recv(1024); break; except socket.timeout: error = 'timeout' break; except: error = 'no pilight ssdp connections found' break; r = responses.values() if len(r) > 0: locationsrc = re.search('Location:([0-9.]+):(.*)', str(r[0]), re.IGNORECASE) if locationsrc: server = locationsrc.group(1).strip() port = locationsrc.group(2).strip() configFile = '/etc/pilight/config.json' piPrefs = {} try: prefsFile = open(configFile, 'r') piPrefs = json.loads(prefsFile.read()) if 'webserver-http-port' in piPrefs['settings']: port = piPrefs['settings']['webserver-http-port'] if 'webserver-port' in piPrefs['settings']: port = piPrefs['settings']['webserver-port'] except: logERR(True) # will terminate / quiet pilightVersion = str(piPrefs['registry']['pilight']['version']['current']) rv = [server, port, pilightVersion, error] #print (" ** piDiscover pilight (v." + version + ") **\n" # + (str(responses)).replace("\\x00","").replace("\\r\\n","\n")) logInfo (" ** piDiscover pilight " + str(rv), xColor) logSys (" ** piDiscover pilight " + str(rv), xColor) return rv
def scheduleSet(onTime, actualDevice, currentSwitch, switchTime): #--------------------------------- ''' lampe2; on,+:02 actualDevice= lampe2; currentSwitch= on,+:02 ''' actualSwitch = currentSwitch.strip().replace("%20", "").split(",") if ('on' in actualSwitch or 'off' in actualSwitch) == False: return xS("piSchedule.noState") # ERROR: no on/off if xP.prefs['pilightVersion'] > '7.0': # for 7.0 Nightly #http://x.x.x.x:xx/control?device=studyfloorlamp&state=on message = "/control?device=" + actualDevice + "&state=" + str(actualSwitch[0]) else: message = '/send?{"action":"control","code":{"device":"' + actualDevice \ + '","state":"' + str(actualSwitch[0]) + '"}}' # piSchedule direct on/off switching if len(actualSwitch) == 1: arg = {} arg['message'] = message info = '{0:12} {1:15}'.format(actualDevice[0:12], currentSwitch.replace(',', ' ')) arg['info'] = info fire_pilight(arg) #sleep(2) # for testing .. delay between directly switching jmsg = [str(onTime)[0:19], actualDevice, currentSwitch] return [onTime, jmsg, switchTime] xTime = onTime deltaTime = "*" # check xTime if valid and process different time options # xTime = '2014-04-17 22:06:00' NEED secs, even if ':00' for nSwitch in actualSwitch: nSwitch = nSwitch.strip() # have dateTime or sunrise or sunset if nSwitch == 'sunrise': xTime = parser.parse(xP.prefs['sunrise']) elif nSwitch == 'sunset': xTime = parser.parse(xP.prefs['sunset']) # --- use deltaTime # '+' add or '-' subtract time value # '~' add or '~-' subtract 'random' time value elif nSwitch[0] == '+' or nSwitch[0] == "-" \ or nSwitch[0] == "~": h = 0 min = 0 sec = 0 random_subtract = False if nSwitch[0:2] == "~-": # subtract random time random_subtract = True delta = nSwitch[2:] else: delta = nSwitch[1:] xDelta = delta.split(":") nDelta = len(xDelta) if nDelta >= 1: h = 0 if xDelta[0] == '' else int(xDelta[0]) if nDelta >= 2: min = 0 if xDelta[1] == '' else int(xDelta[1]) if nDelta == 3: sec = 0 if xDelta[2] == '' else int(xDelta[2]) deltaTime = timedelta(hours=h, minutes=min, seconds=sec) if nSwitch[0] == '+': # # add timedelta logInfo (" delta + : " + nSwitch) xTime = xTime + deltaTime #++++++++ if nSwitch[0] == '-': # # substract timedelta logInfo (" delta - : " + nSwitch) deltaTime = -deltaTime xTime = xTime + deltaTime #++++++++ elif nSwitch[0] == '~': # # add random minutes rMin = h * 60 + min if random_subtract: deltaTime = -timedelta(minutes=random.randrange(rMin)) else: deltaTime = timedelta(minutes=random.randrange(rMin)) logInfo (" random : " + nSwitch + " --> deltaTime : " + str(deltaTime)) xTime = xTime + deltaTime #++++++++ # ... use deltaTime elif nSwitch == 'on' or nSwitch == "off" or nSwitch == "time" : pass else: # check for absolute time not to be 24:00 and any other unknown format try: if (nSwitch == "24:00"): nSwitch = "23:59" xTime = parser.parse(nSwitch) except: nSwitch = 'err:' + str(nSwitch) logInfo(" +++ " + xS("piSchedule.unknownString") + ">>" + nSwitch + "<<") logInfo(" +++++ check nSwitch >>" + str(nSwitch) +"<< xTime >>" + str(xTime) + "<<") xTime = xTime + timedelta(seconds=random.randrange(60)) logInfo (" baseTime + delta : " + str(xTime)[0:19]) # remember 'on' state time wasOnTime = onTime onTime = xTime jmsg = [] # check if xTime is before actual time if (xTime < datetime.now()): logInfo (" +++ SKIP : " + str(xTime)[0:19] + " :: " + currentSwitch.strip() + " +++ " + xS("piSchedule.beforeTime") + " +++") else: logInfo (" ..set Job : " + str(xTime)[0:19] + " :: " + actualDevice + " :: " + currentSwitch) jmsg = [str(xTime)[0:19], actualDevice, currentSwitch] jobName = str(int(time.time() * 1000))[6:] info = ('{0:12} {1:15} '.format(actualDevice[0:12], currentSwitch.replace(',', ' '))) if 'off' in actualSwitch: info = info + " (on: " + str(wasOnTime)[11:16] + ")" cJob = (sched.add_job(fire_pilight, 'date', run_date=str(xTime), args=[{'message':message, 'info':info}], id=jobName)) logSys(" .. Job to be appended to jobs id=jobName " + jobName + "\n " + str(cJob) + "\n"+ str([{'message':message, 'info':info}])) logSys("&& xTime " + str(xTime) + " switchT " + str(switchTime)) if xTime > switchTime: switchTime = xTime return [onTime, jmsg, switchTime]