Skip to content

Commit

Permalink
Merge branch 'master' of github.com:acaird/raspi-scale
Browse files Browse the repository at this point in the history
  • Loading branch information
acaird committed Mar 5, 2015
2 parents b525a17 + 9a5f3c5 commit cb165bd
Show file tree
Hide file tree
Showing 6 changed files with 66 additions and 80 deletions.
53 changes: 23 additions & 30 deletions scale.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,24 +76,21 @@ def readadc(adcnum, clockpin, mosipin, misopin, cspin):
try:
f = open(cfg['raspberryPiConfig']['plotlyCredsFile'])
except:
print "=========================== ERROR ==========================="
print "I couldn't open the file '{0}'".format(cfg['raspberryPiConfig']['plotlyCredsFile'])
print "to read the plot.ly settings, so I can't make a plot and"
print "am giving up."
print "(I am:", os.path.abspath(os.path.dirname(sys.argv[0]))+"/"+sys.argv[0],")"
print "=========================== ERROR ==========================="
logging.error("I couldn't open the file %s to read the plot.ly settings, so I can't make a plot and am giving up. I am %s/%s",
cfg['raspberryPiConfig']['plotlyCredsFile'], os.path.abspath(os.path.dirname(sys.argv[0])),sys.argv[0])
exit (1)

plotlyConfig = yaml.safe_load(f)
f.close()

if args.debug == None:
DEBUG = cfg['raspberryPiConfig']['debug']
logging.basicConfig(level=logging.DEBUG)
else:
DEBUG = args.debug
logging.basicConfig(level=logging.DEBUG)

if DEBUG:
print "Initializing."
logging.debug("Initializing.")

if not cfg['raspberryPiConfig']['alertChannels']:
cfg['raspberryPiConfig']['alertChannels'] = ''
Expand Down Expand Up @@ -150,31 +147,30 @@ def readadc(adcnum, clockpin, mosipin, misopin, cspin):
# If we will need Twitter credentials, read them now
#
if 'twitter' in cfg['raspberryPiConfig']['alertChannels'] or 'twitter' in cfg['raspberryPiConfig']['updateChannels']:
if DEBUG:
print "Reading Twitter credentials from ",cfg['twitterConfiguration']['twitterCredsFile']

logging.debug ("Reading Twitter credentials from ",cfg['twitterConfiguration']['twitterCredsFile'])

try:
f = open(cfg['twitterConfiguration']['twitterCredsFile'])
twitterCredentials = yaml.safe_load(f)
f.close()
except:
if DEBUG:
print "=========================== ERROR ==========================="
print "I couldn't open the file '{0}'".format(cfg['twitterConfiguration']['twitterCredsFile'])
print "to read the twitter credentials, so I can't tweet."
print "(I am:", os.path.abspath(os.path.dirname(sys.argv[0]))+"/"+sys.argv[0],")"
print "=========================== ERROR ==========================="
logging.error("I couldn't open the file %s to read the twitter credentials, so I can't tweet. I am: %s/%s",
cfg['twitterConfiguration']['twitterCredsFile'],
os.path.abspath(os.path.dirname(sys.argv[0])),
sys.argv[0])

cfg['raspberryPiConfig']['alertChannels'].remove('twitter')
cfg['raspberryPiConfig']['updateChannels'].remove('twitter')
cfg['raspberryPiConfig']['alertChannels'].remove('twitter')
cfg['raspberryPiConfig']['updateChannels'].remove('twitter')

oTime = cfg['raspberryPiConfig']['updateTime']

while cfg['raspberryPiConfig']['updateTime'] % cfg['raspberryPiConfig']['checkTime']:
cfg['raspberryPiConfig']['updateTime'] += 1

if oTime != cfg['raspberryPiConfig']['updateTime'] and DEBUG:
print "\"updateTime\" changed from {0} to {1} so it would divide evenly by \"checkTime\".".format(oTime, cfg['raspberryPiConfig']['updateTime'])
if oTime != cfg['raspberryPiConfig']['updateTime']:
logging.debug ("\"updateTime\" changed from %s to %s so it would divide evenly by \"checkTime\".",
oTime, cfg['raspberryPiConfig']['updateTime']))

# This totally isn't a clock, it's a counter. But we use it sort of
# like a clock.
Expand All @@ -189,8 +185,7 @@ def readadc(adcnum, clockpin, mosipin, misopin, cspin):
if alert not in alertState:
alertState[alert] = 0

if DEBUG:
print "Ready."
logging.debug ("Ready.")

while True:

