def sendErrorMail(mystr, fatalError=False): global mailBackoffCount, mailBackoffCount, mailLastSentTime global mailLastSubject, mailNumRepeats nbody = email_body_prefix log.info('Repeating last message, Rep Cnt = {}, BOCnt = {}'.format( mailNumRepeats, mailBackoffCount)) # Check to see if we're repeating the message too quickly. if mystr == mailLastSubject: currTime = time.time() if (currTime - mailLastSentTime) < (60 * 60): mailNumRepeats += 1 log.info('... sendErrorMail(skipping)') # Enough time has not passed, don't send it. return else: # Different subject line, so reset things mailLastSubject = mystr if mailNumRepeats: # Give the user an indication of the numbrer of repts. mystr = "(Prev rptd * {} times) ".format(mailBackoffCount) mailLastSentTime = time.time() mailNumRepeats = 0 headers = [ "From: " + sender, "Subject: " + subject + ": " + mystr, "To: " + recipient, "MIME-Version: 1.0", "Content-Type: text/plain" ] headers = "\r\n".join(headers) try: heat_status = 1 - wiringpi.digitalRead(HEATER_PIN) fan_status = 1 - wiringpi.digitalRead(FAN_PIN) nbody = nbody + "\r\nPithy shut down!!!\r\n" if fatalError else "" + \ "\r\n\r\nThermod V1 Status at " + lnow() + ":\r\n" try: temp_status = subprocess.check_output( ['/bin/cat', STATUS_FILE]) # Prepend a tab to each line nbody = nbody + "\tContents of Status File = {}\r\n".format( repr(temp_status)) except Exception as e: nbody = nbody + '\tCannot get Status File ({}): {}\r\n'.format( STATUS_FILE, repr(e)) hvac_state = getHVACState() tempHumid = getTemp() nbody = nbody + "\thvacState = " + str(hvac_state) + "\r\n" nbody = nbody + "\temp+humid = " + repr(tempHumid) + "\r\n" nbody = nbody + "\theatStatus = " + str(heat_status) + "\r\n" nbody = nbody + "\tfanStatus = " + str(fan_status) + "\r\n" if fatalError: nbody = nbody + "\r\nPithy received fatal error, exiting program\r\n" session = smtplib.SMTP_SSL("{}:{}".format(SMTP_SERVER, SMTP_PORT)) session.login(username, password) session.sendmail(sender, recipient, headers + "\r\n\r\n" + nbody) session.quit() except Exception as e: log.error("Error trying to send email warning:{}".format(repr(e)))
def updateTemp(): dprint('---- updateTemp()') rv = getTemp() if len(rv) != 2: # Must've had an error, log it and use the last known value log.warning("websrvd:{}: error reading tempHumid value".format(lnow())) temp = updateTemp.lastTemp humidity = updateTemp.lastHumid else: temp = rv[0] rv = (str(round(temp, 1))) return (rv)
import sqlite3, sys, datetime import getTemp #setings sensorLookUp = {"10 DE C6 35 1 8 0 86" : "outside", \ "10 C4 EB 35 1 8 0 6" : "test"} date = datetime.datetime.now().strftime("%Y-%m-%d") time = datetime.datetime.now().strftime("%H:%M") sensorReadings = {} while 1: try: temp, rom = getTemp.getTemp() except: print "not able to get temp at", date, time sys.exit() if rom != "null": sensorReadings[sensorLookUp[rom]] = temp else: break conn = sqlite3.connect("/home/simon/tempLog/temp.db") c = conn.cursor() for sensor in sensorReadings: c.execute("insert into temp values(?, ?, ?, ?)",\ [date, time, sensorReadings[sensor], sensor]) conn.commit();
import numpy as np # create configuration file sleeptime = 1 UDP_IP_ADDRESS = "192.168.1.102" UDP_PORT_NO = 6789 hx = configureStrain() device_file = configureTemp() try: while True: # get data strain = getStrain(hx) temp = getTemp(device_file) print("Strain", strain) print("Temperature", temp) #time.sleep(sleeptime) sys = np.array([strain, temp], dtype=float) payload = sys.tobytes() clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) clientSock.sendto(payload, (UDP_IP_ADDRESS, UDP_PORT_NO)) except (KeyboardInterrupt, SystemExit): print('Bye :)') finally: GPIO.cleanup()
def run(): # Line below makes us log immediately upon running the first time. lastLog = datetime.now() - timedelta(minutes=6) lastMail = datetime.now() configureGPIO() # Write our PID to PID_FILE try: with open(PID_FILE, "w") as outfile: print('{}'.format(os.getpid()), file=outfile) except IOError: pass # change cwd to whatever directory thermod.py is in abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) # d888888b d8b db d88888b d888888b d8b db d888888b d888888b d88888b # `88' 888o 88 88' `88' 888o 88 `88' `~~88~~' 88' # 88 88V8o 88 88ooo 88 88V8o 88 88 88 88ooooo # 88 88 V8o88 88~~~ 88 88 V8o88 88 88 88~~~~~ # .88. 88 V888 88 .88. 88 V888 .88. 88 88. # Y888888P VP V8P YP Y888888P VP V8P Y888888P YP Y88888P # # db .d88b. .d88b. d8888b. # 88 .8P Y8. .8P Y8. 88 `8D # 88 88 88 88 88 88oodD' # 88 88 88 88 88 88~~~ # 88booo. `8b d8' `8b d8' 88 # Y88888P `Y88P' `Y88P' 88 switch_mode = 'off' while True: tempHumid = getTemp() if len(tempHumid) < 2: log.warning("thermod:{}: error reading tempHumid value".format( lnow())) indoor_temp = lastTemp humidity = lastHumid else: indoor_temp = float(tempHumid[0]) humidity = float(tempHumid[1]) hvac_state = getHVACState() # Save this value in case we have to change state of the # GPIO old_switch_mode = switch_mode try: file = open(STATUS_FILE, "r") target_temp = float(file.readline().rstrip('\n')) switch_mode = file.readline().rstrip('\n') file.close() except Exception as e: defStatus = 'off' # Set default operation modes if the statusfile isn't found. target_temp = 70.0 switch_mode = defStatus log.info('no_alarm: Can\'t read STATUS_FILE {}, so writing' ' ( {} / {} )to it\nReason: {}'.format( STATUS_FILE, target_temp, defStatus, repr(e))) # Rewrite the STATUS_FILE so that we aren't in this error # state and we don't keep on spewing messages. try: with open(STATUS_FILE, "w") as ofile: print('{:f}\n{}\n'.format(target_temp, switch_mode), file=ofile) except IOError: log.fatal('Cannot re-write missing STATUS_FILE {}'.format( STATUS_FILE)) sys.exit(144) # Log values so far now = datetime.now() logElapsed = now - lastLog mailElapsed = now - lastMail # heat_mode -- check if beyond tolerance # it's 72, we want it to be 78, and the error threshold is 5 = this # triggers if ((mailEnabled == True) and (mailElapsed > timedelta(minutes=20) and (float(target_temp) - indoor_temp) > error_threshold) and (switch_mode == 'heat')): sendErrorMail('Heat beyond threshold ({} - {} = {}) > {}'.format( target_temp, indoor_temp, float(target_temp) - indoor_temp, error_threshold)) lastMail = datetime.now() log.info("MAIL: Sent mail to " + recipient + \ " at " + now.strftime('%F %T')) # logging actual temp and indoor temp to sqlite database. # you can do fun things with this data, like make charts! if logElapsed > timedelta(minutes=6) and sqliteEnabled: sqlCursor.execute('INSERT INTO logging VALUES(?, ?, ?, ?, ?, ?)', (now, trimFloat(indoor_temp), target_temp, trimFloat(humidity), switch_mode, hvac_state)) conn.commit() lastLog = datetime.now() # $hvac_state has the following values: # 'idle', 'fan', 'heat' # $switch_mode has the following: # 'off', 'fan', 'heat' if switch_mode == 'heat': if hvac_state != 'heat': # Fan or Idle if indoor_temp < target_temp - inactive_hysteresis: log.info('STATE: Switching to heat at {}, ' 'hvac_state = {}'.format(lnow(), hvac_state)) hvac_state = hvac_heat() # If we've reached temp to get to, shut the heat and fan down. elif hvac_state == 'heat': # heating if indoor_temp > target_temp + active_hysteresis: log.info('STATE: Switching to fan idle at {}, ' 'hvac_state = {}'.format(lnow(), hvac_state)) hvac_idle_fan() log.info('STATE: Switching to ALL_OFF at {}, ' 'hvac_state = {}'.format(lnow(), hvac_state)) hvac_state = hvac_all_off() elif switch_mode == 'fan': hvac_state = hvac_fan() else: # switch_mode == 'off' # # The switch_mode is "off", so we have to check if the hvac_state is actually # off as well. If not, then we have to turn it off. # if not (switch_mode == "off"): log_fatal("Invalid switch_mode <{}>".format(switch_mode)) assert (switch_mode == "off") if hvac_state != 'off': log.info('Turning system off, previous hvac_state = {}'.format( hvac_state)) if hvac_state == 'heat': # Heating is on, turn it off log.info("STATE: switch is off, turning off heat and fan") log.info('STATE: Switching to fan idle at {}, ' 'hvac_state = {}'.format(lnow(), hvac_state)) hvac_idle_fan() log.info('STATE: Switching to ALL_OFF at {}, ' 'hvac_state = {}'.format(lnow(), hvac_state)) if hvac_state != 'off': hvac_state = hvac_all_off() # logging stuff heat_status = 1 - wiringpi.digitalRead(HEATER_PIN) fan_status = 1 - wiringpi.digitalRead(FAN_PIN) # "DBG:********"; from pdb import set_trace as bp; bp() def dpv(exp): caller = sys._getframe(1) return ('\n\t\t{} = {}'.format(exp, caller.f_locals[exp.strip()])) log.info("**** Debug Status ****" + dpv("target_temp") + dpv("switch_mode") + dpv("hvac_state ") + dpv("indoor_temp") + # dpv("lastTemp") + # dpv("lastHumid") + dpv("heat_status") + dpv("fan_status ")) time.sleep(5) # Use these values in case we can't fetch them from the # thermostat for mail error logging. lastTemp = indoor_temp lastHumid = humidity
if "1" in package: TurnOn(SendObj) elif "2" in package: TurnOff(SendObj) elif "3" in package: IsOn(SendObj) elif "exit" in package: sys.exit() elif len(str(package)) >= 3: SendObj.sendData(bytesToSend) therm = open('/sys/bus/w1/devices/28-000004abf982/w1_slave','r') #print(therm.read()) temp = therm.read() temp = float(temp[temp.index('t=') + 2:]) / 1000 temp = (temp * 9.0 / 5.0) + 32 print(temp) print(getTemp.getTemp()) else: #nRF receiver print('\nReceiver') SET_CONFIG = 0x1F #Receiver SendObj.setupRadio() print("\nReceiving data") i=0 while 1: SendObj.receiveData() time.sleep(SMALL_PAUSE)