Example #1
0
def main():

    # Setup exit handlers
    signal.signal(signal.SIGTSTP, SIGTSTP_handler)
    signal.signal(signal.SIGINT, SIGINT_handler)

    lock = threading.Lock()
    qIn = Queue.Queue()
    qOut = Queue.Queue()

    # Start File Logger
    print "Starting Logger.."
    global logger
    logger = FileLogger.startLogger("/var/log/NestSensor.log", 1000000, 5)
    logger.info("Starting Logger...")

    global nestsensor
    nestsensor = NestSensor(lock, qIn, qOut, logger)

    # Initialize NestSensor module
    if not nestsensor.init():
        print "Error: initializing NestSensor"
        sys.exit()

    #nestsensor.run()					# run on main thread
    nestsensor.start()  # start thread

    # Pass message to child
    msg = message()
    msg.timestamp = time()
    msg.command = "measure:temp?"
    msg.argument = ""
    qIn.put(msg)

    msg = message()
    msg.timestamp = time()
    msg.command = "measure:humidity?"
    msg.argument = ""
    qIn.put(msg)

    # Monitor for messages from child
    while True:
        if not qOut.empty():
            msg = qOut.get()
            if isinstance(msg, message):
                print(
                    strftime("[%H:%M:%S]: ", localtime()) +
                    "Message from NestSensor\t" + str(msg.command) + "\t" +
                    str(msg.argument))
                logger.info(
                    strftime("[%H:%M:%S]: ", localtime()) +
                    "Message from NestSensor\t" + str(msg.command) + "\t" +
                    str(msg.argument))
        sleep(0.1)

    nestsensor.join()

    # Wait for termination
    signal.pause()
Example #2
0
def main():
    #	while True:
    #		print "Pressure: " + str(read_avg_pressure(100)) + "mbar"
    #		sleep(10)

    # Setup exit handlers
    signal.signal(signal.SIGTSTP, SIGTSTP_handler)
    signal.signal(signal.SIGINT, SIGINT_handler)

    lock = threading.Lock()
    qIn = Queue.Queue()
    qOut = Queue.Queue()

    # Start File Logger
    print "Starting Logger.."
    global logger
    logger = FileLogger.startLogger("/var/log/RPi_Pressure.log", 1000000, 5)
    logger.info("Starting Logger...")

    global rpipressure
    rpipressure = RPi_Pressure(lock, qIn, qOut, logger)

    # Initialize RPi Pressure module
    if not rpipressure.init():
        print "Error: initializing RPi Pressure"
        sys.exit()

    #rpipressure.run()					# run on main thread
    rpipressure.start()  # start thread

    # Pass message to child
    msg = message()
    msg.timestamp = time()
    msg.command = "measure:pressure?"
    msg.argument = ""
    qIn.put(msg)

    # Monitor for messages from child
    while True:
        if not qOut.empty():
            msg = qOut.get()
            if isinstance(msg, message):
                print(
                    strftime("[%H:%M:%S]: ", localtime()) +
                    "Message from RPi Pressure\t" + str(msg.command) + "\t" +
                    str(msg.argument))
                logger.info(
                    strftime("[%H:%M:%S]: ", localtime()) +
                    "Message from RPi Pressure\t" + str(msg.command) + "\t" +
                    str(msg.argument))
        sleep(0.1)

    rpipressure.join()

    # Wait for termination
    signal.pause()
