Esempio n. 1
0
def readParams():
		global output
		global INPgpioType,OUTPUTlastvalue
		global oldRaw, lastRead


		inp,inpRaw,lastRead2 = U.doRead(lastTimeStamp=lastRead)
		if inp == "": return
		if lastRead2 == lastRead: return
		lastRead   = lastRead2
		if inpRaw == oldRaw: return
		oldRaw	   = inpRaw
		oldoutput		  = output

		U.getGlobalParams(inp)
		if "output"			in inp : output =				(inp["output"])
		if "debugRPI"		in inp:	 G.debug=			  int(inp["debugRPI"]["debugRPIOUTPUT"])


		restart = False
			
		if "OUTPUTgpio-1-ONoff" not in output:
			print "OUTPUTgpio-1-ONoff not in output" 
			exit()
				
		if restart:
			U.restartMyself(reason="new parameters")
Esempio n. 2
0
def readParams():
    global output
    global INPgpioType, OUTPUTlastvalue
    global oldRaw, lastRead

    inp, inpRaw, lastRead2 = U.doRead(lastTimeStamp=lastRead)
    if inp == "": return
    if lastRead2 == lastRead: return
    lastRead = lastRead2
    if inpRaw == oldRaw: return
    oldRaw = inpRaw
    oldoutput = output

    U.getGlobalParams(inp)
    if "output" in inp: output = (inp["output"])
    if "debugRPI" in inp: G.debug = int(inp["debugRPI"]["debugRPIOUTPUT"])

    restart = False

    if "OUTPUTgpio-1-ONoff" not in output:
        print "OUTPUTgpio-1-ONoff not in output"
        exit()

    if restart:
        U.restartMyself(reason="new parameters")
Esempio n. 3
0
def readParams():
    global sList, sensors
    global INPgpioType, INPUTcount, INPUTlastvalue
    global oldRaw, lastRead

    INPUTcount = U.checkresetCount(INPUTcount)

    inp, inpRaw, lastRead2 = U.doRead(lastTimeStamp=lastRead)
    if inp == "": return
    if lastRead2 == lastRead: return
    lastRead = lastRead2
    if inpRaw == oldRaw: return
    oldRaw = inpRaw

    oldSensors = sensors

    U.getGlobalParams(inp)
    if "sensors" in inp: sensors = (inp["sensors"])
    if "debugRPI" in inp: G.debug = int(inp["debugRPI"]["debugRPISENSOR"])

    restart = False
    sList = ""
    for sensor in sensors:
        sList += sensor

    if "INPUTgpio" not in sList:
        print "INPUTgpio not in sensorlist"
        exit()
    else:
        if oldSensors != {}:  # this is {}  at startup.. dont do anything
            for sensor in sensors:
                if "INPUTgpio" in sensor.split("-")[0]:
                    if sensor not in oldSensors:
                        restart = True
                        U.toLog(
                            -1, "new sensor def:" +
                            unicode(sensors[sensor][devId]["INPUTS"]))
                        break
                    for devId in sensors[sensor]:
                        if devId not in oldSensors[sensor]:
                            restart = True
                            U.toLog(
                                -1, "new sensor def:" +
                                unicode(sensors[sensor][devId]["INPUTS"]))
                            break
                        if sensors[sensor][devId]["INPUTS"] != oldSensors[
                                sensor][devId]["INPUTS"]:
                            restart = True
                            U.toLog(
                                -1, "new sensor def:" +
                                unicode(sensors[sensor][devId]["INPUTS"]))
                            U.toLog(
                                -1, "old sensor def:" +
                                unicode(oldSensors[sensor][devId]["INPUTS"]))
                            break
                if restart: break

    if restart:
        U.restartMyself(reason="new parameters")
