Beispiel #1
0
    def run(self):
        print('starting kipp zonen data gathering')
        while True:
            try:
                self.running = True
                g_DATA = currentValues()
                self.serialConnection = serial.Serial(
                    self.SERIAL_PORT, self.SERIAL_BAUD,
                    timeout=30)  #, timeout=30
                curLine = self.serialConnection.readline()
                curLineStr = str(curLine, 'utf-8')

                if "W:" in curLineStr:
                    curValues = curLineStr.split()
                    if len(curValues) == 16:
                        LOG_KIPP.info(curLineStr)
                        g_DATA.updateKippZonenData(curValues[2], curValues[3],
                                                   curValues[4])
                        #g_DATA.STATUS_KIPP = "OK"
                        ActivityData().KIPPActive()

            except Exception as e:
                g_DATA = currentValues()
                LOG_KIPP.error(
                    "error acquiring pyranometer values. Service will be restarted"
                    .format(self.restartCounter))
                g_DATA.STATUS_KIPP = "error acquiring pyranometer values. Service will be restarted".format(
                    self.restartCounter)
                self.running = False
                print(e)
                if self.restartCounter < 10:
                    time.sleep(60)
                    self.restartCounter = self.restartCounter + 1
                else:
                    LOG_KIPP.error(
                        "error in serial port data listening... tried restarting 10x...shutting it down. \n {}"
                        .format(e))
                    EmailError().emailMe(
                        "error in serial port data listening... tried restarting 10x...shutting it down. \n {}"
                        .format(e))
                    raise Exception(e)
Beispiel #2
0
class StartInfo:
    g_SETTINGS = ProjectSettings()
    g_DATA = currentValues()

    def __init__(self, *args, **kwargs):
        pass

    def SendInfo(self):
        try:
            print("sending start info")
            info = {
                'time': datetime.now().strftime("%m/%d/%Y, %H:%M:%S"),
                'status': "STARTING NEW SESSION.",
                'ID': self.g_DATA.ID
            }
            print("sending start info {} ".format(info))
            r = requests.post(self.g_SETTINGS.ServerIP + '/MBPC/b',
                              timeout=10,
                              json=info)
            response = r.json()
            print(info)
            print(response)
        except Exception as e:
            print(e)
Beispiel #3
0
    if hours > 23 and minutes > 50 or hours > 24:
        LOG_MAIN.info("SCHEDUELED RESTART HAPPENING")
        EmailError().emailMe(
            "Scheudled shutting down. Duration: {}".format(activeTime))
        return
    LOG_MAIN.error("script exiting... for reasons unknown")
    EmailError().emailMe(
        "script exiting... for reasons unknown - duration: {}".format(
            activeTime))


import atexit
atexit.register(goodbye)

if __name__ == "__main__":
    print(os.getpid(), file=open("/home/pi/cron/PID_KNXTNO.pid", "w"))
    try:
        settings = ProjectSettings()
        settings.GAD_TABLE = GAD_MAP_TABLE_OUTSIDE
        settings.ServerIP = "http://90.145.162.7:8109"  #"http://90.145.162.7:8109"
        g_DATA = currentValues()
        g_DATA.GAD_TABLE = GAD_MAP_TABLE_OUTSIDE
        startLogging()

        main()

    except Exception as e:
        emailNotice = EmailError()
        emailNotice.emailMe(e)
        quit()
Beispiel #4
0
class ConnectToServer(threading.Thread):
    g_SETTINGS = ProjectSettings()
    g_DATA = currentValues()

    def __init__(self, *args, **kwargs):
        threading.Thread.__init__(self)
        self.setDaemon(False)
        print('INFO: connecting to server...')

    def run(self):
        runStartedTime = datetime.now().strftime("%m_%d-%H_%M_%S")
        runCounter = 0
        firstRun = True
        locaJSONData = dict()
        waitTime = 300
        print("starting while loop...")
        while True:
            LOG_MAIN.info("MAIN CLIENT-SERVER LOOP RUNNING")
            runCounter = runCounter + 1
            print("connecting to server for the {}x time\run started on:{}".
                  format(runCounter, runStartedTime))
            try:
                KNX().refreshKNXData()
                ActivityData().refreshData()

                print("while loop... get updated values...")
                print(self.g_DATA)
                localJSONData = self.g_DATA.getUpdatedValues()
                print("LocalJsonData:",
                      json.dumps(localJSONData, sort_keys=True, indent=4))

                time.sleep(5)

                #                continue
                #                if runCounter==1:#we do this to prevent 800 values at the start
                #                    time.sleep(waitTime)
                #                    continue

                server_BlindsData = self.getServerData(localJSONData)
                print("ServerJsonData:",
                      json.dumps(server_BlindsData, sort_keys=True, indent=4))

                if "error" in server_BlindsData or "error" in localJSONData:
                    time.sleep(waitTime)
                    continue

                time.sleep(5)

                print('comparing and moving blinds...')
                self.compareAndupdatePhysicalBlindsPosition(
                    server_BlindsData, localJSONData)
                ActivityData().ServerActive()
                time.sleep(5)

                print("waiting 300 seconds to send new data to server...")
                time.sleep(waitTime)

            except Exception as e:
                exc_type, exc_value, exc_tb = sys.exc_info()
                tb = traceback.format_exception(exc_type, exc_value, exc_tb)
                LOG_MAIN.error(tb)
                print(
                    "error ... waiting 300 seconds to try send new data to server...\n{}"
                    .format(e))
                #emailNotice = EmailError()
                #emailNotice.emailMe(e)
                #time.sleep(waitTime)
                raise e

    def getServerData(self, current_blinds_values):
        error = False
        errorList = list()
        try:
            r = requests.post(self.g_SETTINGS.ServerIP + '/MBPC/b',
                              timeout=50,
                              json=current_blinds_values)
            server_blinds_values = r.json()
            LOG_SENT_RECIEVED.info(current_blinds_values)
            LOG_SENT_RECIEVED.info(server_blinds_values)

            if 'error' in server_blinds_values['status']:
                return server_blinds_values
            else:
                return server_blinds_values
        except Exception as e:
            error = EmailError()
            error.emailMe(e)
            print("error getting server data")
            return "error"

    def compareAndupdatePhysicalBlindsPosition(self, server_blinds_values,
                                               current_JSON):
        from LKNX.LKNX_ReadWriteValue import KNXWriter
        current_blinds_values = current_JSON['get_controls']

        if server_blinds_values['status'] == 'ok':
            preferred_blind = server_blinds_values['preferred_blind']

            #WRITE TO PREFERED GROUP
            for group_name in server_blinds_values:
                if any(val in group_name
                       for val in ['status', 'time', 'preferred_blind']):
                    continue

                if str(preferred_blind) in group_name:
                    curBlindPos = current_blinds_values[group_name]
                    requestedBlindPos = server_blinds_values[group_name]

                    #move prefered blind if change is beyond "threshold" (no point moving it 1%)
                    if abs(curBlindPos - requestedBlindPos) > 3:
                        print(
                            "move blind...curBlindPos = {} requestedBlindPos = {}"
                            .format(curBlindPos, requestedBlindPos))
                        print("move blind...moving group: {} value: {}".format(
                            group_name, requestedBlindPos))
                        KNXWriter(name=group_name, value=requestedBlindPos)
                        print('move blind...WRITE COMPLETE')
                        #TODO CREATE DERIVED THREADED CLASS FROM KNXWRITER THAT PERFORMS CHECK AFTER 2 MINUTES
                else:
                    #move non preffered blind to default position
                    print('move non preffered blind to default position...')
                    KNXWriter(name=group_name, value=0)

            #DISABLED. Store previous data for any future comparison
            #self.old_blinds_values = server_blinds_values

        else:
            error = EmailError()
            error.emailMe("move blind...error with parsing blinds values")
            print('move blind...server status not OK')
            time.sleep(25)
            pass