Example #3
0
def main():

	# Setup exit handlers
	signal.signal(signal.SIGTSTP, SIGTSTP_handler)
	signal.signal(signal.SIGINT, SIGINT_handler)
	
	lock = threading.Lock()
	qIn = Queue.Queue()
	qOut = Queue.Queue()

	# Start File Logger
	print "Starting Logger.."
	global logger
	logger = FileLogger.startLogger("/var/log/NestSensor.log", 1000000, 5)
	logger.info("Starting Logger...")

	global nestsensor
	nestsensor = NestSensor(lock, qIn, qOut, logger)

	# Initialize NestSensor module
	if not nestsensor.init():
		print "Error: initializing NestSensor"
		sys.exit()

	#nestsensor.run()					# run on main thread
	nestsensor.start()					# start thread

	# Pass message to child
	msg = message()
	msg.timestamp = time()
	msg.command = "measure:temp?"
	msg.argument = ""
	qIn.put(msg)

	msg = message()
	msg.timestamp = time()
	msg.command = "measure:humidity?"
	msg.argument = ""
	qIn.put(msg)

	# Monitor for messages from child
	while True:
		if not qOut.empty():
			msg = qOut.get()
			if isinstance(msg, message):
				print (strftime("[%H:%M:%S]: ", localtime()) + "Message from NestSensor\t" + str(msg.command) +"\t" + str(msg.argument))
				logger.info (strftime("[%H:%M:%S]: ", localtime()) + "Message from NestSensor\t" + str(msg.command) +"\t" + str(msg.argument))
		sleep(0.1)

	nestsensor.join()
	
	# Wait for termination
	signal.pause()
Example #4
0
def main():
#	while True:
#		print "Pressure: " + str(read_avg_pressure(100)) + "mbar"
#		sleep(10)

	# Setup exit handlers
	signal.signal(signal.SIGTSTP, SIGTSTP_handler)
	signal.signal(signal.SIGINT, SIGINT_handler)
	
	lock = threading.Lock()
	qIn = Queue.Queue()
	qOut = Queue.Queue()

	# Start File Logger
	print "Starting Logger.."
	global logger
	logger = FileLogger.startLogger("/var/log/RPi_Pressure.log", 1000000, 5)
	logger.info("Starting Logger...")

	global rpipressure
	rpipressure = RPi_Pressure(lock, qIn, qOut, logger)

	# Initialize RPi Pressure module
	if not rpipressure.init():
		print "Error: initializing RPi Pressure"
		sys.exit()

	#rpipressure.run()					# run on main thread
	rpipressure.start()					# start thread

	# Pass message to child
	msg = message()
	msg.timestamp = time()
	msg.command = "measure:pressure?"
	msg.argument = ""
	qIn.put(msg)

	# Monitor for messages from child
	while True:
		if not qOut.empty():
			msg = qOut.get()
			if isinstance(msg, message):
				print (strftime("[%H:%M:%S]: ", localtime()) + "Message from RPi Pressure\t" + str(msg.command) +"\t" + str(msg.argument))
				logger.info (strftime("[%H:%M:%S]: ", localtime()) + "Message from RPi Pressure\t" + str(msg.command) +"\t" + str(msg.argument))
		sleep(0.1)

	rpipressure.join()
	
	# Wait for termination
	signal.pause()
Example #5
0
    def metrics_failure_summary(self, df, **kwargs):
        tablefmt = kwargs.get('tablefmt', 'html')
        self.mdLogger.
        print("\n## {} metrics: last {} records from {} to {} , now is {} in {}\n\n"
              .format(kwargs.get('name'),
                      kwargs.get('size'),
                      kwargs.get('beginTime'),
                      kwargs.get('endTime'),
                      FileLogger.getCurrentTimeStr('%Y-%m-%d %H:%M:%S'),
                      self.env))

        if (kwargs.get('columns')):
            mdTable = tabulate(df, headers=kwargs.get('columns'), tablefmt=tablefmt)
        else:
            mdTable = tabulate(df, headers='keys', tablefmt=tablefmt)
        self.mdLogger.append(mdTable)
        return mdTable
