def interactive_TStat(TStat): """ function provides interactive dialog """ # methods supported # keys = ['set', 'get', 'esc'] key_dict = [] while True: key_input = raw_input("\n\ninteractive mode, enter method and parameter ('esc' to exit): ") key_input.strip("\t\n\r") if " " in key_input: key_dict = key_input.split(" ") else: key_dict.append(key_input) if len(key_dict) >= 1: method = key_dict[0] if len(key_dict) >= 2: param = key_dict[1] if len(key_dict) >= 3: valu = key_dict[2] if method == "get": if len(key_dict) != 2: print "\nparse error in string '%s', 'get' method requires 1 parameter, exiting..." % key_input sys.exit(-1) print "\nparam '%s' returns: %s" % (param, TStat._get(param)) if method == "set": if len(key_dict) != 3: print "\nparse error in string '%s', 'set' method requires 2 parameters, exiting..." % key_input sys.exit(-1) print "\nparam '%s' was set to: %s, changing to: %s" % (param, TStat._get(param), valu) TStat._post(param, valu) print "\nparam '%s' returns: %s" % (param, TStat._get(param)) elif method == "esc": print "\nescape sequence detected, exiting interactive mode..." sys.exit(0)
FILE = 'getYesterdaysUsage' getUsage = False if not os.path.exists(FILE): open(FILE,'w').close() getUsage=True # getUsage if we have to create the file # get last time FILE was modified lastSuccess = time.ctime(os.path.getmtime(FILE)) dateLastSuccess = datetime.strptime(lastSuccess,'%a %b %d %H:%M:%S %Y') #If file was modified on a day that is not today, update usage stats if dateLastSuccess.day != datetime.now().day: getUsage = True if getUsage == True: t = TStat('thermostat-FD-BB-6F.chiefmarley.local') heatUsage = t.getHeatUsageYesterday() coolUsage = t.getCoolUsageYesterday() heatMinutes = heatUsage['hour'] * 60 + heatUsage['minute'] coolMinutes = coolUsage['hour'] * 60 + coolUsage['minute'] currentTime = int(round(time.time())) touch(FILE) conn = sqlite3.connect('/home/andy/djangoProjects/leeHouseSite/sqlite/db.sql3') c = conn.cursor() c.execute("insert into restInterface_hvac_runtime values (NULL," + str(currentTime) + "," + str(heatMinutes) +"," + str(coolMinutes) + ")") conn.commit()
FILE = 'getYesterdaysUsage' getUsage = False if not os.path.exists(FILE): open(FILE, 'w').close() getUsage = True # getUsage if we have to create the file # get last time FILE was modified lastSuccess = time.ctime(os.path.getmtime(FILE)) dateLastSuccess = datetime.strptime(lastSuccess, '%a %b %d %H:%M:%S %Y') #If file was modified on a day that is not today, update usage stats if dateLastSuccess.day != datetime.now().day: getUsage = True if getUsage == True: t = TStat('thermostat-FD-BB-6F.chiefmarley.local') heatUsage = t.getHeatUsageYesterday() coolUsage = t.getCoolUsageYesterday() heatMinutes = heatUsage['hour'] * 60 + heatUsage['minute'] coolMinutes = coolUsage['hour'] * 60 + coolUsage['minute'] currentTime = int(round(time.time())) touch(FILE) conn = sqlite3.connect( '/home/andy/djangoProjects/leeHouseSite/sqlite/db.sql3') c = conn.cursor() c.execute("insert into restInterface_hvac_runtime values (NULL," + str(currentTime) + "," + str(heatMinutes) + "," + str(coolMinutes) + ")")
def main(tstatAddr, commandMap=None, username=None, password=None, calName="Thermostat"): # Connect to thermostat tstat = TStat.TStat(tstatAddr) # Command map is used to translate things like "Wake" into "Heat 70" if commandMap is None: commandMap = {} calendar_service = getCalendarService(username, password) # Create date range for event search today = datetime.datetime.today() gmt = time.gmtime() gmtDiff = datetime.datetime(gmt[0], gmt[1], gmt[2], gmt[3], gmt[4]) - today tomorrow = datetime.datetime.today()+datetime.timedelta(days=8) query = gdata.calendar.service.CalendarEventQuery() query.start_min = "%04i-%02i-%02i" % (today.year, today.month, today.day) query.start_max = "%04i-%02i-%02i" % (tomorrow.year, tomorrow.month, tomorrow.day) print "start_min:", query.start_min print "start_max:", query.start_max # Look for a calendar called calName feed = calendar_service.GetOwnCalendarsFeed() for i, a_calendar in enumerate(feed.entry): if a_calendar.title.text == calName: query.feed = a_calendar.content.src if query.feed is None: print "No calendar with name '%s' found" % calName return # Search for the event that has passed but is closest to the current time # There is probably a better way to do this... closest = None closestDT = None closestWhen = None closestEvent = None closestCommand = None closestValue = None periods = {} feed = calendar_service.CalendarQuery(query) for i, an_event in enumerate(feed.entry): #print '\t%s. %s' % (i, an_event.title.text,) # Try to map named time period into actual command text = an_event.title.text.strip() if not text in PERIODS: if commandMap.has_key(text): text = commandMap[text] print "Translated %s into %s" % (an_event.title.text.strip(), text) # Skip events that are not valid commands try: (command, value) = text.splitlines()[0].split() except: command = text if command not in COMMANDS: print "Warning: '%s' is not a valid command" % text continue try: float(value) except: if value not in ['Off', 'On', 'Auto']: print "Warning: '%s' is not a valid command" % an_event.title.text continue for a_when in an_event.when: d = a_when.start_time.split("T")[0] t = a_when.start_time.split("T")[1].split(".")[0] (year, month, day) = [int(p) for p in d.split("-")] (hour, min, sec) = [int(p) for p in t.split(":")] dt = datetime.datetime(year, month, day, hour, min, sec)-gmtDiff #print "DT:", dt d = dt-datetime.datetime.today() #print "d.days:", d.days if text in PERIODS: if not periods.has_key(dt.day): periods[dt.day] = {} periods[dt.day][text] = dt else: # Skip events that are in the future if d.days >= 0: continue if closest is None: closest = d closestDT = dt closestWhen = a_when closestEvent = an_event closestCommand = command closestValue = value else: if d.days < closest.days: continue if d.seconds > closest.seconds: closest = d closestDT = dt closestWhen = a_when closestEvent = an_event closestCommand = command closestValue = value print "Found periods:", periods # Handle programmed periods periodCommands = {} for day in range(0,7): if not periodCommands.has_key(day): periodCommands[day] = [] for p in PERIODS: if periods.has_key(p): periodCommands.append(int(periods[p].hour*60+periods[p].minute)) periodCommands.append(int(commandMap[p].split()[-1])) else: periodCommands.append(periodCommands[-2]) periodCommands.append(periodCommands[-2]) print "Commands:", periodCommands if closestEvent is None: print "No events found" return text = closestEvent.title.text print "Closest event: %s at %s" % (text, closestDT) #(command, value) = text.splitlines()[0].split() command, value = (closestCommand, closestValue) if command == 'Heat': value = int(value) if value >= HEAT_MIN and value <= HEAT_MAX: print "Setting heat to %s" % int(value) #tstat.setHeatPoint(value) else: print "Value out of acceptable heat range:", value elif command == 'Cool': value = int(value) if value >= COOL_MIN and value <= COOL_MAX: print "Setting cool to %s" % value tstat.setCoolPoint(int(value)) else: print "Value out of acceptable cool range:", value elif command == 'Fan': print "Setting fan to %s" % value tstat.setFanMode(value) elif command == 'Mode': print "Setting mode to %s" % value tstat.setTstatMode(value)
#client.emitEvent(internalid, "event.device.statechanged", "0", "") if content["command"] == "setthermostatfanmode": print "set radio thermostat fan mode: " + internalid if content["command"] == "setthermostathold": print "set radio thermostat hold: " + internalid # specify our message handler method client.addHandler(messageHandler) ipAddress = agoclient.getConfigOption("radiothermostat", "ipaddress", "0.0.0.0") tempUnit = agoclient.getConfigOption("system", "units", "SI") #print "IP: ", ipAddress #print "UNIT: ", tempUnit t = TStat(ipAddress) t.setCacheExpiry(15) client.addDevice(ipAddress, "thermostat") #TODO implement thread here for polling # in the background or need to handle some other communication. If you don't need one or if you want to keep things simple at the moment just skip this section. class readThermostat(threading.Thread): #def cToF(tempC): #retval = float((float(tempC) * (9.0/5/0)) + 32) #return retval #def fToC(tempF): #retval = float((float(tempF) - 32) / (9.0/5.0)) #return retval
#client.emitEvent(internalid, "event.device.statechanged", "0", "") if content["command"] == "setthermostatfanmode": print "set radio thermostat fan mode: " + internalid if content["command"] == "setthermostathold": print "set radio thermostat hold: " + internalid # specify our message handler method client.addHandler(messageHandler) ipAddress = agoclient.getConfigOption("radiothermostat", "ipaddress", "0.0.0.0") tempUnit = agoclient.getConfigOption("system", "units", "SI") #print "IP: ", ipAddress #print "UNIT: ", tempUnit t = TStat(ipAddress) t.setCacheExpiry(15) client.addDevice(ipAddress, "thermostat") #TODO implement thread here for polling # in the background or need to handle some other communication. If you don't need one or if you want to keep things simple at the moment just skip this section. class readThermostat(threading.Thread): #def cToF(tempC): #retval = float((float(tempC) * (9.0/5/0)) + 32) #return retval #def fToC(tempF): #retval = float((float(tempF) - 32) / (9.0/5.0)) #return retval def __init__(self,):
#!/usr/bin/python ''' Gets the current temperature from the thermostat in Kitchen ''' from TStat import * import time import requests t = TStat('thermostat-FD-BB-6F.chiefmarley.local') try: tempInFahr = t.getCurrentTemp() tempInKelv = ((tempInFahr - 32) *.555556) + 273.15 tempInsertVal = int(round(tempInKelv*100)) requests.get('http://127.0.0.1/restInterface/msg/TMP50' + str(tempInsertVal)) except: pass