Beispiel #5
0
class ActivityData(metaclass=Singleton):
    StartTime=datetime.now()     
    KIPPTime=datetime.now() 
    VBUSTime=datetime.now() 
    KNXTime=datetime.now() 
    KNXSensorsTime=datetime.now()     
    KNXBlindsTime=datetime.now()     
        
    ServerTime=datetime.now() 
    threshold=350
    g_DATA= currentValues()
    
    def __init__(self, *args, **kwargs):
        for key in kwargs:
            setattr(self, key, kwargs[key])
        return super().__init__(*args, **kwargs) 
    
    def refreshData(self):
        self.runTime=str(timedelta(seconds=(datetime.now()   -self.StartTime).total_seconds() ))
        self.deltaVBUS=(datetime.now()   -self.VBUSTime).total_seconds()
        self.deltaKNX =(datetime.now()   -self.KNXTime).total_seconds()
        self.deltaKNXSensors =(datetime.now()   -self.KNXSensorsTime).total_seconds()       
        self.deltaBlinds  =(datetime.now()   -self.KNXBlindsTime).total_seconds()   
        
        self.deltaKIPP=(datetime.now()   -self.KIPPTime).total_seconds()
        self.deltaServer=(datetime.now()   -self.ServerTime).total_seconds() 
        
        print ("runTime {}".format(self.runTime))
        print ("deltaVBUS {}".format(self.deltaVBUS))
        print ("deltaKNXSensors {}".format(self.deltaKNXSensors))  
        print ("deltaKNXBlinds {}".format(self.deltaBlinds))          
        print ("deltaKIPP {}".format(self.deltaKIPP))    
        print ("deltaServer {}".format(self.deltaServer)) 
        
        self.g_DATA.STATUS_KIPP = str("Kipp zonen sensors updated {}s ago".format(self.deltaKIPP))
        self.g_DATA.STATUS_SENSORS_KNX = str("KNX sensors updated {}s ago".format(max(self.deltaKNXSensors,self.deltaVBUS)))
        self.g_DATA.STATUS_BLINDS = str("KNX blind positions updated {}s ago".format(self.deltaBlinds))
        self.g_DATA.STATUS_SERVER = str("Last server data:{}s ago".format(self.deltaServer))
        self.g_DATA.STATUS = str("OK")
        LOG_ACTIVITY.info  ("runTime {}".format(self.runTime))
                
    def check(self):
        timeNow=datetime.now().strftime("%H:%M:%S")
        self.refreshData()
        print("{} - ...activity check running...".format(timeNow), file=open("/home/pi/cron/LOG_KNXTNO.log", "a"))
        if self.deltaKIPP >self.threshold or \
            self.deltaVBUS>self.threshold or \
            self.deltaKNX>self.threshold or \
            self.deltaServer> self.threshold:
            LOG_ACTIVITY.error("{} - hasta la vista... baby...\n\n".format(timeNow), file=open("/home/pi/cron/LOG_KNXTNO.log", "a"))
            sys.exit()   
            
    def KIPPActive(self):
        self.KIPPTime=datetime.now()            
    def VBUSActive(self):
        self.VBUSTime=datetime.now()   
    def KNXSensorsActive(self):
        self.KNXSensorsTime=datetime.now()  
    def KNXBlindsActive(self):
        self.KNXBlindsTime=datetime.now()  
        
    def KNXActive(self):
        self.KNXTime=datetime.now()         
    def ServerActive (self):
        self.ServerTime=datetime.now()