def getCurrentPatterns(): global marksONoff, hoursPix, minutesPix, ticksMMHH global clockDict, inp try: if clockDict["ticks"]["MM"]["npix"] ==1: minutesPix = 1 else: minutesPix = -1 if clockDict["ticks"]["HH"]["ringNo"] ==[8,1]: hoursPix = 1 elif clockDict["ticks"]["HH"]["ringNo"] ==[8,6,4]: hoursPix = 3 else: hoursPix = 4 if minutesPix == 1 and hoursPix ==1: ticksMMHH = 0 # this is the fewest pixel mode elif minutesPix == 1 and hoursPix ==3: ticksMMHH = 1 elif minutesPix == 1 and hoursPix ==4: ticksMMHH = 2 elif minutesPix == -1 and hoursPix ==3: ticksMMHH = 3 elif minutesPix == -1 and hoursPix ==4: ticksMMHH = 4 else: ticksMMHH = 4 if clockDict["marks"]["MM"]["marks"] == []: marksONoff = 0 # = no marks elif clockDict["marks"]["MM"]["marks"] == [0, 15, 30, 45]: marksONoff = 1 else: #must be:[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55] if clockDict["marks"]["SS"]["marks"] == []: marksONoff = 2 elif clockDict["marks"]["HH"]["marks"] == [0]: marksONoff = 4 else: marksONoff = 3 except Exception, e: print u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e) U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)) print "clockDict=", clockDict,"<<"
def setPatternTo(ticks="" ,marks="", save=True, restart=True, ExtraLED=False): global inp, clockDict, DEVID global ticksOptions, marksOptions try: if ticks !="": clockDict["ticks"] = copy.copy(ticksOptions[ticks]) inp["output"]["neopixelClock"][DEVID][0]["ticks"] = copy.copy(ticksOptions[ticks]) if marks !="": clockDict["marks"] = copy.copy(marksOptions[marks]) inp["output"]["neopixelClock"][DEVID][0]["marks"] = copy.copy(marksOptions[marks]) if ExtraLED and ticks !="" and marks !="": l0 = 60 + 48 + 40 +32 +1 clockDict["extraLED"] = {"ticks":[ii+l0 for ii in range(ticks+4*marks)], "RGB":[100,100,100],"blink":[1,0]} # start on 8 ring getCurrentPatterns() if save: saveParameters() if restart: startNEOPIXEL() except Exception, e: print u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e) U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)) print "clockDict", clockDict print "inp", inp print "DEVID", DEVID print "ticks", ticks print "marks", marks
def setTimeZone(upDown): global clockLightSet, enableupDown,enableHH,enableMM,enableDD,enableDDonOFF, enableTZset,enablePattern,enableLight,currHH, currMM, currDD, currTZ, useRTC, newDate, resetGPIO, lastButtonTime, switchON global inp, DEVID, clockDict global timeZones,timeZone l0=60 + 48 + 40 + 32 +1 ind = currTZ U.toLog(1,"set timezone "+ upDown) if upDown =="UP": ind +=1 else: ind -=1 if ind > 12: ind = 12 if ind <-12: ind = -12 tz= timeZones[ind+12] currTZ = ind U.toLog(0, 'set tz: '+upDown+ ' new tz: '+ str(ind)+" "+tz) clockDict["extraLED"] = {"ticks":[ii+l0 for ii in range(ind+12)], "RGB":[100,100,100],"blink":[1,0]} # start on 8 ring clockDict["clockLightSet"] = clockLightSet inp["output"]["neopixelClock"][DEVID][0]["clockLightSet"] = clockDict["clockLightSet"] inp["output"]["neopixelClock"][DEVID][0]["extraLED"] = clockDict["extraLED"] writeTZ(tz) #print "timeZone", inp["output"]["neopixelClock"][DEVID][0]["timeZone"] startNEOPIXEL() return
def downPressed(gpio): global clockDict, clockLightSet, enableupDown,enableHH,enableMM,enableDD,enableDDonOFF, enableTZset,enablePattern,enableLight,currHH, currMM, currDD, currTZ, useRTC, newDate, resetGPIO, lastButtonTime, switchON if not enableupDown: return button = "DOWN" if checkLastButtonPressTiming(button) !=0: return time.sleep(0.1) U.toLog(1, button+" button") if enableHH: currHH -=1 if currHH < 0: currHH = 23 if currHH > 23: currHH = 0 clockDict["extraLED"] = {"ticks":[currHH*2 + 60 + 48 + 40 + 32 ], "RGB":[200,200,200],"blink":[1,0]} # start on 8 ring startNEOPIXELNewTime(currHH, currMM, currDD) elif enableMM: currMM -=1 if currMM < 0: currMM = 59 if currMM > 59: currMM = 0 clockDict["extraLED"] = {"ticks":[currMM ], "RGB":[200,200,200],"blink":[1,0]} # start on 8 ring startNEOPIXELNewTime(currHH, currMM, currDD) elif enableDD: currDD -=1 startNEOPIXELNewTime(currHH, currMM, currDD) elif enableTZset: setTimeZone("DOWN") elif enableLight: setLIGHT("DOWN") elif enablePattern: setPatternUPdown("DOWN") elif enableDDonOFF: showNWstatus() return
def setModeTo(newMode, calledFrom="", powerCycle=True, force=False): global nextModeSwitchNotBefore, minTimeBetweenModeSwitch global status, ProgramStart #if time.time() - ProgramStart < 20: return U.toLog(0, "try to set new mode " + newMode + " from " + status["currentMode"] + " tt - nextModeSwitchNotBefore: " + str(time.time() - nextModeSwitchNotBefore) + " called from: " + calledFrom, doPrint=doPrint) if (time.time() - nextModeSwitchNotBefore < 0) and not force: return False U.toLog(0, "setting mode to: " + newMode + "; from currrentMode: " + status["currentMode"], doPrint=False) if status["currentMode"] != newMode or force: setSwitch(newMode, powerCycle=powerCycle) status["lastMode"] = status["currentMode"] status["currentMode"] = newMode nextModeSwitchNotBefore = time.time() + 3 return True return False
def startMCP3008(devId): global spi0,spi1 spiAdd=0 try: ss= "" if "spiMCP3008" in sensors: ss="spiMCP3008" if "spiMCP3008-1" in sensors: ss="spiMCP3008-1" if ss!="" : if sensors[ss][devId]["spiAddress"]!="": spiAdd=int(sensors[ss][devId]["spiAddress"]) if spiAdd >1 : spiAdd = 1 if spiAdd <0 : spiAdd = 0 if spiAdd == 0: spi0 = spidev.SpiDev() spi0.open(0,0) if spiAdd == 1: spi1 = spidev.SpiDev() spi1.open(0,1) #print spiAdd, spi0,spi1 except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)) U.toLog(-1, u"spi channel used: "+ unicode(spiAdd)+"; dev= "+unicode(dev))
class MyTCPHandler(SocketServer.BaseRequestHandler): def handle(self): global currentGPIOValues, piVersion # self.request is the TCP socket connected to the client data = "" while True: buffer = self.request.recv(2048).strip() U.toLog(2, "len of buffer:" + str(len(buffer))) if not buffer: break data += buffer #U.toLog(1, "{} wrote:".format(self.client_address[0])) try: commands = json.loads(data.strip("\n")) except Exception, e: U.toLog( -1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)) U.toLog(-1, " bad command: json failed " + unicode(buffer)) return U.toLog(2, "len of package:" + str(len(data))) for next in commands: if execGeneral(next): continue cmdJ = json.dumps(next) U.toLog(1, " cmd= " + cmdJ) #print cmdJ cmdOut = "/usr/bin/python " + G.homeDir + "execcommands.py '" + cmdJ + "' &" os.system(cmdOut) time.sleep(0.1) readParams() return
def getMyprogram(sensor, data): global sensors, sValues, displayInfo if sensor not in sensors: return data try: data[sensor] = {} for devId in sensors[sensor]: if "freeParameter" in sensors[sensor][devId]: freeParameter = sensors[sensor][devId]["freeParameter"] else: freeParameter = "" params = json.dumps({ "devId": devId, "freeParameter": freeParameter }) ## this is my program action " #print "getsensorvalue cmd to myprogra"+cmd v = "xxx" try: v = json.loads(v) except: v = {} #print "v:", v if v != {}: data[sensor][devId] = copy.copy(v) if devId in badSensors: del badSensors[devId] else: data = incrementBadSensor(devId, sensor, data) except Exception, e: U.toLog( -1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
def line(self,pos): try: sx = 1 sy = 1 xStart = pos[1] xEnd = pos[3] yStart = pos[0] yEnd = pos[2] if pos[3]-pos[1]< 0: sx =-1 xStart = pos[3] xEnd = pos[1] if pos[2]-pos[0]< 0: sy =-1 if xStart == xEnd: for y in range(yStart,yEnd+sy,sy): self.PIXELS[y][pos[1]]=applyIntensity(pos[4:7]) return m = float(pos[2]-pos[0])/(pos[3]-pos[1]) b = -m*pos[1] + pos[0] for x in range(max(0,min(self.maxX,xStart)),max(0,min(self.maxX,xEnd+1))): y = int(x * m + b) self.PIXELS[max(0,min(self.maxY1,y))][x]=applyIntensity(pos[4:7]) return except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)) U.toLog(-1, u"pos " + unicode(pos))
def readObjTempC(self): try: """Read sensor object temperature (i.e. temperature of item in front of the sensor) and return its value in degrees celsius.""" # Read raw values and scale them to required units. Tdie = self.readRawDieTemperature() Vobj = self.readRawVoltage() Vobj *= 156.25 # 156.25 nV per bit U.toLog(0,'Vobj = {0:0.4} nV'.format(Vobj)) Vobj /= 1000000000.0 # Convert nV to volts Tdie *= 0.03125 # Convert to celsius Tdie += 273.14 # Convert to kelvin # Compute object temperature following equations from: # http://www.ti.com/lit/ug/sbou107/sbou107.pdf Tdie_ref = Tdie - TMP006_TREF S = 1.0 + TMP006_A1*Tdie_ref + TMP006_A2*math.pow(Tdie_ref, 2.0) S *= TMP006_S0 S /= 10000000.0 S /= 10000000.0 Vos = TMP006_B0 + TMP006_B1*Tdie_ref + TMP006_B2*math.pow(Tdie_ref, 2.0) fVobj = (Vobj - Vos) + TMP006_C2*math.pow((Vobj - Vos), 2.0) Tobj = math.sqrt(math.sqrt(math.pow(Tdie, 4.0) + (fVobj/S))) return Tobj - 273.15 except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)) return ""
def calibrate(self, tun_cap): """Calibrate the lightning sensor - this takes up to half a second and is blocking. The value of tun_cap should be between 0 and 15, and is used to set the internal tuning capacitors (0-120pF in steps of 8pF) """ time.sleep(0.08) registers = self.read_data() if registers ==[]: return -1 if tun_cap is not None: if tun_cap < 16 and tun_cap > -1: self.set_byte(0x08, (registers[8] & 0xF0) | tun_cap) time.sleep(0.002) else: raise Exception("Value of TUN_CAP must be between 0 and 15") U.toLog(-1, "setting cap param to %d = %d pF" %( tun_cap, tun_cap*8),doPrint=True) self.set_byte(0x3D, 0x96) time.sleep(0.002) registers = self.read_data() if registers ==[]: return -1 self.set_byte(0x08, registers[8] | 0x20) time.sleep(0.002) self.set_byte(0x08, registers[8] & 0xDF) time.sleep(0.002) return 0
def getValues(devId): global sensor, sensors, amg88xxsensor, badSensor global oldPixels global startTime global lastMeasurement global uniformityOLD, movementOLD, horizontal1OLD, horizontal2OLD, vertical1OLD, vertical2OLD try: ret ="" if amg88xxsensor[devId] =="": badSensor +=1 return "badSensor" i2cAdd = U.muxTCA9548A(sensors[sensor][devId]) # switch mux on if requested and use the i2c address of the mix if enabled ##print oldPixels oldPixels[devId] , maxV, minV, average, nPixels, AmbientTemperature, uniformity, movement, movementAbs= amg88xxsensor[devId].readPixels(oldPixels[devId]) #print " average %5.1f AmbientTemperature %5.1f movement %4.2f movementAbs %4.2f uniformity %4.2f "%( average, AmbientTemperature, movement, movementAbs, uniformity) #print " movement %4.2f uniformity %4.2f horizontal1 %4.1f horizontal2 %4.1f vertical1 %4.1f vertical2 %4.1f"%( movement-movementOLD, uniformity-uniformityOLD, horizontal1-horizontal1OLD, horizontal2-horizontal2OLD, vertical1-vertical1OLD, vertical2-vertical2OLD) ret = {"Movement": ( "%7.1f"%( movement ) ).strip(), "MovementAbs": ( "%7.1f"%( movementAbs ) ).strip(), # "Vertical1": ( "%7.3f"%( vertical1 ) ).strip(), # "Horizontal1": ( "%7.3f"%( horizontal1 ) ).strip(), "Uniformity": ( "%7.1f"%( uniformity ) ).strip(), "AmbientTemperature": ( "%7.1f"%( AmbientTemperature ) ).strip(), "MaximumPixel": ( "%7.1f"%( maxV ) ).strip(), "MinimumPixel": ( "%7.1f"%( minV ) ).strip(), "temp": ( "%7.1f"%( average ) ).strip(), "rawData": json.dumps(oldPixels[devId]).replace(" ","")} U.toLog(2, unicode(ret)) badSensor = 0 except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)) badSensor+=1 if badSensor >3: ret = "badSensor"
def write8(self, reg, value): try: self.bus.write_byte_data(self.i2c_address, reg, value) except Exception, e: U.toLog( -1, u"write8 in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
def readU8(self, reg): try: return self.bus.read_byte_data(self.i2c_address, reg) except Exception, e: U.toLog( -1, u"readU8 in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
def checkIfRelayON(): global lastRelayONCheck global gpioIn, gpioSWP, ON, off, cyclePower global eventStartedList, lastGPIOStatus, newGPIOStatus if time.time()- lastRelayONCheck < 3: return lastRelayONCheck = time.time() gpioStatus = getGPIO(gpioIn,calledFrom="checkRelay") maxONTime = 40 if gpioStatus: if cyclePower: if sensorMode == "checkIfIsRaining": if time.time()- eventStartedList[nEvenstStarted-1] < maxONTime: return U.toLog(-1, "resetting device in \"check if raining mode\", signal relay is ON for > "+str(maxONTime)+"secs: %d"%( time.time()- eventStartedList[0])+" to enable to detect new rain" ,doPrint=doPrint) else: if time.time()- eventStartedList[nEvenstStarted-1] < 5: return U.toLog(-1, "hanging? resetting device, signal relay is on for > "+str(maxONTime)+"secs: "+str( time.time()- eventStartedList[0])+" current Status"+status["currentMode"] ,doPrint=doPrint) powerCyleRelay() eventStartedList= [time.time()-(7+5*(nEvenstStarted-ii)) for ii in range(nEvenstStarted-1)]+[eventStartedList[nEvenstStarted-1]] else: if time.time()- eventStartedList[nEvenstStarted-1] < 10: return elif time.time()- eventStartedList[nEvenstStarted-1] < 145: #set to drizzle setModeTo("highSensitive", calledFrom="checkIfRelayON", powerCycle=False, force = False) sendShortStatus(rainMsg["highSensitive"]) else: # set to rain setModeTo("medSensitive", calledFrom="checkIfRelayON", powerCycle=False, force = False) sendShortStatus(rainMsg["medSensitive"])
def writeList(self, command, buf): try: self.bus.write_i2c_block_data(self.i2c_address, command, buf) except Exception, e: U.toLog( -1, u"writeList in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
def getValues(devId): global sensor, sensors, INAsensor, badSensor global actionDistanceOld, actionShortDistance, actionShortDistanceLimit, actionMediumDistance, actionMediumDistanceLimit, actionLongDistance, actionLongDistanceLimit i2cAdd = U.muxTCA9548A(sensors[sensor][devId]) for ii in range(2): try: ShuntVoltage = INAsensor[devId].getShuntVoltage_V() BusVoltage = INAsensor[devId].getBusVoltage_mV() Current = INAsensor[devId].getCurrent_mA() Power = INAsensor[devId].getPower_mW() #print "SV:",ShuntVoltage, " BV:",BusVoltage, " C:",Current, " P:",Power data = { "ShuntVoltage": ("%7.1f" % ShuntVoltage).strip(), "BusVoltage": ("%7d" % BusVoltage).strip(), "Power": ("%7d" % Power).strip(), "Current": ("%7.1f" % Current).strip() } badSensor = 0 U.muxTCA9548Areset() return data except Exception, e: if badSensor > 2 and badSensor < 5: U.toLog( -1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)) U.toLog(-1, u"Current>>" + unicode(Current) + "<<") badSensor += 1
def setTimeZone(upDown): global clockLightSet, enableupDown,enableHH,enableMM,enableDD,enableDDonOFF, enableTZset,enablePattern,enableLight,currHH, currMM, currDD, currTZ, useRTC, newDate, resetGPIO, lastButtonTime, switchON global inp, DEVID, clockDict global timeZone l0=60 + 48 + 40 + 32 +1 ind = currTZ U.toLog(1,"set timezone "+ upDown) if upDown =="UP": ind +=1 else: ind -=1 if ind > 12: ind = 12 if ind <-12: ind = -12 tz= G.timeZones[ind+12] currTZ = ind U.toLog(0, 'set tz: '+upDown+ ' new tz: '+ str(ind)+" "+tz) clockDict["extraLED"] = {"ticks":[ii+l0 for ii in range(ind+12)], "RGB":[100,100,100],"blink":[1,0]} # start on 8 ring clockDict["clockLightSet"] = clockLightSet inp["output"]["neopixelClock"][DEVID][0]["clockLightSet"] = clockDict["clockLightSet"] inp["output"]["neopixelClock"][DEVID][0]["extraLED"] = clockDict["extraLED"] makeTZ(tz) #print "timeZone", inp["output"]["neopixelClock"][DEVID][0]["timeZone"] startNEOPIXEL() return
def calibrateSensor(devId): global sensors, sensor global mhz16sensor global CO2normal, CO2offset, sensitivity i2cAdd = U.muxTCA9548A( sensors[sensor][devId] ) # switch mux on if requested and use the i2c address of the mix if enabled #print "calibrating" ret = "" try: CO2offset[devId] = 0 mhz16sensor[devId].calibrate() time.sleep(5) ret = getValues(devId, nMeasurements=3) if ret == "badSensor": print " calibration did not work exit " print ret time.sleep(5) return co2 = ret["CO2"] CO2offset[devId] = CO2normal[devId] - co2 #print "calib co2, CO2offset, CO2normal: ", co2, CO2offset[devId], CO2normal[devId] except Exception, e: print "ret =", ret U.toLog( -1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
def getMyprogram(sensor, data): global sensors, sValues, displayInfo if sensor not in sensors : return data try: data[sensor] ={} for devId in sensors[sensor]: if "freeParameter" in sensors[sensor][devId]: freeParameter = sensors[sensor][devId]["freeParameter"] else: freeParameter ="" params = json.dumps({"devId":devId,"freeParameter":freeParameter}) ## this is my program action " #print "getsensorvalue cmd to myprogra"+cmd v = "xxx" try: v=json.loads(v) except: v={} #print "v:", v if v!={}: data[sensor][devId] = copy.copy(v) if devId in badSensors: del badSensors[devId] else: data= incrementBadSensor(devId,sensor,data) except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
def get_accel_data(self, g = False): """Gets and returns the X, Y and Z values from the accelerometer. If g is True, it will return the data in g If g is False, it will return the data in m/s^2 Returns a dictionary with the measurement results. """ x = self.read_i2c_word(self.ACCEL_XOUT0) y = self.read_i2c_word(self.ACCEL_YOUT0) z = self.read_i2c_word(self.ACCEL_ZOUT0) accel_scale_modifier = None accel_range = self.read_accel_range(True) if accel_range == self.ACCEL_RANGE_2G: accel_scale_modifier = self.ACCEL_SCALE_MODIFIER_2G elif accel_range == self.ACCEL_RANGE_4G: accel_scale_modifier = self.ACCEL_SCALE_MODIFIER_4G elif accel_range == self.ACCEL_RANGE_8G: accel_scale_modifier = self.ACCEL_SCALE_MODIFIER_8G elif accel_range == self.ACCEL_RANGE_16G: accel_scale_modifier = self.ACCEL_SCALE_MODIFIER_16G else: U.toLog(-1,"Unkown range - accel_scale_modifier set to self.ACCEL_SCALE_MODIFIER_2G") accel_scale_modifier = self.ACCEL_SCALE_MODIFIER_2G x = x / accel_scale_modifier y = y / accel_scale_modifier z = z / accel_scale_modifier if not g: x = x * self.GRAVITIY_MS2 y = y * self.GRAVITIY_MS2 z = z * self.GRAVITIY_MS2 return {'x': round(x,2), 'y': round(y,2), 'z': round(z,2)}
def formatNumber(ddd, data,distanceUnits): dist1 = 0 dist = 0 dist0 = "" ud = "" try: dist1 = float(data) dist = float(data) if distanceUnits =="cm" or distanceUnits =="0.01": ud = "cm" dist0 = ("%8.1f"%(dist)).replace(" ","") elif distanceUnits =="inches" or distanceUnits =="0.0254": ud = 'in' dist = dist/2.54 dist0 = ("%7.1f"%(dist)).replace(" ","") elif distanceUnits =="feet" or distanceUnits =="0.348": ud = 'ft' dist = dist*0.0348 dist0 = ("%7.1f"%(dist)).replace(" ","") elif distanceUnits =="yard" or distanceUnits =="0.9144": ud = "yd" dist = dist*0.009144 dist0 = ("%8.2f"%(dist)).replace(" ","") else: ud = "m" dist = dist*0.01 dist0 = ("%8.2f"%(dist)).replace(" ","") except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
def readParams(): global sensors, sensor global rawOld global theSENSORdict global oldRaw, lastRead try: inp,inpRaw,lastRead2 = U.doRead(lastTimeStamp=lastRead) if inp == "": return if lastRead2 == lastRead: return lastRead = lastRead2 if inpRaw == oldRaw: return oldRaw = inpRaw U.getGlobalParams(inp) if "sensors" in inp: sensors = (inp["sensors"]) if "debugRPI" in inp: G.debug= int(inp["debugRPI"]["debugRPISENSOR"]) if sensor not in sensors: U.toLog(-1, G.program+" is not in parameters = not enabled, stopping "+G.program+".py" ) exit() for devId in sensors[sensor]: U.getMAGReadParameters(sensors[sensor][devId],devId) if devId not in theSENSORdict: startTheSensor(devId, G.i2cAddress, G.offsetTemp[devId], G.magOffset[devId], G.magDivider[devId], G.declination[devId], G.magResolution[devId],G.enableCalibration[devId]) U.setMAGParams(theSENSORdict[devId],magOffset=G.magOffset[devId], magDivider=G.magDivider[devId],enableCalibration=G.enableCalibration[devId], declination=G.declination[devId], offsetTemp=G.offsetTemp[devId]) theSENSORdict = U.cleanUpSensorlist( sensors[sensor], theSENSORdict) except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
def calibrate(self): try: self.send(self.cmd_calibrateZero) self.parse(self.receive()) return except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
def __init__(self,i2cAddress=_AS726X_ADDRESS): try: self._driver_led = False self._indicator_led = False self._driver_led_current = Adafruit_AS726x.DRIVER_CURRENT_LIMITS.index(12.5) self._indicator_led_current = Adafruit_AS726x.INDICATOR_CURRENT_LIMITS.index(1) self._conversion_mode = Adafruit_AS726x.MODE_2 self._integration_time = 0 self._gain = Adafruit_AS726x.GAIN.index(1) self.address =_AS726X_ADDRESS self.bus = smbus.SMBus(1) #reset device self._virtual_write(_AS726X_CONTROL_SETUP, 0x80) #wait for it to boot up time.sleep(1) #try to read the version reg to make sure we can connect version = self._virtual_read(_AS726X_HW_VERSION) #TODO: add support for other devices if version != 0x40: raise ValueError("device could not be reached or this device is not supported!") self._integration_time = 140 self._conversion_mode = Adafruit_AS726x.MODE_2 self._gain = 16 self._norm = 16.*140. / (self._gain*self._integration_time*_counts_Per_mu_Watt) except Exception, e: print u"init in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e) U.toLog(-1, u"init in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
def readData(self): try: """Read the accelerometer and magnetometer value. A tuple of tuples will be returned with: ((accel X, accel Y, accel Z), (mag X, mag Y, mag Z)) """ # Read the accelerometer as signed 16-bit little endian values. accel_raw = self._accel.readList( LSM303_REGISTER_ACCEL_OUT_X_L_A | 0x80, 6) accel = struct.unpack('<hhh', accel_raw) # Convert to 12-bit values by shifting unused bits. accel = [accel[0] >> 4, accel[1] >> 4, accel[2] >> 4] for ii in range(3): accel[ii] *= self.accfactor[ii] # Read the magnetometer. mag_raw = self._mag.readList(LSM303_REGISTER_MAG_OUT_X_H_M, 6) magx = struct.unpack('>hhh', mag_raw) mag = [0, 0, 0] for ii in range(3): mag[ii] = magx[ii] * self.magfactor[ii] print magx, accel return (accel, mag) except Exception, e: U.toLog( -1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
def startSensor(devId, i2cAddress): global sensors, sensor global startTime global gasBaseLine, gasBurnIn global BMEsensor, firstValue U.toLog(-1, "==== Start BME680 ===== @ i2c= " + unicode(i2cAddress)) startTime = time.time() gasBaseLine = 0 gasBurnIn = [] i2cAdd = U.muxTCA9548A( sensors[sensor][devId] ) # switch mux on if requested and use the i2c address of the mix if enabled print " starting with ic2= " + str(i2cAdd) try: BMEsensor[devId] = BME680(i2c_addr=i2cAdd) except Exception, e: U.toLog( -1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)) BMEsensor[devId] = "" U.muxTCA9548Areset() return
def getDistance(): global sensor, sensors, first, tof, badSensor global actionDistanceOld, actionShortDistance, actionShortDistanceLimit, actionMediumDistance, actionMediumDistanceLimit, actionLongDistance, actionLongDistanceLimit try: if first: time.sleep(3) ; first = False for ii in range(10): distance = tof.get_distance() if (distance > 0): distance = min(distance,10000.)/10. # = 10 meters = 10,000 mm badSensor = 0 #print " bf action test ", actionShortDistance, actionMediumDistance, actionLongDistance if actionShortDistance !="": if actionDistanceOld !="short" and distance <= actionShortDistanceLimit: if actionDistanceOld != "short": os.system(actionShortDistance) actionDistanceOld ="short" if actionMediumDistance !="": if actionDistanceOld !="medium" and distance > actionShortDistanceLimit and distance < actionLongDistanceLimit: if actionDistanceOld != "medium": os.system(actionMediumDistance) actionDistanceOld ="medium" if actionLongDistance !="": if actionDistanceOld !="long" and distance >= actionLongDistanceLimit: if actionDistanceOld != "long": os.system(actionLongDistance) actionDistanceOld ="long" return ("%7.1f"%(distance)).strip() # return in cm if badSensor >3: return "badSensor" except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)) U.toLog(-1, u"distance>>" + unicode(distance)+"<<")
def startGPIO(): global sensors, INPUTcount, lastGPIO try: lastGPIO={} for nn in range(30): lastGPIO[nn] ="" GPIO.setmode(GPIO.BCM) for n in range(30): sensor="INPUTgpio-"+str(n) if sensor not in sensors: continue for devId in sensors[sensor]: if "INPUTS" not in sensors[sensor][devId]: continue ss = sensors[sensor][devId]["INPUTS"] for nn in range(len(ss)): if "gpio" not in ss[nn]: continue gpioPIN = int(ss[nn]["gpio"]) type = ss[nn]["inpType"] count = ss[nn]["count"] if count =="off": INPUTcount[gpioPIN] = 0 if type == "open": GPIO.setup(gpioPIN, GPIO.IN) elif type == "high": GPIO.setup(gpioPIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) elif type == "low": GPIO.setup(gpioPIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) elif type == "inOpen": GPIO.setup(gpioPIN, GPIO.IN) return except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e),doPrint=True) U.toLog(-1,"startGPIO: "+ unicode(sensors),doPrint=True)
def getValues(devId): global sensor, sensors, thisSensor, badSensor global startTime global gasBaseLine, gasBurnIn, lastMeasurement, calibrateIfgt,setCalibration, firstValue try: if thisSensor[devId] =="": badSensor +=1 return "badSensor" retData= thisSensor[devId].getData() if retData != "badSensor": data = {"pm10_standard": retData[0], "pm25_standard": retData[1], "pm100_standard": retData[2], "pm10_env": retData[3], "pm25_env": retData[4], "pm100_env": retData[5], "particles_03um": retData[6], "particles_05um": retData[7], "particles_10um": retData[8], "particles_25um": retData[9], "particles_50um": retData[10], "particles_100um": retData[11] } U.toLog(2, unicode(data)) badSensor = 0 return data except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
def startTheSensor(devId, i2cAddress, offsetTemp, magOffset, magDivider, declination, magResolution, enableCalibration): global theSENSORdict try: U.toLog( -1, "==== Start " + G.program + " ===== @ i2c= " + unicode(i2cAddress) + " devId=" + unicode(devId)) if magOffset == [0, 0, 0]: theSENSORdict[devId] = THESENSORCLASS( address=i2cAddress, magDivider=magDivider, enableCalibration=enableCalibration, declination=declination, magOffset=magOffset, offsetTemp=offsetTemp) if enableCalibration: theSENSORdict[devId].calibrate(calibTime=5) else: theSENSORdict[devId] = THESENSORCLASS( address=i2cAddress, magDivider=magDivider, enableCalibration=enableCalibration, declination=declination, offsetTemp=offsetTemp) except Exception, e: U.toLog( -1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
def startSENSOR(devId, i2cAddress): global theSENSORdict try: U.toLog(-1,"==== Start "+G.program+" ===== @ i2c= " +unicode(i2cAddress)+" devId=" +unicode(devId)) theSENSORdict[devId] = THESENSORCLASS(i2cAddress=i2cAddress) except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
def get_gyro_data(self): """Gets and returns the X, Y and Z values from the gyroscope. Returns the read values in a dictionary. """ x = self.read_i2c_word(self.GYRO_XOUT0) y = self.read_i2c_word(self.GYRO_YOUT0) z = self.read_i2c_word(self.GYRO_ZOUT0) gyro_scale_modifier = None gyro_range = self.read_gyro_range(True) if gyro_range == self.GYRO_RANGE_250DEG: gyro_scale_modifier = self.GYRO_SCALE_MODIFIER_250DEG elif gyro_range == self.GYRO_RANGE_500DEG: gyro_scale_modifier = self.GYRO_SCALE_MODIFIER_500DEG elif gyro_range == self.GYRO_RANGE_1000DEG: gyro_scale_modifier = self.GYRO_SCALE_MODIFIER_1000DEG elif gyro_range == self.GYRO_RANGE_2000DEG: gyro_scale_modifier = self.GYRO_SCALE_MODIFIER_2000DEG else: U.toLog(-1,"Unkown range - gyro_scale_modifier set to self.GYRO_SCALE_MODIFIER_250DEG") gyro_scale_modifier = self.GYRO_SCALE_MODIFIER_250DEG x = (x / gyro_scale_modifier) y = (y / gyro_scale_modifier) z = (z / gyro_scale_modifier) return {'x': round(x,2), 'y': round(y,2), 'z': round(z,2)}
def readData(self): try: """Read the accelerometer and magnetometer value. A tuple of tuples will be returned with: ((accel X, accel Y, accel Z), (mag X, mag Y, mag Z)) """ # Read the accelerometer as signed 16-bit little endian values. accel_raw = self._accel.readList(LSM303_REGISTER_ACCEL_OUT_X_L_A | 0x80, 6) accel = struct.unpack('<hhh', accel_raw) # Convert to 12-bit values by shifting unused bits. accel = [accel[0] >> 4, accel[1] >> 4, accel[2] >> 4] for ii in range(3): accel[ii] *= self.accfactor[ii] # Read the magnetometer. mag_raw = self._mag.readList(LSM303_REGISTER_MAG_OUT_X_H_M, 6) magx = struct.unpack('>hhh', mag_raw) mag =[0,0,0] for ii in range(3): mag[ii] = magx[ii] * self.magfactor[ii] print magx, accel return (accel, mag) except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
def readDieTempC(self): """Read sensor die temperature and return its value in degrees celsius.""" try: Tdie = self.readRawDieTemperature() return Tdie * 0.03125 except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
def getValues(devId): global sensor, sensors, thisSensor, badSensor global startTime global gasBaseLine, gasBurnIn, lastMeasurement, calibrateIfgt, setCalibration, firstValue try: if thisSensor[devId] == "": badSensor += 1 return "badSensor" retData = thisSensor[devId].getData() if retData != "badSensor": data = { "pm10_standard": retData[0], "pm25_standard": retData[1], "pm100_standard": retData[2], "pm10_env": retData[3], "pm25_env": retData[4], "pm100_env": retData[5], "particles_03um": retData[6], "particles_05um": retData[7], "particles_10um": retData[8], "particles_25um": retData[9], "particles_50um": retData[10], "particles_100um": retData[11] } U.toLog(2, unicode(data)) badSensor = 0 return data except Exception, e: U.toLog( -1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
def startSensor(devId): global sensors, sensor, badSensor global startTime global as3935sensor global inside, minStrikes, tuneCapacitor, minNoiseFloor, interruptGPIO, noiseFlorSet,calibrationDynamic, noiseFloor, CapValue U.toLog(-1,"==== Start "+G.program+" ===== @ i2c= " +unicode(i2cAddress),doPrint=True) startTime =time.time() i2cAdd = U.muxTCA9548A(sensors[sensor][devId]) # switch mux on if requested and use the i2c address of the mix if enabled try: as3935sensor[devId] = RPi_AS3935(address=i2cAdd, minNoiseFloor=minNoiseFloor) as3935sensor[devId].set_indoors( inside == 1) noiseFlorSet = as3935sensor[devId].set_noise_floor(max(noiseFloor,minNoiseFloor)) as3935sensor[devId].set_min_strikes(minStrikes) if as3935sensor[devId].calibrate(tuneCapacitor) ==-1: time.sleep(10) data={"sensors":{sensor:{devId:{"eventType":"badsensor"}}}} badSensor else: badSensor = False except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)) data={"sensors":{sensor:{devId:{"eventType":"badsensor"}}}} badSensor = True
def getValues(devId): global sensor, sensors, as726xsensor, badSensor global LEDmA, doAverage, LEDBlink, gain i2cAdd = U.muxTCA9548A(sensors[sensor][devId]) data ={"blue":"","green":"","yellow":"","orange":"","red":"","violet":"","temp":"","LEDcurrent":0} try: for ii in range(20): if as726xsensor[devId].data_ready(): break time.sleep(.1) ##print "blue" , as726xsensor[devId].blue() data["blue"] = as726xsensor[devId].blue() data["green"] = as726xsensor[devId].green() data["yellow"] = as726xsensor[devId].yellow() data["orange"] = as726xsensor[devId].orange() data["red"] = as726xsensor[devId].red() data["violet"] = as726xsensor[devId].violet() data["temp"] = as726xsensor[devId].temperature() badSensor = 0 U.muxTCA9548Areset() return data except Exception, e: if badSensor >-1 and badSensor < 5000: U.toLog(-1, u"getValues in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)) U.toLog(-1, unicode(data) ) badSensor+=1
def __init__(self, accelerationGain=1, magGain=0): try: accel_address = LSM303_ADDRESS_ACCEL self.i2cAddA = accel_address mag_address = LSM303_ADDRESS_MAG i2c = None """Initialize the LSM303 accelerometer & magnetometer. The hires boolean indicates if high resolution (12-bit) mode vs. low resolution (10-bit, faster and lower power) mode should be used. """ # Setup I2C interface for accelerometer and magnetometer. import Adafruit_GPIO.I2C as I2C i2c = I2C self._accel = i2c.get_i2c_device(accel_address) self._mag = i2c.get_i2c_device(mag_address) # Enable the accelerometer self.set_acc_gain(accelerationGain=int(accelerationGain)) # Enable the magnetometer self.set_mag_gain(magGain=int(magGain)) except Exception, e: U.toLog( -1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
def saveLastCommands(items): try: f = open(G.homeDir+"neopixel.last","w") f.write(json.dumps(items)) f.close() except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
def __init__(self, busNumber=1, address=0x0E, magDivider=1, enableCalibration=False, declination=0,magOffset="", offsetTemp=0, magResolution =1): try: self.busNumber = busNumber try: self.bus = smbus.SMBus(self.busNumber) except Exception, e: U.toLog(-1,'couldn\'t open bus: {0}'.format(e)) return self.enableCalibration = enableCalibration self.heading = 0 self.calibrationFile = G.homeDir+G.program+'.calib' if address =="": address = self.myaddress self.address = address self.offsetTemp = 0 self.magDivider = 1. self.declination = 0. self.calibrations = {'maxX':0,'minX':0,'maxY':0, 'minY':0, 'maxZ':0, 'minZ':0} self.magOffset = [0,0,0] if magOffset!="": self.enableCalibration = False U.setMAGParams(self,magOffset=magOffset, magDivider=magDivider, declination=declination, offsetTemp=offsetTemp) if not self.initSensor(): return if self.enableCalibration: self.calibrations= U.loadCalibration(self.calibrationFile) U.magCalibrate(self, force = False,calibTime=5)
def receive(self): try: n = 9 buf = [] start = time.clock() errcountMAX = 2 while n > 0: try: rx_level = self.read_register( self.RXLVL ) # are there enough bytes available to read , should be 9. except Exception, e: time.sleep(0.004) errcountMAX -= 1 if errcountMAX == 0: U.toLog( 0, u"receive read_register too may tries stopping read, has error='%s'" % (e)) return buf continue if rx_level > n: rx_level = n buf.extend( self.i2c.read_i2c_block_data(self.i2c_addr, self.RHR, rx_level)) n = n - rx_level if time.clock() - start > 0.2: break return buf
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 readParams(): global sensors, sensor global theSENSORdict global oldRaw, lastRead try: inp,inpRaw,lastRead2 = U.doRead(lastTimeStamp=lastRead) if inp == "": return if lastRead2 == lastRead: return lastRead = lastRead2 if inpRaw == oldRaw: return oldRaw = inpRaw U.getGlobalParams(inp) if "sensors" in inp: sensors = (inp["sensors"]) if "debugRPI" in inp: G.debug= int(inp["debugRPI"]["debugRPISENSOR"]) if sensor not in sensors: U.toLog(-1, G.program+" is not in parameters = not enabled, stopping "+G.program+".py" ) exit() for devId in sensors[sensor]: U.getMAGReadParameters(sensors[sensor][devId],devId) if devId not in theSENSORdict: startTheSensor(devId, G.i2cAddress, G.magResolution[devId], G.declination[devId], G.magOffset[devId], G.magDivider[devId], G.enableCalibration[devId]) U.setMAGParams(theSENSORdict[devId],magOffset= G.magOffset[devId], magDivider= G.magDivider[devId], declination= G.declination[devId]) theSENSORdict = U.cleanUpSensorlist( sensors[sensor], theSENSORdict) except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
def getDATAdht(DHTpin,Type): global sensorDHT, startDHT t,h="","" try: ii=startDHT[str(DHTpin)] except: if startDHT =="": startDHT={} sensorDHT={} startDHT[str(DHTpin)] = 1 if Type.lower() == "dht11": sensorDHT[str(DHTpin)] = Adafruit_DHT.DHT11 else: sensorDHT[str(DHTpin)] = Adafruit_DHT.DHT22 try: h,t = Adafruit_DHT.read_retry(sensorDHT[str(DHTpin)], int(DHTpin)) if unicode(h) == "None" or unicode(t) == "None": print " return data failed: "+str(h)+" "+str(t), Type, "pin",str(DHTpin), " try again" time.sleep(1) h,t = Adafruit_DHT.read_retry(sensorDHT[str(DHTpin)], int(DHTpin)) #f h is not None and t is not None: #print " return data: "+str(h)+" "+str(t), Type, "pin",str(DHTpin) # # sensorDHT="" return ("%.2f"%float(t)).strip(),("%3d"%float(h)).strip() #else: return "" ,"" except Exception, e: U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)) U.toLog(-1, u" pin: "+ str(DHTpin)+" return value: t="+ unicode(t)+"; h=" + unicode(h) )
def startMCP3008(devId): global spi0, spi1 spiAdd = 0 try: ss = "" if "spiMCP3008" in sensors: ss = "spiMCP3008" if "spiMCP3008-1" in sensors: ss = "spiMCP3008-1" if ss != "": if sensors[ss][devId]["spiAddress"] != "": spiAdd = int(sensors[ss][devId]["spiAddress"]) if spiAdd > 1: spiAdd = 1 if spiAdd < 0: spiAdd = 0 if spiAdd == 0: spi0 = spidev.SpiDev() spi0.open(0, 0) if spiAdd == 1: spi1 = spidev.SpiDev() spi1.open(0, 1) #print spiAdd, spi0,spi1 except Exception, e: U.toLog( -1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e)) U.toLog( -1, u"spi channel used: " + unicode(spiAdd) + "; dev= " + unicode(dev))
def __init__(self, busNumber=1, address=0x1E, magResolution =1,enableCalibration=False, magDivider = 1.,declination=0, magOffset=""): self.busNumber = busNumber try: self.bus = smbus.SMBus(self.busNumber) except Exception, e: U.toLog(-1,'couldn\'t open bus: {0}'.format(e)) return
def sleep(self): """Put TMP006 into low power sleep mode. No measurement data will be updated while in sleep mode. """ control = self.readU16BE(TMP006_CONFIG) control &= ~(TMP006_CFG_MODEON) self.write16(TMP006_CONFIG, control) U.toLog(0, 'TMP006 entered sleep mode.')
def readRawVoltage(self): """Read raw voltage from TMP006 sensor. Meant to be used in the calculation of temperature values. """ raw = self.readS16BE(TMP006_VOBJ) U.toLog(0,'Raw voltage: 0x{0:04X} ({1:0.4F} uV)'.format(raw & 0xFFFF, raw * 156.25 / 1000.0)) return raw
def matrix(self,pos): if isinstance(pos[0], list): for y in range(len(pos)): for x in range(len(pos[0])): self.PIXELS[max(0,min(self.maxY1,y))][max(0,min(self.maxX1,x))] = applyIntensity(pos[y][x]) else: U.toLog(-1,u" error type:"+cType+" pos:"+ unicode(pos) ) return