Example #6
0
def triggerAlerts(category, env, interval, emailList):
    alertItems = tool.alertConfig.get_alert_config_items()

    for key, value in alertItems:
        print(key, value)

        metricsChecker = MetricsChecker(category, env, key, value)

        if not metricsChecker.isEnabled:
            print("{} is not enabled".format(key))
            continue

        if metricsChecker.isSnoozed():
            print("{} is not snoozed".format(key))
            continue

        df, totalErrCnt = metricsChecker.queryErrorRecords(interval, size=10)

        queryErrCnt = df.index.size

        alertFlag = metricsChecker.needTriggeredByCount(totalErrCnt)

        if (metricsChecker.totalQuery):
            totalCount = metricsChecker.queryTotalCount('1d')
            alertFlag = alertFlag or metricsChecker.needTriggeredByRatio(totalErrCnt, totalCount)

            print("queryErrCnt={}, totalErrCnt={}, totalCount={}, alertFlag={}".format(queryErrCnt, totalErrCnt,
                                                                                       totalCount, alertFlag))

        if (alertFlag):
            print("trigger alert for {}".format(key))

            timeStr = FileLogger.getCurrentTimeStr('%Y-%m-%dT%H:%M:%S')
            metricsChecker.reporter.title = 'Metrics_Alert_Report_at_%s' % timeStr
            metricsChecker.makeFailureSummary(df, interval)
            metricsChecker.reporter.mdLogger.
            print("\n* Query string: {}".format(metricsChecker.failureQuery))
            metricsChecker.reporter.mdLogger.
            print("* Queried Metrics Error Count={}, Total Metrics Error Count={}, Total Metrics Count={}".format(
                queryErrCnt, totalErrCnt, totalCount))
            metricsChecker.reporter.sendEmail(emailList)
Example #7
0
def main():

    # Start File Logger
    print "Starting Logger.."
    logger = FileLogger.startLogger("/var/log/HomeWeather.log", 1000000, 5)
    logger.info("Starting Logger...")

    # Check for internet connection
    #URL = "http://www.google.com"
    #print "Checking for internet connection..."
    #logger.info("Checking for internet connection...")
    #for retry in range(10):
    #	try:
    #		response = requests.get(URL)
    #	except Exception as e:
    #		print "Failed to connect to Internet"
    #		print e
    #		logger.error("Failed to connect to Internet", exc_info=True)
    #		sleep(3)
    #	if response.ok:
    #		break

    lock = threading.Lock()

    # Initialize sensors
    if not initSensors(lock, logger):
        cleanup()
        sys.exit()
    sleep(30)  # wait for sensors to initialize

    # Initialize plotly
    if not initPlotly(lock, logger):
        cleanup()
        sys.exit()

    # Setup exit handlers
    signal.signal(signal.SIGTSTP, SIGTSTP_handler)
    signal.signal(signal.SIGINT, SIGINT_handler)

    # Wait for termination
    signal.pause()
Example #8
0
def main():
	
	# Start File Logger
	print "Starting Logger.."
	logger = FileLogger.startLogger("/var/log/HomeWeather.log", 1000000, 5)
	logger.info("Starting Logger...")
	
	# Check for internet connection
	#URL = "http://www.google.com"
	#print "Checking for internet connection..."
	#logger.info("Checking for internet connection...")
	#for retry in range(10):
	#	try:
	#		response = requests.get(URL)
	#	except Exception as e:
	#		print "Failed to connect to Internet"
	#		print e
	#		logger.error("Failed to connect to Internet", exc_info=True)
	#		sleep(3)
	#	if response.ok:
	#		break

	lock = threading.Lock()

	# Initialize sensors
	if not initSensors(lock, logger):
		cleanup()
		sys.exit()
	sleep(30)				# wait for sensors to initialize
	
	# Initialize plotly
	if not initPlotly(lock, logger):
		cleanup()
		sys.exit()

	# Setup exit handlers
	signal.signal(signal.SIGTSTP, SIGTSTP_handler)
	signal.signal(signal.SIGINT, SIGINT_handler)
	
	# Wait for termination
	signal.pause()
