def measureWU(api_key, index, lat, lon): # get WeatherUnderground data try: webiopi.debug("Starting WU measure") url = "http://api.wunderground.com/api/" + api_key + "/conditions/q/" + lat + "," + lon + ".json" r = requests.get(url, timeout=2) data = r.json() dat = data["current_observation"] try: temp = str(round(dat["temp_c"], 1)) except: temp = "U" #hr = str(round(dat["relative_humidity"], 1)) match = re.search('([\d\.]+)%', dat["relative_humidity"]) if match: hr = match.group(1) else: hr = "U" match = re.search('([\d\.]+)', dat["precip_1hr_metric"]) if match: rain = match.group(1) else: rain = "U" #match = re.search('([\d\.]+)%', dat["clouds"]["all"]) clouds = "0" except: temp = "U" hr = "U" clouds = "U" rain = "U" webiopi.info("! WU request error ! %s %s" % (sys.exc_info()[0], sys.exc_info()[1])) finally: values = [temp, hr, clouds, rain] webiopi.debug("WU values = %s" % values) return values[index]
def __init__(self, inputBCM, lights): webiopi.info('LightControl has initialized for inputBCM {0} and lightsBCM {1}'.format(inputBCM, lights)) self.inputBCM = inputBCM GPIO.setFunction(inputBCM, GPIO.IN, GPIO.PUD_UP) self.lightSet = LightSet(lights) self.lightSet.update() self.lastStatus = True
def measureDHT(DHTtype, gpio, index): try: script = os.path.join(eziopi_dir, "scripts/adafruit_dht") tries = 5 for i in range(tries): val = str(subprocess.check_output([script, DHTtype, str(gpio)])) match = re.search('Temp.+\s([\d\.]+)\s.+Hum.+\s([\d\.]+)\s%', val) if match: temp, hr = match.group(1), match.group(2) webiopi.debug("DHT22 measure %s: temp=%s hr=%s" % (str(i+1), temp, hr)) break else: # Erreur mesure gpioDHT22 if i == tries-1: temp = "U" hr = "U" webiopi.info("! DHT22 error after %s tries ! - stop trying" % str(i+1)) else: time.sleep(2) except: temp = "U" hr = "U" webiopi.exception("! DHT22 error ! %s" % sys.exc_info()[1]) finally: values = [temp, hr] return values[index]
def measureRelay(gpio): try: gpio = int(gpio) gpioState = int(GPIO.digitalRead(gpio)) except: gpioState = "U" webiopi.info("! error checking gpio %s state ! %s - %s" % (gpio, sys.exc_info()[0], sys.exc_info()[1])) finally: return gpioState
def loop(): global refreshTimeInterval global allGpsData try: webiopi.info('Read:%s' % getAllGpsData()) except Exception as Err: webiopi.debug('%s' % Err) finally: # Cyclic Period webiopi.sleep(1)
def saveSettings(numStart, timeDelay, maxNum, maxTTL, maxAgression): global settings webiopi.info('saving settings') #save the settings settings.setValue(constants.NUM_LIFEFORMS_START, numStart) settings.setValue(constants.SECONDS_BETWEEN_LOOPS, timeDelay) settings.setValue(constants.MAX_LIFEFORMS, maxNum) settings.setValue(constants.MAX_TTL, maxTTL) settings.setValue(constants.MAX_AGRESSION, maxAgression) return json.dumps({"message": "Settings Saved"})
def setup(): webiopi.info("Script with macros - Setup") try: # Setup GPIOs sensorlist = sensors.keys() for sensorname in sensorlist: sensor = sensors[sensorname] if sensor["type"] == "DHT22" or sensor["type"] == "relay": GPIO.setFunction(sensor["id"], GPIO.OUT) GPIO.digitalWrite(sensor["id"], GPIO.LOW) except: webiopi.exception("! setup failed ! %s %s" % (sys.exc_info()[0], sys.exc_info()[1])) pass
def logLine(message, debug=False): global logArray global is_running if (debug): #if debug don't put in logArray webiopi.debug(message) else: #both print to log and logArray webiopi.info(message) if (is_running): logArray.append(message)
def process(line): webiopi.info("Received: " + line) params = line.split("|", 1) # split checksum from message if len(params) != 2: webiopi.warn("Invalid line: %s " % line) return checksum = calc_checksum(params[1]) if params[0] != checksum: webiopi.warn("Invalid checksum: %s (%s instead of %s)" % (params[1], checksum, params[0])) return params = params[1].split("|") count = len(params) if count < maxSensor + maxButtons: webiopi.warn("Invalid line: %s (%d)" % (line, count)) return # process params message = "" index = 0 for data in params: if index < maxSensor: sensors[index] = int(data) # store sensor value elif index < maxSensor + maxButtons: carButtons[index - maxSensor] = int(data) # store button state else: message += "%s|" % data # last value is a string (may contain commas) index += 1 message = message.strip("|") # handle question answer using last 2 buttons global lastAnswer, lastQuestion # debug = "%s|%s" % (lastQuestion, message) # webiopi.debug(debug) # if lastQuestion != "" and lastQuestion == message: if carButtons[maxButtons - 2] >= 1: lastAnswer = "Yes" lastQuestion = "" elif carButtons[maxButtons - 1] >= 1: lastAnswer = "No" lastQuestion = "" pitButtons[maxButtons - 2] = carButtons[maxButtons - 2] pitButtons[maxButtons - 1] = carButtons[maxButtons - 1] return 0
def process(line): webiopi.info("Received: " + line) params = line.split("|", 1) # split checksum from message if len(params) != 2: webiopi.warn("Invalid line: %s " % line) return checksum = calc_checksum(params[1]) if params[0] != checksum: webiopi.warn("Invalid checksum: %s (%s instead of %s)" % (params[1], checksum, params[0])) return params = params[1].split("|") count = len(params) if count < maxSensor+maxButtons: webiopi.warn("Invalid line: %s (%d)" % (line, count)) return # process params message = "" index = 0 for data in params: if index < maxSensor: sensors[index] = int(data) # store sensor value elif index < maxSensor+maxButtons: carButtons[index-maxSensor] = int(data) # store button state else: message += "%s|" % data # last value is a string (may contain commas) index += 1 message = message.strip("|") # handle question answer using last 2 buttons global lastAnswer, lastQuestion # debug = "%s|%s" % (lastQuestion, message) # webiopi.debug(debug) # if lastQuestion != "" and lastQuestion == message: if carButtons[maxButtons-2] >= 1: lastAnswer = "Yes" lastQuestion = "" elif carButtons[maxButtons-1] >= 1: lastAnswer = "No" lastQuestion = "" pitButtons[maxButtons-2] = carButtons[maxButtons-2] pitButtons[maxButtons-1] = carButtons[maxButtons-1] return 0
def setup(): global settings global logArray #load the settings file settings = Settings('/home/pi/Artificial_Life/') #setup the log array logArray = [] #unicorn hat setup unicorn.set_layout(unicorn.AUTO) unicorn.brightness(0.5) unicorn.rotation(0) unicorn.brightness(0.5) webiopi.info('setup complete')
def destroy(): webiopi.info("Script with macros - Destroy") try: # Reset GPIOs for app in cfgAll["app"]: map = cfgAll["app"][app]["map"] #webiopi.debug("map=%s" % map) for item in map: if "cmd" in item: #webiopi.debug("cmd=%s" % cmd) for i in item["cmd"]: gpio = i["gpio"] GPIO.setFunction(gpio, GPIO.OUT) GPIO.digitalWrite(gpio, GPIO.LOW) # Shutdown APScheduler global sched sched.shutdown() except: webiopi.exception("! destroy failed ! %s %s" % (sys.exc_info()[0], sys.exc_info()[1])) pass
def setup(): webiopi.info("Script with macros - Setup") try: # Setup GPIOs for app in cfgAll["app"]: map = cfgAll["app"][app]["map"] #webiopi.debug("map=%s" % map) for item in map: if "cmd" in item: #webiopi.debug("cmd=%s" % cmd) for i in item["cmd"]: gpio = i["gpio"] GPIO.setFunction(gpio, GPIO.OUT) GPIO.digitalWrite(gpio, GPIO.LOW) # Setup APScheduler global sched sched.start() except: webiopi.exception("! setup failed ! %s %s" % (sys.exc_info()[0], sys.exc_info()[1])) pass
def loop(): try: loc = cfgAll["location"] lat = loc["lat"] lon = loc["lon"] for graph in graphs: dsnames = "" values = "" sources = graph["sources"] for source in sources: if source["disabled"] == True: webiopi.debug("data source %s disabled !" % source["ds"]) else: sensor = sensors[source["sensor"]] if sensor["disabled"] == False: if sensor["type"] == "WU": data = measureWU(sensor["id"], source["data_index"], lat, lon) elif sensor["type"] == "DHT22": data = measureDHT("22", sensor["id"], source["data_index"]) elif sensor["type"] == "DS18B20": data = measureDS18B20(sensor["id"]) elif sensor["type"] == "relay": data = measureRelay(sensor["id"]) else: webiopi.info("! sensor %s type unknown (%s) !" % (source["sensor"], sensor["type"])) data = "U" else: # Sensor disabled, unknown data webiopi.debug("! sensor -%s- disabled !" % (source["sensor"])) data = "U" dsnames += ':' + source["ds"] values += ':' + str(data) # Remove first character (":") in ds names list dss = dsnames[1:] rrdupdate = rrdtool.update(statusDir + graph["rrd"], '--template', dss, 'N' + values) except: webiopi.info("! loop failed ! %s %s" % (sys.exc_info()[0], sys.exc_info()[1])) pass finally: # delay next measure in 5 min time.sleep(300)
def loop(): global motor1 global motor2 global RCCar_Mode global refreshTimeInterval global allGpsData try: if RCCar_Mode != -1: #webiopi.debug('goSync') motor1.syncMotorFromCommandStatus() motor2.syncMotorFromCommandStatus() webiopi.info('Read:%s' % getAllGpsData()) except Exception as Err: webiopi.debug('%s' % Err) finally: # Cyclic Period webiopi.sleep(1)
def progPool(prog, rank, act, deact, duration): try: act = int(act) # Activate pump for delay before measurement delay = 1200 GPIO.digitalWrite(act, 1) # not reboot-proof method !!!!! time.sleep(delay) GPIO.digitalWrite(act, 0) rrd = statusDir + "water.rrd" temp = lastRRD(rrd, "temp", 0) webiopi.debug("Pool water temp: %s°C" % temp) # Calculate filtration total time if temp is None: webiopi.debug("Unknown Pool Temp !") tFilter = 12*3600 else: temp = round(float(temp), 1) if temp < 0: tFilter = 12*3600 elif 0 < temp < 10: tFilter = 3600 elif temp > 24: # max filter time tFilter = 12*3600 else: tFilter = round(temp/2*3600) # Filtration on 2 steps duration = round(tFilter/2) webiopi.debug("Pool filtration step duration: %ss" % duration) today = datetime.date.today() run1 = datetime.datetime.combine(today, datetime.time(8, 0)) run2 = datetime.datetime.combine(today, datetime.time(14, 0)) sched.add_job(actProg, "date", [prog, rank, str(act), deact, str(duration)], id=str(act) + '-' + rank + '-' + 'pool1', name='run1', next_run_time=run1, jobstore='file') sched.add_job(actProg, "date", [prog, rank, str(act), deact, str(duration)], id=str(act) + '-' + rank + '-' + 'pool2', name='run2', next_run_time=run2, jobstore='file') except: webiopi.info("! pool command error ! %s - %s" % (sys.exc_info()[0], sys.exc_info()[1]))
def actFan(prog, rank, act, deact, duration, hrMin, hrMax): try: act = int(act) hrMin = int(hrMin) hrMax = int(hrMax) duration = int(duration) rrd = statusDir + "hr.rrd" delay = 1800 last = lastRRD(rrd, "In", delay) #webiopi.debug("last = %s" % last) actState = int(GPIO.digitalRead(act)) if not last: # hr unknown webiopi.info("hr unknown - activate fan") GPIO.digitalWrite(act, 1) else: # check if any hr NOK hrOK = True for val in last: if val < hrMin or val > hrMax: hrOK = False if not actState: # Fan is off if hrOK is True: webiopi.debug("fan off - hr OK - do nothing !") else: webiopi.debug("fan off - hr NOK - activate fan !") GPIO.digitalWrite(act, 1) else: # Fan is on if hrOK is True: webiopi.debug("fan on - hr OK - deactivate fan") GPIO.digitalWrite(act, 0) else: webiopi.debug("fan on - hr NOK - do nothing !") except: webiopi.info("! fan command error ! %s - %s" % (sys.exc_info()[0], sys.exc_info()[1]))
def actProg(prog, rank, act, deact, duration): try: progRun = str(act) + '-' + rank + '-' + prog webiopi.info("running prog: %s" % progRun) duration = int(duration) # check GPIOs state act = int(act) actState = GPIO.digitalRead(act) deactState = None if deact: deact = int(deact) deactState = GPIO.digitalRead(deact) # Activate if none is already active if not actState and not deactState: GPIO.digitalWrite(act, 1) # Schedule deactivate job progId = str(act) + '-' + 'deact' exec_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time() + duration)) sched.add_job(deactRemote, "date", [str(act)], id=progId, next_run_time=exec_date, name=progId) # do not activate if another job is running else: webiopi.info("end prog %s ! another job is running ! do nothing" % progRun) except: webiopi.exception("! error activating program ! %s %s" % (sys.exc_info()[0], sys.exc_info()[1]))
def sendMessage(message): unquoted = unquote_plus(str(message)) webiopi.info("sendMessage: %s" % unquoted) global lastQuestion, lastAnswer lastQuestion = unquoted lastAnswer = ""
def printLifeformNo(no): webiopi.info("Lifeforms: " + str(no))