Esempio n. 4
0
def readParams():
    global sensors, sensor
    global rawOld
    global theSENSORdict, resetPin
    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
        externalSensor = False
        sensorsOld = copy.copy(sensors)

        if "sensors" in inp: sensors = (inp["sensors"])
        if "debugRPI" in inp: G.debug = int(inp["debugRPI"]["debugRPISENSOR"])

        U.getGlobalParams(inp)

        if sensor not in sensors:
            U.toLog(
                -1, G.program +
                "is not in parameters = not enabled, stopping " + G.program)
            exit()

        for devId in sensors[sensor]:
            changed = U.getMAGReadParameters(sensors[sensor][devId], devId)
            if changed.find("accelerationGain") > -1 or changed.find(
                    "magGain") > -1:
                U.restartMyself(reason="new gain seetungs require restart ",
                                doPrint=False)

            if devId not in theSENSORdict:
                startSENSOR(devId, G.i2cAddress)

        deldevID = {}
        for devId in theSENSORdict:
            if devId not in sensors[sensor]:
                deldevID[devId] = 1
        for dd in deldevID:
            del theSENSORdict[dd]
        if len(theSENSORdict) == 0:
            ####exit()
            pass

    except Exception, e:
        U.toLog(
            -1,
            u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
Esempio n. 5
0
def readParams():
		global sList,sensors
		global INPgpioType,INPUTcount,INPUTlastvalue
		global oldRaw, lastRead

		INPUTcount= U.checkresetCount(INPUTcount)


		inp,inpRaw,lastRead2 = U.doRead(lastTimeStamp=lastRead)
		if inp == "": return
		if lastRead2 == lastRead: return
		lastRead   = lastRead2
		if inpRaw == oldRaw: return
		oldRaw	   = inpRaw

		oldSensors		  = sensors

		U.getGlobalParams(inp)
		if "sensors"			in inp : sensors =				(inp["sensors"])
		if "debugRPI"			in inp:	 G.debug=			  int(inp["debugRPI"]["debugRPISENSOR"])

		restart = False
		sList = ""
		for sensor in sensors:
			sList+=sensor
			
		if "INPUTgpio" not in sList:
			print "INPUTgpio not in sensorlist" 
			exit()
		else:
			if oldSensors != {}: # this is {}  at startup.. dont do anything 
				for sensor in sensors:
					if "INPUTgpio" in sensor.split("-")[0]:
						if sensor not in oldSensors:
							restart=True
							U.toLog(-1, "new sensor def:" + unicode( sensors[sensor][devId]["INPUTS"])	)
							break
						for devId in sensors[sensor]:
							if devId  not in oldSensors[sensor]:
								restart=True
								U.toLog(-1, "new sensor def:" + unicode( sensors[sensor][devId]["INPUTS"])	)
								break
							if sensors[sensor][devId]["INPUTS"] != oldSensors[sensor][devId]["INPUTS"]:
								restart=True
								U.toLog(-1, "new sensor def:" + unicode( sensors[sensor][devId]["INPUTS"])	 )
								U.toLog(-1, "old sensor def:" + unicode(oldSensors[sensor][devId]["INPUTS"]) )
								break
					if restart: break
				
		if restart:
			U.restartMyself(reason="new parameters")
Esempio n. 6
0
def readParams():
	global sensors, sensor
	global rawOld
	global theSENSORdict, resetPin
	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
		externalSensor=False
		sensorsOld= copy.copy(sensors)

		if "sensors"			in inp:	 sensors =				 (inp["sensors"])
		if "debugRPI"			in inp:	 G.debug=			  int(inp["debugRPI"]["debugRPISENSOR"])

		U.getGlobalParams(inp)
		
		
 
		if sensor not in sensors:
			U.toLog(-1, G.program+"is not in parameters = not enabled, stopping "+G.program )
			exit()
			
				
		for devId in sensors[sensor]:
			changed=  U.getMAGReadParameters(sensors[sensor][devId],devId) 
			if	changed.find("accelerationGain") >-1  or changed.find("magGain") >-1: 
				U.restartMyself(reason="new gain seetungs require restart ",doPrint=False)

				
			if devId not in theSENSORdict:
				startSENSOR(devId, G.i2cAddress)
				
		deldevID={}		   
		for devId in theSENSORdict:
			if devId not in sensors[sensor]:
				deldevID[devId]=1
		for dd in  deldevID:
			del theSENSORdict[dd]
		if len(theSENSORdict) ==0: 
			####exit()
			pass

	except	Exception, e:
		U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
Esempio n. 7
0
def startBNO(devId, i2cAddress):
	global BNO055sensor
	try:
		U.toLog(-1,"==== Start BNO055 ===== @ i2c= " +unicode(i2cAddress)+"	 devId=" +unicode(devId))
		if resetPin !=-1:
			BNO055sensor[devId] = BNO055(i2cAddress=i2cAddress, resetPin=resetPin)
		else:
			BNO055sensor[devId] = BNO055(i2cAddress=i2cAddress)
		configAvailable = False
		if not BNO055sensor[devId].begin():
			time.sleep(0.5)
			if not BNO055sensor[devId].begin():
				raise RuntimeError('BEGIN: Failed to initialize BNO055! Is the sensor connected?')

		# Print system status and self test result.
		status, self_test, error = BNO055sensor[devId].get_system_status()
		U.toLog(0,'BEGIN: System status:	  {0}'.format(status&0b01111111)+ "	   (5 is normal)")
		U.toLog(0,'BEGIN: Self test result:	  0x{0:02X}'.format(self_test)+ " (0x0F is normal)")
		# Print out an error if system status is in error mode.
		if status == 0x01:
			U.toLog(-1,'BEGIN: System error: {0}'.format(error))
			U.toLog(-1,'BEGIN: See datasheet section 4.3.59 for the meaning.')

		# Print BNO055 software revision and other diagnostic data.
		sw, bl, accel, mag, gyro = BNO055sensor[devId].get_revision()
		U.toLog(0,'BEGIN: Software version:	  {0}'.format(sw))
		U.toLog(0,'BEGIN: Bootloader version: {0}'.format(bl))
		U.toLog(0,'BEGIN: Accelerometer ID:	  0x{0:02X}'.format(accel))
		U.toLog(0,'BEGIN: Magnetometer ID:	  0x{0:02X}'.format(mag))
		U.toLog(0,'BEGIN: Gyroscope ID:		  0x{0:02X}\n'.format(gyro))
		if mag ==0 or accel ==0 or gyro ==0: 
				time.sleep(1)
				U.restartMyself(reason=" init not working, sensor does not report properly (IDs =0 )", doPrint=False)

	except	Exception, e:
		U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
Esempio n. 8
0
                if devId not in lastValues:
                    lastValues[devId] = copy.copy(lastValues0)
                    lastValues2[devId] = copy.copy(lastValues0)
                values = getValues(devId)
                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)
                        resetSensor(devId=devId)
                    else:
                        U.restartMyself(param="",
                                        reason="badsensor",
                                        doPrint=True)
                    lastValues2[devId] = copy.copy(lastValues0)
                    lastValues[devId] = copy.copy(lastValues0)
                    continue
                elif values["particles_03um"] != "":

                    data["sensors"][sensor][devId] = values
                    deltaN = 0
                    for xx in lastValues0:
                        try:
                            current = float(values[xx])
                            delta = current - lastValues2[devId][xx]
                            deltaN = max(
                                deltaN,
                                abs(delta) /
Esempio n. 9
0
				else:
					deltaN = 0
					ok = True
					for color in values:
						if values[color] =="": 
							ok = False
							data["sensors"][sensor][devId]["violet"] = "badSensor"
							sendURLnow = True
							break
					if not ok: 
						rebootCount +=1
						continue

					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")

					values["LEDcurrent"]  =LEDmALast

					avsend = False
					if doAverage > 0:
						averages[devId]["n"] += 1
						for color in values:
							averages[devId][color] += values[color]
							values[color] = averages[devId][color]/averages[devId]["n"]
							if averages[devId]["n"] >= doAverage: 
								averages[devId][color] = 0
						if averages[devId]["n"] >= doAverage: 
							averages[devId]["n"] = 0
							avsend = True
Esempio n. 10
0
def readParams():
    global sensor, sensors
    global gpioIn, gpioSW1, gpioSW2, gpioSW5, gpioSWP, cyclePower, sensorMode
    global ON, off
    global oldRaw, lastRead
    global switchToLowerSensitive, switchToHigherSensitive, bucketSize, bucketSize0, sendMSGEverySecs
    global status
    try:
        restart = False

        inp, inpRaw, lastRead2 = U.doRead(lastTimeStamp=lastRead)
        if inp == "": return
        if lastRead2 == lastRead: return
        lastRead = lastRead2
        if inpRaw == oldRaw: return
        oldRaw = inpRaw

        oldSensors = sensors

        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(0,
                    "no " + G.program + " sensor defined, exiting",
                    doPrint=True)
            exit()

        sens = sensors[sensor]
        found = {
            str(ii): {
                "RISING": 0,
                "GPIOchanged": 0,
                "BOTH": 0
            }
            for ii in range(100)
        }
        for devId in sens:
            sss = sens[devId]
            if "gpioIn" not in sss: continue
            if "gpioSW5" not in sss: continue
            if "gpioSW2" not in sss: continue
            if "gpioSW1" not in sss: continue
            if "gpioSWP" not in sss: continue
            if "sensorMode" not in sss: continue

            cp = sss["cyclePower"] != "0"

            if gpioIn != -1 and gpioIn != int(sss["gpioIn"]):
                restart = True
                U.toLog(0,
                        "gpios channel changed, need to restart",
                        doPrint=True)
                U.restartMyself(param="", reason=" new gpioIn", doPrint=True)
                return

            cyclePower = True
            if gpioSWP != int(sss["gpioSWP"]):
                gpioSWP = int(sss["gpioSWP"])
                if gpioSWP > 0: GPIO.setup(gpioSWP, GPIO.OUT)
                powerOFF(calledFrom="read")
            if gpioSW1 != int(sss["gpioSW1"]):
                gpioSW1 = int(sss["gpioSW1"])
                if gpioSW1 > 0: GPIO.setup(gpioSW1, GPIO.OUT)
            if gpioSW2 != int(sss["gpioSW2"]):
                gpioSW2 = int(sss["gpioSW2"])
                if gpioSW2 > 0: GPIO.setup(gpioSW2, GPIO.OUT)
            if gpioSW5 != int(sss["gpioSW5"]):
                gpioSW5 = int(sss["gpioSW5"])
                if gpioSW5 > 0: GPIO.setup(gpioSW5, GPIO.OUT)
            switchToLowerSensitive[
                "checkIfIsRaining"] = 10  # int(sss["TimeSwitchSensitivityRainToMayBeRaining"])
            switchToLowerSensitive[
                "maybeRain"] = 10  # int(sss["TimeSwitchSensitivityMayBeRainingToHigh"])
            switchToLowerSensitive[
                "highSensitive"] = 10  # int(sss["TimeSwitchSensitivityHighToMed"])
            switchToLowerSensitive[
                "medSensitive"] = 10  # int(sss["TimeSwitchSensitivityMedToLow"])

            switchToHigherSensitive[
                "lowSensitive"] = 100  # int(sss["TimeSwitchSensitivityLowToMed"])
            switchToHigherSensitive[
                "medSensitive"] = 100  # int(sss["TimeSwitchSensitivityMedToHigh"])
            switchToHigherSensitive[
                "highSensitive"] = 100  # int(sss["TimeSwitchSensitivityHighToAnyRain"])
            try:
                rainScaleFactor = float(sss["rainScaleFactor"])
            except:
                rainScaleFactor = 1.

            if gpioIn != int(sss["gpioIn"]):
                gpioIn = int(sss["gpioIn"])
                GPIO.setup(gpioIn, GPIO.IN, pull_up_down=GPIO.PUD_UP)
                GPIO.add_event_detect(gpioIn,
                                      GPIO.FALLING,
                                      callback=GPIOchanged,
                                      bouncetime=100)
                if sss["sensorMode"] != "dynamic":
                    setModeTo("checkIfIsRaining", calledFrom="readParams1")

            if sensorMode != sss["sensorMode"]:
                if sss["sensorMode"] != "dynamic":
                    sendShortStatus(rainMsg["checkIfIsRaining"])
                    nextModeSwitchNotBefore = time.time() + 2
                setModeTo(sss["sensorMode"],
                          force=True,
                          calledFrom="readParams2")

            sensorMode = sss["sensorMode"]
            sendMSGEverySecs = float(sss["sendMSGEverySecs"])
            time.sleep(0.4)
            powerON(calledFrom="read")
            cyclePower = cp

            bucketSize = {}
            for kk in bucketSize0:
                bucketSize[kk] = bucketSize0[kk] * rainScaleFactor

    except Exception, e:
        U.toLog(-1,
                u"in Line '%s' has error='%s'" %
                (sys.exc_traceback.tb_lineno, e),
                doPrint=True)
Esempio n. 11
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")
Esempio n. 12
0
                    deltaN = 0
                    ok = True
                    for color in values:
                        if values[color] == "":
                            ok = False
                            data["sensors"][sensor][devId][
                                "violet"] = "badSensor"
                            sendURLnow = True
                            break
                    if not ok:
                        rebootCount += 1
                        continue

                    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")

                    values["LEDcurrent"] = LEDmALast

                    avsend = False
                    if doAverage > 0:
                        averages[devId]["n"] += 1
                        for color in values:
                            averages[devId][color] += values[color]
                            values[color] = averages[devId][color] / averages[
                                devId]["n"]
                            if averages[devId]["n"] >= doAverage:
                                averages[devId][color] = 0
                        if averages[devId]["n"] >= doAverage:
                            averages[devId]["n"] = 0
Esempio n. 13
0
		if	data0 != {}:
			if data0 != lastData or (tt-lastMsg > G.sendToIndigoSecs) or quick: #
				lastGPIO= U.doActions(data0,lastGPIO, sensors, sensBase+"-1")
							
				lastMsg=tt
				lastData=copy.copy(data0)
				data["sensors"]		= data0
				U.sendURL(data)

		U.makeDATfile(G.program, data)
		quick = U.checkNowFile(G.program)
		U.manageActions("-loop-")
		if loopCount%50==0:
			U.echoLastAlive(G.program)
			if time.time()- lastRead > 10:
				readParams()
				lastRead = time.time()

		if restartCount >0:
			U.restartMyself(param="", reason=" io error",doPrint=True)

		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)

	   