Example #9
0
def quickTest(emailSender, emailReceiver, **kwargs):
    recipients = [emailReceiver]

    mdLogger = FileLogger.MarkdownLogger('test.md')

    mdLogger.
    print("# Pager duty alert test email")

    mdLogger.
    print("\n\n")
    mdLogger.printTableTitle(['date', 'pool', 'error count'])
    mdLogger.printTableRow(['2018-8-1', 'east-china', 3000])
    mdLogger.printTableRow(['2018-8-2', 'east-china', 4000])
    mdLogger.printTableRow(['2018-8-3', 'east-china', 5000])
    mdLogger.printTableRow(['2018-8-4', 'east-china', 6000])
    mdLogger.printTableRow(['2018-8-5', 'east-china', 7000])

    mdLogger.
    print("\n\n")

    sender = EmailSender.EmailSender(emailSender, **kwargs)

    sender.sendWithImages("Production Alert Email", recipients, mdLogger.toHtml(), "../template/email_template.j2")
Example #10
0
    def __init__(self,
                 filename,
                 title=None,
                 isShow=True,
                 isBlock=False,
                 needChangePath=False,
                 **kwargs):

        self.filename = filename
        self.title = title
        self.isShow = isShow
        self.isBlock = isBlock
        self.defaultStyle = ['bs-', 'ro-', 'y^-']

        plt.style.use('seaborn-whitegrid')

        self.fig = plt.figure()

        if (needChangePath):
            self.pngFile = "./logs/{}/{}.png".format(
                FileLogger.getCurrentTimeStr(),
                os.path.basename(self.filename))
        else:
            self.pngFile = filename
Example #11
0
def main():

	
	# Start File Logger
	print "Starting Logger.."
	global logger
	logger = FileLogger.startLogger("/var/log/HomeWeather.log", 1000000, 5)
	logger.info("Starting Logger...")
	
	# Check for internet connection
	#URL = "http://www.google.com"
	#print "Checking for internet connection..."
	#logger.info("Checking for internet connection...")
	#for retry in range(10):
	#	try:
	#		response = requests.get(URL)
	#	except Exception as e:
	#		print "Failed to connect to Internet"
	#		print e
	#		logger.error("Failed to connect to Internet", exc_info=True)
	#		sleep(3)
	#	if response.ok:
	#		break

	# Init TempoDB
	#global tempo_client
	#tempo_client = init_tempo(tempo_key, tempo_secret)

	# Init MySQLdb
	db = MySQLdatabase.Connect(mysql_host, mysql_login, mysql_pw, mysql_db)
	if (db == None):
		
		cleanup()
		return

	#Start Plotly Timer
	print "Starting Plotly Timer..."
	global tPlotlyPeriod, tPlotly
	tPlotlyPeriod = 60 * 1
	py = plotlyClient.initPlotly(plotly_un, plotly_key)
	if py:	
		tPlotly = Timer(0, PlotlyTimer, [py, db])
		tPlotly.start()
	else:
		cleanup()
		return

	# Start Nest Timer
	print "Starting Nest Timer..."
	global n, tNestPeriod, tNest
	n = nest.Nest(nlogin, npasswd)
	n.login()
	tNestPeriod = 60 * 3
	tNest = Timer(0, NestTimer, [n, db])
	tNest.start()

	# Start WU Timer
	#print "Starting WU Timer..."
	#global tWUPeriod, tWU
	#tWUPeriod = 60 * 15
	#tWU = Timer(0, WUTimer, [db])
	#tWU.start()
	
	# Start ForecastIO Timer
	print "Starting ForecastIO Timer..."
	global tForecastIOPeriod, tForecastIO
	tForecastIOPeriod = 60 * 3
	tForecastIO = Timer(0, ForecastIOTimer, [db])
	tForecastIO.start()

	# Start Raspberry Pi Temp Timer
	print "Starting Raspberry Pi Timer..."
	global tRPiPeriod, tRPi
	tRPiPeriod = 60 * 3
	device_file = RPi_Temp.initTemp()
	if (device_file):
		tRPi = Timer(0, RPiTimer, [device_file, db])
		tRPi.start()

	# Start Arduino Timer
	print "Starting Arduino Timer..."
	global tArduinoPeriod, tArduino
	tArduinoPeriod = 60 * 3
	tArduino = Timer(0, ArduinoTimer, [db])
	tArduino.start()
	
	# Setup exit handlers
	signal.signal(signal.SIGTSTP, SIGTSTP_handler)
	signal.signal(signal.SIGINT, SIGINT_handler)
	
	# Wait for termination
	signal.pause()
