Esempio n. 1
0
def resetEverything():
	print "resetting everything back to default, then reboot "
	U.killOldPgm(myPID,"neopixel.py")
	os.system('sudo cp '+G.homeDir+'interfaces-DEFAULT-clock /etc/network/interfaces')
	os.system('cp '+G.homeDir+'parameters-DEFAULT-clock '+G.homeDir+'parameters')
	os.system('sudo cp '+G.homeDir+'wpa_supplicant.conf-DEFAULT-clock /etc/wpa_supplicant/wpa_supplicant.conf')
	os.system('cp '+G.homeDir+'patterns-DEFAULT-clock  '+G.homeDir+'patterns')
	time.sleep(2)
	os.system("sudo killall -9 python; sudo sync;sleep 2; sudo reboot -f")
	return ## dummy
Esempio n. 2
0
def resetEverything():
	print "resetting everything back to default, then reboot "
	U.killOldPgm(myPID,"neopixel.py")
	os.system('sudo cp '+G.homeDir+'interfaces-DEFAULT-clock /etc/network/interfaces')
	os.system('cp '+G.homeDir+'parameters-DEFAULT-clock '+G.homeDir+'parameters')
	os.system('sudo cp '+G.homeDir+'wpa_supplicant.conf-DEFAULT-clock /etc/wpa_supplicant/wpa_supplicant.conf')
	os.system('cp '+G.homeDir+'patterns-DEFAULT-clock  '+G.homeDir+'patterns')
	time.sleep(2)
	os.system("sudo killall -9 python; sudo sync;sleep 2; sudo reboot -f")
	return ## dummy