Esempio n. 14
0
                lastGPIO = U.doActions(data0, lastGPIO, sensors,
                                       sensBase + "-1")

                lastMsg = tt
                lastData = copy.copy(data0)
                data["sensors"] = data0
                U.sendURL(data)

        U.makeDATfile(G.program, data)
        quick = U.checkNowFile(G.program)
        U.manageActions("-loop-")
        if loopCount % 50 == 0:
            U.echoLastAlive(G.program)
            if time.time() - lastRead > 10:
                readParams()
                lastRead = time.time()

        if restartCount > 0:
            U.restartMyself(param="", reason=" io error", doPrint=True)

        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 readParams():
		global sensors
		global oldRaw, lastRead, INPUTS
		global counts, countSignals
		global useWhichGPIO, useThreads


		inp,inpRaw,lastRead2 = U.doRead(lastTimeStamp=lastRead)
		if inp == "": return
		if lastRead2 == lastRead: return
		lastRead   = lastRead2
		if inpRaw == oldRaw: return
		oldRaw	   = inpRaw

		oldSensors  = sensors

		U.getGlobalParams(inp)
		if "sensors"			in inp : sensors =				(inp["sensors"])
		if "debugRPI"			in inp:	 G.debug=			  int(inp["debugRPI"]["debugRPISENSOR"])
		if oldSensors == sensors: return 

		restart = False
			
		if G.program  not in sensors:
			print G.program + "  not in sensors" 
			stopProgram()

		oldINPUTS  = copy.deepcopy(INPUTS)
		restart    = False
		if sensor in sensors:
			for devId in sensors[sensor]:
				new = False
				sens = sensors[sensor][devId]
				if devId not in INPUTS: 
					INPUTS[devId]  = {"pinALastValue":9999999, "incrementIfGT4Signals": "0", "lastChangeTime":0, "pinBLastValue":9999999, "pinA":21, "pinB":20, "inverse": True,"direction": 0, "newCycle":False, "distinctTransition":False, "ignorePinValue": "0","lastEvent": 0, "resetTimeCheck":0.001}
					#INPUTS[devId]["LockRotary"] = threading.Lock()		# create lock for rotary switch

				if devId not in counts:
					counts[devId] = 0
				if devId not in countSignals:
					countSignals[devId] = 0

				if "INPUT_0" in sens:
					if  INPUTS[devId]["pinA"] != int(sens["INPUT_0"]):
						INPUTS[devId]["pinA"]  = int(sens["INPUT_0"])
						new = True

				if "INPUT_1" in sens:
					if  INPUTS[devId]["pinB"] != int(sens["INPUT_1"]):
						INPUTS[devId]["pinB"]  = int(sens["INPUT_1"])
						new = True

				if "resetTimeCheck" in sens:
						INPUTS[devId]["resetTimeCheck"]  		= float(sens["resetTimeCheck"])

				if "inverse" in sens:
						INPUTS[devId]["inverse"]   				= (sens["inverse"] == "1")

				if "distinctTransition" in sens:
						INPUTS[devId]["distinctTransition"]		= (sens["distinctTransition"] == "1")

				if "ignorePinValue" in sens:
						INPUTS[devId]["ignorePinValue"] 		= int(sens["ignorePinValue"])

				if "incrementIfGT4Signals" in sens:
						INPUTS[devId]["incrementIfGT4Signals"]  = (sens["incrementIfGT4Signals"]=="1")

				if "useWhichGPIO" in sens:
						xxx 							 = sens["useWhichGPIO"].split("-")
						if  useWhichGPIO != xxx[0]:
							new = True
						if  useThreads != (xxx[1] == "threads"):
							new = True
						useWhichGPIO = xxx[0]
						useThreads	 = xxx[1] == "threads"
						
					
				if oldINPUTS != {} and new:
					restart = True
					break
				elif oldINPUTS == {} or new:
					startGPIO(devId)
		if restart:
			stopProgram(action ="onlyThread")
			U.restartMyself(reason="new parameters")
		return 
Esempio n. 16
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] 

					if	 sensitivity[devId] =="small" : recalib = [20,20]
Esempio n. 17
0
            if time.time() - lastRead > 5:
                readParams()
                lastRead = time.time()
                if U.checkResetFile(G.program):
                    resetValues()
                    checkIfMSGtoBeSend(force=True)

            checkIfRelayON()

            checkIfDownGradedNeeded()
            checkIfMSGtoBeSend()

            if loopCount % 60 == 0:
                U.echoLastAlive(G.program)

        getGPIO(gpioIn, calledFrom="loop")

        if restart:
            U.restartMyself(param="", reason=" new definitions", doPrint=True)

        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)
