def execGeneral(next): global inp if "command" not in next: return False if next["command"] !="general": return False if "cmdLine" not in next: return False try: # execute unix command if next["cmdLine"].lower().find("sudo reboot")>-1 or next["cmdLine"].lower().find("sudo halt")>-1: os.system(next["cmdLine"] ) return True # execute set time command if next["cmdLine"].find("setTime")>-1: tt = time.time() items = next["cmdLine"].split("=") mactime = items[1] os.system('date -s "'+mactime+'"') mactt = time.mktime( datetime.datetime.strptime(mactime,"%Y-%m-%d %H:%M:%S.%f").timetuple() ) deltaTime = tt - mactt U.sendURL(data={"deltaTime":deltaTime},sendAlive="alive", wait=False) if "useRTC" in inp and inp["useRTC"] !="": os.system("hwclock --systohc") # set hw clock to system time stamp, only works if HW is enabled return True # execute set time command if next["cmdLine"].find("refreshNTP")>-1: U.startNTP() return True if next["cmdLine"].find("stopNTP")>-1: U.stopNTP() return True except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
def checkIfMSGtoBeSend(force=False): global lastCalcCheck, sendMSGEverySecs, ProgramStart, sensorMode, switchToLowerSensitive if time.time() - lastCalcCheck < max( sendMSGEverySecs, switchToLowerSensitive[status["currentMode"]]) and not force: return if time.time() - ProgramStart < 5: return rate, totalRain, measurementTime, nBuckets, nBucketsSinceReset = calcRates( ) data = {"sensors": {sensor: {}}} rainLevel = rainMsg[status["currentMode"]] for devId in sensors[sensor]: data["sensors"][sensor][devId] = { "rainRate": round(rate, 4), "totalRain": round(totalRain, 4), "nBucketsTotal": nBuckets, "nBuckets": nBucketsSinceReset, "measurementTime": round(measurementTime, 1), "mode": sensorMode, "sensitivity": status["currentMode"], "bucketSize": bucketSize[status["currentMode"]], "rainLevel": rainLevel } U.sendURL(data, wait=False) resetMes() if nBuckets < 4 and time.time() - lastCalcCheck > 40 and rainLevel > 1: checkIfDownGradedNeeded(force=True) U.writeRainStatus(status) lastCalcCheck = time.time()
def checkIfAliveNeedsToBeSend(): try: if time.time( ) - G.lastAliveSend > 330: # do we have to send alive signal to plugin? U.sendURL(sendAlive=True) except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e), permanentLog=True)
def sendShortStatus(level): global sensorMode, status, ProgramStart, lastShortMsgSend, lastShortMsg, bucketSize if time.time() - ProgramStart < 5: return if time.time() - lastShortMsgSend < 0.5: return data={"sensors":{sensor:{}}} for devId in sensors[sensor]: data["sensors"][sensor][devId] = {"rainLevel":level,"mode":sensorMode,"sensitivity":status["currentMode"],"bucketSize":bucketSize[status["currentMode"]] } if lastShortMsg != data["sensors"][sensor]: U.sendURL(data,wait=False) lastShortMsgSend = time.time() lastShortMsg = data["sensors"][sensor] return
def resetContinuousEvents(): global GPIOdict, contEVENT, sensor for gpio in GPIOdict: ggg = GPIOdict[gpio] if ggg["timeWindowForContinuousEvents"] > 0: igpio = int(gpio) if contEVENT[igpio] > 0: if tt - contEVENT[igpio] > ggg["timeWindowForContinuousEvents"]: contEVENT[igpio] = -1 # was expired send off then send ON data = {"sensors": {sensor: {ggg["devId"]: {}}}} data["sensors"][sensor][ggg["devId"]]["continuous"] = -1 U.sendURL(data, wait=False)
def resetContinuousEvents(): global GPIOdict, contEVENT, sensor for gpio in GPIOdict: ggg = GPIOdict[gpio] if ggg["timeWindowForContinuousEvents"] > 0: igpio= int(gpio) if contEVENT[igpio] > 0: if tt - contEVENT[igpio] > ggg["timeWindowForContinuousEvents"]: contEVENT[igpio] = -1 # was expired send off then send ON data = {"sensors":{sensor:{ggg["devId"]:{}}}} data["sensors"][sensor][ggg["devId"]]["continuous"] = -1 U.sendURL(data,wait=False)
def checkIfMSGtoBeSend(force =False): global lastCalcCheck, sendMSGEverySecs, ProgramStart, sensorMode, switchToLowerSensitive if time.time()- lastCalcCheck < max( sendMSGEverySecs, switchToLowerSensitive[status["currentMode"]] ) and not force: return if time.time() - ProgramStart < 5 : return rate, totalRain, measurementTime, nBuckets,nBucketsSinceReset= calcRates() data={"sensors":{sensor:{}}} rainLevel = rainMsg[status["currentMode"]] for devId in sensors[sensor]: data["sensors"][sensor][devId] = {"rainRate": round(rate,4), "totalRain": round(totalRain,4),"nBucketsTotal": nBuckets,"nBuckets": nBucketsSinceReset, "measurementTime":round(measurementTime,1),"mode":sensorMode,"sensitivity":status["currentMode"],"bucketSize":bucketSize[status["currentMode"]],"rainLevel":rainLevel} U.sendURL(data,wait=False) resetMes() if nBuckets < 4 and time.time()- lastCalcCheck > 40 and rainLevel > 1: checkIfDownGradedNeeded( force = True ) U.writeRainStatus(status) lastCalcCheck = time.time()
def sendShortStatus(level): global sensorMode, status, ProgramStart, lastShortMsgSend, lastShortMsg, bucketSize if time.time() - ProgramStart < 5: return if time.time() - lastShortMsgSend < 0.5: return data = {"sensors": {sensor: {}}} for devId in sensors[sensor]: data["sensors"][sensor][devId] = { "rainLevel": level, "mode": sensorMode, "sensitivity": status["currentMode"], "bucketSize": bucketSize[status["currentMode"]] } if lastShortMsg != data["sensors"][sensor]: U.sendURL(data, wait=False) lastShortMsgSend = time.time() lastShortMsg = data["sensors"][sensor] return
def execGeneral(next): global inp if "command" not in next: return False if next["command"] != "general": return False if "cmdLine" not in next: return False try: # execute unix command if next["cmdLine"].lower().find("sudo reboot") > -1 or next[ "cmdLine"].lower().find("sudo halt") > -1: os.system(next["cmdLine"]) return True # execute set time command if next["cmdLine"].find("setTime") > -1: tt = time.time() items = next["cmdLine"].split("=") mactime = items[1] os.system('date -s "' + mactime + '"') mactt = time.mktime( datetime.datetime.strptime(mactime, "%Y-%m-%d %H:%M:%S.%f").timetuple()) deltaTime = tt - mactt U.sendURL(data={"deltaTime": deltaTime}, sendAlive="alive", wait=False) if "useRTC" in inp and inp["useRTC"] != "": os.system( "hwclock --systohc" ) # set hw clock to system time stamp, only works if HW is enabled return True # execute set time command if next["cmdLine"].find("refreshNTP") > -1: U.startNTP() return True if next["cmdLine"].find("stopNTP") > -1: U.stopNTP() return True except Exception, e: U.toLog( -1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
oldmute = mute oldmono = mono oldhighCut = highCut oldnoiseCancel = noiseCancel oldbandLimit = bandLimit oldDTCon = DTCon oldPLLREF = PLLREF oldXTAL = XTAL oldHLSI = HLSI if len(okFrequencies) > 0: #for ii in range(len(okFrequencies)): # print ii, okFrequencies[ii] data={} data["setTEA5767"]={} data["setTEA5767"][devIdFound] = {"channels":okFrequencies} U.sendURL({"sensors":data}) fastMute ="" fastFreq ="" fastMono ="" time.sleep(1) readNew() if tt- lastParams > 5: readParams() lastParams= tt U.echoLastAlive(G.program) except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
if "devId" in command: devId = str(command["devId"]) else: devId = "0" import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) try: if cmd == "up": GPIO.setup(pin, GPIO.OUT) if inverseGPIO: GPIO.output(pin, False) U.sendURL({"outputs":{"OUTPUTgpio-1-ONoff":{devId:{"actualGpioValue":"low"}}}}) else: GPIO.output(pin, True) U.sendURL({"outputs":{"OUTPUTgpio-1-ONoff":{devId:{"actualGpioValue":"high"}}}}) elif cmd == "down": GPIO.setup(pin, GPIO.OUT) if inverseGPIO: GPIO.output(pin, True) U.sendURL({"outputs":{"OUTPUTgpio-1-ONoff":{devId:{"actualGpioValue":"high"}}}}) else: GPIO.output(pin, False ) U.sendURL({"outputs":{"OUTPUTgpio-1-ONoff":{devId:{"actualGpioValue":"low"}}}}) elif cmd == "analogWrite":
def doSensors(pkt,UUID,Maj,Min,mac,rx,tx): global BLEsensorMACs, sensor try: data ={sensor:{}} if mac not in BLEsensorMACs: return if time.time() - BLEsensorMACs[mac]["lastUpdate"] < BLEsensorMACs[mac]["updateIndigoTiming"]: #print "rejecting ", time.time() - BLEsensorMACs[mac]["lastUpdate"] , BLEsensorMACs[mac]["updateIndigoTiming"] return #print "accepting ", time.time() - BLEsensorMACs[mac]["lastUpdate"] , BLEsensorMACs[mac]["updateIndigoTiming"] BLEsensorMACs[mac]["lastUpdate"] = time.time() devId = BLEsensorMACs[mac]["devId"] data = {sensor:{devId:{}}} if BLEsensorMACs[mac]["type"] =="myBLUEt": RawData = list(struct.unpack("BBB", pkt[31:34])) # get bytes # 31,32,33 (starts at # 0 , #33 has sign, if !=0 subtract 2**15 if RawData[2] != 0: tSign = 0x10000 # == 65536 == 2<<15 else: tSign = 0 r8 = RawData[1] << 8 sensorData = ( r8 + RawData[0] - tSign ) /100. UUID = UUID[0:12]+"-"+Maj+"-"+Min try: temp = (sensorData + BLEsensorMACs[mac]["offsetTemp"]) * BLEsensorMACs[mac]["multiplyTemp"] except: temp = sensorData data[sensor][devId] = {"temp":temp,"type":BLEsensorMACs[mac]["type"],"mac":mac,"rssi":float(rx),"txPower":float(tx),"UUID":UUID} elif BLEsensorMACs[mac]["type"] =="blueRadio": return #RawData = list(struct.unpack("BBB", pkt[31:34])) # get bytes # 31,32,33 (starts at # 0 , #33 has sign, if !=0 subtract 2**15 #if RawData[2] != 0: tSign = 0x10000 # == 65536 == 2<<15 #else: tSign = 0 #r8 = RawData[1] << 8 #sensorData = ( r8 + RawData[0] - tSign ) /100. #UUID = UUID[0:12]+"-"+Maj+"-"+Min #try: temp = (sensorData + BLEsensorMACs[mac]["offsetTemp"]) * BLEsensorMACs[mac]["multiplyTemp"] #except: temp = sensorData #data[sensor][devId] = {"temp":temp,"type":BLEsensorMACs[mac]["type"],"mac":mac,"rssi":float(rx),"txPower":float(tx),"UUID":UUID} elif BLEsensorMACs[mac]["type"] =="windWeatherFlow": print mac, UUID, Maj,Min,"pkt: ", len(pkt), pkt RawData = list(struct.unpack("BBBBBBBBB", pkt[31:31+(2+2+2+2+1)])) # get 25 bytes print "RawData: ", RawData start= 0 name = "", RawData[0:16] wind = (RawData[start+0] <<8 + RawData[start+2])/10. temp = (RawData[start+2] <<8 + RawData[start+4])/10. windC = (RawData[start+4] <<8 + RawData[start+8])/10. Batt = (RawData[start+6] <<8 + RawData[start+8])/10. pow = RawData[start+8] UUID = UUID[0:12]+"-"+Maj+"-"+Min sensor = "BLEsensor" devId = BLEsensorMACs[mac]["devId"] try: wind = (wind + BLEsensorMACs[mac]["offsetWind"]) * BLEsensorMACs[mac]["multiplyWind"] except: wind = wind try: temp = (temp + BLEsensorMACs[mac]["offsetTemp"]) * BLEsensorMACs[mac]["multiplyTemp"] except: temp = temp data[sensor][devId] = {"temp":temp,"Wind":wind,"WindChill":windC,"Battery":Batt,"Power":pow, "type":BLEsensorMACs[mac]["type"],"mac":mac,"rssi":float(rx),"txPower":float(tx),"UUID":UUID} print "wind, temp, windC, Batt, pow ", wind, temp, windC, Batt, pow if data[sensor][devId] !={}: U.sendURL({"sensors":data}) except Exception, e: U.toLog(-1,u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)) print u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)
if sensor in sensors: # data["sensors"] = {sensor: {}} for id in sensors[sensor]: data["sensors"][sensor][id] = {} v = checkIfRunning(launchCheck[id]) if v != "not checked": if v == "not running": startSensors(launchCommand[id]) v = checkIfRunning(launchCheck[id]) data["sensors"][sensor][id]["status"] = v ### send data to plugin if loopCount % 1 == 0 or quick or lastData != data: if data != {} and (time.time() - lastMsg > minSendDelta): lastMsg = time.time() U.sendURL(data, squeeze=False) lastData = copy.copy(data) # check if we should send data now, requested by plugin quick = U.checkNowFile(G.program) # make alive file for mast to signal we are still running if loopCount % 20 == 0: U.echoLastAlive(G.program) except Exception, e: U.toLog( -1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)) time.sleep(sensorRefreshSecs) # sleep the requested amount
def checkIfAliveNeedsToBeSend(): try: if time.time() - G.lastAliveSend> 330: # do we have to send alive signal to plugin? U.sendURL(sendAlive=True ) except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e),permanentLog=True)
cmd = "sudo hciconfig " dataW = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate() U.toLog(1, unicode(dataW)) data = {"BLEreport":{}} data["BLEreport"]["hciconfig"] = dataW cmd = "sudo hciconfig hci0 down; sudo hciconfig hci0 up ; sudo timeout -s SIGINT 15s hcitool lescan " dataW = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate() U.toLog(1, unicode(dataW)) data["BLEreport"]["hcitool lescan"] = dataW cmd = "sudo timeout -s SIGINT 25s hcitool scan " dataW = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate() U.toLog(1, unicode(dataW)) data["BLEreport"]["hcitool scan"] = dataW U.toLog(1, unicode(data)) U.sendURL(data,squeeze=False) time.sleep(2) os.system("sudo reboot") exit() except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)) continue if "device" not in next: U.toLog(-1," bad cmd no device given "+unicode(next)) continue device=next["device"]
tt = time.time() data = {"sensors": {}} sendNOW = False if sensor in sensors: data["sensors"] = {sensor:{}} for devId in sensors[sensor]: if devId not in lastValue: lastValue[devId] =-500. values = getValues(devId) if values == "": continue data["sensors"][sensor][devId] = {} if values =="badSensor": sensorWasBad = True data["sensors"][sensor][devId]["current"]="badSensor" if badSensor < 5: U.toLog(-1," bad sensor") U.sendURL(data) lastValue[devId] =-100. continue elif values["temp"] !="" : if sensorWasBad: # sensor was bad, back up again, need to do a restart to set config U.restartMyself(reason=" back from bad sensor, need to restart to get sensors reset",doPrint="False") data["sensors"][sensor][devId] = values current = float(values["temp"]) delta = current-lastValue[devId] deltaN = abs(delta) / max (0.5,(current+lastValue[devId])/2.) else: continue #print values, deltaN, deltaX[devId] if ( ( deltaN > deltaX[devId] ) or ( tt - abs(G.sendToIndigoSecs) > G.lastAliveSend ) or
def handle_interrupt(channel): global as3935sensor,sensors, sensor, lastEvent, lastTime, lastSend, restartNeededCounter, interruptGPIO, calibrationDynamic global noiseFlorSet time.sleep(0.003) if interruptGPIO != channel: return if sensor in sensors: data = {"sensors": {sensor:{}}} msg ={} for devId in sensors[sensor]: distance = -1 energy = 0 reason = as3935sensor[devId].get_interrupt() lastEvent = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") lastTime = time.time() #print "event; reason: ",reason, lastEvent msg = {"eventType":"measurement","lightning":"","distance":-1,"energy":-1} if reason == 1: if noiseFlorSet < 7 and calibrationDynamic == 1: msg["lightning"] = "Noise level too high - adjusting" as3935sensor[devId].raise_noise_floor() restartNeededCounter =0 else: msg["lightning"] = "Noise level too high - no adjustment due to setting" elif reason == 4: if calibrationDynamic == 1 : msg["lightning"] = "Disturber detected - masking" as3935sensor[devId].set_mask_disturber(True) restartNeededCounter =0 else: msg["lightning"] = "Disturber detected - no masking due to setting" elif reason == 8: energy = as3935sensor[devId].get_energy() distance = as3935sensor[devId].get_distance() msg["lightning"] = "lightning detected" msg["distance"] = distance msg["energy"] = energy restartNeededCounter =0 elif reason == 255: U.toLog(0, "read error", doPrint=True) restartNeededCounter +=1 continue elif reason == 0: U.toLog(0, "nothing read, skipping event ", doPrint=True) continue else: U.toLog(0, "unknown read error, reason: "+unicode(reason), doPrint=True) restartNeededCounter +=1 continue if msg !="lightning detected": #print "reject ", msg if time.time() - lastSend < 180: return data["sensors"][sensor][devId]=msg U.toLog(1, " sending:"+ unicode(data), doPrint=False) U.sendURL(data,squeeze=False) msg["lastEvent"] = lastEvent msg["lastTime"] = lastTime lastSend = time.time() f=open(G.homeDir+"lightning.dat","w") f.write(json.dumps(msg)) f.close()
def fillGPIOdict(gpio, risingOrFalling): global INPUTcount, GPIOdict, sensor, BURSTS, lastGPIO, longEVENT, contEVENT, sensors ggg = GPIOdict[str(gpio)] tt = time.time() countChanged = False if tt - ggg["lastSignal"] > ggg["deadTime"]: ggg["count"] += 1 INPUTcount[int(gpio)] += 1 ggg["lastSignal"] = tt U.toLog( 2, risingOrFalling + " edge on %d2" % gpio + " gpio, count: %d" % ggg["count"] + ", timest: %6.1f" % tt + ", lastSendC: %6.1f" % ggg["lastsendCount"] + ", minSendDelta: %d" % ggg["minSendDelta"]) countChanged = True ############### this EVENTtype requires a minBurstsinTimeWindowToTrigger in timeWindowForBursts to trigger ### burst = 0 bbb = BURSTS[gpio] if ggg["minBurstsinTimeWindowToTrigger"] > 0: ll = len(bbb) for kk in range(ll): ii = ll - kk - 1 if tt - bbb[ii][0] > ggg["timeWindowForBursts"]: del bbb[ii] U.toLog( 2, "BURST: " + str(ll) + " " + str(tt) + " " + str(bbb) + " " + str(ggg["timeWindowForBursts"])) ll = len(bbb) if ll == 0 or tt - bbb[-1][0] < ggg["deadTimeBurst"]: bbb.append([tt, 1]) U.toLog(2, "BURST: in window " + str(ggg["timeWindowForBursts"])) ll += 1 delupto = -1 for kk in range(ll): ii = ll - kk - 1 bbb[ii][1] += 1 if bbb[ii][1] >= ggg["minBurstsinTimeWindowToTrigger"]: U.toLog( 2, "BURST triggered " + risingOrFalling + " edge .. on %d2" % gpio + " gpio, burst# " + unicode(ii) + "; #signals=" + unicode(bbb[ii][1]) + "-- in " + unicode(ggg["timeWindowForBursts"]) + "secs time window") burst = tt delupto = ii - 1 break if delupto > 0: for kk in range(delupto): del bbb[delupto - kk - 1] ############### this EVENTtype requires a pulse every second for timeWindowForLongEvents seconds ### lEVENTtt = 0 bbb = longEVENT[gpio] if ggg["timeWindowForLongEvents"] > 0: U.toLog( 2, "longEVENT(1): " + str(ll) + " " + str(tt) + "; timeWindowForLongEvents: " + str(ggg["timeWindowForLongEvents"]) + " secs") ll = len(bbb) if True: bbb.append([tt, tt + ggg["pulseEveryXXsecsLongEvents"]]) U.toLog(2, "contEVENT(2): in window ; N events=" + unicode(ll)) ll += 1 delupto = -1 for kk in range(ll): ii = ll - kk - 1 delta1 = tt - bbb[ii][1] delta0 = tt - bbb[ii][0] if delta1 > 0. and delupto == -1: delupto = ii - 1 U.toLog(2, "longEVENT(3) rejected ") continue if delta0 >= ggg["timeWindowForLongEvents"]: U.toLog(2, "longEVENT(4) triggered ") lEVENTtt = tt delupto = ii - 1 bbb[ii][1] = tt + ggg["pulseEveryXXsecsLongEvents"] if delupto > 0: for kk in range(delupto): del bbb[delupto - kk - 1] ############### this EVENTtype requires a pulse to start the CONT event, will extend event if new pulse arrives before timeWindowForContinuousEvents is over ### cEVENTtt = 0 if ggg["timeWindowForContinuousEvents"] > 0: if contEVENT[gpio] == -1 or contEVENT[gpio] == 0: # new event cEVENTtt = tt elif tt - contEVENT[gpio] > ggg["timeWindowForContinuousEvents"]: # was expired send off then send ON data = {"sensors": {sensor: {ggg["devId"]: {}}}} data["sensors"][sensor][ggg["devId"]]["continuous"] = -1 U.sendURL(data, wait=False) time.sleep(0.01) cEVENTtt = tt # or just conti nue old c event = just update contEVENT not need to send data contEVENT[gpio] = tt U.toLog(2, "cEVENT(1): " + str(tt) + "; cEVENTtt=" + unicode(cEVENTtt)) data = {"sensors": {sensor: {ggg["devId"]: {}}}} if (tt - ggg["lastsendBurst"] > ggg["minSendDelta"]) and burst > 0: data["sensors"][sensor][ggg["devId"]]["burst"] = int(burst) data["sensors"][sensor][ggg["devId"]]["count"] = ggg["count"] ggg["lastsendBurst"] = tt ggg["lastsendCount"] = tt if burst > 0: lastGPIO = U.doActions(data["sensors"], lastGPIO, sensors, sensor, theAction="1") if (tt - ggg["lastsendContinuousEvent"] > ggg["minSendDelta"]) and cEVENTtt > 0: data["sensors"][sensor][ggg["devId"]]["continuous"] = int(cEVENTtt) data["sensors"][sensor][ggg["devId"]]["count"] = ggg["count"] ggg["lastsendContinuousEvent"] = tt ggg["lastsendCount"] = tt if cEVENTtt > 0: lastGPIO = U.doActions(data["sensors"], lastGPIO, sensors, sensor, theAction="3") if (tt - ggg["lastsendlongEvent"] > ggg["minSendDelta"]) and lEVENTtt > 0: data["sensors"][sensor][ggg["devId"]]["longEvent"] = int(lEVENTtt) data["sensors"][sensor][ggg["devId"]]["count"] = ggg["count"] ggg["lastsendlongEvent"] = tt ggg["lastsendCount"] = tt if lEVENTtt > 0: lastGPIO = U.doActions(data["sensors"], lastGPIO, sensors, sensor, theAction="2") if (tt - ggg["lastsendCount"] > ggg["minSendDelta"]) and countChanged: data["sensors"][sensor][ggg["devId"]]["count"] = ggg["count"] ggg["lastsendCount"] = tt if data["sensors"][sensor][ggg["devId"]] != {}: U.sendURL(data, wait=False) U.writeINPUTcount(INPUTcount)
def doSensors(pkt, UUID, Maj, Min, mac, rx, tx): global BLEsensorMACs, sensor try: data = {sensor: {}} if mac not in BLEsensorMACs: return if time.time() - BLEsensorMACs[mac]["lastUpdate"] < BLEsensorMACs[mac][ "updateIndigoTiming"]: #print "rejecting ", time.time() - BLEsensorMACs[mac]["lastUpdate"] , BLEsensorMACs[mac]["updateIndigoTiming"] return #print "accepting ", time.time() - BLEsensorMACs[mac]["lastUpdate"] , BLEsensorMACs[mac]["updateIndigoTiming"] BLEsensorMACs[mac]["lastUpdate"] = time.time() devId = BLEsensorMACs[mac]["devId"] data = {sensor: {devId: {}}} if BLEsensorMACs[mac]["type"] == "myBLUEt": RawData = list( struct.unpack("BBB", pkt[31:34]) ) # get bytes # 31,32,33 (starts at # 0 , #33 has sign, if !=0 subtract 2**15 if RawData[2] != 0: tSign = 0x10000 # == 65536 == 2<<15 else: tSign = 0 r8 = RawData[1] << 8 sensorData = (r8 + RawData[0] - tSign) / 100. UUID = UUID[0:12] + "-" + Maj + "-" + Min try: temp = (sensorData + BLEsensorMACs[mac]["offsetTemp"] ) * BLEsensorMACs[mac]["multiplyTemp"] except: temp = sensorData data[sensor][devId] = { "temp": temp, "type": BLEsensorMACs[mac]["type"], "mac": mac, "rssi": float(rx), "txPower": float(tx), "UUID": UUID } elif BLEsensorMACs[mac]["type"] == "blueRadio": return #RawData = list(struct.unpack("BBB", pkt[31:34])) # get bytes # 31,32,33 (starts at # 0 , #33 has sign, if !=0 subtract 2**15 #if RawData[2] != 0: tSign = 0x10000 # == 65536 == 2<<15 #else: tSign = 0 #r8 = RawData[1] << 8 #sensorData = ( r8 + RawData[0] - tSign ) /100. #UUID = UUID[0:12]+"-"+Maj+"-"+Min #try: temp = (sensorData + BLEsensorMACs[mac]["offsetTemp"]) * BLEsensorMACs[mac]["multiplyTemp"] #except: temp = sensorData #data[sensor][devId] = {"temp":temp,"type":BLEsensorMACs[mac]["type"],"mac":mac,"rssi":float(rx),"txPower":float(tx),"UUID":UUID} elif BLEsensorMACs[mac]["type"] == "windWeatherFlow": print mac, UUID, Maj, Min, "pkt: ", len(pkt), pkt RawData = list( struct.unpack("BBBBBBBBB", pkt[31:31 + (2 + 2 + 2 + 2 + 1)])) # get 25 bytes print "RawData: ", RawData start = 0 name = "", RawData[0:16] wind = (RawData[start + 0] << 8 + RawData[start + 2]) / 10. temp = (RawData[start + 2] << 8 + RawData[start + 4]) / 10. windC = (RawData[start + 4] << 8 + RawData[start + 8]) / 10. Batt = (RawData[start + 6] << 8 + RawData[start + 8]) / 10. pow = RawData[start + 8] UUID = UUID[0:12] + "-" + Maj + "-" + Min sensor = "BLEsensor" devId = BLEsensorMACs[mac]["devId"] try: wind = (wind + BLEsensorMACs[mac]["offsetWind"] ) * BLEsensorMACs[mac]["multiplyWind"] except: wind = wind try: temp = (temp + BLEsensorMACs[mac]["offsetTemp"] ) * BLEsensorMACs[mac]["multiplyTemp"] except: temp = temp data[sensor][devId] = { "temp": temp, "Wind": wind, "WindChill": windC, "Battery": Batt, "Power": pow, "type": BLEsensorMACs[mac]["type"], "mac": mac, "rssi": float(rx), "txPower": float(tx), "UUID": UUID } print "wind, temp, windC, Batt, pow ", wind, temp, windC, Batt, pow if data[sensor][devId] != {}: U.sendURL({"sensors": data}) except Exception, e: U.toLog( -1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)) print u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)
timeOKCalibration[devId ] = 0 if loopCount ==0: calibTime = time.time() calibrateSensor(devId) loopCount +=1 values = getValues(devId, nMeasurements=3 ) if values == "": continue data["sensors"][sensor][devId]={} if values =="badSensor": sensorWasBad = True data["sensors"][sensor][devId]="badSensor" if badSensor < 5: U.toLog(-1," bad sensor") U.sendURL(data) else: U.restartMyself(param="", reason="badsensor",doPrint=True) lastValues[devId] =copy.copy(lastValues0) if badSensor > 5: reStartReq = True continue elif values["CO2"] !="" : if sensorWasBad: # sensor was bad, back up again, need to do a restart to set config U.restartMyself(reason=" back from bad sensor, need to restart to get sensors reset",doPrint="False") if values["raw"] < 300: U.restartMyself(reason=" sensor value below 300ppm, need to restart to get sensors reset, waiting 2 minute ",doPrint="False") time.sleep(120.) data["sensors"][sensor][devId] = values needCalibration = False x1 = data["sensors"][sensor][devId]["CO2"] - CO2normal[devId]
##U.checkIfAliveNeedsToBeSend(lastMsg) if time.time()- lastRead > 10: readParams() lastRead = time.time() if restart: U.restartMyself(param="", reason=" new definitions",doPrint=True) if loopCount%100==0: U.echoLastAlive(G.program) if loopCount%100==0 or countReset: data={"sensors":{sensor:{}}} for gpio in GPIOdict: if "devId" not in GPIOdict[gpio]: continue data["sensors"][sensor][GPIOdict[gpio]["devId"]]={"count": GPIOdict[gpio]["count"],"burst":0} U.sendURL(data,wait=False) countReset = False loopCount+=1 time.sleep(shortWait) except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e),doPrint=True) time.sleep(5.) sys.exit(0)
def fillGPIOdict(gpio,risingOrFalling): global INPUTcount, GPIOdict, sensor, BURSTS, lastGPIO, longEVENT, contEVENT, sensors ggg = GPIOdict[str(gpio)] tt= time.time() countChanged = False if tt- ggg["lastSignal"] > ggg["deadTime"]: ggg["count"]+=1 INPUTcount[int(gpio)]+=1 ggg["lastSignal"] = tt U.toLog(2, risingOrFalling+" edge on %d2"%gpio+" gpio, count: %d"% ggg["count"]+", timest: %6.1f"%tt+", lastSendC: %6.1f"%ggg["lastsendCount"]+", minSendDelta: %d"%ggg["minSendDelta"]) countChanged = True ############### this EVENTtype requires a minBurstsinTimeWindowToTrigger in timeWindowForBursts to trigger ### burst=0 bbb = BURSTS[gpio] if ggg["minBurstsinTimeWindowToTrigger"] > 0: ll =len(bbb) for kk in range(ll): ii = ll - kk -1 if tt-bbb[ii][0] > ggg["timeWindowForBursts"]: del bbb[ii] U.toLog(2, "BURST: "+str(ll)+" "+str(tt)+" "+ str(bbb)+" "+str(ggg["timeWindowForBursts"] )) ll =len(bbb) if ll == 0 or tt - bbb[-1][0] < ggg["deadTimeBurst"]: bbb.append([tt,1]) U.toLog(2, "BURST: in window "+str(ggg["timeWindowForBursts"])) ll +=1 delupto = -1 for kk in range(ll): ii = ll - kk -1 bbb[ii][1]+=1 if bbb[ii][1] >= ggg["minBurstsinTimeWindowToTrigger"]: U.toLog(2, "BURST triggered "+ risingOrFalling+" edge .. on %d2"%gpio+" gpio, burst# "+unicode(ii)+"; #signals="+ unicode(bbb[ii][1])+ "-- in "+ unicode(ggg["timeWindowForBursts"]) +"secs time window") burst = tt delupto = ii-1 break if delupto >0: for kk in range(delupto): del bbb[delupto - kk -1] ############### this EVENTtype requires a pulse every second for timeWindowForLongEvents seconds ### lEVENTtt=0 bbb = longEVENT[gpio] if ggg["timeWindowForLongEvents"] > 0: U.toLog(2, "longEVENT(1): "+str(ll)+" "+str(tt)+"; timeWindowForLongEvents: "+str(ggg["timeWindowForLongEvents"])+" secs" ) ll =len(bbb) if True: bbb.append([tt,tt+ggg["pulseEveryXXsecsLongEvents"]]) U.toLog(2, "contEVENT(2): in window ; N events="+ unicode(ll) ) ll += 1 delupto = -1 for kk in range(ll): ii = ll - kk -1 delta1 = tt - bbb[ii][1] delta0 = tt - bbb[ii][0] if delta1 > 0. and delupto == -1: delupto = ii-1 U.toLog(2, "longEVENT(3) rejected ") continue if delta0 >= ggg["timeWindowForLongEvents"]: U.toLog(2, "longEVENT(4) triggered ") lEVENTtt = tt delupto = ii-1 bbb[ii][1] = tt+ggg["pulseEveryXXsecsLongEvents"] if delupto >0: for kk in range(delupto): del bbb[delupto - kk -1] ############### this EVENTtype requires a pulse to start the CONT event, will extend event if new pulse arrives before timeWindowForContinuousEvents is over ### cEVENTtt=0 if ggg["timeWindowForContinuousEvents"] > 0: if contEVENT[gpio] == -1 or contEVENT[gpio] == 0: # new event cEVENTtt = tt elif tt - contEVENT[gpio] > ggg["timeWindowForContinuousEvents"]: # was expired send off then send ON data = {"sensors":{sensor:{ggg["devId"]:{}}}} data["sensors"][sensor][ggg["devId"]]["continuous"] = -1 U.sendURL(data,wait=False) time.sleep(0.01) cEVENTtt = tt # or just conti nue old c event = just update contEVENT not need to send data contEVENT[gpio] = tt U.toLog(2, "cEVENT(1): "+str(tt)+"; cEVENTtt="+ unicode(cEVENTtt) ) data = {"sensors":{sensor:{ggg["devId"]:{}}}} if (tt - ggg["lastsendBurst"] > ggg["minSendDelta"]) and burst > 0 : data["sensors"][sensor][ggg["devId"]]["burst"] = int(burst) data["sensors"][sensor][ggg["devId"]]["count"] = ggg["count"] ggg["lastsendBurst"] = tt ggg["lastsendCount"] = tt if burst >0: lastGPIO= U.doActions(data["sensors"],lastGPIO, sensors, sensor,theAction="1") if (tt - ggg["lastsendContinuousEvent"] > ggg["minSendDelta"]) and cEVENTtt > 0 : data["sensors"][sensor][ggg["devId"]]["continuous"] = int(cEVENTtt) data["sensors"][sensor][ggg["devId"]]["count"] = ggg["count"] ggg["lastsendContinuousEvent"] = tt ggg["lastsendCount"] = tt if cEVENTtt >0: lastGPIO= U.doActions(data["sensors"],lastGPIO, sensors, sensor,theAction="3") if (tt - ggg["lastsendlongEvent"] > ggg["minSendDelta"]) and lEVENTtt > 0 : data["sensors"][sensor][ggg["devId"]]["longEvent"] = int(lEVENTtt) data["sensors"][sensor][ggg["devId"]]["count"] = ggg["count"] ggg["lastsendlongEvent"] = tt ggg["lastsendCount"] = tt if lEVENTtt >0: lastGPIO= U.doActions(data["sensors"],lastGPIO, sensors, sensor,theAction="2") if (tt - ggg["lastsendCount"] > ggg["minSendDelta"]) and countChanged: data ["sensors"][sensor][ggg["devId"]]["count"] = ggg["count"] ggg["lastsendCount"] = tt if data["sensors"][sensor][ggg["devId"]] !={}: U.sendURL(data,wait=False) U.writeINPUTcount(INPUTcount)
data["sensors"] = {} speed = 0 distance = 0 if sensor in sensors: for devId in sensors[sensor]: if devId not in lastDist: lastDist[devId] = -500. lastTime[devId] = 0. distance = getDistance() data["sensors"] = {sensor: {}} data["sensors"][sensor] = {devId: {}} if distance == "badSensor": first = True U.toLog(-1, " bad sensor") data["sensors"][sensor][devId]["distance"] = "badSensor" U.sendURL(data) lastDist[devId] = -100. continue elif distance != "": data["sensors"][sensor][devId]["distance"] = distance dist = float(distance) delta = dist - lastDist[devId] deltaN = abs(delta) / max(0.5, (dist + lastDist[devId]) / 2.) if loopCount % 20 == 0 or deltaN > 0.1: lux = getLight() if lux != "": data["sensors"][sensor][devId]["lux"] = lux lastLux = float(lux) else: data["sensors"][sensor][devId]["lux"] = lastLux
if "devId" in command: devId = str(command["devId"]) else: devId = "0" import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) try: if cmd == "up": GPIO.setup(pin, GPIO.OUT) if inverseGPIO: GPIO.output(pin, False) U.sendURL({"outputs":{"OUTPUTgpio-1-ONoff":{devId:{"actualGpioValue":"low"}}}}) else: GPIO.output(pin, True) U.sendURL({"outputs":{"OUTPUTgpio-1-ONoff":{devId:{"actualGpioValue":"high"}}}}) elif cmd == "down": GPIO.setup(pin, GPIO.OUT) if inverseGPIO: GPIO.output(pin, True) U.sendURL({"outputs":{"OUTPUTgpio-1-ONoff":{devId:{"actualGpioValue":"high"}}}}) else: GPIO.output(pin, False ) U.sendURL({"outputs":{"OUTPUTgpio-1-ONoff":{devId:{"actualGpioValue":"low"}}}}) elif cmd == "analogWrite":
break except Exception, e: #print e #print lastData[sens][dd] #print data[sens][dd] changed = 7 break # print "changed", changed, tt-lastMsg, G.sendToIndigoSecs , tt-lastMsg, G.deltaChangedSensor, data if data != {} and (changed > 0 or ((tt - lastMsg) > G.sendToIndigoSecs or (tt - lastMsg) > 200)): lastMsg = tt lastData = copy.copy(data) try: #U.toLog(2, u"sending url: "+unicode(data)) U.sendURL({"sensors": data}) except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e), permanentLog=True) time.sleep(0.05) quick = U.checkNowFile(G.program) U.makeDATfile(G.program, data) U.echoLastAlive(G.program) tt = time.time() NSleep = int(sensorRefreshSecs) * 2 if tt - lastregularCycle > sensorRefreshSecs:
if restart: U.restartMyself(param="", reason=" new definitions", doPrint=True) if loopCount % 100 == 0: U.echoLastAlive(G.program) if loopCount % 100 == 0 or countReset: data = {"sensors": {sensor: {}}} for gpio in GPIOdict: if "devId" not in GPIOdict[gpio]: continue data["sensors"][sensor][GPIOdict[gpio]["devId"]] = { "count": GPIOdict[gpio]["count"], "burst": 0 } U.sendURL(data, wait=False) countReset = False loopCount += 1 time.sleep(shortWait) except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e), doPrint=True) time.sleep(5.) sys.exit(0)