Esempio n. 3
0
def stopSensors(launchCmd):
    try:
        # do your init here
        U.killOldPgm(myPID, launchCmd)
        ## add any init code here for address # addr
        U.toLog(-1, u"stopping	" + unicode(launchCmd))
    except Exception, e:
        U.toLog(
            -1,
            u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
        U.toLog(-1, u"launchCmd used: " + unicode(launchCmd))
Esempio n. 4
0
myPID = str(os.getpid())
readParams()
U.toLog(1, "setPCF8591  command :" + unicode(sys.argv))

command = json.loads(sys.argv[1])

if "i2cAddress" in command:
    i2cAddress = int(command["i2cAddress"])
else:
    U.toLog(
        -1,
        "setPCF8591dac bad command " + command + "  i2cAddress not included")
    exit(1)

U.killOldPgm(myPID,
             "setPCF8591dac.py",
             param1='"i2cAddress": "' + str(i2cAddress) +
             '"')  # del old instances of myself if they are still running

U.toLog(2, "startAtDateTime" + str(command["startAtDateTime"]))
U.toLog(2, "time.time()    " + str(time.time()))

if "startAtDateTime" in command:
    try:
        delayStart = max(
            0,
            U.calcStartTime(command, "startAtDateTime") - time.time())
        if delayStart > 0:
            U.toLog(2, "delayStart delayed by: " + str(delayStart))
            time.sleep(delayStart)
    except Exception, e:
        U.toLog(
Esempio n. 5
0

if "cmd" in command:
	cmd= command["cmd"]
	if cmd not in allowedCommands:
		U.toLog(-1, G.program +" bad command " + command + "  allowed:" + unicode(allowedCommands))
		exit(1)

if "pin" in command:
	pin= int(command["pin"])
else:
		U.toLog(-1, G.program +" bad command " + command + "  pin not included")
		exit(1)


U.killOldPgm(myPID, G.program+".py", param1='"pin":',param2= '"'+str(pin)+'",')	 # old old instances of myself if they are still running


delayStart = max(0,U.calcStartTime(command,"startAtDateTime")-time.time())
if delayStart > 0: 
	time.sleep(delayStart)

if "values" in command:
	values =  command["values"]
	
	
#	 "values:{analogValue:"analogValue+",pulseUp:"+ pulseUp + ",pulseDown:" + pulseDown + ",nPulses:" + nPulses+"}

try:
	if "pulseUp" in values:		pulseUp = float(values["pulseUp"])
	else:						pulseUp = 0
Esempio n. 6
0
####### main pgm / loop ############


global myBLEmac, BLEsensorMACs
global oldRaw,	lastRead, sensor
oldRaw					= ""
lastRead				= 0
G.debug				= 2
G.authentication	= "digest"
# get params
myBLEmac			= ""
BLEsensorMACs		= {}

myPID			= str(os.getpid())
#kill old G.programs
U.killOldPgm(myPID,G.program+".py")



sensor				= G.program	 
readParams(True)


# getIp address 
if U.getIPNumber() > 0:
	print " no ip number "
	time.sleep(10)
	exit()


## start bluetooth
Esempio n. 7
0
    if inp == "": return
    try:
            if u"debugRPI"          in inp:  debug=             int(inp["debugRPI"]["debugRPImystuff"])
    except:
        pass

# ===========================================================================
# Main
# ===========================================================================


try:
        readParams()

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

        U.toLog(-1, "myoutput  received text :"+unicode(sys.argv))
        print "myoutput  received text :"+unicode(sys.argv)

        # rest is up to you  the text indgo has send is in sys.argv[1] [2] ....
        if len(sys.argv) >1 :
            text = sys.argv[1]

            #eg reboot if you send the reboot command
            if unicode(text).find("reboot") > -1 :
                os.system("reboot")


            # if set gpoio high ..
            elif unicode(text).find("gpio 21 high") > -1:
Esempio n. 8
0
lastRead				= 0


resetPin					= -1
badSelfTest					= 0
lastWriteCalibration		= 0
CALlast						= 0
G.debug						= 5
loopCount					= 0
NSleep						= 100
sensors						= {}
sensor						= G.program
quick						= False
BNO055sensor				={}
myPID		= str(os.getpid())
U.killOldPgm(myPID,G.program+".py")# kill old instances of myself if they are still running


if U.getIPNumber() > 0:
	time.sleep(10)
	exit()

readParams()

time.sleep(1)

lastRead = time.time()

U.echoLastAlive(G.program)

Esempio n. 9
0
sensorList			= "0"
G.authentication	= "digest"
restartBLEifNoConnect = True
sensor				= G.program
macList				={}
waitMin				=2.
oldRaw				= ""
try:
	onlyThisMAC	  = sys.argv[1]
except:
	onlyThisMAC = ""


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

loopCount		  = 0
sensorRefreshSecs = 90
U.toLog(-1, "starting BLEconnect program ")
readParams()

time.sleep(1)  # give HCITOOL time to start

shortWait			= 1.	# seconds  wait between loop
lastEverything		= time.time()-10000. # -1000 do the whole thing initially
lastAlive			= time.time()
lastData			= {}
lastRead			= -1
Esempio n. 10
0
sensorList			= "0"
G.authentication	= "digest"
restartBLEifNoConnect = True
sensor				= G.program
macList				={}
waitMin				=2.
oldRaw				= ""
try:
	onlyThisMAC	  = sys.argv[1]
except:
	onlyThisMAC = ""


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

loopCount		  = 0
sensorRefreshSecs = 90
U.toLog(-1, "starting BLEconnect program ")
readParams()

time.sleep(1)  # give HCITOOL time to start

shortWait			= 1.	# seconds  wait between loop
lastEverything		= time.time()-10000. # -1000 do the whole thing initially
lastAlive			= time.time()
lastData			= {}
lastRead			= -1
Esempio n. 11
0
##
##	  --- utils
#
#
import sys
import os
import time
sys.path.append(os.getcwd())
import piBeaconGlobals as G
import piBeaconUtils as U

if __name__ == "__main__":
    G.program = "copyToTemp"
    timeLastFile = 0
    myPID = str(os.getpid())
    U.killOldPgm(myPID, G.program + ".py")

    os.system("chmod a+w -R " + G.homeDir + "*")
    os.system("chown -R pi:pi " + G.homeDir + "*")
    try:
        os.system("touch " + G.homeDir + "temp/touchFile")
        timeLastFile = os.path.getmtime(G.homeDir + "temp/touchFile") - 1
    except:
        timeLastFile = 0

    while True:
        doCopy = 0

        if os.path.isfile(G.homeDir + "temp/touchFile"):
            if timeLastFile != os.path.getmtime(G.homeDir + "temp/touchFile"):
                doCopy = 1
Esempio n. 12
0

if "cmd" in command:
	cmd= command["cmd"]
	if cmd not in allowedCommands:
		U.toLog(-1, G.program +" bad command " + command + "  allowed:" + unicode(allowedCommands))
		exit(1)

if "pin" in command:
	pin= int(command["pin"])
else:
		U.toLog(-1, G.program +" bad command " + command + "  pin not included")
		exit(1)


U.killOldPgm(myPID, G.program+".py", param1='"pin":',param2= '"'+str(pin)+'",')	 # old old instances of myself if they are still running


delayStart = max(0,U.calcStartTime(command,"startAtDateTime")-time.time())
if delayStart > 0: 
	time.sleep(delayStart)

if "values" in command:
	values =  command["values"]
	
	
#	 "values:{analogValue:"analogValue+",pulseUp:"+ pulseUp + ",pulseDown:" + pulseDown + ",nPulses:" + nPulses+"}

try:
	if "pulseUp" in values:		pulseUp = float(values["pulseUp"])
	else:						pulseUp = 0
Esempio n. 13
0
######### main ######

myPID       = str(os.getpid())
readParams()
U.toLog(1, "setPCF8591  command :" + unicode(sys.argv))

command = json.loads(sys.argv[1])

if "i2cAddress" in command:
    i2cAddress= int(command["i2cAddress"])
else:
    U.toLog(-1, "setPCF8591dac bad command " + command + "  i2cAddress not included")
    exit(1)
    
U.killOldPgm(myPID,"setPCF8591dac.py", param1='"i2cAddress": "' + str(i2cAddress) + '"')# del old instances of myself if they are still running

U.toLog(2, "startAtDateTime"+ str(command["startAtDateTime"]))
U.toLog(2, "time.time()    "+ str(time.time()))


if "startAtDateTime" in command:
    try:
        delayStart = max(0,U.calcStartTime(command,"startAtDateTime")-time.time())
        if delayStart > 0:
            U.toLog(2, "delayStart delayed by: "+ str(delayStart))
            time.sleep(delayStart)
    except  Exception, e:
        U.toLog(-1,  u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))

Esempio n. 14
0
		x('<html>')
		x(	'<head style="background-color:rgb(50, 50,50);"> </head>')
		x(	'<body style="background-color:rgb(50, 50,50); color:rgb(150, 150,150); font-family:Courier;">')
		x(		'<b>SunDial Current status</b><br>')
		for item in data:
			x(	item +'<br>')
		x(	'</body>')
		x('</html>')
 
global pid, dataFile
dataFile	= G.homeDir+"temp/sunDial.status"
port 		= 80
try:
	port     = int(sys.argv[1])
	dataFile = sys.argv[2]
except: pass


f=open( G.homeDir+"ipAddress","r")
ipNumber = f.read()
f.close()
pid =  os.getpid()

U.killOldPgm(str(pid),"/webserverWhenOnline.py")
time.sleep(0.5)


server = HTTPServer(('', port), GetHandler)
print "Starting web server, access at "+ipNumber+":"+str(port)
server.serve_forever()
Esempio n. 15
0
def startNEOPIXEL(setClock = ""):
	global devTypeLEDs, speed, speedOfChange, clockLightSet,clockMode, clockLightSetOverWrite, LEDintensityFactor
	global DEVID, clockDict, inp 


	try:
		# define short cuts
		clockDict["LEDsum"]		=[]
		clockDict["LEDstart"]	=[]
	
		HHMMSSDDnofTicks={"HH":12,"MM":60,"SS":60,"DD":31}

		lightset = clockLightSet
		if lightset =="auto":
			lightset = clockLightSetOverWrite  ## put here input from light sensor 

		if	 True										: multHMS = 1.	; multMark=1.
		if	 LEDintensityFactor.lower() =="offoff"		: multHMS = 0.12; multMark=0.0
		elif LEDintensityFactor.lower() =="nightoff"	: multHMS = 0.15; multMark=0.0
		elif LEDintensityFactor.lower() =="nightdim"	: multHMS = 0.20; multMark=0.0
		elif LEDintensityFactor.lower() =="daylow"		: multHMS = 0.40; multMark=0.90
		elif LEDintensityFactor.lower() =="daymedium"	: multHMS = 0.60; multMark=0.95
		elif LEDintensityFactor.lower() =="dayhigh"		: multHMS = 1.0 ; multMark=1.0


		if lightset.lower() =="offoff"   :
			setNightOffPatterns()
		elif lightset.lower() =="nightoff"   :
			setNightPatterns()
		else:
			restorefromNightPatterns()

		lll = 0
		for r in clockDict["rings"]:
			clockDict["LEDstart"].append(lll)
			lll+=r
			clockDict["LEDsum"].append(lll)
		maxLED = lll
		
		for tt in ["HH","MM","SS","DD"]:
			lll = 0
			for r in clockDict["ticks"][tt]["ringNo"]:
				lll +=clockDict["rings"][r]
			clockDict["ticks"][tt]["LEDsum"]   = lll
			clockDict["ticks"][tt]["LEDstart"] = 0
			if len(clockDict["ticks"][tt]["ringNo"]) >0:
				clockDict["ticks"][tt]["LEDstart"]= clockDict["LEDstart"][clockDict["ticks"][tt]["ringNo"][0]]
			lll = 0
			for r in clockDict["marks"][tt]["ringNo"]:
				lll +=clockDict["rings"][r]
			clockDict["marks"][tt]["LEDsum"]   = lll
			clockDict["marks"][tt]["LEDstart"] = 0
			if len(clockDict["marks"][tt]["ringNo"]) >0:
				clockDict["marks"][tt]["LEDstart"]= clockDict["LEDstart"][clockDict["marks"][tt]["ringNo"][0]]


		string = ""
		for tt in ["HH","MM","SS"]:
			string+=  " "+tt+":" +unicode(clockDict["marks"][tt])
		U.toLog(1, u"startNEOPIXEL..lightset: "+unicode(lightset)+string)
##20181122-02:21:04 startNEOPIXEL..lightset: offoff;  clockDict[marks] {u'MM': {'LEDstart': 0, u'RGB': [0, 0, 0], u'ringNo': [], 'LEDsum': 0, u'marks': []}, u'SS': {'LEDstart': 0, u'RGB': [0, 0, 0], u'ringNo': [], 'LEDsum': 0, u'marks': []}, u'DD': {'LEDstart': 0, u'RGB': [0, 0, 0], u'ringNo': [], 'LEDsum': 0, u'marks': []}, u'HH': {'LEDstart': 0, u'RGB': [0, 0, 0], u'ringNo': [], 'LEDsum': 0, u'marks': []}}

		pos={}
		for tt in ["HH","MM","SS","DD"]:
			ticks = HHMMSSDDnofTicks[tt]
			ind =[]
			nRings		= len(clockDict["ticks"][tt]["ringNo"])
			if nRings ==0: continue
			ringNo		= clockDict["ticks"][tt]["ringNo"]
			if ringNo ==[]: continue
			LEDstart	= clockDict["ticks"][tt]["LEDstart"]
			LEDsInRing0 = clockDict["rings"][ringNo[0]]
			LEDsum		= clockDict["ticks"][tt]["LEDsum"]
		
			if clockDict["ticks"][tt]["npix"] ==3:	# only for single ring
				for ii in range(clockDict["rings"][ringNo[0]]):
					left		= ii+LEDstart - 1
					mid			= ii+LEDstart
					right		= ii+LEDstart + 1
					if left	 <	LEDstart:			left   = LEDstart + LEDsum -1
					if right >= LEDstart + LEDsum:	right  = LEDstart
					ind.append([left,mid,right])
				RGB= calcRGBdimm(clockDict["ticks"][tt]["RGB"],multHMS,minLight=True)
				pos[tt]= {"RGB":RGB,"index":ind,"blink":clockDict["ticks"][tt]["blink"]}

			elif clockDict["ticks"][tt]["npix"] ==-1: #fill ring up to number
				for tick in range(ticks): 
					tIndex =[]
					##for jj in range(LEDsInRing0):
					for nR in range(nRings):  ### add if # of tick < # of led in ring 
						LEDsinRING		= clockDict["rings"][ringNo[nR]]
						LEDStartinRING	= clockDict["LEDstart"][ringNo[nR]]
						if	 ticks > LEDsinRING:  maxT = int(tick / (float(ticks)/LEDsinRING))
						elif ticks < LEDsinRING:  maxT = int(tick * (float(LEDsinRING)/ticks)) 
						else:					  maxT = tick 
						fromT =0
						if maxT == LEDsinRING-1: # starts at 0 oterhwise no -1 
							fromT=1
						for ii in range(fromT,maxT+1):
							tIndex.append(ii+ LEDStartinRING)
					ind.append(tIndex)
				RGB= calcRGBdimm(clockDict["ticks"][tt]["RGB"],multHMS,minLight=True)
				pos[tt]= {"RGB":RGB,"index":ind,"blink":clockDict["ticks"][tt]["blink"]}

			elif clockDict["ticks"][tt]["npix"] ==1: # single led 
				for tick in range(ticks): 
					tIndex =[]
					##for jj in range(LEDsInRing0):
					for nR in range(nRings):  ### add if # of tick < # of led in ring 
						LEDsinRING		= clockDict["rings"][ringNo[nR]]
						LEDStartinRING	= clockDict["LEDstart"][ringNo[nR]]
						if ticks > LEDsinRING:
							tIndex.append(int(tick / (float(ticks)/LEDsinRING)) + LEDStartinRING)
						elif ticks < LEDsinRING:
							tIndex.append(int(tick * (float(LEDsinRING)/ticks)) + LEDStartinRING)
						else:
							tIndex.append(tick + LEDStartinRING)
					ind.append(tIndex)
				RGB= calcRGBdimm(clockDict["ticks"][tt]["RGB"],multHMS,minLight=True)
				pos[tt]= {"RGB":RGB,"index":ind,"blink":clockDict["ticks"][tt]["blink"]}

			elif clockDict["ticks"][tt]["npix"] ==0: # do not show
				pass

		marks={}
		if (lightset.lower()).find("off") ==-1: 
			for tt in ["HH","MM","SS","DD"]:
				index=[[]]
				if tt not in clockDict["marks"]			 : continue
				if clockDict["marks"][tt] =={}			 : continue
				if clockDict["marks"][tt]["marks"] == [] : continue
				ticks = HHMMSSDDnofTicks[tt]
				for	 nR in range(len(clockDict["marks"][tt]["ringNo"])):
					ringNo		= clockDict["marks"][tt]["ringNo"][nR]
					LEDstart	= clockDict["LEDstart"][ringNo]
					LEDsinRING	= clockDict["rings"][ringNo]
					mult = float(LEDsinRING) / ticks
					for ll in clockDict["marks"][tt]["marks"]:
						ii = int(ll*mult + LEDstart)
						if ii < maxLED:
							index[0].append(ii)
				marks[tt] = {"RGB":[min(int(multMark*x),255) for x in clockDict["marks"][tt]["RGB"]],"index":index}

		if marks == {}: 
			marks = ""
		pos["marks"] = marks

		pos["speed"] = speed

		pos["extraLED"] =""
		if "extraLED" in clockDict and clockDict["extraLED"] !="":
			pos["extraLED"] ={}
			if "RGB" in clockDict["extraLED"]:
				pos["extraLED"]["RGB"]	 = clockDict["extraLED"]["RGB"]
			else:
				pos["extraLED"]["RGB"]	 = [100,100,100]
			if "blink" in clockDict["extraLED"]:
				pos["extraLED"]["blink"] = clockDict["extraLED"]["blink"]
			else:
				pos["extraLED"]["blink"] = [1,1]
			ind =[]
			for tick in clockDict["extraLED"]["ticks"]:
				ind.append(tick)
			pos["extraLED"]["index"] = [ind]
			


		U.toLog(3, " starting neopixel with:"+ unicode(pos) )	 
		#print	" starting neopixel with MM :", unicode(pos["MM"]["RGB"])
		#print	" starting neopixel with:", unicode(pos["marks"])

		out={"resetInitial": "", "repeat": -1,"command":[{"type": "clock","position":pos, "display": "immediate","speedOfChange":speedOfChange,"marks":marks,"speed":speed}]}
		if setClock !="":
			out["setClock"] = setClock
			clockMode ="setClockStarted"
		else:
			clockMode ="run"
		
		if not U.pgmStillRunning("neopixel.py neopixelClock"):
			U.killOldPgm(myPID,"neopixel.py")
			os.system("/usr/bin/python "+G.homeDir+"neopixel.py neopixelClock &" )
		setNEOinput(out)

	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,"<<"
Esempio n. 16
0
test=[False for ii in range(10)]
try:
	f=open(G.homeDir+"installLibs.done","r")
	test[0]= float(f.read())
	f.close()
except: test[0] = -1

myPID			= str(os.getpid())

upgradeOpSys =""
try:
	upgradeOpSys = sys.argv[1]
	print datetime.datetime.now().strftime("%Y%m%d-%H:%M:%S")+" installLibs	 will do a complete upgrade of the opsys , this might take a LOOONG time"
	# kill some of the programs that might be in conflict with installing new opsys s..
	U.killOldPgm(myPID,"callbeacon.py")
	U.killOldPgm(myPID,"beaconloop.py")
	U.killOldPgm(myPID,"BLEconnect.py")
	U.killOldPgm(myPID,"getsensorvalues.py")
	U.killOldPgm(myPID,"receiveGPIOcommands.py")
	U.killOldPgm(myPID,"ultrasoundDistance.py")
	U.killOldPgm(myPID,"display.py")
	os.system("rm " + G.homeDir + "installLibs.done	 >/dev/null 2>&1")
	test[0] = -1
	arguments = unicode(sys.argv)
except:
	print datetime.datetime.now().strftime("%Y%m%d-%H:%M:%S")+" installLibs no opsys upgrade requested"
	arguments = ""


test[1] = not os.path.isfile(G.homeDir0+"Adafruit_Python_DHT/setup.py")
Esempio n. 17
0
def startNEOPIXEL(setClock = ""):
	global devTypeLEDs, speed, speedOfChange, clockLightSet,clockMode, clockLightSetOverWrite, LEDintensityFactor
	global DEVID, clockDict, inp 


	try:
		# define short cuts
		clockDict["LEDsum"]		=[]
		clockDict["LEDstart"]	=[]
	
		HHMMSSDDnofTicks={"HH":12,"MM":60,"SS":60,"DD":31}

		lightset = clockLightSet
		if lightset =="auto":
			lightset = clockLightSetOverWrite  ## put here input from light sensor 

		if	 True										: multHMS = 1.	; multMark=1.
		if	 LEDintensityFactor.lower() =="offoff"		: multHMS = 0.12; multMark=0.0
		elif LEDintensityFactor.lower() =="nightoff"	: multHMS = 0.15; multMark=0.0
		elif LEDintensityFactor.lower() =="nightdim"	: multHMS = 0.20; multMark=0.0
		elif LEDintensityFactor.lower() =="daylow"		: multHMS = 0.40; multMark=0.90
		elif LEDintensityFactor.lower() =="daymedium"	: multHMS = 0.60; multMark=0.95
		elif LEDintensityFactor.lower() =="dayhigh"		: multHMS = 1.0 ; multMark=1.0


		if lightset.lower() =="offoff"   :
			setNightOffPatterns()
		elif lightset.lower() =="nightoff"   :
			setNightPatterns()
		else:
			restorefromNightPatterns()

		lll = 0
		for r in clockDict["rings"]:
			clockDict["LEDstart"].append(lll)
			lll+=r
			clockDict["LEDsum"].append(lll)
		maxLED = lll
		
		for tt in ["HH","MM","SS","DD"]:
			lll = 0
			for r in clockDict["ticks"][tt]["ringNo"]:
				lll +=clockDict["rings"][r]
			clockDict["ticks"][tt]["LEDsum"]   = lll
			clockDict["ticks"][tt]["LEDstart"] = 0
			if len(clockDict["ticks"][tt]["ringNo"]) >0:
				clockDict["ticks"][tt]["LEDstart"]= clockDict["LEDstart"][clockDict["ticks"][tt]["ringNo"][0]]
			lll = 0
			for r in clockDict["marks"][tt]["ringNo"]:
				lll +=clockDict["rings"][r]
			clockDict["marks"][tt]["LEDsum"]   = lll
			clockDict["marks"][tt]["LEDstart"] = 0
			if len(clockDict["marks"][tt]["ringNo"]) >0:
				clockDict["marks"][tt]["LEDstart"]= clockDict["LEDstart"][clockDict["marks"][tt]["ringNo"][0]]


		string = ""
		for tt in ["HH","MM","SS"]:
			string+=  " "+tt+":" +unicode(clockDict["marks"][tt])
		U.toLog(1, u"startNEOPIXEL..lightset: "+unicode(lightset)+string)
##20181122-02:21:04 startNEOPIXEL..lightset: offoff;  clockDict[marks] {u'MM': {'LEDstart': 0, u'RGB': [0, 0, 0], u'ringNo': [], 'LEDsum': 0, u'marks': []}, u'SS': {'LEDstart': 0, u'RGB': [0, 0, 0], u'ringNo': [], 'LEDsum': 0, u'marks': []}, u'DD': {'LEDstart': 0, u'RGB': [0, 0, 0], u'ringNo': [], 'LEDsum': 0, u'marks': []}, u'HH': {'LEDstart': 0, u'RGB': [0, 0, 0], u'ringNo': [], 'LEDsum': 0, u'marks': []}}

		pos={}
		for tt in ["HH","MM","SS","DD"]:
			ticks = HHMMSSDDnofTicks[tt]
			ind =[]
			nRings		= len(clockDict["ticks"][tt]["ringNo"])
			if nRings ==0: continue
			ringNo		= clockDict["ticks"][tt]["ringNo"]
			if ringNo ==[]: continue
			LEDstart	= clockDict["ticks"][tt]["LEDstart"]
			LEDsInRing0 = clockDict["rings"][ringNo[0]]
			LEDsum		= clockDict["ticks"][tt]["LEDsum"]
		
			if clockDict["ticks"][tt]["npix"] ==3:	# only for single ring
				for ii in range(clockDict["rings"][ringNo[0]]):
					left		= ii+LEDstart - 1
					mid			= ii+LEDstart
					right		= ii+LEDstart + 1
					if left	 <	LEDstart:			left   = LEDstart + LEDsum -1
					if right >= LEDstart + LEDsum:	right  = LEDstart
					ind.append([left,mid,right])
				RGB= calcRGBdimm(clockDict["ticks"][tt]["RGB"],multHMS,minLight=True)
				pos[tt]= {"RGB":RGB,"index":ind,"blink":clockDict["ticks"][tt]["blink"]}

			elif clockDict["ticks"][tt]["npix"] ==-1: #fill ring up to number
				for tick in range(ticks): 
					tIndex =[]
					##for jj in range(LEDsInRing0):
					for nR in range(nRings):  ### add if # of tick < # of led in ring 
						LEDsinRING		= clockDict["rings"][ringNo[nR]]
						LEDStartinRING	= clockDict["LEDstart"][ringNo[nR]]
						if	 ticks > LEDsinRING:  maxT = int(tick / (float(ticks)/LEDsinRING))
						elif ticks < LEDsinRING:  maxT = int(tick * (float(LEDsinRING)/ticks)) 
						else:					  maxT = tick 
						fromT =0
						if maxT == LEDsinRING-1: # starts at 0 oterhwise no -1 
							fromT=1
						for ii in range(fromT,maxT+1):
							tIndex.append(ii+ LEDStartinRING)
					ind.append(tIndex)
				RGB= calcRGBdimm(clockDict["ticks"][tt]["RGB"],multHMS,minLight=True)
				pos[tt]= {"RGB":RGB,"index":ind,"blink":clockDict["ticks"][tt]["blink"]}

			elif clockDict["ticks"][tt]["npix"] ==1: # single led 
				for tick in range(ticks): 
					tIndex =[]
					##for jj in range(LEDsInRing0):
					for nR in range(nRings):  ### add if # of tick < # of led in ring 
						LEDsinRING		= clockDict["rings"][ringNo[nR]]
						LEDStartinRING	= clockDict["LEDstart"][ringNo[nR]]
						if ticks > LEDsinRING:
							tIndex.append(int(tick / (float(ticks)/LEDsinRING)) + LEDStartinRING)
						elif ticks < LEDsinRING:
							tIndex.append(int(tick * (float(LEDsinRING)/ticks)) + LEDStartinRING)
						else:
							tIndex.append(tick + LEDStartinRING)
					ind.append(tIndex)
				RGB= calcRGBdimm(clockDict["ticks"][tt]["RGB"],multHMS,minLight=True)
				pos[tt]= {"RGB":RGB,"index":ind,"blink":clockDict["ticks"][tt]["blink"]}

			elif clockDict["ticks"][tt]["npix"] ==0: # do not show
				pass

		marks={}
		if (lightset.lower()).find("off") ==-1: 
			for tt in ["HH","MM","SS","DD"]:
				index=[[]]
				if tt not in clockDict["marks"]			 : continue
				if clockDict["marks"][tt] =={}			 : continue
				if clockDict["marks"][tt]["marks"] == [] : continue
				ticks = HHMMSSDDnofTicks[tt]
				for	 nR in range(len(clockDict["marks"][tt]["ringNo"])):
					ringNo		= clockDict["marks"][tt]["ringNo"][nR]
					LEDstart	= clockDict["LEDstart"][ringNo]
					LEDsinRING	= clockDict["rings"][ringNo]
					mult = float(LEDsinRING) / ticks
					for ll in clockDict["marks"][tt]["marks"]:
						ii = int(ll*mult + LEDstart)
						if ii < maxLED:
							index[0].append(ii)
				marks[tt] = {"RGB":[min(int(multMark*x),255) for x in clockDict["marks"][tt]["RGB"]],"index":index}

		if marks == {}: 
			marks = ""
		pos["marks"] = marks

		pos["speed"] = speed

		pos["extraLED"] =""
		if "extraLED" in clockDict and clockDict["extraLED"] !="":
			pos["extraLED"] ={}
			if "RGB" in clockDict["extraLED"]:
				pos["extraLED"]["RGB"]	 = clockDict["extraLED"]["RGB"]
			else:
				pos["extraLED"]["RGB"]	 = [100,100,100]
			if "blink" in clockDict["extraLED"]:
				pos["extraLED"]["blink"] = clockDict["extraLED"]["blink"]
			else:
				pos["extraLED"]["blink"] = [1,1]
			ind =[]
			for tick in clockDict["extraLED"]["ticks"]:
				ind.append(tick)
			pos["extraLED"]["index"] = [ind]
			


		U.toLog(3, " starting neopixel with:"+ unicode(pos) )	 
		#print	" starting neopixel with MM :", unicode(pos["MM"]["RGB"])
		#print	" starting neopixel with:", unicode(pos["marks"])

		out={"resetInitial": "", "repeat": -1,"command":[{"type": "clock","position":pos, "display": "immediate","speedOfChange":speedOfChange,"marks":marks,"speed":speed}]}
		if setClock !="":
			out["setClock"] = setClock
			clockMode ="setClockStarted"
		else:
			clockMode ="run"
		
		if not U.pgmStillRunning("neopixel.py neopixelClock"):
			U.killOldPgm(myPID,"neopixel.py")
			os.system("/usr/bin/python "+G.homeDir+"neopixel.py neopixelClock &" )
		setNEOinput(out)

	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,"<<"
Esempio n. 18
0
						if "fileMode" in next and next["fileMode"].lower() =="a": m="a"
						#print "write to",next["fileName"], json.dumps(next["fileContents"]), m
						f=open(next["fileName"],m)
						f.write(next["fileContents"])
						f.close()
						if "touchFile" in next and next["touchFile"]:
							os.system("echo	 "+str(time.time())+" > "+G.homeDir+"temp/touchFile" )
						os.system("sudo chown -R  pi  "+G.homeDir)
					except	Exception, e:
						U.toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
				continue


			if cmd =="BLEreport":
				try:
					U.killOldPgm(-1,"master.py")
					U.killOldPgm(-1,"beaconloop.py")
					U.killOldPgm(-1,"BLEconnect.py")
					U.getIPNumber()
					data   = {"BLEreport":{},"pi":str(G.myPiNumber)}
					
					cmd = "sudo hciconfig "
					dataW = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()
					U.toLog(1, unicode(dataW))
					data   = {"BLEreport":{}}
					data["BLEreport"]["hciconfig"]			  = dataW
					cmd = "sudo hciconfig hci0 down; sudo hciconfig hci0 up ; sudo timeout -s SIGINT 15s hcitool lescan "
					dataW = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()
					U.toLog(1, unicode(dataW))
					data["BLEreport"]["hcitool lescan"]		  = dataW
					cmd = "sudo timeout -s SIGINT 25s hcitool scan "
Esempio n. 19
0
sensors = {}
enableTXpinsAsGpio = "0"
enableSPIpinsAsGpio = "0"
authentication = "digest"
quick = False
output = {}

readParams()

if U.getIPNumber() > 0:
    U.toLog(-1, " getsensors no ip number  exiting ", doPrint=True)
    time.sleep(10)
    exit()

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

NSleep = int(sensorRefreshSecs)
if G.networkType in G.useNetwork and U.getNetwork() == 1:
    if U.getIPNumber() > 0:
        print datetime.datetime.now().strftime(
            "%Y%m%d-%H:%M:%S"
        ) + " " + G.program + " no ip number working, giving up"
        time.sleep(10)
        exit()
eth0IP, wifi0IP, G.eth0Enabled, G.wifiEnabled = U.getIPCONFIG()

tt = time.time()
badSensors = {}
lastData = {}
lastMsg = 0
Esempio n. 20
0
                    f = open(next["fileName"], m)
                    f.write(next["fileContents"])
                    f.close()
                    if "touchFile" in next and next["touchFile"]:
                        os.system("echo	 " + str(time.time()) + " > " +
                                  G.homeDir + "temp/touchFile")
                    os.system("sudo chown -R  pi  " + G.homeDir)
                except Exception, e:
                    U.toLog(
                        -1, u"in Line '%s' has error='%s'" %
                        (sys.exc_traceback.tb_lineno, e))
            continue

        if cmd == "BLEreport":
            try:
                U.killOldPgm(-1, "master.py")
                U.killOldPgm(-1, "beaconloop.py")
                U.killOldPgm(-1, "BLEconnect.py")
                U.getIPNumber()
                data = {"BLEreport": {}, "pi": str(G.myPiNumber)}

                cmd = "sudo hciconfig "
                dataW = subprocess.Popen(cmd,
                                         shell=True,
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE).communicate()
                U.toLog(1, unicode(dataW))
                data = {"BLEreport": {}}
                data["BLEreport"]["hciconfig"] = dataW
                cmd = "sudo hciconfig hci0 down; sudo hciconfig hci0 up ; sudo timeout -s SIGINT 15s hcitool lescan "
                dataW = subprocess.Popen(cmd,