Esempio n. 18
0
def readParams():
	global sensor, sensors
	global gpioIn , gpioSW1 ,gpioSW2, gpioSW5, gpioSWP, cyclePower, sensorMode
	global ON, off
	global oldRaw, lastRead
	global switchToLowerSensitive, switchToHigherSensitive, bucketSize,bucketSize0, sendMSGEverySecs
	global status
	try:
		restart = False


		inp,inpRaw,lastRead2 = U.doRead(lastTimeStamp=lastRead)
		if inp == "": return
		if lastRead2 == lastRead: return
		lastRead  = lastRead2
		if inpRaw == oldRaw: return
		oldRaw	   = inpRaw


		oldSensors		  = sensors

		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(0,	"no "+ G.program+" sensor defined, exiting",doPrint=True)
			exit()

		sens= sensors[sensor]
		found ={str(ii):{"RISING":0,"GPIOchanged":0,"BOTH":0 } for ii in range(100)}
		for devId in sens:
			sss= sens[devId]
			if "gpioIn"					   not in sss: continue
			if "gpioSW5"				   not in sss: continue
			if "gpioSW2"				   not in sss: continue
			if "gpioSW1"				   not in sss: continue
			if "gpioSWP"				   not in sss: continue
			if "sensorMode"				   not in sss: continue
			
			cp	= sss["cyclePower"] != "0"

			if gpioIn != -1 and gpioIn != int(sss["gpioIn"]):
				restart = True
				U.toLog(0,	"gpios channel changed, need to restart",doPrint=True)
				U.restartMyself(param="", reason=" new gpioIn",doPrint=True)
				return 

			cyclePower = True 
			if gpioSWP != int(sss["gpioSWP"]):
				gpioSWP = int(sss["gpioSWP"])
				if gpioSWP >0: GPIO.setup(gpioSWP, GPIO.OUT)
				powerOFF(calledFrom="read")
			if gpioSW1 != int(sss["gpioSW1"]):
				gpioSW1 = int(sss["gpioSW1"])
				if gpioSW1 >0: GPIO.setup(gpioSW1, GPIO.OUT)
			if gpioSW2 != int(sss["gpioSW2"]):
				gpioSW2 = int(sss["gpioSW2"])
				if gpioSW2 >0: GPIO.setup(gpioSW2, GPIO.OUT)
			if gpioSW5 != int(sss["gpioSW5"]):
				gpioSW5 = int(sss["gpioSW5"])
				if gpioSW5 >0: GPIO.setup(gpioSW5, GPIO.OUT)
			switchToLowerSensitive["checkIfIsRaining"]	= 10# int(sss["TimeSwitchSensitivityRainToMayBeRaining"])
			switchToLowerSensitive["maybeRain"]			= 10# int(sss["TimeSwitchSensitivityMayBeRainingToHigh"])
			switchToLowerSensitive["highSensitive"]		= 10# int(sss["TimeSwitchSensitivityHighToMed"])
			switchToLowerSensitive["medSensitive"]		= 10# int(sss["TimeSwitchSensitivityMedToLow"])
			
			switchToHigherSensitive["lowSensitive"]		= 100# int(sss["TimeSwitchSensitivityLowToMed"])
			switchToHigherSensitive["medSensitive"]		= 100# int(sss["TimeSwitchSensitivityMedToHigh"])
			switchToHigherSensitive["highSensitive"]	= 100# int(sss["TimeSwitchSensitivityHighToAnyRain"])
			try: rainScaleFactor						= float(sss["rainScaleFactor"])
			except: rainScaleFactor						= 1.
				
			if gpioIn != int(sss["gpioIn"]):
				gpioIn	= int(sss["gpioIn"])
				GPIO.setup(gpioIn,	GPIO.IN, pull_up_down=GPIO.PUD_UP)
				GPIO.add_event_detect(gpioIn, GPIO.FALLING,		callback=GPIOchanged, bouncetime=100)  
				if sss["sensorMode"] != "dynamic":	setModeTo("checkIfIsRaining", calledFrom="readParams1")

			if sensorMode != sss["sensorMode"]:
				if sss["sensorMode"] != "dynamic":
					sendShortStatus(rainMsg["checkIfIsRaining"])
					nextModeSwitchNotBefore= time.time()+2
				setModeTo(sss["sensorMode"],force=True, calledFrom="readParams2")

			sensorMode									= sss["sensorMode"]
			sendMSGEverySecs							= float(sss["sendMSGEverySecs"])
			time.sleep(0.4)
			powerON(calledFrom="read")
			cyclePower = cp

			bucketSize={}
			for kk in bucketSize0:
				bucketSize[kk] = bucketSize0[kk]*rainScaleFactor

			
	except	Exception, e:
		U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e),doPrint=True)
Esempio n. 19
0
			if time.time()- lastRead > 5:
				readParams()
				lastRead = time.time()
				if U.checkResetFile(G.program):
					resetValues()
					checkIfMSGtoBeSend(force=True)
					

			checkIfRelayON()

			checkIfDownGradedNeeded()
			checkIfMSGtoBeSend()

			if loopCount%60==0:
					U.echoLastAlive(G.program)
			
		getGPIO(gpioIn,calledFrom="loop")

		if restart:
			U.restartMyself(param="", reason=" new definitions",doPrint=True)


		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)