Example #12
0
    def make_report_files(self, title):
        baseFileName = "./logs/{}_{}".format(self.title, FileLogger.getCurrentTimeStr('%Y%m%d%H%M%S'))

        self.mdLogger = FileLogger.MarkdownLogger(baseFileName + '.md')
        self.csvLogger = FileLogger.CsvLogger(baseFileName + '.csv', None, False)
        self.csvFiles.append(self.csvLogger.getFilePath())
import sys,os,getopt
import traceback
import commands
sys.path.append("/DG/activeRelease/lib/python_lib/")

from pythonodbcdriver import pyodbcdriver ### Using pyodbc to get GG connection handle
import FileLogger

LOG_FILE_PATH = '/DGlogs/GGExecuteQuery.py
logger = FileLogger.logger(LOG_FILE_PATH);
log = logger.getlogger();
connectionObject=None

def Usage():
    print '  This script would insert records in DefaultCacheConfigurationProfile Table of GGain provided no record is present for id=1'
    print '  \n'
    print '  USAGE : python /DG/activeRelease/GGExecuteQuery.py'
    sys.exit(2)

def InsertDefaultCacheConfigurationProfile():
    DefaultCConfigCntQry = 'select count(*) from "DefaultCacheConfigurationProfile".DefaultCacheConfigurationProfile where id=1'
    IdCntDefaultCConfig = connectionObject.execute(DefaultCConfigCntQry,1)
    if IdCntDefaultCConfig == -1:
       log.error("Failed to Execute Query %s"%(DefaultCConfigCntQry))
       sys.exit(1)

    if int(IdCntDefaultCConfig[1][0][0]) == 0:
        InsertDefaultCConfigQry = "insert into \"DefaultCacheConfigurationProfile\".DefaultCacheConfigurationProfile(id,cacheMode,atomicityMode,writeSynchronizationMode,backups,statisticsEnabled) Values(1,'PARTITIONED','TRANSACTIONAL','FULL_SYNC',1,true)"
        Status = connectionObject.execute(InsertDefaultCConfigQry)
        if Status == -1:
           log.error("Failed to Execute Query %s"%(InsertDefaultCConfigQry))
