def humid_contol(humid, use_fans=False): global humid_state humid_low = float(set_dic['humid_low']) if humid < humid_low and humid_state != 'up_on': msg = "should turn the humidifer on, it's " + str( humid) + " and the low limit is " + str(humid_low) if humid_state == 'unknown': msg = "Script initialised, humid " + str( humid) + ", low limit is " + str( humid_low) + " checking humidifier is on" humid_state = 'up_on' pigrow_defs.write_log(script, msg, loc_dic['loc_switchlog']) humid_on.humid_on(set_dic, loc_dic['loc_switchlog']) if use_fans == True: fans_on.fans_on(set_dic, loc_dic['loc_switchlog']) elif humid > humid_low and humid_state != 'up_off': msg = ("should turn the humidifier off, it's " + str(humid) + " and the low limit is " + str(humid_low)) if humid_state == 'unknown': msg = "Script initialised, humid " + str( humid) + ", low limit is " + str( humid_low) + " checking humidifier is off" humid_state = 'up_off' pigrow_defs.write_log(script, msg, loc_dic['loc_switchlog']) humid_off.humid_off(set_dic, loc_dic['loc_switchlog']) if use_fans == True: fans_off.fans_off(set_dic, loc_dic['loc_switchlog'])
def dehumid_control(humid, use_fans=False): global dehumid_state humid_high = float(set_dic['humid_high']) if humid > humid_high and dehumid_state != 'down_on': msg = "should turn dehumidifer on, it's " + str( humid) + " and the high limit is " + str(humid_high) if dehumid_state == 'unknown': msg = "Script initialised, humid " + str( humid) + ", the high limit is " + str( humid_high) + " checking it's on" dehumid_state = 'down_on' pigrow_defs.write_log(script, msg, loc_dic['loc_switchlog']) dehumid_on.dehumid_on(set_dic, loc_dic['loc_switchlog']) if use_fans == True: fans_off.fans_off(set_dic, loc_dic['loc_switchlog']) elif humid < humid_high and dehumid_state != 'down_off': msg = "should turn dehumid off, it's " + str( humid) + " and the high limit is " + str(humid_high) if dehumid_state == 'unknown': msg = "Script initialised, humid " + str( humid) + ", high limit is " + str( humid_high) + " checking it's off" dehumid_state = 'down_off' pigrow_defs.write_log(script, msg, loc_dic['loc_switchlog']) dehumid_off.dehumid_off(set_dic, loc_dic['loc_switchlog']) if use_fans == True: fans_on.fans_on(set_dic, loc_dic['loc_switchlog'])
def read_and_log(loc_dic): try: humidity, temperature = Adafruit_DHT.read_retry( Adafruit_DHT.DHT22, set_dic['gpio_dht22sensor']) if humidity == None or temperature == None or humidity > 101: print(" -- problem reading sensor on GPIO:" + set_dic['gpio_dht22sensor'] + "--") return '-1', '-1', '-1' else: humidity = round(humidity, 2) temperature = round(temperature, 2) timno = datetime.datetime.now() try: with open(loc_dic['loc_dht_log'], "a") as f: line = str(temperature) + '>' + str(humidity) + '>' + str( timno) + '\n' f.write(line) except: print["-LOG ERROR-"] pigrow_defs.write_log('checkDHT.py', 'writing dht log failed', loc_dic['err_log']) return humidity, temperature, timno except: print(" -- problem reading sensor on GPIO:" + set_dic['gpio_dht22sensor'] + "--") return '-1', '-1', '-1'
def heater_control(temp): global heater_state #checks to see if current temp should result in heater on or off templow = float(set_dic['heater_templow']) temphigh = float(set_dic['heater_templow']) ## using templow here is not a mistake, plan is to add buffer zones or some something print(" ~ ~ ~ heater controll function started ~ ~ ~") print("temp = " + temp) print(" templow = " + templow) print(" temphigh = " + temphigh) print("Use Fans = " + str(use_fans)) print("heater state = " + str(heater_state)) # if too cool if temp < templow and heater_state != 'on': message = "It's cold, temp is" + str(temp) + " degrees! the low limit is " + str(templow) + " so turning heater on." if heater_state == 'unknown': message = "Script initialised, it's " + str(temp) + " degrees! the low limit is " + str(templow) + " so checking heater's on" pigrow_defs.write_log(script, message,loc_dic['loc_switchlog']) heater_on.heater_on(set_dic, loc_dic['loc_switchlog']) heater_state = 'on' # if too hot elif temp > temphigh and heater_state != 'off': print(" temp greater than temphigh and the heater is off ") message = "it's warm, temp is " + str(temp) + " degrees, the high limit is " + str(temphigh) + " so turning heater off" if heater_state == 'unknown': message = "Script initialised, it's " + str(temp) + " degrees! the low limit is " + str(templow) + " so checking heater's off" pigrow_defs.write_log(script, message,loc_dic['loc_switchlog']) heater_off.heater_off(set_dic, loc_dic['loc_switchlog']) heater_state = 'off' else: message = "doing nothing, it's " + str(temp) + " degrees and the heater is " + heater_state #print(" --not worth logging but, " + message) print("") print(" ~ ~ ~ heater controll function finished ~ ~ ~")
def humid_contol(humid, use_fans=False): global humid_state msg = " no change" if cli_output_level == "max": print(" ~ ~ ~ humidifier controll function started ~ ~ ~") humid_low = float(set_dic['humid_low']) if humid < humid_low and humid_state != 'up_on': msg = "should turn the humidifer on, it's " + str( humid) + " and the low limit is " + str(humid_low) if humid_state == 'unknown': msg = "Script initialised, humid " + str( humid) + ", low limit is " + str( humid_low) + " checking humidifier is on" humid_state = 'up_on' pigrow_defs.write_log(script, msg, loc_dic['loc_switchlog']) humid_on.humid_on(set_dic, loc_dic['loc_switchlog']) elif humid > humid_low and humid_state != 'up_off': msg = ("should turn the humidifier off, it's " + str(humid) + " and the low limit is " + str(humid_low)) if humid_state == 'unknown': msg = "Script initialised, humid " + str( humid) + ", low limit is " + str( humid_low) + " checking humidifier is off" humid_state = 'up_off' pigrow_defs.write_log(script, msg, loc_dic['loc_switchlog']) humid_off.humid_off(set_dic, loc_dic['loc_switchlog']) if cli_output_level == "max": print(msg)
def dehumid_control(humid, use_fans=False): global dehumid_state msg = " no change" if cli_output_level == "max": print(" ~ ~ ~ dehumidifier controll function started ~ ~ ~") humid_high = float(set_dic['humid_high']) if humid > humid_high and dehumid_state != 'down_on': msg = "should turn dehumidifer on, it's " + str( humid) + " and the high limit is " + str(humid_high) if dehumid_state == 'unknown': msg = "Script initialised, humid " + str( humid) + ", the high limit is " + str( humid_high) + " checking it's on" dehumid_state = 'down_on' pigrow_defs.write_log(script, msg, loc_dic['loc_switchlog']) dehumid_on.dehumid_on(set_dic, loc_dic['loc_switchlog']) elif humid < humid_high and dehumid_state != 'down_off': msg = "should turn dehumid off, it's " + str( humid) + " and the high limit is " + str(humid_high) if dehumid_state == 'unknown': msg = "Script initialised, humid " + str( humid) + ", high limit is " + str( humid_high) + " checking it's off" dehumid_state = 'down_off' pigrow_defs.write_log(script, msg, loc_dic['loc_switchlog']) dehumid_off.dehumid_off(set_dic, loc_dic['loc_switchlog']) if cli_output_level == "max": print(msg)
def RF_on(set_dic, switch_log): script = 'RF_on.py' msg = ("") msg += (" #############################################\n") msg += (" ## Turning the RF - ON ##\n") from rpi_rf import RFDevice if 'gpio_RF' in set_dic: if not str(set_dic['gpio_RF']).strip() == '': gpio_pin = int(set_dic['gpio_RF']) else: print(" - RF gpio pin not set") else: msg += (" !! NO RF SET !!\n") msg += (" !! run config program or edit config.txt !!\n") msg += (" !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n") pigrow_defs.write_log(script, 'Failed - due to none set in config', switch_log) return msg rfdevice = RFDevice(gpio_pin) rfdevice.enable_tx() rfdevice.tx_code(15465751, 1, 432) rfdevice.tx_repeat = 5 msg += (" ## using GPIO " + str(gpio_pin) + " ##\n") msg += (" #############################################\n") pigrow_defs.set_condition(condition_name="RF", trig_direction="on", cooldown="none") pigrow_defs.write_log(script, 'RF turned on', switch_log) return msg
def heater_control(temp, use_fans=True): global heater_state # checks to see if current temp should result in heater on or off templow = float(set_dic['heater_templow']) # plan is to add buffer zones or some something temphigh = float(set_dic['heater_templow']) if temp < templow and heater_state != 'on': message = "It's cold, temp is" + \ str(temp) + " degrees! the low limit is " + \ str(templow) + " so turning heater on." if heater_state == 'unknown': message = "Script initialised, it's " + \ str(temp) + " degrees! the low limit is " + \ str(templow) + " so checking heater's on" pigrow_defs.write_log(script, message, loc_dic['loc_switchlog']) heater_on.heater_on(set_dic, loc_dic['loc_switchlog']) if use_fans == True: fans_on.fans_on(set_dic, loc_dic['loc_switchlog']) heater_state = 'on' elif temp > temphigh and heater_state != 'off': message = "it's warm, temp is " + \ str(temp) + " degrees, the high limit is " + \ str(temphigh) + " so turning heater off" if heater_state == 'unknown': message = "Script initialised, it's " + \ str(temp) + " degrees! the low limit is " + \ str(templow) + " so checking heater's off" pigrow_defs.write_log(script, message, loc_dic['loc_switchlog']) heater_off.heater_off(set_dic, loc_dic['loc_switchlog']) if use_fans == True: fans_off.fans_off(set_dic, loc_dic['loc_switchlog']) heater_state = 'off' else: message = "doing nothing, it's " + \ str(temp) + " degrees and the heater is " + heater_state
def log_in(): global reddit, inbox, subreddit try: print("logging in") reddit = praw.Reddit(user_agent=my_user_agent, client_id=my_client_id, client_secret=my_client_secret, username=my_username, password=my_password) inbox = reddit.inbox subreddit = reddit.subreddit(subreddit) print "Connected to reddit, found subreddit; " + str(subreddit.title) pigrow_defs.write_log(script, 'Initialized and logged into reddit.', loc_dic['loc_switchlog']) return True except Exception as e: message = 'Failed to log into reddit, ' + str(e) pigrow_defs.write_log(script, message, loc_dic['loc_switchlog']) return False
def fans_off(set_dic, switch_log): script = 'fans_off.py' msg =("\n") msg +=(" #############################################\n") msg +=(" ## Turning the fans - OFF ##\n") if 'gpio_fans' in set_dic and not str(set_dic['gpio_fans']).strip() == '': gpio_pin = int(set_dic['gpio_fans']) gpio_pin_on = set_dic['gpio_fans_on'] import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(gpio_pin, GPIO.OUT) if gpio_pin_on == "low": GPIO.output(gpio_pin, GPIO.HIGH) gpio_pin_dir = 'high' elif gpio_pin_on == "high": gpio_pin_dir = 'low' GPIO.output(gpio_pin, GPIO.LOW) else: msg +=(" !! CAN'T DETERMINE GPIO DIRECTION !!\n") msg +=(" !! run config program or edit config.txt !!\n") msg +=(" !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n") pigrow_defs.write_log(script, 'Failed - no direction set in config', switch_log) return msg else: msg +=(" !! NO fans SET !!\n") msg +=(" !! run config program or edit config.txt !!\n") msg +=(" !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n") pigrow_defs.write_log(script, 'Failed - due to none set in config', switch_log) return msg msg +=(" ## by switching GPIO "+str(gpio_pin)+" to "+gpio_pin_dir+" ##\n") msg +=(" #############################################\n") pigrow_defs.write_log(script, 'fans turned off', switch_log) return msg
def check_lamp(on_time, off_time): current_time = datetime.datetime.now().time() msg = 'Script initialised, performing lamp state check;' pigrow_defs.write_log(script, msg, loc_dic['loc_switchlog']) if True: if on_time > off_time: if current_time > on_time or current_time < off_time: lamp_on.lamp_on(set_dic, loc_dic['loc_switchlog']) return 'lamp on', True else: lamp_off.lamp_off(set_dic, loc_dic['loc_switchlog']) return 'lamp off', True elif on_time < off_time: if current_time > on_time and current_time < off_time: lamp_on.lamp_on(set_dic, loc_dic['loc_switchlog']) return 'the lamp on', True else: lamp_off.lamp_off(set_dic, loc_dic['loc_switchlog']) return 'the lamp off', True elif current_time == on_time: return ' - Actually it was a crazy coincidence, exact time match! cron will switch it for us', False return 'error', False
def check_lamp(on_time, off_time): current_time = datetime.datetime.now().time() msg = 'Script initialised, performing lamp state check;' pigrow_defs.write_log(script, msg, loc_dic['loc_switchlog']) if True: if on_time > off_time: if current_time > on_time or current_time < off_time: lamp_on.lamp_on(set_dic, loc_dic['loc_switchlog']) return 'a lamp on', True else: lamp_off.lamp_off(set_dic, loc_dic['loc_switchlog']) return 'a lamp off', True elif on_time < off_time: if current_time > on_time and current_time < off_time: lamp_on.lamp_on(set_dic, loc_dic['loc_switchlog']) return 'the lamp on', True else: lamp_off.lamp_off(set_dic, loc_dic['loc_switchlog']) return 'the lamp off', True elif current_time == on_time: return 'changing', False return 'magness', False
def humid_on(set_dic, switch_log): script = 'humid_on.py' msg = ("") msg += (" #############################################\n") msg += (" ## Turning the humidifier - ON ##\n") if 'gpio_humid' in set_dic and not str( set_dic['gpio_humid']).strip() == '': gpio_pin = int(set_dic['gpio_humid']) gpio_pin_on = set_dic['gpio_humid_on'] import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(gpio_pin, GPIO.OUT) if gpio_pin_on == "low": GPIO.output(gpio_pin, GPIO.LOW) elif gpio_pin_on == "high": GPIO.output(gpio_pin, GPIO.HIGH) else: msg += (" !! CAN'T DETERMINE GPIO DIRECTION !!\n") msg += (" !! run config program or edit config.txt !!\n") msg += (" !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n") pigrow_defs.write_log(script, 'Failed - no direction set in config', switch_log) return msg else: msg += (" !! NO humid SET !!\n") msg += (" !! run config program or edit config.txt !!\n") msg += (" !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n") pigrow_defs.write_log(script, 'Failed - due to none set in config', switch_log) return msg msg += (" ## by switching GPIO " + str(gpio_pin) + " to " + gpio_pin_on + " ##\n") msg += (" #############################################\n") pigrow_defs.set_condition(condition_name="humid", trig_direction="on", cooldown="none") pigrow_defs.write_log(script, 'Humidifier turned on', switch_log) return msg
def lamp_on(set_dic, switch_log): script = 'lamp_on.py' msg = ("") msg += (" #############################################\n") msg += (" ## Turning the lamp - ON ##\n") if 'gpio_lamp' in set_dic: if not str(set_dic['gpio_lamp']).strip() == '': gpio_pin = int(set_dic['gpio_lamp']) gpio_pin_on = set_dic['gpio_lamp_on'] import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(gpio_pin, GPIO.OUT) if gpio_pin_on == "low": GPIO.output(gpio_pin, GPIO.LOW) elif gpio_pin_on == "high": GPIO.output(gpio_pin, GPIO.HIGH) else: msg += ( " !! CAN'T DETERMINE GPIO DIRECTION !!\n") msg += ( " !! run config program or edit config.txt !!\n") msg += (" !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n") pigrow_defs.write_log(script, 'Failed - no direction set in config', switch_log) return msg else: msg += (" !! NO lamp SET !!\n") msg += (" !! run config program or edit config.txt !!\n") msg += (" !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n") pigrow_defs.write_log(script, 'Failed - due to none set in config', switch_log) return msg msg += (" ## by switching GPIO " + str(gpio_pin) + " to " + gpio_pin_on + " ##\n") msg += (" #############################################\n") pigrow_defs.write_log(script, 'lamp turned on', switch_log) return msg
import time import Adafruit_DHT homedir = os.getenv("HOME") sys.path.append(homedir + '/Pigrow/scripts/') import pigrow_defs sys.path.append(homedir + '/Pigrow/scripts/switches/') import heater_on, heater_off, humid_on, humid_off, dehumid_on, dehumid_off, fans_on, fans_off, lamp_on, lamp_off loc_dic = pigrow_defs.load_locs(homedir + "/Pigrow/config/dirlocs.txt") set_dic = pigrow_defs.load_settings(loc_dic['loc_settings'], err_log=loc_dic['err_log']) #print set_dic if 'log_frequency' in set_dic: log_time = set_dic['log_frequency'] else: err_msg = "Unable to load log_frequency from config file" pigrow_defs.write_log('checkDHT.py', err_msg, loc_dic['err_log']) err_msg += ", " + loc_dic['loc_settings'] print(err_msg) for argu in sys.argv[1:]: if '=' in argu: thearg = str(argu).split('=')[0] thevalue = str(argu).split('=')[1] if thearg == 'log_time' or thearg == 'delay': log_time = int(thevalue) elif thearg == 'log_non': if thevalue.lower() == 'true' or thevalue == '0': log_non = True else: log_non = False elif thearg == 'use_heat':
def check_msg(): path = homedir + '/Pigrow/' wikilink = "[Settings Wiki](https://www.reddit.com/r/" + str( subreddit) + "/wiki/" + str(wiki_title) + ")" for msg in reddit.inbox.unread(): print("") print(' - ' + msg.author) print(' - ' + msg.subject) print(' - ' + msg.body) msg.mark_read() if msg.author == watcher_name: print("Trusted User settings access enabled.") try: msgsub = msg.subject.split(":") except: print("Not a valid format") msgfrom = praw.models.Redditor(reddit, name=msg.author, _data=None) if msgsub[0] == "set": if msgsub[1] in pi_set: reply, passed = change_setting(str(msgsub[1]), str(msg.body)) write_set('wiki') reply += " \n \nvisit " + wikilink + " for more info" msgfrom.message('Pigrow Settings', reply[0:10000]) if passed == "pass": pigrow_defs.write_log(script, reply, loc_dic['loc_switchlog']) elif msgsub[0] == "cmd": if msgsub[1] == "reboot": print("User requests reboot!") elif msgsub[1] == "power off": print("User Requests Power Off!") elif msgsub[1] == "restore defaults": print("User want to resotore defauls") elif msgsub[1] == "update pigrow": print("User want to update pigrow!") elif msgsub[1] == "send_cmd": print("Oh gosh, the user has a command for us...") msg_codeword = str(msg.body).split("|")[0] msg_cmd = str(str(msg.body).split("|")[1:])[2:-2] if codeword == codeword: print( "hmmm, they knew the secret code word... we should let them...." ) try: os.system(msg_cmd) msgfrom.message( 'Pigrow Settings', 'ok, run ' + msg_cmd + " for you...") except Exception as e: msgfrom.message( 'Pigrow Settings', 'sorry, tried ' + msg_cmd + " but it failed... \n \n" + str(e)) else: print("Didn't know the codeword, chasing them off...") msgfrom.message( 'Pigrow Settings', 'Sorry, wrong codeword, not doing it :p') elif msgsub[1] == "archive_grow": print("--Archiving grow") responce = pigrow_defs.archive_grow(loc_dic, str(msg.body)) pigrow_defs.write_log(script, "Prior grow data archived.", loc_dic['loc_switchlog']) msgfrom.message('Pigrow Settings', responce) elif msgsub[1] == "log": print( "--User has something they want to add to the log...") pigrow_defs.write_log("User via Reddit", str(msg.body), loc_dic['loc_switchlog']) elif msgsub[1] == "send_settings": print("--User want to see settings!") write_set(msg.author) elif msgsub[1] == "update_wiki": print("--User want to see settings!") write_set('wiki') msgfrom.message('Pigrow Control', "Settings Wiki written at " + wikilink) elif msgsub[1] == 'datawall': print("--User want's a datawall!") datawalllink = "[Settings Wiki](https://www.reddit.com/r/" + str( subreddit) + "/wiki/" + str(wiki_title) + "datawall)" os.system(path + "scripts/visualisation/caps_graph.py") os.system(path + "scripts/visualisation/temp_graph.py hours=24") os.system(path + "scripts/visualisation/humid_graph.py hours=24") os.system(path + "scripts/visualisation/selflog_graph.py") os.system(path + "scripts/visualisation/assemble_datawall.py") photo_loc = subreddit.stylesheet.upload( 'datawall', path + "graphs/datawall.jpg") page_text = "#Datawall \n \n" page_text += '![datawall](%%datawall%%) \n \n' praw.models.WikiPage(reddit, subreddit, live_wiki_title).edit(page_text) live_wikilink = "[Datawall](https://www.reddit.com/r/" + str( subreddit) + "/wiki/" + str(live_wiki_title) + ")" msgfrom.message( 'Pigrow Control', "Datawall uploaded to " + str(live_wikilink)) elif msgsub[1] == "timelapse_hour": print( "Generating the last hour into a timelapse, this will take a while..." ) os.system( path + "scripts/visualisation/timelapse_assemble.py of=" + homedir + "/Pigrow/graphs/hour.gif dc=hour1 ds=1 fps=5 ow=r") #msgfrom.message('Pigrow Control', "Gif created " + homedir + "/Pigrow/graphs/hour.gif")#at " + giflink) photo_loc = subreddit.stylesheet.upload( 'onehour', path + "graphs/hour.gif") page_text = "#Last Hour \n \n" page_text += '![onehour](%%onehour%%) \n \n' praw.models.WikiPage(reddit, subreddit, live_wiki_title).edit(page_text) live_wikilink = "[Timelapse](https://www.reddit.com/r/" + str( subreddit) + "/wiki/" + str(live_wiki_title) + ")" msgfrom.message( 'Pigrow Control', "Last hour timelapse gif uploaded to " + str(live_wikilink)) elif msgsub[1] == "timelapse_5hours": print( "Generating the last five hours into a timelapse, this will take a while..." ) os.system( path + "scripts/visualisation/timelapse_assemble.py of=" + homedir + "/Pigrow/graphs/5hours.gif dc=hour5 ds=1 fps=5 ow=r") msgfrom.message( 'Pigrow Control', "Gif created " + homedir + "/Pigrow/graphs/5hours.gif") #at " + giflink) elif msgsub[1] == "timelapse_day": print( "Generating the last day into a timelapse, this will take a while..." ) os.system( path + "scripts/visualisation/timelapse_assemble.py of=" + homedir + "/Pigrow/graphs/day.gif dc=day1 ds=1 fps=5 ts=8 ow=r") msgfrom.message('Pigrow Control', "Gif created " + homedir + "/Pigrow/graphs/day.gif") #at " + giflink) elif msgsub[1] == "timelapse_week": print( "Generating the last week into a timelapse, this will take a while..." ) os.system( path + "scripts/visualisation/timelapse_assemble.py of=" + homedir + "/Pigrow/graphs/week.gif dc=hour5 ds=1 fps=5 ow=r") msgfrom.message( 'Pigrow Control', "Gif created " + homedir + "/Pigrow/graphs/week.gif") #at " + giflink) elif msgsub[1] == "addcron": print("User wants to add job to cron;") new_job = make_cron_from(msg.body) print new_job if new_job != False: cron.write() msgfrom.message('Pigrow Control', "Cron job " + str(new_job) + " added.") else: msgfrom.message('Pigrow Control', "Sorry, that wasn't a valid cron job") elif msgsub[0] == "crontog": job = cron[int(msgsub[1])] if job.enabled == True: job.enable(False) truefalse = "False" else: job.enable(True) truefalse = "True" cron.write() msgfrom.message('Pigrow Control', "toggled to " + truefalse) elif msgsub[0] == "cronmod": job = cron[int(msgsub[1])] print("Attempting to alter cron job" + str(job)) new_job = make_cron_from(msg.body) print new_job if new_job != False: #if job.command == new_job.command: cron.remove(job) cron.write() msgfrom.message( 'Pigrow Control', "Cron job " + str(job) + " changed to " + str(new_job)) #else: # cron.remove(new_job) # msgfrom.message('Pigrow Control', "Sorry, can't change scripts when modifying cron job, it's dangerous") else: msgfrom.message('Pigrow Control', "Sorry, that wasn't a valid cron job") else: reply = "Sorry, couldn't understand what you wanted, " reply += "visit " + wikilink + " for more info" whereto = praw.models.Redditor(reddit, name=msg.author, _data=None) whereto.message('Pigrow Settings', reply[0:10000]) print( "Didn't understand what they wanted, if they wanted anything." ) else: print("THIS IS NOT A TRUSTED USER - THEY CAN NOT EDIT SETTINGS!") print("")
def write_set(whereto='wiki'): page_text = '#Pigrow Settings \n\n' page_text += 'This displays the current settings from the pigrow, \n' page_text += 'to change these settings you can message your pigrow' page_text += 'via reddit by simply clicking on the link in the table \n' page_text += 'leave the subject as the setting you wish to change and' page_text += 'put the new value in the body of the message. \n' page_text += ' \n' page_text += '|Name|Setting| \n' page_text += '|--:|---| \n' for key, value in pi_set.iteritems(): #print key, value page_text += '|[' + key + '](https://www.reddit.com/message/compose/?to=' + my_username + '&subject=set:' + str( key) + '&message=' + str(value) + ')|' + str(value) + ' \n' page_text += ("") page_text += ( "To view an explanation of each setting go see [configuring the pigrow](wiki link goes here) in the documentation " ) ### ## LOAD SWITCH FILE # switch_list = [] days_to_show = 7 switch_list_limit = 10 try: with open(loc_switchlog, "r") as f: logitem = f.read() logitem = logitem.split("\n") print('There are ' + str(len(logitem)) + ' readings in the switch log.') oldest_allowed_date = thetime - datetime.timedelta(days=days_to_show) curr_line = len(logitem) - 1 except: print("switch not loaded, try running pi_setup") pigrow_defs.write_log(script, 'switch log file error', loc_dic['err_log']) return ("FAILED DUE TO NO SWTICH LOG FILE") while curr_line >= 0: try: item = logitem[curr_line] item = item.split("@") switch_date = item[1].split(".")[0] w_script = item[0] err_detail = item[2] date = datetime.datetime.strptime(switch_date, '%Y-%m-%d %H:%M:%S') if date < oldest_allowed_date: break switch_list.append([w_script, switch_date, err_detail]) if len(switch_list) >= switch_list_limit: break curr_line = curr_line - 1 except: print("line" + str(curr_line) + " didn't parse, ignoring") curr_line = curr_line - 1 #print item switch_item = item page_text += ' \n \n' page_text += '#Cron' page_text += ' \n \n' page_text += 'Current Cron file; \n \n' page_text += 'Enabled|time|Command|Comment|-|Line \n' page_text += ':-:|---|---|---|--:|--- \n' cjob = 0 for job in cron: modlink = 'https://www.reddit.com/message/compose/?to=' + my_username + '&subject=cronmod:' + str( cjob) + '&message=updated_line_here' enabledlink = 'https://www.reddit.com/message/compose/?to=' + my_username + '&subject=crontog:' + str( cjob) + '&message=plz' enabled = job.is_enabled() page_text += "[" + str(enabled) + "](" + enabledlink + ")|" + str( job.slices) + "|" page_text += str(job.command) + "|" + str(job.comment) + "|" page_text += "[modify](" + modlink + ")|" + str(job) + " \n" cjob = cjob + 1 page_text += " \n \n" page_text += '[Add New Cron Job;](https://www.reddit.com/message/compose/?to=' + my_username + '&subject=cmd:addcron&message=plz)' page_text += ' \n \n' page_text += '#Switch Log \n \n' page_text += 'Showing ' + str(switch_list_limit) + ' from the last ' + str( days_to_show) + ' days of activity. \n \n' page_text += '|Script|Time|Event \n' page_text += '|---|:-:|--- \n' for a in switch_list: page_text += '|' + a[0] + '|' + str(a[1]) + '|' + a[2] + ' \n' page_text += ' \n' ### cmdlink = "(https://www.reddit.com/message/compose/?to=" + my_username + "&subject=cmd:" page_text += ' \n' page_text += ' \n' page_text += ' The following settings are not yet all implimented' page_text += ' They will run functions found in pigrow_defs' page_text += ' \n \n' page_text += '|Pi Command|Action|Notes \n' page_text += '|:-:|:-:|--- \n' page_text += '|Power Off|Remotely shuts down the pi|passwrod protected, if enabled include password in body of text \n' page_text += '|Reboot|Remotely reboots the pi|password protected \n' page_text += '|Factory Reset|Restores Pigrow Defaults|password protected \n' page_text += '|Update Pigrow|Automatically updates software|password protected \n' page_text += '|[Send Command]' + cmdlink + 'send_cmd&message=PASSWORD pipe CMD if you don\' want reddit ear to wait finish with &)|Send a bash command directly to the pi (dangerous)|lets you do almost anything, which is dangerous.. end command with an & if you don\'t want reddit_ear to wait for it to finish PASS|COMMAND \n' page_text += "|[Log]" + cmdlink + "log)|Create a custom log event|Include the text of the log event in the body of the message \n" page_text += "|[update_wiki]" + cmdlink + "update_wiki)|Updates or creates the settings wiki|Replies with a link to it. \n" page_text += "|[Archive Grow]" + cmdlink + "archive_grow)|Stores all the data for the current grow in an archive folder and starts a new grow|password protected \n" page_text += "|Generate System Report|Creates a current pigrow system report and sends it to the user|Includes diskfull, uptime, etc \n" page_text += "|[Generate Data Wall]" + cmdlink + "datawall)|Create visual display of pigrow status from logs| \n" page_text += "|[Generate Timelapse Hour]" + cmdlink + "timelapse_hour)|Creates a timelapse gif of the current day so far, uploads it and sends a link to the user| \n" page_text += "|[Generate Timelapse 5Hours]" + cmdlink + "timelapse_5hour)|Creates video of last five hours, uploads and links user|size limited due to upload restrictions \n" page_text += "|[Generate Timelapse day]" + cmdlink + "timelapse_day)|Creates video of last day, applies timeskip to limit size.| \n" page_text += "|[Generate Timelapse week]" + cmdlink + "timelapse_week)|Creates video of last week, applies large timeskip to limit size.| \n" page_text += "|[send_settings]" + cmdlink + "send_settings)|Replies to the user with the settings menu|| \n" page_text += " \n \n" page_text += "*this section work in progress, links will be added as the functions are* \n" page_text += " \n \n" #determine local ip - apparently this works on macs if you change the 0 to a 1 but i don't buy apple products so... try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect( ('8.8.8.8', 0)) # connecting to a UDP address doesn't send packets local_ip_address = s.getsockname()[0] page_text += 'Current local network IP ' + str(local_ip_address) except: page_text += 'Local IP not deduced, sorry...' print("writing " + str(len(page_text)) + " characters to reddit") if whereto == 'wiki': praw.models.WikiPage(reddit, subreddit, wiki_title).edit(page_text[0:524288]) else: try: whereto = praw.models.Redditor(reddit, name=whereto, _data=None) whereto.message('Pigrow Settings', page_text[0:10000]) #, from_subreddit=subreddit) except: pigrow_defs.write_log(script, "couldn't contact redditor, wrong naem?", loc_dic['err_log'])
25, 8, 7, 1, 12, 16, 20, 21 ] #valid gpio numbers using the gpio (BCM) NOT the board numbering system intonly = ['heater_templow', 'heater_temphigh', 'log_frequency'] if 'loc_switchlog' in loc_dic: loc_switchlog = loc_dic['loc_switchlog'] if 'loc_settings' in loc_dic: loc_settings = loc_dic['loc_settings'] if 'err_log' in loc_dic: err_log = loc_dic['err_log'] my_user_agent = 'Pigrow updater tester thing V0.6 (by /u/The3rdWorld)' try: my_client_id = loc_dic['my_client_id'] my_client_secret = loc_dic['my_client_secret'] my_username = loc_dic['my_username'] my_password = loc_dic['my_password'] except: message = "REDDIT SETTINGS NOT FOUND IN " + str(loc_locs) pigrow_defs.write_log(script, message, loc_dic['loc_switchlog']) raise try: subreddit = loc_dic["subreddit"] wiki_title = loc_dic['wiki_title'] live_wiki_title = loc_dic['live_wiki_title'] use_wiki = True except: message = "No subreddit details set, can't update live pages" pigrow_defs.write_log(script, message, loc_dic['loc_switchlog']) subreddit = '' wiki_title = '' live_wiki_title = '' use_wiki = False try: watcher_name = loc_dic['watcher_name']
line += str(key) + "=" + str(value) + ">" #print('Found ' + str(len(vcgecmd_info)) + ' graphable metrics in vcgecmd_info') # runnig script counter scripts_to_check = [ 'reddit_settings_ear.py', 'checkDHT.py', 'trigger_watcher.py', 'watcher_button.py' ] for script in scripts_to_check: script_info = check_scripts(script) for key, value in sorted(script_info.items()): line += str(key) + "=" + str(value) + ">" #print('Found ' + str(len(script_info)) + ' with active script info for ' + script) #for script in scripts_to_check: # script_status = check_script_running(script) # for key, value in sorted(script_status.items()): # line += str(script + '_' + key) + "=" + str(value) + ">" line = line[:-1] + '\n' # find the log and add a line to it if 'adv_self_log' in loc_dic: log_location = loc_dic['adv_self_log'] else: log_location = homedir + '/Pigrow/logs/adv_selflog.txt' try: with open(log_location, "a") as f: f.write(line) #print(" - log written - ", line) except: print["-LOG ERROR-"] pigrow_defs.write_log('adv_selflog.py', 'writing self log failed', loc_dic['err_log'])
def fan_control(temp, humid, heat_use_fan=True, hum_use_fan=False, dehum_use_fan=False): global fans_state message = " - No change" if cli_output_level == "max": print(" -- Fan controll") if heat_use_fan == True: temphigh = float(set_dic['heater_temphigh']) if temp > temphigh and fans_state != 'on': message = "too hot, temp is " + str( temp) + " degrees, the high limit is " + str( temphigh) + " so turning the fans on" fans_on.fans_on(set_dic, loc_dic['loc_switchlog']) fans_state = 'on' pigrow_defs.write_log(script, message, loc_dic['loc_switchlog']) elif temp < temphigh and fans_state != 'off': message = "not too hot, temp is " + str( temp) + " degrees, the high limit is " + str( temphigh) + " so turning the fans off" fans_off.fans_off(set_dic, loc_dic['loc_switchlog']) fans_state = 'off' pigrow_defs.write_log(script, message, loc_dic['loc_switchlog']) # humid up if hum_use_fan == True: hum_low = float(set_dic['humid_low']) if humid < hum_low and fans_state != 'on': message = "not humid enough, humidity is " + str( humid) + " %, the low limit is " + str( hum_low) + " so turning the fans on" fans_on.fans_on(set_dic, loc_dic['loc_switchlog']) fans_state = 'on' pigrow_defs.write_log(script, message, loc_dic['loc_switchlog']) elif temp > hum_low and fans_state != 'off': message = "humid enough, humidity is " + str( humid) + " %, the low limit is " + str( hum_low) + " so turning the fans off" fans_off.fans_off(set_dic, loc_dic['loc_switchlog']) fans_state = 'off' pigrow_defs.write_log(script, message, loc_dic['loc_switchlog']) # humid down if dehum_use_fan == True: hum_high = float(set_dic['humid_high']) if humid > hum_high and fans_state != 'on': message = "too humid, humidity is " + str( humid) + " %, the high limit is " + str( hum_high) + " so turning the fans on" fans_on.fans_on(set_dic, loc_dic['loc_switchlog']) fans_state = 'on' pigrow_defs.write_log(script, message, loc_dic['loc_switchlog']) elif humid < hum_high and fans_state != 'off': message = "humid low enough, humidity is " + str( humid) + " %, the high limit is " + str( hum_high) + " so turning the fans off" fans_off.fans_off(set_dic, loc_dic['loc_switchlog']) fans_state = 'off' pigrow_defs.write_log(script, message, loc_dic['loc_switchlog']) if cli_output_level == "max": print(message)
25, 8, 7, 1, 12, 16, 20, 21 ] #valid gpio numbers using the gpio (BCM) NOT the board numbering system intonly = ['heater_templow', 'heater_temphigh', 'log_frequency'] if 'loc_switchlog' in loc_dic: loc_switchlog = loc_dic['loc_switchlog'] if 'loc_settings' in loc_dic: loc_settings = loc_dic['loc_settings'] if 'err_log' in loc_dic: err_log = loc_dic['err_log'] my_user_agent = 'Pigrow updater tester thing V0.6 (by /u/The3rdWorld)' try: my_client_id = loc_dic['my_client_id'] my_client_secret = loc_dic['my_client_secret'] my_username = loc_dic['my_username'] my_password = loc_dic['my_password'] except: message = "REDDIT SETTINGS NOT FOUND IN " + str(loc_locs) pigrow_defs.write_log(script, message, loc_dic['err_log']) raise try: subreddit = loc_dic["subreddit"] wiki_title = loc_dic['wiki_title'] live_wiki_title = loc_dic['live_wiki_title'] use_wiki = True except: message = "No subreddit details set, can't update live pages" pigrow_defs.write_log(script, message, loc_dic['err_log']) subreddit = '' wiki_title = '' live_wiki_title = '' use_wiki = False try: watcher_name = loc_dic['watcher_name']
speed_data['Download'] = speed_info[6].strip() speed_data['Upload'] = speed_info[7].strip() return speed_data if __name__ == '__main__': scripts_to_check = [ 'reddit_settings_ear.py', 'checkDHT.py' ] # 'chromium-browse'] #this doesn't work :( works for 'atom' and 'bash' needs fix print(" ######################################") print("######### Net Speed LOGGER ############") line = "timenow=" + str(datetime.datetime.now()) + ">" speed_data = speed_test() for key, value in sorted(speed_data.items()): line += str(key) + "=" + str(value) + ">" line = line[:-1] + "\n" # find the log and add a line to it if 'netspeed_log' in loc_dic: log_location = loc_dic['netspeed_log'] else: log_location = homedir + '/Pigrow/logs/netspeed_log.txt' try: with open(log_location, "a") as f: f.write(line) print(" - log written - ", line) print("----") except: print["-LOG ERROR-"] pigrow_defs.write_log('selflog_netspeed.py', 'writing self log failed', loc_dic['err_log'])
def run_water(set_dic, switch_log, duration): print("") print(" #############################################\n") print(" ## Preparing to Water Plants ##\n") if 'gpio_water' in set_dic and not str( set_dic['gpio_water']).strip() == '': gpio_pin = int(set_dic['gpio_water']) gpio_water_on = set_dic['gpio_water_on'] import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(gpio_pin, GPIO.OUT) if gpio_water_on == "low": print(" ## Turning the Water - ON ##\n") print(" ## by switching GPIO " + str(gpio_pin) + " to " + gpio_water_on + " ##\n") GPIO.output(gpio_pin, GPIO.LOW) print(" ## Waiting " + str(duration) + " seconds ##\n") time.sleep(duration) print(" ## Turning the Water - OFF ##\n") GPIO.output(gpio_pin, GPIO.HIGH) print(" #############################################\n") elif gpio_water_on == "high": print(" ## Turning the Water - ON ##\n") print(" ## by switching GPIO " + str(gpio_pin) + " to " + gpio_water_on + " ##\n") GPIO.output(gpio_pin, GPIO.HIGH) print(" ## Waiting " + str(duration) + " seconds ##\n") time.sleep(duration) print(" ## Turning the Water - OFF ##\n") GPIO.output(gpio_pin, GPIO.LOW) print(" #############################################\n") else: msg = ( " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n" ) msg += ( " !! CAN'T DETERMINE GPIO DIRECTION !!\n" ) msg += ( " !! Fix with the Remote Gui or edit pigrow_config.txt !!\n" ) msg += ( " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n" ) pigrow_defs.write_log(script, 'Failed - no direction set in config', switch_log) return msg else: msg = ( " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n" ) msg += ( " !! No water control device set !!\n" ) msg += ( " !! Fix with the Remote Gui or edit pigrow_config.txt !!\n" ) msg += ( " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n") pigrow_defs.write_log(script, 'Failed - due to no gpio pin set in config', switch_log) return msg msg = 'watered for ' + str(duration) + ' seconds.' pigrow_defs.write_log(script, msg, switch_log) return msg
button_log = None button_loc = None for key, value in list(pigrow_settings.items()): button_key = "button_" + button_name if button_key in key: if "type" in key: button_type = value elif "log" in key: button_log = value elif "loc" in key: button_loc = value if button_type == None or button_log == None or button_loc == None: err_msg = "Button settings not found in " + loc_dic['loc_settings'] print(err_msg) pigrow_defs.write_log('log_sensor_module.py', err_msg, loc_dic['err_log']) sys.exit() def listen(gpio_num, log_path, *args): button = Button(gpio_num) def pressed(): #print( " Button Pressed " ) listen.press_start = time.time() def released(): #print( " Button released " ) listen.press_end = time.time() button.wait_for_press()
sys.exit() else: #if the file doesn't exist check if we should try again and if so try again print("Error: Image file not found") # If trying more than once if attempts > 1: for attempt in range(1,attempts+1): time.sleep(retry_delay) if not os.path.isfile(caps_path + filename): print("-- Trying attempt " + str(attempt) + " of " + str(attempts)) if cam_opt == "uvccapture": filename = take_with_uvccapture(s_val, c_val, g_val, b_val, x_dim, y_dim, cam_num, uvc_extra, caps_path) if os.path.isfile(caps_path + filename): print("Done on extra attempt " + str(attempt)) sys.exit() elif cam_opt == "fswebcam": filename = take_with_fswebcam(s_val, c_val, g_val, b_val, x_dim, y_dim, cam_num, fsw_extra, caps_path) if os.path.isfile(caps_path + filename): print("Done on try " + str(attempt)) sys.exit() #once all extra attempts have been made give it one last check then tell #the user we failed to create the file and try to write a error log entry if not os.path.isfile(caps_path + filename): print("FAILED no photos taken.") errmsg = "Failed with " + str(attempts) + " extra attempts, no photo saved." if log_error == True: try: pigrow_defs.write_log(script, errmsg, loc_dic['err_log']) except Exception as e: print("couldn't log error :( " + str(e))
# try: # pid = get_pid('doggo') # print pid # except: # print("No program of that name running.") if __name__ == '__main__': # 'chromium-browse'] #this doesn't work :( works for 'atom' and 'bash' needs fix scripts_to_check = ['reddit_settings_ear_2.py', 'checkDHT.py'] print("################################################") print("######### SELF CHECKING INFO LOGGER ############") info = gather_data(path) line = '' for key, value in info.iteritems(): line += str(key) + "=" + str(value) + ">" for script in scripts_to_check: script_status = check_script_running(script) #print("The script " + script + " has " + script_status['num_running'] + " instances running") for key, value in script_status.iteritems(): line += str(script + '_' + key) + "=" + str(value) + ">" line += '\n' print line try: with open(loc_dic['self_log'], "a") as f: f.write(line) except Exception: print["-LOG ERROR-"] pigrow_defs.write_log('checkDHT.py', 'writing dht log failed', loc_dic['err_log'])