Esempio n. 20
0
def readParams():
	global sensor, sensors
	global INPgpioType,INPUTcount,INPUTlastvalue
	global GPIOdict, restart
	global oldRaw, lastRead
	try:
		restart = False


		inp,inpRaw,lastRead2 = U.doRead(lastTimeStamp=lastRead)
		if inp == "": return
		if lastRead2 == lastRead: return
		lastRead  = lastRead2
		if inpRaw == oldRaw: return
		oldRaw	   = inpRaw

		oldSensors		  = sensors

		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(0,	"no "+ G.program+" sensor defined, exiting",doPrint=True)
			exit()

		sens= sensors[sensor]
		#print "sens:", sens
		found ={str(ii):{"RISING":0,"FALLING":0,"BOTH":0 } for ii in range(100)}
		for devId in sens:
			sss= sens[devId]
			if "gpio"							not in sss: continue
			if "deadTime"						not in sss: continue
			if "risingOrFalling"				not in sss: continue
			if "minSendDelta"					not in sss: continue
			if "bounceTime"						not in sss: continue
			if "deadTime"						not in sss: continue
			if "deadTimeBurst"					not in sss: continue
			if "inpType"						not in sss: continue
			if "timeWindowForBursts"			not in sss: continue
			if "timeWindowForLongEvents"		not in sss: continue
			if "timeWindowForContinuousEvents"	not in sss: continue
			if "minBurstsinTimeWindowToTrigger" not in sss: continue

			gpio						= sss["gpio"]
			risingOrFalling				= sss["risingOrFalling"]
			inpType						= sss["inpType"]

			try:	bounceTime			= int(sss["bounceTime"])
			except: bounceTime			= 10

			try:	timeWindowForLongEvents = float(sss["timeWindowForLongEvents"])
			except: timeWindowForLongEvents = -1

			try:	minSendDelta		= int(sss["minSendDelta"])
			except: minSendDelta		= 1

			try:	deadTime			= float(sss["deadTime"])
			except: deadTime			= 1

			try:	deadTimeBurst		= float(sss["deadTimeBurst"])
			except: deadTimeBurst		= 1

			try:	timeWindowForBursts = int(sss["timeWindowForBursts"])
			except: timeWindowForBursts = -1

			try:	minBurstsinTimeWindowToTrigger = int(sss["minBurstsinTimeWindowToTrigger"])
			except: minBurstsinTimeWindowToTrigger = -1

			try:	timeWindowForLongEvents = float(sss["timeWindowForLongEvents"])
			except: timeWindowForLongEvents = -1

			try:	pulseEveryXXsecsLongEvents = float(sss["pulseEveryXXsecsLongEvents"])
			except: pulseEveryXXsecsLongEvents = -1

			try:	timeWindowForContinuousEvents = float(sss["timeWindowForContinuousEvents"])
			except: timeWindowForContinuousEvents = -1


			found[gpio][risingOrFalling]		 = 1
			if gpio in GPIOdict and "risingOrFalling" in GPIOdict[gpio]: 
					if GPIOdict[gpio]["bounceTime"] !=	bounceTime: 
						restart=True
						return
					if GPIOdict[gpio]["risingOrFalling"] !=	 risingOrFalling: 
						restart=True
						return
					GPIOdict[gpio]["deadTime"]								= deadTime
					GPIOdict[gpio]["deadTimeBurst"]							= deadTimeBurst
					GPIOdict[gpio]["devId"]									= devId
					GPIOdict[gpio]["minSendDelta"]							= minSendDelta
					GPIOdict[gpio]["minBurstsinTimeWindowToTrigger"]		= minBurstsinTimeWindowToTrigger
					GPIOdict[gpio]["timeWindowForBursts"]					= timeWindowForBursts
					GPIOdict[gpio]["timeWindowForLongEvents"]				= timeWindowForLongEvents
					GPIOdict[gpio]["timeWindowForContinuousEvents"]			= timeWindowForContinuousEvents
					GPIOdict[gpio]["pulseEveryXXsecsLongEvents"]			= pulseEveryXXsecsLongEvents
					GPIOdict[gpio]["lastsendBurst"]							= 0
					GPIOdict[gpio]["lastsendCount"]							= 0
					GPIOdict[gpio]["lastsendlongEvent"]						= 0
					GPIOdict[gpio]["lastsendContinuousEvent"]				= 0
					if inpType != GPIOdict[gpio]["inpType"]:
						if	 inpType == "open":
							GPIO.setup(int(gpio), GPIO.IN)
						elif inpType == "high":
							GPIO.setup(int(gpio), GPIO.IN, pull_up_down=GPIO.PUD_UP)
						elif inpType == "low":
							GPIO.setup(int(gpio), GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
					GPIOdict[gpio]["inpType"]	 = inpType
					continue 
			elif gpio in GPIOdict and "risingOrFalling" not in GPIOdict[gpio]: 
				print "setting up ",risingOrFalling
				GPIOdict[gpio]={
								  "devId":							devId,
								  "inpType":						inpType,
								  "minSendDelta":					minSendDelta,
								  "bounceTime":						bounceTime,
								  "deadTime":						deadTime,
								  "deadTimeBurst":					deadTimeBurst,
								  "risingOrFalling":				risingOrFalling,
								  "timeWindowForBursts":			timeWindowForBursts,
								  "timeWindowForLongEvents":		timeWindowForLongEvents,
								  "pulseEveryXXsecsLongEvents":		pulseEveryXXsecsLongEvents,
								  "timeWindowForContinuousEvents":	timeWindowForContinuousEvents,
								  "minBurstsinTimeWindowToTrigger": minBurstsinTimeWindowToTrigger,
								  "lastSignal":						0,
								  "lastsendCount":					0,
								  "lastsendBurst":					0,
								  "lastsendlongEvent":				0,
								  "lastsendContinuousEvent":		0,
								  "count":							0 }
				print  GPIOdict				  
				if	 inpType == "open":
					GPIO.setup(int(gpio), GPIO.IN)
				elif inpType == "high":
					GPIO.setup(int(gpio), GPIO.IN, pull_up_down=GPIO.PUD_UP)
				elif inpType == "low":
					GPIO.setup(int(gpio), GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
				if	risingOrFalling == "RISING": 
					GPIO.add_event_detect(int(gpio), GPIO.RISING,	callback=RISING,  bouncetime=bounceTime)  
				elif  risingOrFalling == "FALLING": 
					GPIO.add_event_detect(int(gpio), GPIO.FALLING,	callback=FALLING, bouncetime=bounceTime)  
				else:
					GPIO.add_event_detect(int(gpio), GPIO.BOTH,		callback=BOTH, bouncetime=bounceTime)  
				GPIOdict[gpio]["inpType"]	 = inpType

			elif gpio not in GPIOdict: # change: reboot 
				GPIOdict[gpio]={
								  "devId":							devId,
								  "inpType":						inpType,
								  "minSendDelta":					minSendDelta,
								  "bounceTime":						bounceTime,
								  "deadTime":						deadTime,
								  "deadTimeBurst":					deadTimeBurst,
								  "risingOrFalling":				risingOrFalling,
								  "timeWindowForBursts":			timeWindowForBursts,
								  "timeWindowForLongEvents":		timeWindowForLongEvents,
								  "pulseEveryXXsecsLongEvents":		pulseEveryXXsecsLongEvents,
								  "timeWindowForContinuousEvents":	timeWindowForContinuousEvents,
								  "minBurstsinTimeWindowToTrigger": minBurstsinTimeWindowToTrigger,
								  "lastSignal":						0,
								  "lastsendCount":					0,
								  "lastsendBurst":					0,
								  "lastsendlongEvent":				0,
								  "lastsendContinuousEvent":		0,
								  "count":							0 }
				print  ""				
				if	 inpType == "open":
					GPIO.setup(int(gpio), GPIO.IN)
				elif inpType == "high":
					GPIO.setup(int(gpio), GPIO.IN, pull_up_down=GPIO.PUD_UP)
				elif inpType == "low":
					GPIO.setup(int(gpio), GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
				if	risingOrFalling == "RISING": 
					GPIO.add_event_detect(int(gpio), GPIO.RISING,	callback=RISING,  bouncetime=bounceTime)  
				elif  risingOrFalling == "FALLING": 
					GPIO.add_event_detect(int(gpio), GPIO.FALLING,	callback=FALLING, bouncetime=bounceTime)  
				else:
					GPIO.add_event_detect(int(gpio), GPIO.BOTH,		callback=BOTH, bouncetime=bounceTime)  
				GPIOdict[gpio]["inpType"]	 = inpType
				
		oneFound = False
		restart=False
		delGPIO={}
		for gpio in GPIOdict:
			for risingOrFalling in["FALLING","RISING","BOTH"]:
				if found[gpio][risingOrFalling]==1: 
					oneFound = True
					continue
				if risingOrFalling in GPIOdict:
					restart=True
					continue
			if GPIOdict[gpio] == {}: delGPIO[gpio]=1
		for gpio in delGPIO:
			if gpio in GPIOdict: del GPIOdict[gpio]
		
		if not oneFound:
			U.toLog(0,	"no	 gpios setup, exiting",doPrint=True)
			exit()
		if	restart:
			U.toLog(0,	"gpios edge channel deleted, need to restart",doPrint=True)
			U.restartMyself(param="", reason=" new definitions",doPrint=True)
			
		U.toLog(0,	"GPIOdict: " +unicode(GPIOdict),doPrint=True)
	except	Exception, e:
		U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e),doPrint=True)
Esempio n. 21
0
def restartNEOpixel(param=""):
	global devType,lastdevType
	U.restartMyself(reason="restarting due to new device type, old="+devTypeLast+" new="+devType, param=param, doPrint=True)
Esempio n. 22
0
def readParams():
		global sensors
		global oldRaw, lastRead, nInputs, INPUTS, nBits


		inp,inpRaw,lastRead2 = U.doRead(lastTimeStamp=lastRead)
		if inp == "": return
		if lastRead2 == lastRead: return
		lastRead   = lastRead2
		if inpRaw == oldRaw: return
		oldRaw	   = inpRaw

		oldSensors  = sensors

		U.getGlobalParams(inp)
		if "sensors"			in inp : sensors =				(inp["sensors"])
		if "debugRPI"			in inp:	 G.debug=			  int(inp["debugRPI"]["debugRPISENSOR"])
		if oldSensors == sensors: return 

		restart = False
			
		if G.program  not in sensors:
			print G.program + "  not in sensors" 
			exit()
		oldINPUTS  = copy.deepcopy(INPUTS)
		restart    = False
		if sensor in sensors:
				for devId in sensors[sensor]:
					new = False
					sens = sensors[sensor][devId]

					nInputs[devId] = int(sens["nInputs"])
					if devId not in INPUTS: 
						INPUTS[devId]  = {"lastValue":-1,"codeType":"bin","pinI":[],"nBits":0}

					INPUTS[devId]["codeType"] = sens["codeType"]

					for nn in range(nInputs[devId]):
						if len(INPUTS[devId]["pinI"]) < nn+1:
							INPUTS[devId]["pinI"].append(-1)
							new = True
						if INPUTS[devId]["pinI"][nn] != sens["INPUT_"+str(nn)]:
							new = True
							INPUTS[devId]["lastValue"] = -1
						INPUTS[devId]["pinI"][nn] = int(sens["INPUT_"+str(nn)])

					if "nBits" in sens: 
						try:    INPUTS[devId]["nBits"]= int(sens["nBits"])
						except: pass

					## oupt GPIOs
					for nn in range(27):
						if "OUTPUT_"+str(nn) in sens:
							if "pinO" not in INPUTS[devId]:
								INPUTS[devId]["pinO"]=[]
								new = True
							if len(INPUTS[devId]["pinO"]) < nn+1:
								INPUTS[devId]["pinO"].append(-1)
								new = True
							if INPUTS[devId]["pinO"][nn] != int(sens["OUTPUT_"+str(nn)]):
								new = True
							INPUTS[devId]["pinO"][nn] = int(sens["OUTPUT_"+str(nn)])
					if oldINPUTS != {} and new:
						restart = True
						break
					elif oldINPUTS == {} or new:
						startGPIO(devId)
				
		if restart:
			U.restartMyself(reason="new parameters")
		return 
Esempio n. 23
0
			for devId in sensors[sensor]:
				if devId not in lastValues: 
					lastValues[devId]  =copy.copy(lastValues0)
					lastValues2[devId] =copy.copy(lastValues0)
				values = getValues(devId)
				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)
						resetSensor(devId=devId)
					else:
						U.restartMyself(param="", reason="badsensor",doPrint=True)
					lastValues2[devId] =copy.copy(lastValues0)
					lastValues[devId]  =copy.copy(lastValues0)
					continue
				elif values["particles_03um"] !="" :
					
					data["sensors"][sensor][devId] = values
					deltaN =0
					for xx in lastValues0:
						try:
							current = float(values[xx])
							delta= current-lastValues2[devId][xx]
							deltaN= max(deltaN,abs(delta) / max (0.5,(current+lastValues2[devId][xx])/2.))
							lastValues[devId][xx] = current
						except: pass
				else:
Esempio n. 24
0
devTypeLEDs					= "start"
inpRaw						= ""
inp							= ""
debug						= 5
first						= False
loopCount					= 0
sensor						= G.program

# check for corrupt parameters file 
U.checkParametersFile("parameters-DEFAULT-clock", force = False)

if readParams() ==3:
		U.toLog(-1," parameters not defined", doPrint=True)
		U.checkParametersFile("parameters-DEFAULT-clock", force = True)
		time.sleep(20)
		U.restartMyself(param=" bad parameters read", reason="",doPrint=True)
	

myPID		= str(os.getpid())
U.killOldPgm(myPID,G.program+".py")# kill old instances of myself if they are still running


U.killOldPgm(myPID,"neopixel.py")

readMarksFile()
getCurrentPatterns()

U.echoLastAlive(G.program)

setAllSwitchesOff()
setupGPIOforTimeset()
Esempio n. 25
0
devTypeLEDs					= "start"
inpRaw						= ""
inp							= ""
debug						= 5
first						= False
loopCount					= 0
sensor						= G.program

# check for corrupt parameters file 
U.checkParametersFile("parameters-DEFAULT-clock", force = False)

if readParams() ==3:
		U.toLog(-1," parameters not defined", doPrint=True)
		U.checkParametersFile("parameters-DEFAULT-clock", force = True)
		time.sleep(20)
		U.restartMyself(param=" bad parameters read", reason="",doPrint=True)
	

myPID		= str(os.getpid())
U.killOldPgm(myPID,G.program+".py")# kill old instances of myself if they are still running


U.killOldPgm(myPID,"neopixel.py")

readMarksFile()
getCurrentPatterns()

U.echoLastAlive(G.program)

setAllSwitchesOff()
setupGPIOforTimeset()
def startGPIO(devId):
	global INPUTS, pinsToDevid
	global threadDict, useThreads
	global useWhichGPIO, PIGPIO, pigpio, lastTick
	global debug

	try:
		pinsToDevid[INPUTS[devId]["pinA"]] = devId
		pinsToDevid[INPUTS[devId]["pinB"]] = devId
		U.toLog(-1, "pinsToDevid "+unicode(pinsToDevid), doPrint=True)

		if useWhichGPIO == "pig":
			if PIGPIO == "":
				import pigpio
				import threading 
				import Queue
				if not U.pgmStillRunning("pigpiod"): 	
					U.toLog(-1, "starting pigpiod", doPrint=True)
					os.system("sudo pigpiod &")
					time.sleep(0.5)
					if not U.pgmStillRunning("pigpiod"): 	
						U.toLog(-1, " restarting myself as pigpiod not running, need to wait for timeout to release port 8888", doPrint=True)
						time.sleep(20)
						U.restartMyself(reason="pigpiod not running")
						exit(0)

				PIGPIO = pigpio.pi()
				threadDict["queue"] = Queue.Queue()
				threadDict["thread"] = threading.Thread(target=workQueue, name="workQueue" )
				threadDict["thread"].start()
				
			if devId not in threadDict:
				threadDict[devId] ={ "pinA":"",  "pinB":"" }

			U.toLog(-1, "PIGPIO setup for devId"+str(devId)+"  "+ str(INPUTS[devId]), doPrint=True)
			PIGPIO.set_mode( INPUTS[devId]["pinA"], pigpio.INPUT)
			PIGPIO.set_pull_up_down( INPUTS[devId]["pinA"], pigpio.PUD_UP )
			PIGPIO.set_mode( INPUTS[devId]["pinB"], pigpio.INPUT)
			PIGPIO.set_pull_up_down( INPUTS[devId]["pinB"], pigpio.PUD_UP )

			threadDict[devId]["pinA"] = PIGPIO.callback(INPUTS[devId]["pinA"], pigpio.EITHER_EDGE, pigEVENTthread)
			threadDict[devId]["pinB"] = PIGPIO.callback(INPUTS[devId]["pinB"], pigpio.EITHER_EDGE, pigEVENTthread)
			return

		elif useWhichGPIO == "rpi":
			U.toLog(-1, "GPIO  setting up gpio "+str(devId)+"  "+ str(INPUTS[devId]), doPrint=True)
			GPIO.setup( INPUTS[devId]["pinA"], GPIO.IN, pull_up_down=GPIO.PUD_UP)
			GPIO.setup( INPUTS[devId]["pinB"], GPIO.IN, pull_up_down=GPIO.PUD_UP)
			if useThreads: 
				if 	"queue" not in threadDict:
					import threading 
					import Queue
					threadDict["queue"] = Queue.Queue()
					threadDict["thread"] = threading.Thread(target=workQueue, name="workQueue" )
					threadDict["thread"].start()
				GPIO.add_event_detect( INPUTS[devId]["pinA"], GPIO.BOTH, callback=gpioEVENTthread ) 		
				GPIO.add_event_detect( INPUTS[devId]["pinB"], GPIO.BOTH, callback=gpioEVENTthread ) 
			else:
				GPIO.add_event_detect( INPUTS[devId]["pinA"], GPIO.BOTH, callback=workEvent ) 		
				GPIO.add_event_detect( INPUTS[devId]["pinB"], GPIO.BOTH, callback=workEvent ) 

		else:
			print " error useWhichGPIO not defined"
			exit()
		

		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,"start "+ G.program+ "  "+ unicode(sensors), doPrint=True)