Example #14
0
def main():

    # Start File Logger
    print "Starting Logger.."
    global logger
    logger = FileLogger.startLogger("/var/log/HomeWeather.log", 1000000, 5)
    logger.info("Starting Logger...")

    # Check for internet connection
    #URL = "http://www.google.com"
    #print "Checking for internet connection..."
    #logger.info("Checking for internet connection...")
    #for retry in range(10):
    #	try:
    #		response = requests.get(URL)
    #	except Exception as e:
    #		print "Failed to connect to Internet"
    #		print e
    #		logger.error("Failed to connect to Internet", exc_info=True)
    #		sleep(3)
    #	if response.ok:
    #		break

    # Init TempoDB
    #global tempo_client
    #tempo_client = init_tempo(tempo_key, tempo_secret)

    # Init MySQLdb
    db = MySQLdatabase.Connect(mysql_host, mysql_login, mysql_pw, mysql_db)
    if (db == None):

        cleanup()
        return

    #Start Plotly Timer
    print "Starting Plotly Timer..."
    global tPlotlyPeriod, tPlotly
    tPlotlyPeriod = 60 * 1
    py = plotlyClient.initPlotly(plotly_un, plotly_key)
    if py:
        tPlotly = Timer(0, PlotlyTimer, [py, db])
        tPlotly.start()
    else:
        cleanup()
        return

    # Start Nest Timer
    print "Starting Nest Timer..."
    global n, tNestPeriod, tNest
    n = nest.Nest(nlogin, npasswd)
    n.login()
    tNestPeriod = 60 * 3
    tNest = Timer(0, NestTimer, [n, db])
    tNest.start()

    # Start WU Timer
    #print "Starting WU Timer..."
    #global tWUPeriod, tWU
    #tWUPeriod = 60 * 15
    #tWU = Timer(0, WUTimer, [db])
    #tWU.start()

    # Start ForecastIO Timer
    print "Starting ForecastIO Timer..."
    global tForecastIOPeriod, tForecastIO
    tForecastIOPeriod = 60 * 3
    tForecastIO = Timer(0, ForecastIOTimer, [db])
    tForecastIO.start()

    # Start Raspberry Pi Temp Timer
    print "Starting Raspberry Pi Timer..."
    global tRPiPeriod, tRPi
    tRPiPeriod = 60 * 3
    device_file = RPi_Temp.initTemp()
    if (device_file):
        tRPi = Timer(0, RPiTimer, [device_file, db])
        tRPi.start()

    # Start Arduino Timer
    print "Starting Arduino Timer..."
    global tArduinoPeriod, tArduino
    tArduinoPeriod = 60 * 3
    tArduino = Timer(0, ArduinoTimer, [db])
    tArduino.start()

    # Setup exit handlers
    signal.signal(signal.SIGTSTP, SIGTSTP_handler)
    signal.signal(signal.SIGINT, SIGINT_handler)

    # Wait for termination
    signal.pause()
Example #15
0
def main():
	
	# Start File Logger
	global logger
	logger = FileLogger.startLogger("/var/log/PostTemperature.log", 1000000, 5)
	logger.info("Starting Logger...")
	
	# Check for internet connection
	#URL = "http://www.google.com"
	#print "Checking for internet connection..."
	#logger.info("Checking for internet connection...")
	#for retry in range(10):
	#	try:
	#		response = requests.get(URL)
	#	except Exception as e:
	#		print "Failed to connect to Internet"
	#		print e
	#		logger.error("Failed to connect to Internet", exc_info=True)
	#		sleep(3)
	#	if response.ok:
	#		break
		

	# Init TempoDB
	global tempo_client
	tempo_client = init_tempo(tempo_key, tempo_secret)

	#Start Plotly Timer
	global tPlotlyPeriod, tPlotly
	tPlotlyPeriod = 60 * 1
	py = plotlyClient.initPlotly(plotly_un, plotly_key)
	if (py and tempo_client):	
		tPlotly = Timer(0, PlotlyTimer, [py, tempo_client])
		tPlotly.start()

	# Start Nest Timer
	global n, tNestPeriod, tNest
	n = nest.Nest(nlogin, npasswd)
	n.login()
	tNestPeriod = 60 * 5
	tNest = Timer(0, NestTimer)
	tNest.start()

	# Start WU Timer
	global tWUPeriod, tWU
	tWUPeriod = 60 * 15
	tWU = Timer(0, WUTimer)
	tWU.start()
	
	# Start Raspberry Pi Temp Timer
	global tRPiPeriod, tRPi
	tRPiPeriod = 60 * 5
	device_file = RPi_Temp.initTemp()
	if (device_file):
		tRPi = Timer(0, RPiTimer, [device_file])
		tRPi.start()

	# Start Arduino Timer
	global tArduinoPeriod, tArduino
	tArduinoPeriod = 60 * 5
	tArduino = Timer(0, ArduinoTimer)
	tArduino.start()
	
	# Setup exit handlers
	signal.signal(signal.SIGTSTP, SIGTSTP_handler)	#Thread stop detected
	signal.signal(signal.SIGINT, SIGINT_handler)	#Ctrl+C detected
	
	# Wait for termination
	signal.pause()
