def EOS_Send(): global ser global ADDRESS global Station global C_Station global EOS_String global cur global db global has_serial global has_db global Buff global E1 global eor_log sleep(1) E = array("B",Buff) if EOS(E[ADDRESS.INDICATOR]) == True: d = datetime.now() date_time = d.isoformat() date_time = re.sub("T"," ",date_time) date_time = re.sub("Z","",date_time) E1 = str(len(Buff)) + "/" x = 0 for e in E: E1 = E1 + str(e) + "-" x += 1 if x == 18: break a = "INSERT INTO FEED VALUES(" + str(E[ADDRESS.INDICATOR]) + ",0,'" + str(E1) + "'," + str(E[ADDRESS.B1]) + "," + str(E[ADDRESS.B2]) + "," + str(E[ADDRESS.B3]) + "," a += str(E[ADDRESS.B4]) + "," + str(E[ADDRESS.B5]) + "," + str(E[ADDRESS.B6]) + "," + str(E[ADDRESS.B7]) + "," + str(E[ADDRESS.B8]) + "," a += str(E[ADDRESS.B9]) + "," + str(E[ADDRESS.B10]) + "," + str(E[ADDRESS.B11]) + ",'" + date_time + "')" test, e, rc = eoss.sqlUpdate(db, a) if test == False: eor_log.info(a + "/" + e) else: if rc == 0: eor_log.info(a + "/" + e) else: eor_log.debug(a) if E[ADDRESS.INDICATOR] == 3: ##check if EOS is processing items cur.execute("Select count(TYPE) C from FEED where IS_DONE = 0") row = cur.fetchone() if row is not None: b = int(row["C"]) if b > 1000: if len(Station.User_Key) > 0: eosp.sendpushover(Station.App_Token, Station.User_Key, "EOS Server appears to be down - exiting", 1) eor_log.critical("Shutting Down - No EOS Server running") has_db = False
def main(): global ADDRESS global SQL global Station global has_db global has_serial global EOS_String global cur global db global eor_log global S_Version """Set up logging files """ try: os.remove(LOG_FILENAME) os.remove(LOG_FILENAME + ".1") os.remove(LOG_FILENAME + ".2") os.remove(LOG_FILENAME + ".3") os.remove(LOG_FILENAME + ".4") os.remove(LOG_FILENAME + ".5") os.remove(LOG_FILENAME + ".6") os.remove(LOG_FILENAME + ".7") os.remove(LOG_FILENAME + ".8") os.remove(LOG_FILENAME + ".9") os.remove(LOG_FILENAME + ".10") except: pass LEVELS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL } if len(sys.argv) > 1: level_name = sys.argv[1] level = LEVELS.get(level_name, logging.NOTSET) logging.basicConfig(filename=LOG_FILENAME, level=level) else: level = logging.INFO ##Change this to modify logging details for all messages DEBUG/INFO logging.basicConfig( filename=LOG_FILENAME, level=level ) ##Change this to modify logging details for all messages DEBUG/INFO eor_log = logging.getLogger('eorLogger') if level == logging.DEBUG: handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=100000, backupCount=10) else: handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=20000, backupCount=10) formatter = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler.setFormatter(formatter) eor_log.addHandler(handler) eor_log.info("Waiting for MYSQL... to start") sleep( 60 ) #wait a couple of min for services to start in case this is a bootup (65) """Ready to Go """ try: EOS_reader = eos_reader() db = mdb.connect(host=eoss.SQL.server, port=eoss.SQL.port, user=eoss.SQL.user, passwd=eoss.SQL.password, db=eoss.SQL.database) ## Set up a cursor to hold data and execute statments cur = db.cursor(mdb.cursors.DictCursor) if getSettings(): version = eosu.getsetting(db, "EOR_VERSION", 0) if version <> S_Version: a = "Update STATION Set STR_VALUE ='%s' where LABEL = 'EOR_VERSION'" % ( S_Version) test, e, rc = eoss.sqlUpdate(db, a) if test == False: eor_log.info(a + "/" + e) else: if rc == 0: eor_log.info(a + "/" + e) else: eor_log.info(a) ##MMQT if Station.Broker_Address <> "": try: auth = { 'username': Station.Broker_USN, 'password': Station.Broker_PWD } publish.single(topic=Station.Name + '/Version/Software/EOR', payload=S_Version, qos=0, retain=True, hostname=Station.Broker_Address, port=Station.Broker_Port, client_id='EOS_Station', auth=auth) sleep(5) publish.single(topic=Station.Name + '/Status/Fan', payload=Station.FanState, qos=0, retain=True, hostname=Station.Broker_Address, port=Station.Broker_Port, client_id='EOS_Station', auth=auth) sleep(5) except: eor_log.error('Error4 sending MQTT Message') cur.execute("Delete from FEED") db.commit() eor_log.info("FEED table has been truncated") has_db = True eor_log.info("Database Connected - Starting") else: has_db = False try: ser.port = Station.port ser.baudrate = Station.baudrate ser.bytsize = Station.bytesize ser.parity = Station.parity ser.stopbits = Station.stopbits ser.timeout = Station.timeout ser.xonoff = Station.xonoff ser.rtscts = Station.rtscts #ser.interCharTimeout = STATION.interCharTimeout ser.open() #starting the stream of info eor_log.info("Serial Port Found") ser.write(chr(13)) ser.flushInput() sleep(1) if setTime(): setAltitude() if type(Station.ID) is int: a = "UPDATE STATION SET INT_VALUE = %d WHERE LABEL = 'STAT_ID'" % ( Station.ID) test, e, rc = eoss.sqlUpdate(db, a) if test == False: eor_log.info(a + "/" + e) else: if rc == 0: eor_log.info(a + "/" + e) else: eor_log.debug(a) #re-set fan to off - default state setFan(0) a = "Update STATION SET STR_Value = 'Fan Off' where LABEL = 'HAS_FAN'" test, e, rc = eoss.sqlUpdate(db, a) if test == False: eor_log.info(a + "/" + e) else: if rc == 0: eor_log.info(a + "/" + e) else: eor_log.debug(a) #restart station ser.write("SE-O 48" + chr(13)) ser.write(chr(13)) ser.flushInput() eor_log.info("Set station for EOS (48) Output") ser.write("Q") #make sure that board is sending weather data has_serial = True except serial.SerialException: has_serial = False if len(Station.User_Key) > 0: eosp.sendpushover( Station.App_Token, Station.User_Key, "EOR Server NOT Running No Serial Port: " + ser.port, 1) eor_log.critical("EOR Server NOT Running No Serial Port: " + ser.port) except Exception, e: if len(Station.User_Key) > 0: eosp.sendpushover(Station.App_Token, Station.User_Key, "EOR Server NOT Running No DB", 1) has_db = False eor_log.critical("EOR server NOT Running: " + str(e))
def run(self): global ser global ADDRESS global Station global EOS_String global cur global db global has_serial global has_db global Buff global Buff2 global E1 global LED global EOS_reader global eor_log while self.running: try: Buff += ser.readline() if len(Buff) >= 18: if Buff.startswith("$EOSSD"): ##this will be a command from hardware to shut down in 1 min and power off self.running = False eor_log.critical( "Shutting Down - On command from Hardware") if len(Station.User_Key) > 0: eosp.sendpushover( Station.App_Token, Station.User_Key, "System is shutting down on command", 1) time.sleep(10) os.system('sudo shutdown -P +1') elif Buff.startswith("$EOS"): E = array("B", Buff) if EOS(E[ADDRESS.INDICATOR]) == True: if eosu.calcchecksum( Buff[:ADDRESS.B11]) == E[ADDRESS.B11]: d = datetime.now() date_time = d.isoformat() date_time = re.sub("T", " ", date_time) date_time = re.sub("Z", "", date_time) E1 = str(len(Buff)) + "/" x = 0 for e in E: E1 = E1 + str(e) + "-" x += 1 if x == 18: break a = "INSERT INTO FEED VALUES(" + str( E[ADDRESS.INDICATOR]) + ",0,'" + str( E1) + "'," + str( E[ADDRESS.B1]) + "," + str( E[ADDRESS.B2]) + "," + str( E[ADDRESS.B3]) + "," a += str(E[ADDRESS.B4]) + "," + str( E[ADDRESS.B5]) + "," + str( E[ADDRESS.B6]) + "," + str( E[ADDRESS.B7]) + "," + str( E[ADDRESS.B8]) + "," a += str(E[ADDRESS.B9]) + "," + str( E[ADDRESS.B10]) + "," + str(E[ ADDRESS.B11]) + ",'" + date_time + "')" test, e, rc = eoss.sqlUpdate(db, a) if test == False: eor_log.info(a + "/" + e) else: if rc == 0: eor_log.info(a + "/" + e) else: eor_log.debug(a) ##check if we need to set/flash LED 3/4/5 every time temp is read (~10 seconds) if E[ADDRESS.INDICATOR] == 3: if setLED(): a = "Update STATION SET STR_VALUE = '" + LED + "' where LABEL = 'LED_STATE'" test, e, rc = eoss.sqlUpdate(db, a) if test == False: eor_log.info(a + "/" + e) else: if rc == 0: eor_log.info(a + "/" + e) else: eor_log.debug(a) ##check if EOS is processing items cur.execute( "Select count(TYPE) C from FEED where IS_DONE = 0" ) row = cur.fetchone() if row is not None: b = int(row["C"]) if b > 1000: if len(Station.User_Key) > 0: eosp.sendpushover( Station.App_Token, Station.User_Key, "EOS Server appears to be down - exiting", 1) eor_log.critical( "Shutting Down - No EOS Server running" ) wiringpi.digitalWrite(LED3, 0) wiringpi.digitalWrite(LED4, 0) wiringpi.digitalWrite(LED5, 0) a = "Update STATION SET STR_VALUE = '00000000' where LABEL = 'LED_STATE'" test, e, rc = eoss.sqlUpdate(db, a) if test == False: eor_log.info(a + "/" + e) else: if rc == 0: eor_log.info(a + "/" + e) else: eor_log.debug(a) has_db = False self.running = False ##check if an update to station is required, will be set by Webman anytime or EOS server at 12:00am Station.Update = eosu.getsetting( db, "DO_UPDATE", 1) if Station.Update > 0: ser.write(chr(13)) ser.flushInput() sleep(1) if Station.Update == 4: # = 4 keep alive signal KeepAlive() eor_log.info( "Keep Alive sent $OK - will continue to read data" ) elif Station.Update == 1: # = 1 normal update if setTime(): if getSettings(): ##Do altitude setAltitude() eor_log.info( "Updating Board Altitude :" + str(Station.Altitude)) # = 2/3 then turn fan off else turn fan on elif Station.Update == 2: a = "Update STATION SET STR_Value = 'Fan Off' where LABEL = 'HAS_FAN'" test, e, rc = eoss.sqlUpdate(db, a) if test == False: eor_log.info(a + "/" + e) else: if rc == 0: eor_log.info(a + "/" + e) else: eor_log.debug(a) setFan(0) fanState = 'Off' eor_log.info("Station fan is OFF") elif Station.Update == 3: a = "Update STATION SET STR_Value = 'Fan On' where LABEL = 'HAS_FAN'" test, e, rc = eoss.sqlUpdate(db, a) if test == False: eor_log.info(a + "/" + e) else: if rc == 0: eor_log.info(a + "/" + e) else: eor_log.debug(a) setFan(1) fanState = 'On' eor_log.info("Station fan is ON") #Clear the flag a = "Update STATION SET INT_VALUE = 0 where LABEL = 'DO_UPDATE'" test, e, rc = eoss.sqlUpdate(db, a) if test == False: eor_log.info(a + "/" + e) else: if rc == 0: eor_log.info(a + "/" + e) else: eor_log.debug(a) ##MMQT if eosu.getsetting( db, "BROKER_ADDRESS", 0) <> "": try: Station.Name = eosu.getsetting( db, "NAME", 0) Station.Broker_Address = eosu.getsetting( db, "BROKER_ADDRESS", 0) Station.Broker_Port = eosu.getsetting( db, "BROKER_PORT", 0) Station.Broker_USN = eosu.getsetting( db, "BROKER_USN", 0) Station.Broker_PWD = eosu.getsetting( db, "BROKER_PWD", 0) auth = { 'username': Station.Broker_USN, 'password': Station.Broker_PWD } publish.single( topic=Station.Name + '/Status/Fan', payload=fanState, qos=0, retain=True, hostname=Station. Broker_Address, port=Station.Broker_Port, client_id='EOS_Station', auth=auth) sleep(5) except: eor_log.error( 'Error sending MQTT Message' ) #restart station ser.write("SE-O 48" + chr(13)) eor_log.info( "Set station for EOS Output - will continue to read data" ) ser.write(chr(13)) Buff = "" ser.flushInput() sleep(1) ser.write("Q") eor_log.debug("Valid checksum :" + str( eosu.calcchecksum(Buff[:ADDRESS.B11])) + "/" + str(E[ADDRESS.B11]) + " in sentence :" + str(E[ADDRESS.INDICATOR])) sleep(1) else: eor_log.error( "Invalid checksum :" + eosu.calcchecksum(Buff[:ADDRESS.B11]) + "/" + E[ADDRESS.B11] + " in :" + Buff) sleep(1) Buff = Buff[18:] else: a = Buff.find("$EOS") if a > 0: Buff = Buff[a:] else: Buff == "" except Exception, e: if len(Station.User_Key) > 0: eosp.sendpushover(Station.App_Token, Station.User_Key, str(e), -1) #shut down if data server is also shutting done. eor_log.error(str(e)) s = str(e) z = s.find('1053') if z > 0: self.running = False eor_log.critical("Shutting Down - No SQL Server")
Station.App_Token, Station.User_Key, "EOR Server NOT Running No Serial Port: " + ser.port, 1) eor_log.critical("EOR Server NOT Running No Serial Port: " + ser.port) except Exception, e: if len(Station.User_Key) > 0: eosp.sendpushover(Station.App_Token, Station.User_Key, "EOR Server NOT Running No DB", 1) has_db = False eor_log.critical("EOR server NOT Running: " + str(e)) if EOS_reader.Up(): try: ## Station : Starting" eorp = WeatherPoller() if len(Station.User_Key) > 0: eosp.sendpushover(Station.App_Token, Station.User_Key, "EOR Server Running", -1) eorp.run() except (KeyboardInterrupt, SystemExit): #when you press ctrl+c print "Killing Thread..." eorp.running = False # wait for the thread to finish what it's doing except Exception, e: print str(e) eorp.running = False print 'Exiting' try: wiringpi.digitalWrite(LED3, 0) wiringpi.digitalWrite(LED4, 0) wiringpi.digitalWrite(LED5, 0) a = "Update STATION SET STR_VALUE = '00000000' where LABEL = 'LED_STATE'"
def main(): global ADDRESS global SQL global Station global C_Station global C_Settings global has_db global has_serial global EOS_String global Buff global cur global db global eor_log global S_Version """Set up logging files """ try: os.remove(LOG_FILENAME) os.remove(LOG_FILENAME + ".1") os.remove(LOG_FILENAME + ".2") os.remove(LOG_FILENAME + ".3") os.remove(LOG_FILENAME + ".4") os.remove(LOG_FILENAME + ".5") os.remove(LOG_FILENAME + ".6") os.remove(LOG_FILENAME + ".7") os.remove(LOG_FILENAME + ".8") os.remove(LOG_FILENAME + ".9") os.remove(LOG_FILENAME + ".10") except: pass LEVELS = {'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL} if len(sys.argv) > 1: level_name = sys.argv[1] level = LEVELS.get(level_name, logging.NOTSET) logging.basicConfig(filename=LOG_FILENAME,level=level) else: level = logging.INFO ##Change this to modify logging details for all messages DEBUG/INFO logging.basicConfig(filename=LOG_FILENAME,level=level) ##Change this to modify logging details for all messages DEBUG/INFO eor_log = logging.getLogger('eorLogger') if level == logging.DEBUG: handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=100000, backupCount=10) else: handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=20000, backupCount=10) formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(lineno)d -> %(message)s") handler.setFormatter(formatter) eor_log.addHandler(handler) eor_log.info("Waiting for MYSQL... to start") sleep(1) #wait a couple of min for services to start in case this is a bootup (65) """Ready to Go """ try: EOS_reader = eos_reader() db = mdb.connect(host= eoss.SQL.server, port = eoss.SQL.port, user= eoss.SQL.user,passwd= eoss.SQL.password, db= eoss.SQL.database) ## Set up a cursor to hold data and execute statments cur = db.cursor(mdb.cursors.DictCursor) if getSettings(): version = eosu.getsetting(db, "EOR_VERSION", 0) if version <> S_Version: a ="Update STATION Set STR_VALUE ='%s' where LABEL = 'EOR_VERSION'" %(S_Version) test, e, rc = eoss.sqlUpdate(db, a) if test == False: eor_log.info(a + "/" + e) else: if rc == 0: eor_log.info(a + "/" + e) else: eor_log.info(a) ##MMQT if Station.Broker_Address <> "": auth = {'username':Station.Broker_USN,'password':Station.Broker_PWD} publish.single(topic= Station.Name + '/Version/Software/EOR',payload=S_Version,qos=0,retain=True, hostname=Station.Broker_Address,port=Station.Broker_Port,client_id='EOS_Station',auth=auth) sleep(5) cur.execute("Delete from FEED") db.commit() eor_log.info("FEED table has been truncated") has_db = True eor_log.info("Database Connected - Starting") else: has_db = False try: ser.port = Station.port ser.baudrate = Station.baudrate ser.bytsize = Station.bytesize ser.parity = Station.parity ser.stopbits = Station.stopbits ser.timeout = Station.timeout ser.xonoff = Station.xonoff ser.rtscts = Station.rtscts #ser.interCharTimeout = STATION.interCharTimeout try: ser.open() #starting the stream of info eor_log.info("Serial Port Found") sleep(1) ser.flushInput() ser.write('?'+ chr(13) + chr(10)) sleep(.2) Buff = ser.readline() print Buff Buff = Buff[:-2] if Buff[:1] <> '0': print 'Station not set up on Device Address 0:' + Buff eor_log.critical("Station not set up as Device Address 0: " + Buff) has_serial = True else: Buff = '' while Buff =='': ser.flushInput() sleep(1) ser.write(C_Station.aXU) sleep(.2) Buff = ser.readline() eor_log.info('Reading serial port for configuration: ' + Buff) if Buff[0:4] == '0XU,': Buff = Buff[4:] Buff = Buff[:-2] buff = Buff items = dict(item.split("=") for item in Buff.split(",")) C_Settings.A = items['A'] #address - 0 C_Settings.M = items['M'] #Communication Protocal - C_Settings.T = items['T'] #Test C_Settings.C = items['C'] #Serial Interface - C_Settings.I = items['I'] #Automatic Interval C_Settings.B = items['B'] #Baud Rate C_Settings.D = items['D'] #Bits C_Settings.P = items['P'] #Parity C_Settings.S = items['S'] #Stop Bits C_Settings.L = items['L'] #Line delay C_Settings.N = items['N'] #Name of device C_Settings.V = items['V'] #Version #Get version C_Settings.V = C_Settings.V[1:-4] Buff = '$EOS' + chr(6) + chr(0) + chr(0) + chr(0) + chr(0) + chr(0) + chr(0) + chr(0) + chr(0) + chr(int(C_Settings.V[:2])) + chr(int(C_Settings.V[3:])) + chr(0) + chr(13) + chr(10) EOS_Send() #test configuration if C_Settings.M == 'P' and C_Settings.C == '2' and C_Settings.B == '019200' and C_Settings.D == '8' and C_Settings.P == 'N' and C_Settings.S == '1': ser.flushInput() sleep(1) #Get wind configuration ser.write(C_Station.aWU) sleep(.2) Buff = ser.readline() eor_log.info('Reading serial port for wind configuration: ' + Buff) Buff = Buff[4:] Buff = Buff[:-2] buff = Buff items = dict(item.split("=") for item in Buff.split(",")) C_Wind.R = items['R'] #Parameter selection C_Wind.I = items['I'] #Update interval C_Wind.A = items['A'] #Average Time C_Wind.G = items['G'] #Min/Max calculation mode C_Wind.U = items['U'] #Speed Units C_Wind.N = items['N'] #NMEA formater C_Wind.D = items['D'] #Direction offsedt C_Wind.F = items['F'] #Sample Rate #Test wind configuration if C_Wind.G == '1' and C_Wind.U == 'K' and C_Wind.N == 'W' and C_Wind.F == '4': ser.flushInput() sleep(1) #Get Temp/Pressure configuration ser.write(C_Station.aTU) sleep(.2) Buff = ser.readline() eor_log.info('Reading serial port for temp configuration: ' + Buff) Buff = Buff[4:] Buff = Buff[:-2] buff = Buff items = dict(item.split("=") for item in Buff.split(",")) C_Temp.R = items['R'] #Parameter selection C_Temp.I = items['I'] #Update Interval C_Temp.P = items['P'] #Pressure Units C_Temp.T = items['T'] #Temperature Units #Test temp/pressure configuration if C_Temp.P == 'H' and C_Temp.T == 'C': ser.flushInput() sleep(1) #Get Rain configuration ser.write(C_Station.aRU) sleep(.2) Buff = ser.readline() eor_log.info('Reading serial port for rain configuration: ' + Buff) Buff = Buff[4:] Buff = Buff[:-2] buff = Buff items = dict(item.split("=") for item in Buff.split(",")) C_Rain.R = items['R'] #Parameter selection C_Rain.I = items['I'] #Update interval C_Rain.U = items['U'] #Persipitation Unots C_Rain.S = items['S'] #Hail Units C_Rain.M = items['M'] #Auto send mode C_Rain.Z = items['Z'] #Counter reste method C_Rain.P = items['P'] #Enabled C_Rain.X = items['X'] #? C_Rain.Y = items['Y'] #? #Test Rain configuration if C_Rain.U =='M' and C_Rain.M == 'T' and C_Rain.Z == 'M' and C_Rain.P == 'Y': ser.flushInput() sleep(1) #Get Solar/Uv configuration ser.write(C_Station.aYU) sleep(.2) Buff = ser.readline() eor_log.info('Reading serial port for solar configuration: ' + Buff) Buff = Buff[4:] Buff = Buff[:-2] buff = Buff items = dict(item.split("=") for item in Buff.split(",")) C_Solar.R = items['R'] #Parameter selection C_Solar.M = items['M'] #Factor if C_Solar.M <> '01045': eor_log.info("FRT Station Solar is out of spec :" + buff) ser.flushInput() sleep(1) ser.write(C_Station.aUV) sleep(.2) Buff = ser.readline() eor_log.info('Reading serial port for Uv configuration: ' + Buff) Buff = Buff[4:] Buff = Buff[:-2] buff = Buff items = dict(item.split("=") for item in Buff.split(",")) C_UV.R = items['R'] #Parameter selection C_UV.M = items['M'] #Factor if C_UV.M <> '00010': eor_log.info("FRT Station UV is out of spec :" + buff) ##everything passed, can proceed eor_log.info("Station ready for FRT Output") has_serial = True else: eor_log.critical("FRT Station rain is misconfigured :" + buff) has_serial = False else: eor_log.critical("FRT Station temp is misconfigured :" + buff) has_serial = False else: eor_log.critical("FRT Station wind is misconfigured :" + buff) has_serial = False else: eor_log.critical("FRT Station is misconfigured :" + buff) has_serial = False else: eor_log.error("Error reading :" + Buff) Buff = '' sleep(1) except: eor_log.critical("Error reading FRT Station") has_serial = False except serial.SerialException: has_serial = False if len(Station.User_Key) > 0: eosp.sendpushover(Station.App_Token, Station.User_Key, "EOR Server NOT Running No Serial Port: " + ser.port, 1) eor_log.critical("EOR Server NOT Running No Serial Port: " + ser.port) except Exception, e: if len(Station.User_Key) > 0: eosp.sendpushover(Station.App_Token, Station.User_Key, "EOR Server NOT Running No DB", 1) has_db = False eor_log.critical("EOR server NOT Running: " + str(e) )