Esempio n. 27
0
def getValues(devId):
	global sensor, sensors,	 BNO055sensor
	global CALlast, lastWriteCalibration, badSelfTest 
	try:
		data = {}
		for ii in range(5):
		   # Read the calibration status, 0=uncalibrated and 3=fully calibrated.
			CALsys, CALgyro, CALaccel, CALmag = BNO055sensor[devId].get_calibration_status()
			status = BNO055sensor[devId]._read_byte(BNO055_SYS_STAT_ADDR)&0b01111111
			if CALsys < 2  or (CALgyro + CALaccel +CALmag) <4  or status !=0b00000101 :
				if badSelfTest > 0:
					U.toLog(1,"CHECK STATUS: badSelfTest count= " +unicode(badSelfTest)+"  not calibrated, wait and try again: "+ unicode({"SYS":str(CALsys),"GYR":str(CALgyro),"ACC":str(CALaccel),"MAG":str(CALmag)}))
					status, self_test, error = BNO055sensor[devId].get_system_status()
					U.toLog(1,'CHECK STATUS: Self test result : 0x{0:02X}'.format(self_test)+ "(0x0F is normal)")
					U.toLog(1,'CHECK STATUS: status result	  : 0x{0:b}'.format(status&0b01111111)+" (101 is normal)")
				badSelfTest +=1
				if badSelfTest > 11:
					U.restartMyself(reason="CHECK STATUS:  self test result failed 11 times", doPrint=False)
				time.sleep(0.3)
				continue
			if badSelfTest > 3:
					U.toLog(1,"CHECK STATUS: SelfTest ok  again , badSelfTest was: "+unicode(badSelfTest)+ ";  "+ unicode({"SYS":str(CALsys),"GYR":str(CALgyro),"ACC":str(CALaccel),"MAG":str(CALmag)}))
			badSelfTest =0
			break
			
		tt= time.time()
		if tt - lastWriteCalibration > 5: 
			BNO055sensor[devId].writeCalibrationToFile(BNO055sensor[devId].get_calibration())
			lastWriteCalibration = tt
			
		
		# Sensor temperature in degrees Celsius:
		t = BNO055sensor[devId].read_temp()

		if t < -30 or t > 80:
			data["calibration"] = {"SYS":str(CALsys),"GYR":str(CALgyro),"ACC":str(CALaccel),"MAG":str(CALmag)  }
		else:
			data["calibration"] = {"SYS":str(CALsys),"GYR":str(CALgyro),"ACC":str(CALaccel),"MAG":str(CALmag)  ,"temp":t}

		# Read the Euler angles for heading, roll, pitch (all in degrees).
		data["EULER"] = fillWithItems(BNO055sensor[devId].read_euler(),["heading","roll","pitch"],2)

		time.sleep(0.01)
		# Gravity acceleration data (i.e. acceleration just from gravity--returned
		# in meters per second squared):
		data["GRAV"] = fillWithItems(BNO055sensor[devId].read_gravity(),["x","y","z"],2)


		time.sleep(0.01)
		# Magnetometer data (in micro-Teslas):
		MAG =  fillWithItems(BNO055sensor[devId].read_magnetometer(),["x","y","z"],1)
		data["MAG"] = MAG


		time.sleep(0.01)
		# Gyroscope data (in degrees per second):
		data["GYR"] = fillWithItems(BNO055sensor[devId].read_gyroscope(),["x","y","z"],2)

		time.sleep(0.01)
		# Accelerometer data (in meters per second squared):
		data["ACC"] = fillWithItems(BNO055sensor[devId].read_accelerometer(),["x","y","z"],1)


		time.sleep(0.01)
		# Linear acceleration data (i.e. acceleration from movement, not gravity--
		# returned in meters per second squared):
		data["LIN"] = fillWithItems(BNO055sensor[devId].read_linear_acceleration(),["x","y","z"],1)

		#print data
		for xx in data:
			U.toLog(2, (xx).ljust(11)+" "+unicode(data[xx]))
		return data
	except	Exception, e:
		U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
