def new_template(): rqstSession = request.get_cookie('pysessionid', secret=prop('cookieSecret')) if check_session(rqstSession) is True: if request.forms.get('save', '').strip(): name = request.forms.get('name').strip() conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() sql = """ insert into template (id_tmpl, template_name) values (nextval('template_id_tmpl_seq'), %(name)s) """ cursor.execute(sql, {'name': name}) conn.commit() cursor.close() return template('new_template') else: return template('new_template') else: pysessionid = '' response.set_cookie('pysessionid', pysessionid, secret=prop('cookieSecret'), Expires='Thu, 01-Jan-1970 00:00:10 GMT', httponly=True) return template('main')
def __init__(self, sensor): logtype = prop('logtype') if logtype == 'file': logFile = prop('loglocation') logging.basicConfig(format='%(asctime)s: %(message)s ',filename=logFile, filemode='a', level=logging.DEBUG) else: logging.basicConfig(level=logging.DEBUG) self.sensor = sensor
def __init__(self, sensor): logtype = prop("logtype") if logtype == "file": logFile = prop("loglocation") logging.basicConfig(format="%(asctime)s: %(message)s ", filename=logFile, filemode="a", level=logging.DEBUG) else: logging.basicConfig(level=logging.DEBUG) self.sensor = sensor
def __init__(self, userid, password): logtype = prop('logtype') if logtype == 'file': logFile = prop('loglocation') logging.basicConfig(format='%(asctime)s: %(message)s ',filename=logFile, filemode='a', level=logging.DEBUG) else: logging.basicConfig(level=logging.DEBUG) self.password = password self.userid = userid
def switch_boiler(shed_state): try: roomTemp = check_temp.temp('room').get_temp() radTemp = check_temp.temp('rad').get_temp() outsideTemp = check_temp.temp('outside').get_temp() conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() sql = """ delete from current_state """ cursor.execute(sql) conn.commit() sql = """ insert into current_state (state) values (%(state)s) """ cursor.execute(sql, {'state': shed_state}) conn.commit() sql = """ insert into log (room_temp, rad_temp, outside_temp, datestamp, state) values (%(roomtemp)s, %(radtemp)s, %(outsidetemp)s, (select now()), %(state)s) """ cursor.execute( sql, { 'roomtemp': roomTemp, 'radtemp': radTemp, 'outsidetemp': outsideTemp, 'state': shed_state }) conn.commit() except Exception as e: logging.debug('error in database connection in switch_boiler: %s' % e) try: pin = int(prop('gpio')) # use P1 header pin numbering convention GPIO.setmode(GPIO.BOARD) # Set up the GPIO channels - one input and one output GPIO.setwarnings(False) GPIO.setup(pin, GPIO.OUT) if shed_state == 'ON': GPIO.output(pin, GPIO.HIGH) elif shed_state == 'OFF': GPIO.output(pin, GPIO.LOW) except Exception as e: logging.debug('Error switching boiler state %s' % e)
def __init__(self, userid, password): logtype = prop('logtype') if logtype == 'file': logFile = prop('loglocation') logging.basicConfig(format='%(asctime)s: %(message)s ', filename=logFile, filemode='a', level=logging.DEBUG) else: logging.basicConfig(level=logging.DEBUG) self.password = password self.userid = userid
def check_temp(self): logtype = prop('logtype') if logtype == 'file': logFile = prop('loglocation') logging.basicConfig(format='%(asctime)s: %(message)s ',filename=logFile, filemode='a', level=logging.DEBUG) else: logging.basicConfig(level=logging.DEBUG) roomTemp = temp.get_temp(self) try: tolerance = int(prop('tolerance')) conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() sql = """ select target_temp from target_temp """ cursor.execute(sql) target_temp = cursor.fetchone() cursor.close() try: target_temp = target_temp[0] logging.debug(target_temp) except: target_temp = None if target_temp is None: logging.debug('No target temp set, setting default to 21') target_temp = 21 upper = target_temp + tolerance lower = target_temp - tolerance logging.debug('lower = %s' % lower) logging.debug('upper = %s' % upper) if roomTemp >= lower and roomTemp <= upper: logging.debug('temp within range') return 'WITHIN' elif roomTemp >= upper: logging.debug('HIGH') return 'HIGH' elif roomTemp <= lower: logging.debug('LOW') return 'LOW' except Exception as e: logging.debug(e)
def check_temp(self): logtype = prop("logtype") if logtype == "file": logFile = prop("loglocation") logging.basicConfig(format="%(asctime)s: %(message)s ", filename=logFile, filemode="a", level=logging.DEBUG) else: logging.basicConfig(level=logging.DEBUG) roomTemp = temp.get_temp(self) try: tolerance = int(prop("tolerance")) conn_string = prop("database") conn = psycopg2.connect(conn_string) cursor = conn.cursor() sql = """ select target_temp from target_temp """ cursor.execute(sql) target_temp = cursor.fetchone() cursor.close() try: target_temp = target_temp[0] logging.debug(target_temp) except: target_temp = None if target_temp is None: logging.debug("No target temp set, setting default to 21") target_temp = 21 upper = target_temp + tolerance lower = target_temp - tolerance logging.debug("lower = %s" % lower) logging.debug("upper = %s" % upper) if roomTemp >= lower and roomTemp <= upper: logging.debug("temp within range") return "WITHIN" elif roomTemp >= upper: logging.debug("HIGH") return "HIGH" elif roomTemp <= lower: logging.debug("LOW") return "LOW" except Exception as e: logging.debug(e)
def check_override(id_shed): logging.debug('id_shed = %s' % id_shed) try: conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() logging.debug('checking override') sql = """ select id_shed, starttime, state from override """ logging.debug(sql) cursor.execute(sql) row = cursor.fetchone() logging.debug(row) ###logging.debug('override row: %s' % row) except Exception as e: logging.debug('override table null: %s' % e) return '0' try: if row is not None: over_shed = row[0] logging.debug("id_shed from override table = %d" % over_shed) logging.debug("id_shed from current schedule = %d" % id_shed) if over_shed != id_shed: cursor.execute("delete from override") conn.commit() logging.debug("override not null, doesn't match schedule") return '0' logging.debug("shedule overridden") return '1' else: return '0' except Exception as e: logging.debug('schedule not overridden: %s' % e) return '0'
def login(): pysessionid = get_sessionid() response.set_cookie('pysessionid', pysessionid, secret=prop('cookieSecret'), httponly=True) return template('login')
def switch_boiler(shed_state): try: roomTemp = check_temp.temp('room').get_temp() radTemp = check_temp.temp('rad').get_temp() outsideTemp = check_temp.temp('outside').get_temp() conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() sql = """ delete from current_state """ cursor.execute(sql) conn.commit() sql = """ insert into current_state (state) values (%(state)s) """ cursor.execute(sql, {'state': shed_state}) conn.commit() sql = """ insert into log (room_temp, rad_temp, outside_temp, datestamp, state) values (%(roomtemp)s, %(radtemp)s, %(outsidetemp)s, (select now()), %(state)s) """ cursor.execute(sql, {'roomtemp':roomTemp, 'radtemp':radTemp, 'outsidetemp':outsideTemp, 'state':shed_state}) conn.commit() except Exception as e: logging.debug('error in database connection in switch_boiler: %s' % e) try: pin = int(prop('gpio')) # use P1 header pin numbering convention GPIO.setmode(GPIO.BOARD) # Set up the GPIO channels - one input and one output GPIO.setwarnings(False) GPIO.setup(pin, GPIO.OUT) if shed_state == 'ON': GPIO.output(pin, GPIO.HIGH) elif shed_state == 'OFF': GPIO.output(pin, GPIO.LOW) except Exception as e: logging.debug('Error switching boiler state %s' % e)
def edit_item(id_shed): try: rqstSession = request.get_cookie('pysessionid', secret=prop('cookieSecret')) if check_session(rqstSession) is True: if request.forms.get('save', '').strip(): id_shed = request.forms.get('id_shed', '').strip() state = request.forms.get('state', '').strip() time = request.forms.get('time', '').strip() conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() sql = """ update schedule set time = %(time)s, state = %(state)s where id_shed = %(id_shed)s """ cursor.execute(sql, { 'time': time, 'state': state, 'id_shed': id_shed }) conn.commit() return template('scheduleConf') else: conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() sql = """ select id_shed, day, time, state from schedule where id_shed = %(id_shed)s """ cursor.execute(sql, {'id_shed': id_shed}) cur_data = cursor.fetchone() return template('edit_schedule', old=cur_data, id_shed=id_shed) else: pysessionid = '' response.set_cookie('pysessionid', pysessionid, secret=prop('cookieSecret'), Expires='Thu, 01-Jan-1970 00:00:10 GMT', httponly=True) redirect('/login') except Exception as e: logging.debug(e) return '<p>Error</p>'
def get_temp(self): sensor = self.sensor if sensor == 'room': Probe = prop('roomProbe') elif sensor == 'rad': Probe = prop('radProbe') elif sensor == 'outside': Probe = prop('outsideProbe') try: f=open(Probe, 'r') for l in f: if 't=' in l: temp=(float(l.split('=',1)[1].strip().replace('\n', '')))/1000 f.close() except Exception as e: logging.debug(e) return temp
def get_temp(self): sensor = self.sensor if sensor == "room": Probe = prop("roomProbe") elif sensor == "rad": Probe = prop("radProbe") elif sensor == "outside": Probe = prop("outsideProbe") try: f = open(Probe, "r") for l in f: if "t=" in l: temp = (float(l.split("=", 1)[1].strip().replace("\n", ""))) / 1000 f.close() except Exception as e: logging.debug(e) return temp
def new_user(): try: rqstSession = request.get_cookie('pysessionid', secret=prop('cookieSecret')) except: pass if check_session(rqstSession) is True: if request.forms.get('save', '').strip(): userid = request.forms.get('userid', '').upper() password = request.forms.get('password').strip() confpassword = request.forms.get('confpassword').strip() logging.debug('new user password = %s' % password) if password is not '' and password == confpassword and userid is not '': hashed_password = auth.passwd(userid, password).hash_password() conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() sql = """ insert into users (id_usrr, userid, password) values (nextval('users_id_usrr_seq'), %(userid)s, %(password)s) """ cursor.execute(sql, { 'userid': userid, 'password': hashed_password }) conn.commit() cursor.close() redirect("/main") else: return template('newuser') else: return template('newuser') else: pysessionid = '' response.set_cookie('pysessionid', pysessionid, secret=prop('cookieSecret'), Expires='Thu, 01-Jan-1970 00:00:10 GMT', httponly=True) return template('login')
def main(): try: try: rqstSession = request.get_cookie('pysessionid', secret=prop('cookieSecret')) except: pass if check_session(rqstSession) is True: try: roomTemp = check_temp.temp('room').get_temp() radTemp = check_temp.temp('rad').get_temp() outsideTemp = check_temp.temp('outside').get_temp() if request.forms.get('override', '').strip(): logging.debug('override') set_override() return template('main', roomTemp=roomTemp, radTemp=radTemp, outsideTemp=outsideTemp) except: pass return template('main', roomTemp=roomTemp, radTemp=radTemp, outsideTemp=outsideTemp) elif request.forms.get('override', '').strip() is '': rqstSession = request.get_cookie('pysessionid', secret=prop('cookieSecret')) username = request.forms.get('username').upper() password = request.forms.get('password').strip() logging.debug(password) if auth.passwd(username, password).check_password() == True: set_session(rqstSession) return template('main', roomTemp=roomTemp, radTemp=radTemp, outsideTemp=outsideTemp) else: return template('login') except Exception as e: logging.debug('exception in main: %s' % e) return '<p>Error</p>'
def set_temp(): rqstSession = request.get_cookie('pysessionid', secret=prop('cookieSecret')) if check_session(rqstSession) is True: if request.forms.get('save', '').strip(): target_temp = request.forms.get('temp').strip() logging.debug('target temp = %s' % target_temp) conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() sql = """ update target_temp set target_temp = %(target_temp)s """ cursor.execute(sql, {'target_temp': target_temp}) conn.commit() cursor.close() redirect("/main") else: logging.debug('set temp page') conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() sql = """ select target_temp from target_temp """ cursor.execute(sql) curr_temp = cursor.fetchone() logging.debug('current target temp = %s' % curr_temp) cursor.close() return template('set_temp', curr_temp=curr_temp) else: pysessionid = '' response.set_cookie('pysessionid', pysessionid, secret=prop('cookieSecret'), Expires='Thu, 01-Jan-1970 00:00:10 GMT', httponly=True) return template('main')
def get_password(self): userid = self.userid logging.debug('get password for %s' % userid) conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() sql = """ select password from users where userid = %(userid)s """ cursor.execute(sql, {'userid':userid}) row = cursor.fetchone() if row is not None: dbpassword = row[0] logging.debug('db password hash %s' % dbpassword) return dbpassword else: logging.debug('No details found for user') return None
def get_password(self): userid = self.userid logging.debug('get password for %s' % userid) conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() sql = """ select password from users where userid = %(userid)s """ cursor.execute(sql, {'userid': userid}) row = cursor.fetchone() if row is not None: dbpassword = row[0] logging.debug('db password hash %s' % dbpassword) return dbpassword else: logging.debug('No details found for user') return None
def check_session(sessionid): sessionDir = prop('sessionDir') d = os.listdir(sessionDir) try: for f in d: #t = int(os.path.getmtime('%s%s' % (sessionDir, sessionid))) t = int(os.path.getmtime('%s%s' % (sessionDir, f))) ct = calendar.timegm(time.gmtime()) if ct - t > 1800: os.remove('%s%s' % (sessionDir, f)) except Exception as e: print(e) pass try: sessions = os.listdir(sessionDir) if sessionid in sessions: file = '%s%s' % (sessionDir, sessionid) f=open(file, 'w') f.close() return True except: return False
def check_session(sessionid): sessionDir = prop('sessionDir') d = os.listdir(sessionDir) try: for f in d: #t = int(os.path.getmtime('%s%s' % (sessionDir, sessionid))) t = int(os.path.getmtime('%s%s' % (sessionDir, f))) ct = calendar.timegm(time.gmtime()) if ct - t > 1800: os.remove('%s%s' % (sessionDir, f)) except Exception as e: print(e) pass try: sessions = os.listdir(sessionDir) if sessionid in sessions: file = '%s%s' % (sessionDir, sessionid) f = open(file, 'w') f.close() return True except: return False
import psycopg2 import time as TIME import datetime from datetime import timedelta import logging from get_props import prop from override import check_override from switch import switch_boiler import check_temp logtype = prop('logtype') if logtype == 'file': logFile = prop('loglocation') logging.basicConfig(format='%(asctime)s: %(message)s ', filename=logFile, filemode='a', level=logging.DEBUG) else: logging.basicConfig(level=logging.DEBUG) def get_schedule(): while True: conn_string = prop('database') logging.debug("Connecting to database ->%s" % (conn_string)) try: conn = psycopg2.connect(conn_string) cursor = conn.cursor() except Exception as e:
def get_schedule(): while True: conn_string = prop('database') logging.debug("Connecting to database ->%s" % (conn_string)) try: conn = psycopg2.connect(conn_string) cursor = conn.cursor() except Exception as e: logging.debug("failed to connect to database -> %s" (e)) try: #get current time and day of week day = datetime.date.today() time = datetime.datetime.now().time() dayOfWeek = datetime.date.strftime(day, '%A') logging.debug(dayOfWeek) #get schedule rows from database sql = """ select s.id_shed, s.day, s.time, s.state from schedule s join template t on t.id_tmpl = s.id_tmpl where upper(s.day) = upper(%(day)s) and s.time <= %(curr_time)s and t.selected = 'Y' order by s.time desc """ cursor.execute(sql, {'day': dayOfWeek, 'curr_time': time}) shed_row = cursor.fetchone() shed_row_str = str(shed_row) logging.debug('current schedule row = %s' % shed_row_str) while shed_row is None: pre_day = day - timedelta(days=1) dayOfWeek = datetime.date.strftime(pre_day, '%A') cursor.execute(sql, {'day': dayOfWeek, 'curr_time': time}) shed_row = cursor.fetchone() shed_row_str = str(shed_row) logging.debug('current schedule row = %s' % shed_row_str) id_shed = shed_row[0] shed_day = shed_row[1] shed_time = shed_row[2] shed_state = shed_row[3] except Exception as e: logging.debug(e) try: sql = """ select state from current_state """ cursor.execute(sql) row = cursor.fetchone() curr_state = row[0] except Exception as e: logging.debug(e) curr_state = 'OFF' try: temp = check_temp.temp('room').check_temp() logging.debug('temp is: %s' % temp) logging.debug('checking override') override = check_override(id_shed) #ON 0 low on #off 1 low on except Exception as e: logging.debug('error in temp or override %s' % e) try: if shed_state == 'ON' and override == '0' and temp == 'LOW' and curr_state == 'OFF': switch_boiler('ON') logging.info( 'switching boiler on \n schedule state = on /n Override = false, temp = low' ) elif shed_state == 'OFF' and override == '1' and temp == 'LOW' and curr_state == 'OFF': switch_boiler('ON') logging.info( 'switching boiler on \n schedule state = off /n Override = true, temp = low' ) else: switch_boiler('OFF') logging.info( 'switching boiler off \n schedule state = %s /n Override = %s, temp = %s' % (shed_state, override, temp)) except Exception as e: logging.debug('error in switch section: %s' % e) t = float(prop('loopsleep')) logging.debug('sleeping for = %s seconds' % t) TIME.sleep(t)
def server_static(path): static = prop('static') return static_file(path, root=static)
def get_schedule(): try: rqstSession = request.get_cookie('pysessionid', secret=prop('cookieSecret')) if check_session(rqstSession) is True: try: delete = request.query['delete'] except: delete = False try: select = request.forms.get('select') except: select = None if delete is not False: id_shed = request.query['id_shed'] conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() sql = """ delete from schedule where id_shed = %(id_shed)s """ cursor.execute(sql, {'id_shed': id_shed}) conn.commit() cursor.close() return template('scheduleConf') elif select is not None: tmpl = request.forms.get('tmpl') conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() sql = """ select s.id_shed, s.day, s.time, s.state, t.template_name from schedule s join template t on (s.id_tmpl = t.id_tmpl) where t.template_name = %(tmpl)s order by s.seq, s.time """ cursor.execute(sql, {'tmpl': tmpl}) result = cursor.fetchall() sql = """ update template set selected = 'N' """ cursor.execute(sql) conn.commit() sql = """ update template set selected = 'Y' where template_name = %(tmpl)s """ cursor.execute(sql, {'tmpl': tmpl}) conn.commit() sql = """ select template_name from template """ cursor.execute(sql) rows = cursor.fetchall() cursor.close() tmpl = [] for row in rows: tmpl.append(row[0]) return template('sched_table', rows=result, tmpl=tmpl) else: conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() sql = """ select s.id_shed, s.day, s.time, s.state, t.template_name from schedule s join template t on (s.id_tmpl = t.id_tmpl) where t.selected = 'Y' order by seq, time """ cursor.execute(sql) result = cursor.fetchall() sql = """ select template_name, (select count(1) from template) as count from template """ cursor.execute(sql) rows = cursor.fetchall() cursor.close() tmpl = [] for row in rows: count = row[1] tmpl.append(row[0]) return template('sched_table', rows=result, tmpl=tmpl, count=count) else: pysessionid = '' response.set_cookie('pysessionid', pysessionid, secret=prop('cookieSecret'), Expires='Thu, 01-Jan-1970 00:00:10 GMT', httponly=True) redirect('/login') except Exception as e: logging.debug(e) return '<p>Error</p>'
import psycopg2 import time as TIME import datetime from datetime import timedelta import logging from get_props import prop from override import check_override from switch import switch_boiler import check_temp logtype = prop("logtype") if logtype == "file": logFile = prop("loglocation") logging.basicConfig(format="%(asctime)s: %(message)s ", filename=logFile, filemode="a", level=logging.DEBUG) else: logging.basicConfig(level=logging.DEBUG) def get_schedule(): while True: conn_string = prop("database") logging.debug("Connecting to database ->%s" % (conn_string)) try: conn = psycopg2.connect(conn_string) cursor = conn.cursor() except Exception as e: logging.debug("failed to connect to database -> %s"(e)) try:
import check_temp import psycopg2 from get_props import prop shed_state = 'ON' roomTemp = check_temp.temp('room').get_temp() radTemp = check_temp.temp('rad').get_temp() outsideTemp = check_temp.temp('outside').get_temp() conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() sql = """ insert into log (room_temp, rad_temp, outside_temp, datestamp, state) values (%(roomtemp)s, %(radtemp)s, %(outsidetemp)s, (select now()), %(state)s) """ cursor.execute(sql, {'roomtemp':roomTemp, 'radtemp':radTemp, 'outsidetemp':outsideTemp, 'state':shed_state}) conn.commit()
import psycopg2 import logging import datetime from datetime import timedelta from get_props import prop logtype = prop('logtype') if logtype == 'file': logFile = prop('loglocation') logging.basicConfig(format='%(asctime)s: %(message)s ',filename=logFile, filemode='a', level=logging.DEBUG) else: logging.basicConfig(level=logging.DEBUG) def check_override(id_shed): logging.debug('id_shed = %s' % id_shed) try: conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() logging.debug('checking override') sql = """ select id_shed, starttime, state from override """ logging.debug(sql) cursor.execute(sql) row = cursor.fetchone() logging.debug(row) ###logging.debug('override row: %s' % row) except Exception as e: logging.debug('override table null: %s' % e) return '0'
def get_schedule(): while True: conn_string = prop("database") logging.debug("Connecting to database ->%s" % (conn_string)) try: conn = psycopg2.connect(conn_string) cursor = conn.cursor() except Exception as e: logging.debug("failed to connect to database -> %s"(e)) try: # get current time and day of week day = datetime.date.today() time = datetime.datetime.now().time() dayOfWeek = datetime.date.strftime(day, "%A") logging.debug(dayOfWeek) # get schedule rows from database sql = """ select s.id_shed, s.day, s.time, s.state from schedule s join template t on t.id_tmpl = s.id_tmpl where upper(s.day) = upper(%(day)s) and s.time <= %(curr_time)s and t.selected = 'Y' order by s.time desc """ cursor.execute(sql, {"day": dayOfWeek, "curr_time": time}) shed_row = cursor.fetchone() shed_row_str = str(shed_row) logging.debug("current schedule row = %s" % shed_row_str) while shed_row is None: pre_day = day - timedelta(days=1) dayOfWeek = datetime.date.strftime(pre_day, "%A") cursor.execute(sql, {"day": dayOfWeek, "curr_time": time}) shed_row = cursor.fetchone() shed_row_str = str(shed_row) logging.debug("current schedule row = %s" % shed_row_str) id_shed = shed_row[0] shed_day = shed_row[1] shed_time = shed_row[2] shed_state = shed_row[3] except Exception as e: logging.debug(e) try: sql = """ select state from current_state """ cursor.execute(sql) row = cursor.fetchone() curr_state = row[0] except Exception as e: logging.debug(e) curr_state = "OFF" try: temp = check_temp.temp("room").check_temp() logging.debug("temp is: %s" % temp) logging.debug("checking override") override = check_override(id_shed) # ON 0 low on # off 1 low on except Exception as e: logging.debug("error in temp or override %s" % e) try: if shed_state == "ON" and override == "0" and temp == "LOW" and curr_state == "OFF": switch_boiler("ON") logging.info("switching boiler on \n schedule state = on /n Override = false, temp = low") elif shed_state == "OFF" and override == "1" and temp == "LOW" and curr_state == "OFF": switch_boiler("ON") logging.info("switching boiler on \n schedule state = off /n Override = true, temp = low") else: switch_boiler("OFF") logging.info( "switching boiler off \n schedule state = %s /n Override = %s, temp = %s" % (shed_state, override, temp) ) except Exception as e: logging.debug("error in switch section: %s" % e) t = float(prop("loopsleep")) logging.debug("sleeping for = %s seconds" % t) TIME.sleep(t)
def new_schedule(): try: rqstSession = request.get_cookie('pysessionid', secret=prop('cookieSecret')) if check_session(rqstSession) is True: if request.forms.get('save', '').strip(): day = request.forms.get('day', '').strip() state = request.forms.get('state', '').strip() time = request.forms.get('time', '').strip() tmpl = request.forms.get('tmpl', '').strip() seq_dict = { 'MONDAY': 1, 'TUESDAY': 2, 'WEDNESDAY': 3, 'THURSDAY': 4, 'FRIDAY': 5, 'SATURDAY': 6, 'SUNDAY': 7 } seq = seq_dict[day] conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() sql = """ insert into schedule (id_shed, day, time, state, seq, id_tmpl) values (nextval('schedule_id_shed_seq'), %(day)s, %(time)s, %(state)s, %(seq)s, (select id_tmpl from template where template_name = %(tmpl)s)) """ cursor.execute( sql, { 'time': time, 'state': state, 'day': day, 'seq': seq, 'tmpl': tmpl }) conn.commit() cursor.close() return template('scheduleConf') else: conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() sql = """ select template_name from template """ cursor.execute(sql) rows = cursor.fetchall() cursor.close() tmpl = [] for row in rows: tmpl.append(row[0]) return template('new_schedule', tmpl=tmpl) else: pysessionid = '' response.set_cookie('pysessionid', pysessionid, secret=prop('cookieSecret'), Expires='Thu, 01-Jan-1970 00:00:10 GMT', httponly=True) redirect('/login') except Exception as e: logging.debug(e) return '<p>Error</p>'
def set_override(): try: logging.debug('setting override') conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() #get current time and day of week day = datetime.date.today() time = datetime.datetime.now().time() dayOfWeek = datetime.date.strftime(day, '%A') logging.debug(dayOfWeek) #get schedule rows from database sql = """ select id_shed, day, time, state from schedule where upper(day) = upper(%(day)s) and time <= %(curr_time)s order by time desc """ cursor.execute(sql, {'day':dayOfWeek, 'curr_time':time}) shed_row = cursor.fetchone() if shed_row is not None: shed_row_str = str(shed_row) logging.debug('1: current schedule row = %s' % shed_row_str) else: logging.debug('no override row') except Exception as e: logging.debug('error in set override database section: %s' % e) while shed_row is None: pre_day = day-timedelta(days=1) dayOfWeek = datetime.date.strftime(pre_day, '%A') cursor.execute(sql, {'day':dayOfWeek, 'curr_time':time}) shed_row = cursor.fetchone() shed_row_str = str(shed_row) logging.debug('2: current schedule row = %s' % shed_row_str) id_shed = shed_row[0] shed_state = shed_row[3] overcheck = check_override(id_shed) logging.debug(overcheck) if overcheck == '1': logging.debug('schedule already overriden so delete override') cursor.execute('delete from override') conn.commit() else: if shed_state == 'ON': state = 'OFF' else: state = 'ON' cursor.execute('delete from override') conn.commit() logging.debug('setting override row') sql = """ insert into override (id_over, id_shed, starttime, state) values (nextval('override_id_over_seq'), %(id_shed)s, %(time)s, %(state)s)""" cursor.execute(sql, {'id_shed':id_shed, 'time':time, 'state':state}) conn.commit() cursor.close()
import check_temp import psycopg2 from get_props import prop shed_state = 'ON' roomTemp = check_temp.temp('room').get_temp() radTemp = check_temp.temp('rad').get_temp() outsideTemp = check_temp.temp('outside').get_temp() conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() sql = """ insert into log (room_temp, rad_temp, outside_temp, datestamp, state) values (%(roomtemp)s, %(radtemp)s, %(outsidetemp)s, (select now()), %(state)s) """ cursor.execute( sql, { 'roomtemp': roomTemp, 'radtemp': radTemp, 'outsidetemp': outsideTemp, 'state': shed_state }) conn.commit()
from bottle import route, redirect, request, run, \ static_file, response, template, error from get_props import prop from session import get_sessionid, set_session, check_session import psycopg2 from override import set_override import auth import logging import check_temp logtype = prop('logtype') if logtype == 'file': logFile = prop('loglocation') logging.basicConfig(format='%(asctime)s: %(message)s ', filename=logFile, filemode='a', level=logging.DEBUG) else: logging.basicConfig(level=logging.DEBUG) @route('/') def login(): pysessionid = get_sessionid() response.set_cookie('pysessionid', pysessionid, secret=prop('cookieSecret'), httponly=True) return template('login')
def set_session(sessionid): sessionDir = prop('sessionDir') file = '%s%s' % (sessionDir, sessionid) f = open(file, 'a') f.close()
def set_override(): try: logging.debug('setting override') conn_string = prop('database') conn = psycopg2.connect(conn_string) cursor = conn.cursor() #get current time and day of week day = datetime.date.today() time = datetime.datetime.now().time() dayOfWeek = datetime.date.strftime(day, '%A') logging.debug(dayOfWeek) #get schedule rows from database sql = """ select id_shed, day, time, state from schedule where upper(day) = upper(%(day)s) and time <= %(curr_time)s order by time desc """ cursor.execute(sql, {'day': dayOfWeek, 'curr_time': time}) shed_row = cursor.fetchone() if shed_row is not None: shed_row_str = str(shed_row) logging.debug('1: current schedule row = %s' % shed_row_str) else: logging.debug('no override row') except Exception as e: logging.debug('error in set override database section: %s' % e) while shed_row is None: pre_day = day - timedelta(days=1) dayOfWeek = datetime.date.strftime(pre_day, '%A') cursor.execute(sql, {'day': dayOfWeek, 'curr_time': time}) shed_row = cursor.fetchone() shed_row_str = str(shed_row) logging.debug('2: current schedule row = %s' % shed_row_str) id_shed = shed_row[0] shed_state = shed_row[3] overcheck = check_override(id_shed) logging.debug(overcheck) if overcheck == '1': logging.debug('schedule already overriden so delete override') cursor.execute('delete from override') conn.commit() else: if shed_state == 'ON': state = 'OFF' else: state = 'ON' cursor.execute('delete from override') conn.commit() logging.debug('setting override row') sql = """ insert into override (id_over, id_shed, starttime, state) values (nextval('override_id_over_seq'), %(id_shed)s, %(time)s, %(state)s)""" cursor.execute(sql, {'id_shed': id_shed, 'time': time, 'state': state}) conn.commit() cursor.close()
def set_session(sessionid): sessionDir = prop('sessionDir') file = '%s%s' % (sessionDir, sessionid) f=open(file, 'a') f.close()