def forceSendState(self): if self._forceSendState: self._forceSendState = False stateChange = StateChange() stateChange.clientSensorId = self.id if self.state == self.triggerState: stateChange.state = 1 else: stateChange.state = 0 stateChange.dataType = self.sensorDataType stateChange.sensorData = self.sensorData return stateChange return None
def forceSendState(self): if (int(time.time()) - self.lastUpdate) > self.interval: self.lastUpdate = int(time.time()) stateChange = StateChange() stateChange.clientSensorId = self.id if self.state == self.triggerState: stateChange.state = 1 else: stateChange.state = 0 stateChange.dataType = self.sensorDataType stateChange.sensorData = self.sensorData return stateChange return None
def execute(self): # time on which the last full sensor states were sent # to the server lastFullStateSent = 0 # Get reference to server communication object. while self.connection is None: time.sleep(0.5) self.connection = self.globalData.serverComm self._isInitialized = True while True: # check if the client is connected to the server # => wait and continue loop until client is connected if not self.connection.isConnected(): time.sleep(0.5) continue # poll all sensors and check their states for sensor in self.sensors: oldState = sensor.getState() sensor.updateState() currentState = sensor.getState() # Check if a sensor alert is forced to send to the server. # => update already known state and continue sensorAlert = sensor.forceSendAlert() if sensorAlert: oldState = currentState asyncSenderProcess = AsynchronousSender( self.connection, self.globalData) # set thread to daemon # => threads terminates when main thread terminates asyncSenderProcess.daemon = True asyncSenderProcess.sendSensorAlert = True asyncSenderProcess.sendSensorAlertSensorAlert = sensorAlert asyncSenderProcess.start() continue # check if the current state is the same # than the already known state => continue elif oldState == currentState: continue # check if the current state is an alert triggering state elif currentState == sensor.triggerState: # check if the sensor triggers a sensor alert # => send sensor alert to server if sensor.triggerAlert: logging.info("[%s]: Sensor alert " % self.fileName + "triggered by '%s'." % sensor.description) # Create sensor alert object to send to the server. sensorAlert = SensorAlert() sensorAlert.clientSensorId = sensor.id sensorAlert.state = 1 sensorAlert.hasOptionalData = sensor.hasOptionalData sensorAlert.optionalData = sensor.optionalData sensorAlert.changeState = sensor.changeState sensorAlert.hasLatestData = sensor.hasLatestData sensorAlert.dataType = sensor.sensorDataType sensorAlert.sensorData = sensor.sensorData asyncSenderProcess = AsynchronousSender( self.connection, self.globalData) # set thread to daemon # => threads terminates when main thread terminates asyncSenderProcess.daemon = True asyncSenderProcess.sendSensorAlert = True asyncSenderProcess.sendSensorAlertSensorAlert = \ sensorAlert asyncSenderProcess.start() # if sensor does not trigger sensor alert # => just send changed state to server else: logging.debug("[%s]: State " % self.fileName + "changed by '%s'." % sensor.description) # Create state change object to send to the server. stateChange = StateChange() stateChange.clientSensorId = sensor.id stateChange.state = 1 stateChange.dataType = sensor.sensorDataType stateChange.sensorData = sensor.sensorData asyncSenderProcess = AsynchronousSender( self.connection, self.globalData) # set thread to daemon # => threads terminates when main thread terminates asyncSenderProcess.daemon = True asyncSenderProcess.sendStateChange = True asyncSenderProcess.sendStateChangeStateChange = \ stateChange asyncSenderProcess.start() # only possible situation left => sensor changed # back from triggering state to a normal state else: # check if the sensor triggers a sensor alert when # state is back to normal # => send sensor alert to server if sensor.triggerAlertNormal: logging.info("[%s]: Sensor alert " % self.fileName + "for back to normal state " + "triggered by '%s'." % sensor.description) # Create sensor alert object to send to the server. sensorAlert = SensorAlert() sensorAlert.clientSensorId = sensor.id sensorAlert.state = 0 sensorAlert.hasOptionalData = sensor.hasOptionalData sensorAlert.optionalData = sensor.optionalData sensorAlert.changeState = sensor.changeState sensorAlert.hasLatestData = sensor.hasLatestData sensorAlert.dataType = sensor.sensorDataType sensorAlert.sensorData = sensor.sensorData asyncSenderProcess = AsynchronousSender( self.connection, self.globalData) # set thread to daemon # => threads terminates when main thread terminates asyncSenderProcess.daemon = True asyncSenderProcess.sendSensorAlert = True asyncSenderProcess.sendSensorAlertSensorAlert = \ sensorAlert asyncSenderProcess.start() # if sensor does not trigger sensor alert when # state is back to normal # => just send changed state to server else: logging.debug("[%s]: State " % self.fileName + "changed by '%s'." % sensor.description) # Create state change object to send to the server. stateChange = StateChange() stateChange.clientSensorId = sensor.id stateChange.state = 0 stateChange.dataType = sensor.sensorDataType stateChange.sensorData = sensor.sensorData asyncSenderProcess = AsynchronousSender( self.connection, self.globalData) # set thread to daemon # => threads terminates when main thread terminates asyncSenderProcess.daemon = True asyncSenderProcess.sendStateChange = True asyncSenderProcess.sendStateChangeStateChange = \ stateChange asyncSenderProcess.start() # Poll all sensors if they want to force an update that should # be send to the server. for sensor in self.sensors: stateChange = sensor.forceSendState() if stateChange: asyncSenderProcess = AsynchronousSender( self.connection, self.globalData) # set thread to daemon # => threads terminates when main thread terminates asyncSenderProcess.daemon = True asyncSenderProcess.sendStateChange = True asyncSenderProcess.sendStateChangeStateChange = stateChange asyncSenderProcess.start() # check if the last state that was sent to the server # is older than 60 seconds => send state update utcTimestamp = int(time.time()) if (utcTimestamp - lastFullStateSent) > 60: logging.debug("[%s]: Last state " % self.fileName + "timed out.") asyncSenderProcess = AsynchronousSender( self.connection, self.globalData) # set thread to daemon # => threads terminates when main thread terminates asyncSenderProcess.daemon = True asyncSenderProcess.sendSensorsState = True asyncSenderProcess.start() # update time on which the full state update was sent lastFullStateSent = utcTimestamp time.sleep(0.5)
def run(self): while True: # check if FIFO file exists # => remove it if it does if os.path.exists(self.fifoFile): try: os.remove(self.fifoFile) except Exception as e: logging.exception( "[%s]: Could not delete " % self.fileName + "FIFO file of sensor with id '%d'." % self.id) time.sleep(10) continue # create a new FIFO file try: os.umask(self.umask) os.mkfifo(self.fifoFile) except Exception as e: logging.exception("[%s]: Could not create " % self.fileName + "FIFO file of sensor with id '%d'." % self.id) time.sleep(10) continue # read FIFO for data data = "" try: fifo = open(self.fifoFile, "r") data = fifo.read() fifo.close() except Exception as e: logging.exception( "[%s]: Could not read data from " % self.fileName + "FIFO file of sensor with id '%d'." % self.id) time.sleep(10) continue logging.debug("[%s]: Received data '%s' from " % (self.fileName, data) + "FIFO file of sensor with id '%d'." % self.id) # parse received data try: message = json.loads(data) # Parse message depending on type. # Type: statechange if str(message["message"]).upper() == "STATECHANGE": # Check if state is valid. tempInputState = message["payload"]["state"] if not self._checkState(tempInputState): logging.error( "[%s]: Received state " % self.fileName + "from FIFO file of sensor with id '%d' " % self.id + "invalid. Ignoring message.") continue # Check if data type is valid. tempDataType = message["payload"]["dataType"] if not self._checkDataType(tempDataType): logging.error( "[%s]: Received data type " % self.fileName + "from FIFO file of sensor with id '%d' " % self.id + "invalid. Ignoring message.") continue # Set new data. if self.sensorDataType == SensorDataType.NONE: self.sensorData = None elif self.sensorDataType == SensorDataType.INT: self.sensorData = int(message["payload"]["data"]) elif self.sensorDataType == SensorDataType.FLOAT: self.sensorData = float(message["payload"]["data"]) # Set state. self.temporaryState = tempInputState # Force state change sending if the data could be changed. if self.sensorDataType != SensorDataType.NONE: # Create state change object that is # send to the server. self.forceSendStateLock.acquire() self.stateChange = StateChange() self.stateChange.clientSensorId = self.id if tempInputState == self.triggerState: self.stateChange.state = 1 else: self.stateChange.state = 0 self.stateChange.dataType = tempDataType self.stateChange.sensorData = self.sensorData self.shouldForceSendState = True self.forceSendStateLock.release() # Type: sensoralert elif str(message["message"]).upper() == "SENSORALERT": # Check if state is valid. tempInputState = message["payload"]["state"] if not self._checkState(tempInputState): logging.error( "[%s]: Received state " % self.fileName + "from FIFO file of sensor with id '%d' " % self.id + "invalid. Ignoring message.") continue # Check if hasOptionalData field is valid. tempHasOptionalData = message["payload"]["hasOptionalData"] if not self._checkHasOptionalData(tempHasOptionalData): logging.error( "[%s]: Received hasOptionalData field " % self.fileName + "from FIFO file of sensor with id '%d' " % self.id + "invalid. Ignoring message.") continue # Check if data type is valid. tempDataType = message["payload"]["dataType"] if not self._checkDataType(tempDataType): logging.error( "[%s]: Received data type " % self.fileName + "from FIFO file of sensor with id '%d' " % self.id + "invalid. Ignoring message.") continue if self.sensorDataType == SensorDataType.NONE: tempSensorData = None elif self.sensorDataType == SensorDataType.INT: tempSensorData = int(message["payload"]["data"]) elif self.sensorDataType == SensorDataType.FLOAT: tempSensorData = float(message["payload"]["data"]) # Check if hasLatestData field is valid. tempHasLatestData = message["payload"]["hasLatestData"] if not self._checkHasLatestData(tempHasLatestData): logging.error( "[%s]: Received hasLatestData field " % self.fileName + "from FIFO file of sensor with id '%d' " % self.id + "invalid. Ignoring message.") continue # Check if changeState field is valid. tempChangeState = message["payload"]["changeState"] if not self._checkChangeState(tempChangeState): logging.error( "[%s]: Received changeState field " % self.fileName + "from FIFO file of sensor with id '%d' " % self.id + "invalid. Ignoring message.") continue # Check if data should be transfered with the sensor alert # => if it should parse it tempOptionalData = None if tempHasOptionalData: tempOptionalData = message["payload"]["optionalData"] # check if data is of type dict if not isinstance(tempOptionalData, dict): logging.warning( "[%s]: Received optional data " % self.fileName + "from FIFO file of sensor with id '%d' " % self.id + "invalid. Ignoring message.") continue # Set optional data. self.hasOptionalData = tempHasOptionalData self.optionalData = tempOptionalData # Set new data. if tempHasLatestData: self.sensorData = tempSensorData # Set state. if tempChangeState: self.temporaryState = tempInputState # Create sensor alert object that is send to the server. self.forceSendAlertLock.acquire() self.sensorAlert = SensorAlert() self.sensorAlert.clientSensorId = self.id if tempInputState == self.triggerState: self.sensorAlert.state = 1 else: self.sensorAlert.state = 0 self.sensorAlert.hasOptionalData = tempHasOptionalData self.sensorAlert.optionalData = tempOptionalData self.sensorAlert.changeState = tempChangeState self.sensorAlert.hasLatestData = tempHasLatestData self.sensorAlert.dataType = tempDataType self.sensorAlert.sensorData = tempSensorData self.shouldForceSendAlert = True self.forceSendAlertLock.release() # Type: invalid else: raise ValueError("Received invalid message type.") except Exception as e: logging.exception("[%s]: Could not parse received data from " % self.fileName + "FIFO file of sensor with id '%d'." % self.id) continue
def execute(self): # time on which the last full sensor states were sent # to the server lastFullStateSent = 0 # Get reference to server communication object. while self.connection is None: time.sleep(0.5) self.connection = self.globalData.serverComm self._isInitialized = True while True: # check if the client is connected to the server # => wait and continue loop until client is connected if not self.connection.isConnected(): time.sleep(0.5) continue # poll all sensors and check their states for sensor in self.sensors: oldState = sensor.getState() sensor.updateState() currentState = sensor.getState() # Check if a sensor alert is forced to send to the server. # => update already known state and continue sensorAlert = sensor.forceSendAlert() if sensorAlert: oldState = currentState asyncSenderProcess = AsynchronousSender( self.connection, self.globalData) # set thread to daemon # => threads terminates when main thread terminates asyncSenderProcess.daemon = True asyncSenderProcess.sendSensorAlert = True asyncSenderProcess.sendSensorAlertSensorAlert = sensorAlert asyncSenderProcess.start() continue # check if the current state is the same # than the already known state => continue elif oldState == currentState: continue # check if the current state is an alert triggering state elif currentState == sensor.triggerState: # check if the sensor triggers a sensor alert # => send sensor alert to server if sensor.triggerAlert: logging.info("[%s]: Sensor alert " % self.fileName + "triggered by '%s'." % sensor.description) # Create sensor alert object to send to the server. sensorAlert = SensorAlert() sensorAlert.clientSensorId = sensor.id sensorAlert.state = 1 sensorAlert.hasOptionalData = sensor.hasOptionalData sensorAlert.optionalData = sensor.optionalData sensorAlert.changeState = sensor.changeState sensorAlert.hasLatestData = sensor.hasLatestData sensorAlert.dataType = sensor.sensorDataType sensorAlert.sensorData = sensor.sensorData asyncSenderProcess = AsynchronousSender( self.connection, self.globalData) # set thread to daemon # => threads terminates when main thread terminates asyncSenderProcess.daemon = True asyncSenderProcess.sendSensorAlert = True asyncSenderProcess.sendSensorAlertSensorAlert = \ sensorAlert asyncSenderProcess.start() # if sensor does not trigger sensor alert # => just send changed state to server else: logging.debug("[%s]: State " % self.fileName + "changed by '%s'." % sensor.description) # Create state change object to send to the server. stateChange = StateChange() stateChange.clientSensorId = sensor.id stateChange.state = 1 stateChange.dataType = sensor.sensorDataType stateChange.sensorData = sensor.sensorData asyncSenderProcess = AsynchronousSender( self.connection, self.globalData) # set thread to daemon # => threads terminates when main thread terminates asyncSenderProcess.daemon = True asyncSenderProcess.sendStateChange = True asyncSenderProcess.sendStateChangeStateChange = \ stateChange asyncSenderProcess.start() # only possible situation left => sensor changed # back from triggering state to a normal state else: # check if the sensor triggers a sensor alert when # state is back to normal # => send sensor alert to server if sensor.triggerAlertNormal: logging.info("[%s]: Sensor alert " % self.fileName + "for back to normal state " + "triggered by '%s'." % sensor.description) # Create sensor alert object to send to the server. sensorAlert = SensorAlert() sensorAlert.clientSensorId = sensor.id sensorAlert.state = 0 sensorAlert.hasOptionalData = sensor.hasOptionalData sensorAlert.optionalData = sensor.optionalData sensorAlert.changeState = sensor.changeState sensorAlert.hasLatestData = sensor.hasLatestData sensorAlert.dataType = sensor.sensorDataType sensorAlert.sensorData = sensor.sensorData asyncSenderProcess = AsynchronousSender( self.connection, self.globalData) # set thread to daemon # => threads terminates when main thread terminates asyncSenderProcess.daemon = True asyncSenderProcess.sendSensorAlert = True asyncSenderProcess.sendSensorAlertSensorAlert = \ sensorAlert asyncSenderProcess.start() # if sensor does not trigger sensor alert when # state is back to normal # => just send changed state to server else: logging.debug("[%s]: State " % self.fileName + "changed by '%s'." % sensor.description) # Create state change object to send to the server. stateChange = StateChange() stateChange.clientSensorId = sensor.id stateChange.state = 0 stateChange.dataType = sensor.sensorDataType stateChange.sensorData = sensor.sensorData asyncSenderProcess = AsynchronousSender( self.connection, self.globalData) # set thread to daemon # => threads terminates when main thread terminates asyncSenderProcess.daemon = True asyncSenderProcess.sendStateChange = True asyncSenderProcess.sendStateChangeStateChange = \ stateChange asyncSenderProcess.start() # Poll all sensors if they want to force an update that should # be send to the server. for sensor in self.sensors: stateChange = sensor.forceSendState() if stateChange: asyncSenderProcess = AsynchronousSender( self.connection, self.globalData) # set thread to daemon # => threads terminates when main thread terminates asyncSenderProcess.daemon = True asyncSenderProcess.sendStateChange = True asyncSenderProcess.sendStateChangeStateChange = stateChange asyncSenderProcess.start() # check if the last state that was sent to the server # is older than 60 seconds => send state update if (time.time() - lastFullStateSent) > 60: logging.debug("[%s]: Last state " % self.fileName + "timed out.") asyncSenderProcess = AsynchronousSender( self.connection, self.globalData) # set thread to daemon # => threads terminates when main thread terminates asyncSenderProcess.daemon = True asyncSenderProcess.sendSensorsState = True asyncSenderProcess.start() # update time on which the full state update was sent lastFullStateSent = time.time() time.sleep(0.5)
def _parseOutput(self, data): # Parse output data try: logging.debug("[%s] Received output from sensor with id '%d': %s" % (self.fileName, self.id, data)) message = json.loads(data) # Parse message depending on type. # Type: statechange if str(message["message"]).upper() == "STATECHANGE": # Check if state is valid. tempInputState = message["payload"]["state"] if not self._checkState(tempInputState): logging.error("[%s]: Received state " % self.fileName + "from output of sensor with id '%d' " % self.id + "invalid. Ignoring output.") return False # Check if data type is valid. tempDataType = message["payload"]["dataType"] if not self._checkDataType(tempDataType): logging.error("[%s]: Received data type " % self.fileName + "from output of sensor with id '%d' " % self.id + "invalid. Ignoring output.") return False # Set new data. if self.sensorDataType == SensorDataType.NONE: self.sensorData = None elif self.sensorDataType == SensorDataType.INT: self.sensorData = int(message["payload"]["data"]) elif self.sensorDataType == SensorDataType.FLOAT: self.sensorData = float(message["payload"]["data"]) # Force state change sending if the data could be changed # or the state has changed. if (self.sensorDataType != SensorDataType.NONE or self.state != tempInputState): # Create state change object that is # send to the server. self.stateChange = StateChange() self.stateChange.clientSensorId = self.id if tempInputState == self.triggerState: self.stateChange.state = 1 else: self.stateChange.state = 0 self.stateChange.dataType = tempDataType self.stateChange.sensorData = self.sensorData self.shouldForceSendState = True # Set state. self.state = tempInputState # Type: sensoralert elif str(message["message"]).upper() == "SENSORALERT": # Check if state is valid. tempInputState = message["payload"]["state"] if not self._checkState(tempInputState): logging.error("[%s]: Received state " % self.fileName + "from output of sensor with id '%d' " % self.id + "invalid. Ignoring output.") return False # Check if hasOptionalData field is valid. tempHasOptionalData = message["payload"]["hasOptionalData"] if not self._checkHasOptionalData(tempHasOptionalData): logging.error("[%s]: Received hasOptionalData field " % self.fileName + "from output of sensor with id '%d' " % self.id + "invalid. Ignoring output.") return False # Check if data type is valid. tempDataType = message["payload"]["dataType"] if not self._checkDataType(tempDataType): logging.error("[%s]: Received data type " % self.fileName + "from output of sensor with id '%d' " % self.id + "invalid. Ignoring output.") return False if self.sensorDataType == SensorDataType.NONE: tempSensorData = None elif self.sensorDataType == SensorDataType.INT: tempSensorData = int(message["payload"]["data"]) elif self.sensorDataType == SensorDataType.FLOAT: tempSensorData = float(message["payload"]["data"]) # Check if hasLatestData field is valid. tempHasLatestData = message["payload"]["hasLatestData"] if not self._checkHasLatestData(tempHasLatestData): logging.error( "[%s]: Received hasLatestData field " % self.fileName + "from output of sensor with id '%d' " % self.id + "invalid. Ignoring output.") return False # Check if changeState field is valid. tempChangeState = message["payload"]["changeState"] if not self._checkChangeState(tempChangeState): logging.error( "[%s]: Received changeState field " % self.fileName + "from output of sensor with id '%d' " % self.id + "invalid. Ignoring output.") return False # Check if data should be transfered with the sensor alert # => if it should parse it tempOptionalData = None if tempHasOptionalData: tempOptionalData = message["payload"]["optionalData"] # check if data is of type dict if not isinstance(tempOptionalData, dict): logging.warning( "[%s]: Received optional data " % self.fileName + "from output of sensor with id '%d' " % self.id + "invalid. Ignoring output.") return False # Set optional data. self.hasOptionalData = tempHasOptionalData self.optionalData = tempOptionalData # Set new data. if tempHasLatestData: self.sensorData = tempSensorData # Set state. if tempChangeState: self.state = tempInputState # Create sensor alert object that is send to the server. self.sensorAlert = SensorAlert() self.sensorAlert.clientSensorId = self.id if tempInputState == self.triggerState: self.sensorAlert.state = 1 else: self.sensorAlert.state = 0 self.sensorAlert.hasOptionalData = tempHasOptionalData self.sensorAlert.optionalData = tempOptionalData self.sensorAlert.changeState = tempChangeState self.sensorAlert.hasLatestData = tempHasLatestData self.sensorAlert.dataType = tempDataType self.sensorAlert.sensorData = tempSensorData self.shouldForceSendAlert = True # Type: invalid else: raise ValueError("Received invalid message type.") except Exception as e: logging.exception("[%s]: Could not parse received data from " % self.fileName + "output of sensor with id '%d'." % self.id) return False return True