Example #16
0
 def getLogger(self, x):
     if x == 1:
         return FileLogger()
     elif x == 2:
         return ConsoleLogger()
Example #17
0
		logger.info (time.strftime("[%H:%M:%S]: EXCEPTION ", time.localtime()) + traceback.format_exc())
		return -1;


        return sensorDict


# Start File Logger
print "Starting Logger.." 
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(27, GPIO.OUT)
GPIO.output(27,True) #Turn power OFF

global logger
logger = FileLogger.startLogger("/var/log/kolektor.log", 1000000, 5) 
state = True 
dictTemp = None
logger.info("Starting Logger...")

ow.init('localhost:4304')

"""i = 0
Sanitarna = 60
Kolektori = 30
"""
# endless loop, on/off for 1 second
while True:
	
	dictTemp = read_all_temp()
	if(dictTemp != -1):
import RPi.GPIO as GPIO  ## Import GPIO Library
import time  ## Import 'time' library.  Allows us to use 'sleep'
import datetime
import FileLogger

# Start File Logger
global logger
logger = FileLogger.startLogger("/var/www/pumpController.log", 5000, 5)
logger.info("Starting Logger...")

logger.info(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S ") + "Script Started")
time.sleep(1)

GPIO.setmode(GPIO.BCM)  ## Use Broadcom pin numbering
gpio_pump = 18
gpio_drain = 24  # maybe copy this format for adding sensors

GPIO.setwarnings(False)
GPIO.setup(gpio_pump, GPIO.OUT)
GPIO.output(gpio_pump, True)
GPIO.setup(gpio_drain, GPIO.OUT)  # not really needed, but keeping in case
GPIO.output(gpio_drain, True)  # not really needed, but keeping in case

script_path = "/home/pi/PiPonics/"
pump_file = script_path + "pump.txt"
drain_file = script_path + "drain.txt"  # probably dont need this

with open(pump_file, "r+") as fo:
    fo.seek(0, 0)
    fo.write("0")
fo.closed
Example #19
0
import RPi.GPIO as GPIO  ## Import GPIO Library
import time  ## Import 'time' library.  Allows us to use 'sleep'
import datetime
import FileLogger

# Start File Logger
global logger
logger = FileLogger.startLogger("/var/www/pumpController3.log", 5000, 5)
logger.info("Starting Logger...")

logger.info(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S ") +
            "Script Started")
time.sleep(1)

GPIO.setmode(GPIO.BOARD)  ## Use BOARD pin numbering
gpio_pump = 36
gpio_valveone = 38
gpio_valvetwo = 40

GPIO.setwarnings(False)
GPIO.setup(gpio_pump, GPIO.OUT)
GPIO.output(gpio_pump, True)
GPIO.setup(gpio_valveone, GPIO.OUT)
GPIO.output(gpio_valveone, True)
GPIO.setup(gpio_valvetwo, GPIO.OUT)
GPIO.output(gpio_valvetwo, True)

script_path = "/home/pi/Aquaponics/PiPonics/"
valveone_file = script_path + "valve1.txt"
valvetwo_file = script_path + "valve2.txt"
Example #20
0
			print (time.strftime("[%H:%M:%S]: ", time.localtime()) + str(sensorDict))
			
	except Exception, e:
		print (time.strftime("[%H:%M:%S]: EXCEPTION ", time.localtime()) + traceback.format_exc())

		if logger:
			logger.error((time.strftime("[%H:%M:%S]: EXCEPTION ", time.localtime()) + traceback.format_exc()), exc_info=True)
		return -1;
	return sensorDict	
		
print "Starting temperature agregator..."	

# Start File Logger
print "Starting Logger.."
global logger
logger = FileLogger.startLogger("/var/log/agregatemp.log", 1000000, 5)
logger.info("Starting Logger...")

# Initialize RPi_Temp module
if not init():
	print "Error: initializing RPi_Temp"
	sys.exit()

dictTemp = None
curFloorPump = None

while True:
	
	try:
		
		#read all sensors on one wire