posted v 1.6.1
fixed:
loopMaxCallBLE variable ws handled incorrectly
added:
added ALIVE signal from rPi to plugin if there are no bluetooth messages. ==> rPi should not expire
Karl
#!/usr/bin/python
# by Karl Wachs
# march 1 2016
# exampel program to get data and send it to indigo
import sys, os, time, json, datetime,subprocess,copy
# ===========================================================================
# utils
# ===========================================================================
def toLog(lvl,msg):
global debug, homeDir
if lvl < debug :
f = open(homeDir+"mysensors.log","a")
f.write(datetime.datetime.now().strftime("%Y%m%d-%H:%M:%S")+" "+msg+"\n")
f.close()
def killOldPgm(myPID,pgmToKill):
global debug, homeDir
try:
cmd= "ps -ef | grep "+pgmToKill+" | grep -v grep"
ret = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()[0]
lines =ret.split("\n")
for line in lines:
if len(line) < 10: continue
line =line.split()
pid = int(line[1])
if pid == int(myPID): continue
toLog(-1, "killing "+pgmToKill)
os.system("sudo kill -9 "+str(pid))
except Exception, e:
toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
# ===========================================================================
# sensor start
# ===========================================================================
def startMySensors(addr=0):
global cAddress
try:
# do your init here
parameter= cAddress[addr]
## add any inti code here for address # addr
toLog(-1, u"starting my sensors "+ unicode(cAddress)+"; dev= "+unicode(addr))
except Exception, e:
toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
toLog(-1, u"channel used: "+ unicode(cAddress)+"; addr= "+unicode(addr))
def getMySensors(addr=0):
global cAddress
try:
parameter= cAddress[addr]
v = ["","","","","","","","","","",]#set return to empty
# do your stuff here, this if for testing to something into the data
x = time.time()
v = [str(x),str(x/2),"0","1","2","3","4","5","6","7"]
return v
except Exception, e:
toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
return ""
# ===========================================================================
# sensor end
# ===========================================================================
# ===========================================================================
# read params
# ===========================================================================
def readParams():
global debug, homeDir,sensorList,cAddress,sensorRefreshSecs
f=open(homeDir+"parameters","r")
lines=f.read().strip("\n").split("\n")
f.close()
sensorList = "0"
cAddressOld = copy.copy(cAddress)
cAddress = {}
f=open(homeDir+"parameters","r")
inp =json.loads(f.read())
f.close()
if "debug" in inp: debug = int(inp["debug"])
if "sensorList" in inp: sensorList = (inp["sensorList"])
if "sensorRefreshSecs" in inp: sensorRefreshSecs = float(inp["sensorRefreshSecs"])/1.5
if "cAddress" in inp: xxx = inp["cAddress"]
if sensorList.find("mysensors") == -1: return
if "mysensors" not in xxx: return
same=True
cAddress= copy.copy(xxx["mysensors"])
# check if anything new
if "mysensors" not in cAddressOld:
same=False
else:
for addr in cAddress:
if addr not in cAddressOld:
same=False
break
elif len(cAddress) != len(cAddressOld):
same=False
break
if cAddressOld[addr] != cAddress[addr]:
same=False
break
if not same: # if anything new start appropriate pgms
# delete old data file
if os.path.isfile(homeDir+"mysensors.dat"):
os.remove(homeDir+"mysensors.dat")
# start each "channel, device or what every you like to do
for addr in cAddress:
startMySensors(addr=addr)
# ===========================================================================
# Main
# ===========================================================================
global debug, homeDir,sensorList, externalSensor,cAddress,sensorRefreshSecs
debug = 5 # will be overwritten in readParams
homeDir = "/home/pi/"
nInputs = 10 # number of input channels 1...10 max
loopCount = 0 # for loop, not used could be deleted, but you might need it
sensorRefreshSecs = 33 # will be overwritten in readParams, number of seconds to sleep in each loop
sensorList = "" # list of sensor, we are looking for "mysensors"
cAddress = [] # store address / parameters we get from indigo in device config of mysensors in readParams
readParams() # get parameters send from indigo
myPID = str(os.getpid())
killOldPgm(myPID,"mysensors.py")# kill old instances of myself if they are still running
lastData ={}
while True: # loop for ever
data={}
try:
### get data
if sensorList.find("mysensors") > -1:# do mysensor
for nAddr in range(len(cAddress)):
v = getMySensors(addr=nAddr)
if v != "":
addr = cAddress[nAddr]
data["mysensors"] = {}
data["mysensors"][addr] = { }
for ii in range(min(nInputs,len(v))):
data["mysensors"][addr]["INPUT_"+str(ii)] = v[ii]
loopCount +=1
# write data in proper format to output file
if data != {} and lastData != data:
lastData =copy.copy(data)
f=open(homeDir+"mysensors.dat","w") # this is the file that wil be used to compose the message to indigo, read by sensors.py
f.write(json.dumps(data)) # looks like: {"mysensors":{"2":{"INPUT_0":123,"INPUT_1":22,..,"INPUT_9":99}}, where "2" is the address parameter we got from indigo
f.close()
except Exception, e:
toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
time.sleep(sensorRefreshSecs) # sleep the requested amount
readParams() # check if we have new parameetrs
sys.exit(0)
plug = indigo.server.getPlugin("com.karlwachs.piBeacon")
if not plug.isEnabled(): return #### piBeacon must be enabled, otherwise nothing here works
plug.executeAction("myoutput",
props ={
"piServerNumber": "0" ## rPi server # 0...9
,"text": "'gpio 21 high'" # use ' inside to send it to sys.arv[1] as one string otherwise it will be split into each word ie sys.argv[2].. [x]
}
)
##will set gip # 21 high, see the my output.py code.
##or
plug.executeAction("myoutput",
props ={
"piServerNumber": "0" ## rPi server # 0...9
,"text": "'reboot'" # use ' inside to send it to sys.arv[1] as one string otherwise it will be split into each word ie sys.argv[2].. [x]
}
)
##would reboot the rPi
# by Karl Wachs
# march 2
# this program will be called if indigo plugin sends a myoutput command
##
import json, sys,subprocess, time,datetime,os
## ===========================================================================
# utils
# ===========================================================================
def readParams():
global debug, homeDir
f=open(homeDir+"parameters","r")
inp =json.loads(f.read())
f.close()
if "debug" in inp: debug= int(inp["debug"])
def toLog(lev, text):
global debug, homeDir
if lev <= debug:
logF=open(homeDir+"myoutput.log","a")
logF.write(datetime.datetime.now().strftime("%Y%m%d-%H:%M:%S")+" "+text+"\n")
logF.close
def killOldPgm(myPID,pgmToKill):
global debug, homeDir
try:
cmd= "ps -ef | grep "+pgmToKill+" | grep -v grep"
ret = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()[0]
lines=ret.split("\n")
for line in lines:
if len(line) < 10: continue
line=line.split()
pid=int(line[1])
if pid == int(myPID): continue
toLog(1, "killing "+pgmToKill)
os.system("sudo kill -9 "+str(pid))
except Exception, e:
toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
# ===========================================================================
# Main
# ===========================================================================
global debug, homeDir
homeDir="/home/pi/"
debug=1
try:
readParams()
myPID = str(os.getpid())
killOldPgm(myPID,"'myoutput.py'")# old old instances of myself if they are still running
toLog(-1,"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 :
text1= sys.argv[1]
#eg reboot if you send the rebot command
if text1.find("reboot") > -1 :
os.system("sudo reboot")
elif text1.find("gpio 21 high") > -1:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(21,GPIO.OUT)
GPIO.output(21,True)
except Exception, e:
toLog(-1, u"in Line '%s' has error='%s'" % (sys.exc_traceback.tb_lineno, e))
exit(0)
## first get plugin
plug = indigo.server.getPlugin("com.karlwachs.piBeacon")
if not plug.isEnabled(): return #### piBeacon must be enabled, otherwise nothing here works
plug.executeAction("playSoundFile",
props ={
"piServerNumber": "0" ## rPi server # 0...9
,"cmd": "omxplayer" # omxplayer for mp3 or aplay for .wav
,"soundFile": "f1.mp3" # file in ~/documents/piBeacon/soundfiles
}
)
plug.executeAction("playSoundFile",
props ={
"piServerNumber": "0" ## rPi server # 0...9
,"cmd": "aplay" # omxplayer for mp3 or aplay for .wav
,"soundFile": "bleep_01.wav" # file in ~/documents/piBeacon/soundfiles
}
)
Users browsing this forum: No registered users and 5 guests