Esempio n. 28
0
def readParams():
    global sensor, sensors
    global INPgpioType, INPUTcount, INPUTlastvalue
    global GPIOdict, restart
    global oldRaw, lastRead
    try:
        restart = False

        inp, inpRaw, lastRead2 = U.doRead(lastTimeStamp=lastRead)
        if inp == "": return
        if lastRead2 == lastRead: return
        lastRead = lastRead2
        if inpRaw == oldRaw: return
        oldRaw = inpRaw

        oldSensors = sensors

        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(0,
                    "no " + G.program + " sensor defined, exiting",
                    doPrint=True)
            exit()

        sens = sensors[sensor]
        #print "sens:", sens
        found = {
            str(ii): {
                "RISING": 0,
                "FALLING": 0,
                "BOTH": 0
            }
            for ii in range(100)
        }
        for devId in sens:
            sss = sens[devId]
            if "gpio" not in sss: continue
            if "deadTime" not in sss: continue
            if "risingOrFalling" not in sss: continue
            if "minSendDelta" not in sss: continue
            if "bounceTime" not in sss: continue
            if "deadTime" not in sss: continue
            if "deadTimeBurst" not in sss: continue
            if "inpType" not in sss: continue
            if "timeWindowForBursts" not in sss: continue
            if "timeWindowForLongEvents" not in sss: continue
            if "timeWindowForContinuousEvents" not in sss: continue
            if "minBurstsinTimeWindowToTrigger" not in sss: continue

            gpio = sss["gpio"]
            risingOrFalling = sss["risingOrFalling"]
            inpType = sss["inpType"]

            try:
                bounceTime = int(sss["bounceTime"])
            except:
                bounceTime = 10

            try:
                timeWindowForLongEvents = float(sss["timeWindowForLongEvents"])
            except:
                timeWindowForLongEvents = -1

            try:
                minSendDelta = int(sss["minSendDelta"])
            except:
                minSendDelta = 1

            try:
                deadTime = float(sss["deadTime"])
            except:
                deadTime = 1

            try:
                deadTimeBurst = float(sss["deadTimeBurst"])
            except:
                deadTimeBurst = 1

            try:
                timeWindowForBursts = int(sss["timeWindowForBursts"])
            except:
                timeWindowForBursts = -1

            try:
                minBurstsinTimeWindowToTrigger = int(
                    sss["minBurstsinTimeWindowToTrigger"])
            except:
                minBurstsinTimeWindowToTrigger = -1

            try:
                timeWindowForLongEvents = float(sss["timeWindowForLongEvents"])
            except:
                timeWindowForLongEvents = -1

            try:
                pulseEveryXXsecsLongEvents = float(
                    sss["pulseEveryXXsecsLongEvents"])
            except:
                pulseEveryXXsecsLongEvents = -1

            try:
                timeWindowForContinuousEvents = float(
                    sss["timeWindowForContinuousEvents"])
            except:
                timeWindowForContinuousEvents = -1

            found[gpio][risingOrFalling] = 1
            if gpio in GPIOdict and "risingOrFalling" in GPIOdict[gpio]:
                if GPIOdict[gpio]["bounceTime"] != bounceTime:
                    restart = True
                    return
                if GPIOdict[gpio]["risingOrFalling"] != risingOrFalling:
                    restart = True
                    return
                GPIOdict[gpio]["deadTime"] = deadTime
                GPIOdict[gpio]["deadTimeBurst"] = deadTimeBurst
                GPIOdict[gpio]["devId"] = devId
                GPIOdict[gpio]["minSendDelta"] = minSendDelta
                GPIOdict[gpio][
                    "minBurstsinTimeWindowToTrigger"] = minBurstsinTimeWindowToTrigger
                GPIOdict[gpio]["timeWindowForBursts"] = timeWindowForBursts
                GPIOdict[gpio][
                    "timeWindowForLongEvents"] = timeWindowForLongEvents
                GPIOdict[gpio][
                    "timeWindowForContinuousEvents"] = timeWindowForContinuousEvents
                GPIOdict[gpio][
                    "pulseEveryXXsecsLongEvents"] = pulseEveryXXsecsLongEvents
                GPIOdict[gpio]["lastsendBurst"] = 0
                GPIOdict[gpio]["lastsendCount"] = 0
                GPIOdict[gpio]["lastsendlongEvent"] = 0
                GPIOdict[gpio]["lastsendContinuousEvent"] = 0
                if inpType != GPIOdict[gpio]["inpType"]:
                    if inpType == "open":
                        GPIO.setup(int(gpio), GPIO.IN)
                    elif inpType == "high":
                        GPIO.setup(int(gpio),
                                   GPIO.IN,
                                   pull_up_down=GPIO.PUD_UP)
                    elif inpType == "low":
                        GPIO.setup(int(gpio),
                                   GPIO.IN,
                                   pull_up_down=GPIO.PUD_DOWN)
                GPIOdict[gpio]["inpType"] = inpType
                continue
            elif gpio in GPIOdict and "risingOrFalling" not in GPIOdict[gpio]:
                print "setting up ", risingOrFalling
                GPIOdict[gpio] = {
                    "devId": devId,
                    "inpType": inpType,
                    "minSendDelta": minSendDelta,
                    "bounceTime": bounceTime,
                    "deadTime": deadTime,
                    "deadTimeBurst": deadTimeBurst,
                    "risingOrFalling": risingOrFalling,
                    "timeWindowForBursts": timeWindowForBursts,
                    "timeWindowForLongEvents": timeWindowForLongEvents,
                    "pulseEveryXXsecsLongEvents": pulseEveryXXsecsLongEvents,
                    "timeWindowForContinuousEvents":
                    timeWindowForContinuousEvents,
                    "minBurstsinTimeWindowToTrigger":
                    minBurstsinTimeWindowToTrigger,
                    "lastSignal": 0,
                    "lastsendCount": 0,
                    "lastsendBurst": 0,
                    "lastsendlongEvent": 0,
                    "lastsendContinuousEvent": 0,
                    "count": 0
                }
                print GPIOdict
                if inpType == "open":
                    GPIO.setup(int(gpio), GPIO.IN)
                elif inpType == "high":
                    GPIO.setup(int(gpio), GPIO.IN, pull_up_down=GPIO.PUD_UP)
                elif inpType == "low":
                    GPIO.setup(int(gpio), GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
                if risingOrFalling == "RISING":
                    GPIO.add_event_detect(int(gpio),
                                          GPIO.RISING,
                                          callback=RISING,
                                          bouncetime=bounceTime)
                elif risingOrFalling == "FALLING":
                    GPIO.add_event_detect(int(gpio),
                                          GPIO.FALLING,
                                          callback=FALLING,
                                          bouncetime=bounceTime)
                else:
                    GPIO.add_event_detect(int(gpio),
                                          GPIO.BOTH,
                                          callback=BOTH,
                                          bouncetime=bounceTime)
                GPIOdict[gpio]["inpType"] = inpType

            elif gpio not in GPIOdict:  # change: reboot
                GPIOdict[gpio] = {
                    "devId": devId,
                    "inpType": inpType,
                    "minSendDelta": minSendDelta,
                    "bounceTime": bounceTime,
                    "deadTime": deadTime,
                    "deadTimeBurst": deadTimeBurst,
                    "risingOrFalling": risingOrFalling,
                    "timeWindowForBursts": timeWindowForBursts,
                    "timeWindowForLongEvents": timeWindowForLongEvents,
                    "pulseEveryXXsecsLongEvents": pulseEveryXXsecsLongEvents,
                    "timeWindowForContinuousEvents":
                    timeWindowForContinuousEvents,
                    "minBurstsinTimeWindowToTrigger":
                    minBurstsinTimeWindowToTrigger,
                    "lastSignal": 0,
                    "lastsendCount": 0,
                    "lastsendBurst": 0,
                    "lastsendlongEvent": 0,
                    "lastsendContinuousEvent": 0,
                    "count": 0
                }
                print ""
                if inpType == "open":
                    GPIO.setup(int(gpio), GPIO.IN)
                elif inpType == "high":
                    GPIO.setup(int(gpio), GPIO.IN, pull_up_down=GPIO.PUD_UP)
                elif inpType == "low":
                    GPIO.setup(int(gpio), GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
                if risingOrFalling == "RISING":
                    GPIO.add_event_detect(int(gpio),
                                          GPIO.RISING,
                                          callback=RISING,
                                          bouncetime=bounceTime)
                elif risingOrFalling == "FALLING":
                    GPIO.add_event_detect(int(gpio),
                                          GPIO.FALLING,
                                          callback=FALLING,
                                          bouncetime=bounceTime)
                else:
                    GPIO.add_event_detect(int(gpio),
                                          GPIO.BOTH,
                                          callback=BOTH,
                                          bouncetime=bounceTime)
                GPIOdict[gpio]["inpType"] = inpType

        oneFound = False
        restart = False
        delGPIO = {}
        for gpio in GPIOdict:
            for risingOrFalling in ["FALLING", "RISING", "BOTH"]:
                if found[gpio][risingOrFalling] == 1:
                    oneFound = True
                    continue
                if risingOrFalling in GPIOdict:
                    restart = True
                    continue
            if GPIOdict[gpio] == {}: delGPIO[gpio] = 1
        for gpio in delGPIO:
            if gpio in GPIOdict: del GPIOdict[gpio]

        if not oneFound:
            U.toLog(0, "no	 gpios setup, exiting", doPrint=True)
            exit()
        if restart:
            U.toLog(0,
                    "gpios edge channel deleted, need to restart",
                    doPrint=True)
            U.restartMyself(param="", reason=" new definitions", doPrint=True)

        U.toLog(0, "GPIOdict: " + unicode(GPIOdict), doPrint=True)
    except Exception, e:
        U.toLog(-1,
                u"in Line '%s' has error='%s'" %
                (sys.exc_traceback.tb_lineno, e),
                doPrint=True)