Expand All @@ -204,10 +199,9 @@ def readadc(adcnum, clockpin, mosipin, misopin, cspin):
if fsr_change > cfg['raspberryPiConfig']['maxChange'] and ( abs(fsr_change) > tolerance ):
last_read = fsr
beans = int((fsr/1024.)*100)
if DEBUG:
print logString.format(currentTime, "CHANGE",
fsr, last_read,
fsr_change, beans)
logging.debug (logString.format(currentTime, "CHANGE",
fsr, last_read,
fsr_change, beans))
scalePlotly.updatePlot (currentTime,
beans,
plotlyConfig['username'],
Expand All @@ -221,10 +215,9 @@ def readadc(adcnum, clockpin, mosipin, misopin, cspin):
if scaleClock % cfg['raspberryPiConfig']['updateTime'] == 0:
last_read = fsr
beans = int((fsr/1024.)*100)
if DEBUG:
print logString.format(currentTime, "UPDATE",
fsr, last_read,
fsr_change, beans)
logging.debug (logString.format(currentTime, "UPDATE",
fsr, last_read,
fsr_change, beans))
if 'plotly' in cfg['raspberryPiConfig']['updateChannels']:
scalePlotly.updatePlot (currentTime,
beans,
Expand Down
18 changes: 6 additions & 12 deletions scaleAlerts.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ def processLowBeanAlerts (fsr, alertState, cfg, currentTime):
if fsr < cfg['raspberryPiConfig']['getMoarBeansNow']:
for alert in cfg['raspberryPiConfig']['alertChannels']:
if alertState[alert] == 0:
if DEBUG:
print "{0} Doing low bean alert {1}".format(currentTime, alert)
logging.debug ("%s Doing low bean alert %s",currentTime, alert)
if alert == 'twitter':
hashTags = " ".join(["#"+m for m in cfg['twitterConfiguration']['twitterAlertHashtags']])
tweet = cfg['twitterConfiguration']['twitterAlertMessage']+" "+ hashTags
Expand All @@ -22,9 +21,6 @@ def processLowBeanAlerts (fsr, alertState, cfg, currentTime):
subject = cfg['emailConfiguration']['emailAlertSubject']
body = cfg['emailConfiguration']['emailAlertMessage'].format(beans,currentTime)

# print "Subject:",subject
# print "\n",body

scaleEmail.sendEmail (cfg['emailConfiguration']['smtpServer'],
cfg['emailConfiguration']['gmailCredsFile'],
cfg['emailConfiguration']['fromAddr'],
Expand All @@ -38,13 +34,10 @@ def processLowBeanAlerts (fsr, alertState, cfg, currentTime):
# above the bean limit and if we had previously set the alert
# channel states
if fsr > (cfg['raspberryPiConfig']['getMoarBeansNow'] * 1.1) and sum([alertState[m] for m in alertState]) > 0:
if DEBUG:
print "{0} plenty of beans; resetting alerts".format(currentTime)
for alert in alertState:
alertState[alert] = 0
alertState.sync()


logging.debug ("%s plenty of beans; resetting alerts",currentTime)
for alert in alertState:
alertState[alert] = 0
alertState.sync()

if __name__ == "__main__":
import yaml
Expand All @@ -54,6 +47,7 @@ def processLowBeanAlerts (fsr, alertState, cfg, currentTime):
import scaleEmail
import argparse
import datetime
import logging

configFile = './scaleConfig.yaml'

Expand Down
25 changes: 13 additions & 12 deletions scaleConfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,9 @@ def readConfig (file):
try:
f = open(file)
except:
print "=========================== ERROR ==========================="
print "I couldn't open the file '{0}'".format(file)
print "to read the settings, so I'll have to think of"
print "something else to do."
print "(I am:", os.path.abspath(os.path.dirname(sys.argv[0]))+"/"+sys.argv[0],")"
print "=========================== ERROR ==========================="
errorString = '''I couldn't open the file {0} to read the settings, so I'll use the defaults. (Logged from {1}/{2})
'''.format(file,os.path.abspath(os.path.dirname(sys.argv[0])),sys.argv[0])
logging.warning(errorString)
exit (1)

# this is list() to make the load_all generator generate
Expand All @@ -76,18 +73,22 @@ def readConfig (file):
if __name__ == "__main__":

import pprint as pp
import logging

configFile = './scaleConfig.yaml'
configFile = './scaleConfig.yaml1'

cfg = readConfig(configFile)

print "The debug setting is",cfg['raspberryPiConfig']['debug']
if cfg['raspberryPiConfig']['debug']:
logging.basicConfig(level=logging.DEBUG)

print "And everything else is:"
logging.warning("The debug setting is %s",cfg['raspberryPiConfig']['debug'])

pp.pprint(cfg)
logging.debug("And everything else is:")

logging.debug(pp.pformat(cfg))

if 'plotly' in cfg['raspberryPiConfig']['alertChannels']:
print "Alert: Plot.ly"
logging.debug("Alert: Plot.ly")
else:
print "Alert: no Plot.ly"
logging.debug("Alert: no Plot.ly")
26 changes: 13 additions & 13 deletions scaleEmail.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,11 @@ def sendEmail (smtpServer, gmailCreds, fAddr, tAddr, subj, body):
with open(gmailCreds) as f:
creds = [x.strip('\n') for x in f.readlines()]
except:
print "=========================== ERROR ==========================="
print "I couldn't open the file '{0}'".format(gmailCreds)
print "to read your GMail login and password, so I can't send"
print "email using the GMail SMTP server, and am giving up."
print "(", os.path.abspath(os.path.dirname(sys.argv[0]))+"/"+sys.argv[0],")"
print "=========================== ERROR ==========================="
errorString = '''I couldn't open the file {0} to read the GMail credentials, so I'm giving up (Logged from {1}/{2})
'''.format(gmailCreds,os.path.abspath(os.path.dirname(sys.argv[0])),sys.argv[0])

logging.error(errorString)

exit (1)

s.starttls()
Expand All @@ -51,17 +50,18 @@ def sendEmail (smtpServer, gmailCreds, fAddr, tAddr, subj, body):

if __name__ == "__main__":

import logging

emailConfigFile = './emailConfig.yaml'

try:
f = open(emailConfigFile)
except:
print "=========================== ERROR ==========================="
print "I couldn't open the file '{0}'".format(emailConfigFile)
print "to read the email settings, so I can't send email and"
print "am giving up."
print "(I am:", os.path.abspath(os.path.dirname(sys.argv[0]))+"/"+sys.argv[0],")"
print "=========================== ERROR ==========================="
errorString = '''I couldn't open the file {0} to read the email settings, so I'm giving up (Logged from {1}/{2})
'''.format(emailConfigFile,os.path.abspath(os.path.dirname(sys.argv[0])),sys.argv[0])

logging.error(errorString)

exit (1)

emailConfig = yaml.safe_load(f)
Expand All @@ -77,4 +77,4 @@ def sendEmail (smtpServer, gmailCreds, fAddr, tAddr, subj, body):
emailConfig['fromAddr'], emailConfig['toAddr'],
subject, body)
if (results):
print "Delivery Failed, at least in part:",results
logging.warning ("Delivery Failed, at least in part: %s",results)
10 changes: 4 additions & 6 deletions scalePlotly.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,10 @@ def updatePlot (timeAndDate,beanPercent,username,apiKey):
try:
f = open(plotlyConfigFile)
except:
print "=========================== ERROR ==========================="
print "I couldn't open the file '{0}'".format(plotlyConfigFile)
print "to read the plot.ly settings, so I can't make a plot and"
print "am giving up."
print "(I am:", os.path.abspath(os.path.dirname(sys.argv[0]))+"/"+sys.argv[0],")"
print "=========================== ERROR ==========================="
errorString = '''I couldn't open the file {0} to read the GMail credentials, so I'm giving up (Logged from {1}/{2})
'''.format(plotlyConfigFile,os.path.abspath(os.path.dirname(sys.argv[0])),sys.argv[0])

logging.error(errorString)
exit (1)

plotlyConfig = yaml.safe_load(f)
Expand Down
14 changes: 7 additions & 7 deletions scaleTwitter.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
def tweetStatus(twitterCredsFile, tweet):

if (len(tweet)>140):
print >> sys.stderr, "Tweet is longer than 140 characters, can't send"
logging.error ("Tweet is longer than 140 characters, can't send")
return(0)

import twitter
Expand All @@ -16,12 +16,11 @@ def tweetStatus(twitterCredsFile, tweet):
twitterCredentials = yaml.safe_load(f)
f.close()
except:
print "=========================== ERROR ==========================="
print "I couldn't open the file '{0}'".format(emailConfigFile)
print "to read the twitter credentials, or maybe I couldn't log in, "
print "so I can't tweet and am giving up."
print "(I am:", os.path.abspath(os.path.dirname(sys.argv[0]))+"/"+sys.argv[0],")"
print "=========================== ERROR ==========================="
errorString = '''I couldn't open the file {0} to read the Twitter credentials, so I'm giving up (Logged from {1}/{2})
'''.format(twitterCredsFile,os.path.abspath(os.path.dirname(sys.argv[0])),sys.argv[0])

logging.error(errorString)

exit (1)


Expand All @@ -37,6 +36,7 @@ def tweetStatus(twitterCredsFile, tweet):

import argparse
import scaleConfig
import logging

configFile = './scaleConfig.yaml'

Expand Down

0 comments on commit cb165bd

Please sign in to comment.