class SocketServer(object): port = 63342 host = socket.gethostbyname(socket.gethostname()) _socketHandler = EventHook() _isSocketUp = False def __del__(self): if self._isSocketUp: self.SocketClosing() def SocketClosing(self): self.s.close() self._isSocketUp = False self.backgroundThread.join() def Setup(self): self.s = socket.socket() self.s.bind((self.host, self.port)) self.s.listen(5) self._isSocketUp = True self.backgroundThread = threading.Thread(target=self.Run, args=()) self.backgroundThread.daemon = True self.backgroundThread.start() def Run(self): while (self._isSocketUp): conn, _ = self.s.accept() data = conn.recv(1024) data = data.decode() self._socketHandler.fire(data=data)
class TemperatureSensor(object): characteristicsPath = "Characteristics/TemperatureSensor.json" _inputVoltage = 0 _coreCurrent = 0 _batteryEvent = EventHook() def __init__(self, inputVoltage): self.jsonHandler = JsonHandler() self.SensorChar = self.jsonHandler.LoadJson(self.characteristicsPath) self.sensingRange = self.SensorChar['SensingRange'] self._inputVoltage = inputVoltage self.TurnOn() def __del__(self): self.TurnOff() def TurnOn(self): self._timer = Timer(30, self.TimerHit) self._timer.start() self.ToActiveMode() def TurnOff(self): self._timer.cancel() def ToActiveMode(self): self._coreCurrent = self.SensorChar['Current']['AciveMode'] def ToShutdownMode(self): self._coreCurrent = self.SensorChar['Current']['ShutdownMode'] def I2CRead(self): self.I2CPowerConsumed() return random.randint(self.sensingRange['Min'], self.sensingRange['Max']) def I2CWrite(self): self.I2CPowerConsumed() def I2CPowerConsumed(self): time = (self.SensorChar['BitSize'] / self.SensorChar['BitRate'] ) / 3600.0 # bitrate is in seconds, convert it to hours power = time * self._inputVoltage * self._coreCurrent self._batteryEvent.fire(powerDischarged=power, reason='TS') def TimerHit(self): time = 30 / 3600 power = time * self._inputVoltage * self._coreCurrent self._batteryEvent.fire(powerDischarged=power, reason='ts Timer') self._timer = Timer(30, self.TimerHit) self._timer.start()
class MicroController(object): characteristicsPath = "Characteristics/MicroController.json" _batteryEvent = EventHook() def __init__(self, inputVoltage): self.jsonHandler = JsonHandler() self.ControllerChar = self.jsonHandler.LoadJson( self.characteristicsPath) self._inputVoltage = inputVoltage self.TurnOn() def __del__(self): self.TurnOff() def TurnOn(self): self._timer = Timer(30, self.TimerHit) self._timer.start() self.ToActiveMode() def TurnOff(self): self._timer.cancel() def ToActiveMode(self): self._coreCurrent = self.ControllerChar['Current']['Mode']['Run'] def ToIdleMode(self): self._coreCurrent = self.ControllerChar['Current']['Mode']['Idle'] def ToSleepMode(self): self._coreCurrent = self.ControllerChar['Current']['Mode']['Sleep'] def I2CRead(self): self.I2CPowerConsumed() def I2CWrite(self): self.I2CPowerConsumed() def I2CPowerConsumed(self): time = (self.ControllerChar['BitSize'] / self.ControllerChar['BitRate'] ) / 3600.0 # bitrate is in seconds, convert it to hours power = time * float(self._inputVoltage) * float(self._coreCurrent) self._batteryEvent.fire(powerDischarged=power, reason='MC') def TimerHit(self): time = 30 / 3600 power = time * self._inputVoltage * self._coreCurrent self._batteryEvent.fire(powerDischarged=power, reason='MC timer') self._timer = Timer(30, self.TimerHit) self._timer.start()
class Sensor(object): _inputVoltage = 0 _coreCurrent = 0 _batteryEvent = EventHook() def __init__(self, sensorName, inputVoltage, timerVal): self._sensorName = sensorName self._timerVal = timerVal self.jsonHandler = JsonHandler() self.SensorChar = self.jsonHandler.LoadJson("Characteristics/" + sensorName + ".json") self._inputVoltage = inputVoltage self.TurnOn() def __del__(self): self.TurnOff() def TurnOn(self): self.StartTimer() self.ToActiveMode() def TurnOff(self): self._timer.cancel() def ToActiveMode(self): self._coreCurrent = self.SensorChar['Current']['AciveMode'] def I2CWrite(self): self.I2CPowerConsumed() def I2CPowerConsumed(self, isRead=True): _type = 'Read' if isRead else 'Write' time = (self.SensorChar['BitSize'] / self.SensorChar['BitRate'] ) / 3600.0 # bitrate is in seconds, convert it to hours power = time * self._inputVoltage * self._coreCurrent self._batteryEvent.fire(powerDischarged=power, reason=(self._sensorName + ' I2C')) def TimerHit(self): time = self._timerVal / 3600 power = time * self._inputVoltage * self._coreCurrent self._batteryEvent.fire(powerDischarged=power, reason=(self._sensorName + " Timer")) self.StartTimer() def StartTimer(self): self._timer = Timer(self._timerVal, self.TimerHit) self._timer.start()
class Bluetooth(object): characteristicsPath = "Characteristics/Bluetooth.json" _inputVoltage = 0 _coreCurrent = 0 _batteryEvent = EventHook() def __init__(self, inputVoltage): self.jsonHandler = JsonHandler() self.BleChar = self.jsonHandler.LoadJson(self.characteristicsPath) self._inputVoltage = inputVoltage self.TurnOn() def __del__(self): self.TurnOff() def ToIdleMode(self): self._coreCurrent = self.BleChar['Current']['CoreIdle'] def ToActiveMode(self): self._coreCurrent = self.BleChar['Current']['CoreActive'] def TurnOff(self): self._timer.cancel() def TurnOn(self): #power drop for pairing s = br * d self._timer = Timer(30, self.TimerHit) self._timer.start() self.ToActiveMode() def PowerConsumed(self, data, isTX=True): type_ = 'TX' if isTX else 'RX' dataSize = getsizeof(data) * 8 time = (dataSize / self.BleChar['BitRate'] ) / 3600.0 # bitrate is in seconds, convert it to hours power = time * self._inputVoltage * self.BleChar['Current'][type_] self._batteryEvent.fire(powerDischarged=power, reason='Bluetooth') def TimerHit(self): time = 30 / 3600 power = time * self._inputVoltage * self._coreCurrent self._batteryEvent.fire(powerDischarged=power, reason='ble timer') self._timer = Timer(30, self.TimerHit) self._timer.start() def Tx(self, data): self.PowerConsumed(data) print("Tx --->>> " + str(data))
class TemperatureSensor(Sensor): _interupt = EventHook() def __init__(self, inputVoltage): super().__init__("TemperatureSensor", 3.0, 30) self.sensingRange = self.SensorChar['SensingRange'] def __del__(self): super().__del__() self._rTimer.cancel() def ToShutdownMode(self): self._coreCurrent = self.SensorChar['Current']['ShutdownMode'] def SetRegister(self): print("SR") self.ToShutdownMode() self._rTimer = Timer(5, self.RHit) self._rTimer.start() def RHit(self): val = random.randint(34, 40) if not (val >= 36 and val <= 38): self._temperature = val self._interupt.fire() time = 0.5 / 3600 power = time * self._inputVoltage * self.SensorChar['Current'][ 'AciveMode'] self._batteryEvent.fire(powerDischarged=power, reason=(self._sensorName + " Timer")) self._rTimer = Timer(5, self.RHit) self._rTimer.start() def RI2CRead(self): self.I2CPowerConsumed() return int(self._temperature) def I2CRead(self): self.I2CPowerConsumed() return random.randint(self.sensingRange['Min'], self.sensingRange['Max'])
class Bluetooth(object): characteristicsPath = "Characteristics/Bluetooth.json" _inputVoltage = 0 _coreCurrent = 0 _batteryEvent = EventHook() _uartEvent = EventHook() _socketClient = SocketClient() _socketServer = SocketServer() def __init__(self, inputVoltage, timerVal): self._timerVal = timerVal self.jsonHandler = JsonHandler() self.BleChar = self.jsonHandler.LoadJson(self.characteristicsPath) self._inputVoltage = inputVoltage self.TurnOn() self.ConnectHandlers() def __del__(self): self.TurnOff() def ConnectHandlers(self): self._socketServer._socketHandler.addHandler(self.Rx) def ToIdleMode(self): self._coreCurrent = self.BleChar['Current']['CoreIdle'] if self._socketServer._isSocketUp: self._socketServer.SocketClosing() def ToActiveMode(self): self._coreCurrent = self.BleChar['Current']['CoreActive'] if self._socketServer._isSocketUp: self._socketServer.SocketClosing() def ToRxMode(self): self._coreCurrent = self.BleChar['Current']['RX'] self._socketServer.Setup() def TurnOff(self): self._timer.cancel() def TurnOn(self): self.StartTimer() self.ToActiveMode() def PowerConsumedUART(self, data): dataSize = getsizeof(data) * 8 time = (dataSize / self.BleChar['BitRate']['UART'] ) / 3600.0 # bitrate is in seconds, convert it to hours power = time * self._inputVoltage * self.BleChar['Current']['UART'] self._batteryEvent.fire(powerDischarged=power, reason=('Bluetooth UART')) def PowerConsumed(self, data, isTX=True): type_ = 'TX' if isTX else 'RX' dataSize = getsizeof(data) * 8 time = (dataSize / self.BleChar['BitRate']['BLE'] ) / 3600.0 # bitrate is in seconds, convert it to hours power = time * self._inputVoltage * self.BleChar['Current'][type_] self._batteryEvent.fire(powerDischarged=power, reason=('Bluetooth ' + type_)) def TimerHit(self): time = 30 / 3600 power = time * self._inputVoltage * self._coreCurrent self._batteryEvent.fire(powerDischarged=power, reason='Bluetooth Timer') self.StartTimer() def StartTimer(self): self._timer = Timer(self._timerVal, self.TimerHit) self._timer.start() def Tx(self, data): self.PowerConsumedUART(data) time.sleep(0.25) self.PowerConsumed(data) #encode it print("Tx --->>> " + str(data)) try: self._socketClient.Transmit(str(data)) except Exception as exp: print("failed due to " + str(exp)) def Rx(self, **kwargs): data = kwargs.get('data') self.PowerConsumed(data, False) self.PowerConsumedUART(data) self._uartEvent.fire(data=data)
class EdgeController(object): characteristicsPath = "Characteristics/EdgeController.json" _batteryEvent = EventHook() def __init__(self, inputVoltage): self.jsonHandler = JsonHandler() self.ControllerChar = self.jsonHandler.LoadJson( self.characteristicsPath) self._inputVoltage = inputVoltage self.TurnOn() def __del__(self): self.TurnOff() def TurnOn(self): self._timer = Timer(30, self.TimerHit) self._timer.start() self.ToActiveMode() def TurnOff(self): self._timer.cancel() def ToActiveMode(self): self._coreCurrent = self.ControllerChar['Current']['Mode']['Active'] def ToShutDownMode(self): self._coreCurrent = self.ControllerChar['Current']['Mode']['ShutDown'] def ToLightSleepMode(self): self._coreCurrent = self.ControllerChar['Current']['Mode'][ 'LightSleep'] def ToDeepSleepMode(self): self._coreCurrent = self.ControllerChar['Current']['Mode']['DeepSleep'] def UartTx(self, data): self.UartPowerConsumed(data) def UartRx(self, data): self.UartPowerConsumed(data) def UartPowerConsumed(self, data): bitSize = getsizeof(data) * 8 time = (bitSize / self.ControllerChar['BitRate']['UART'] ) / 3600.0 # bitrate is in seconds, convert it to hours power = time * float(self._inputVoltage) * float(self._coreCurrent) self._batteryEvent.fire(powerDischarged=power, reason='MC UART') def WifiTx(self, data): self.WifiPowerConsumed(data) print('Wifi TX----->>> ', data) def WifiPowerConsumed(self, data, isTx=True, isVersionB=True): version = 'b' if isVersionB else 'g' _type = 'TX' if isTx else 'RX' bitSize = getsizeof(data) * 8 time = (bitSize / self.ControllerChar['BitRate'][_type][version] ) / 3600.0 # bitrate is in seconds, convert it to hours power = time * float(self._inputVoltage ) * self.ControllerChar['Current'][_type][version] self._batteryEvent.fire(powerDischarged=power, reason='Edge Controller ' + _type + ' ' + version) def TimerHit(self): time = 30 / 3600 power = time * self._inputVoltage * self._coreCurrent self._batteryEvent.fire(powerDischarged=power, reason='MC Timer') self._timer = Timer(30, self.TimerHit) self._timer.start()
class MicroController(object): characteristicsPath = "Characteristics/MicroController.json" _batteryEvent = EventHook() def __init__(self, inputVoltage, sensorID): self.jsonHandler = JsonHandler() self.ControllerChar = self.jsonHandler.LoadJson( self.characteristicsPath) keys = self.jsonHandler.LoadJson("Characteristics/PrivateKey.json") self._privateKey = keys[sensorID] self._inputVoltage = inputVoltage self.TurnOn() def __del__(self): self.TurnOff() def TurnOn(self): self._timer = Timer(30, self.TimerHit) self._timer.start() self.ToActiveMode() def TurnOff(self): self._timer.cancel() def ToActiveMode(self): self._coreCurrent = self.ControllerChar['Current']['Mode']['Run'] def ToIdleMode(self): self._coreCurrent = self.ControllerChar['Current']['Mode']['Idle'] def ToSleepMode(self): self._coreCurrent = self.ControllerChar['Current']['Mode']['Sleep'] def I2CRead(self): self.I2CPowerConsumed() def I2CWrite(self): self.I2CPowerConsumed() def I2CPowerConsumed(self): time = (self.ControllerChar['BitSize'] / self.ControllerChar['BitRate']['I2C'] ) / 3600.0 # bitrate is in seconds, convert it to hours power = time * float(self._inputVoltage) * float(self._coreCurrent) self._batteryEvent.fire(powerDischarged=power, reason='MC I2C') def UartPowerConsumed(self, data): bitSize = getsizeof(data) / 8 time = (bitSize / self.ControllerChar['BitRate']['UART'] ) / 3600.0 # bitrate is in seconds, convert it to hours power = time * float(self._inputVoltage) * float(self._coreCurrent) self._batteryEvent.fire(powerDischarged=power, reason='MC I2C') def TimerHit(self): time = 30 / 3600 power = time * self._inputVoltage * self._coreCurrent self._batteryEvent.fire(powerDischarged=power, reason='MC Timer') self._timer = Timer(30, self.TimerHit) self._timer.start() def Encrypt(self, data): key = self._privateKey ShiftKey = key % 10 data = data ^ key if len(str(ShiftKey)) == 1: data = data << ShiftKey return data def Dcrypt(self, data, key): ShiftKey = key % 10 if len(str(ShiftKey)) == 1: data = data >> ShiftKey data = data ^ key return data
class EdgeController(object): characteristicsPath = "Characteristics/EdgeController.json" _batteryEvent = EventHook() def __init__(self, inputVoltage, sensorID): self.jsonHandler = JsonHandler() self.ControllerChar = self.jsonHandler.LoadJson( self.characteristicsPath) keys = self.jsonHandler.LoadJson("Characteristics/PrivateKey.json") self._privateKey = keys[sensorID] self._inputVoltage = inputVoltage self.TurnOn() def __del__(self): self.TurnOff() def TurnOn(self): self._timer = Timer(30, self.TimerHit) self._timer.start() self.ToActiveMode() def TurnOff(self): self._timer.cancel() def ToActiveMode(self): self._coreCurrent = self.ControllerChar['Current']['Mode']['Active'] def ToShutDownMode(self): self._coreCurrent = self.ControllerChar['Current']['Mode']['ShutDown'] def ToLightSleepMode(self): self._coreCurrent = self.ControllerChar['Current']['Mode'][ 'LightSleep'] def ToDeepSleepMode(self): self._coreCurrent = self.ControllerChar['Current']['Mode']['DeepSleep'] def UartTx(self, data): self.UartPowerConsumed(data) def UartRx(self, data): self.UartPowerConsumed(data) def UartPowerConsumed(self, data): bitSize = getsizeof(data) / 8 time = (bitSize / self.ControllerChar['BitRate']['UART'] ) / 3600.0 # bitrate is in seconds, convert it to hours power = time * float(self._inputVoltage) * float(self._coreCurrent) self._batteryEvent.fire(powerDischarged=power, reason='MC UART') def WifiTx(self, data): self.WifiPowerConsumed(data) print('Wifi TX----->>> ', data) def WifiPowerConsumed(self, data, isTx=True, isVersionB=True): version = 'b' if isVersionB else 'g' _type = 'TX' if isTx else 'RX' bitSize = getsizeof(data) / 8 time = (bitSize / self.ControllerChar['BitRate'][_type][version] ) / 3600.0 # bitrate is in seconds, convert it to hours power = time * float(self._inputVoltage ) * self.ControllerChar['Current'][_type][version] self._batteryEvent.fire(powerDischarged=power, reason='Edge Controller ' + _type + ' ' + version) def I2CRead(self): self.I2CPowerConsumed() def I2CWrite(self): self.I2CPowerConsumed() def I2CPowerConsumed(self): time = (self.ControllerChar['BitSize'] / self.ControllerChar['BitRate']['I2C'] ) / 3600.0 # bitrate is in seconds, convert it to hours power = time * float(self._inputVoltage) * float(self._coreCurrent) self._batteryEvent.fire(powerDischarged=power, reason='MC I2C') def TimerHit(self): time = 30 / 3600 power = time * self._inputVoltage * self._coreCurrent self._batteryEvent.fire(powerDischarged=power, reason='Edge Controller Timer') self._timer = Timer(30, self.TimerHit) self._timer.start() def Encrypt(self, data): key = self._privateKey ShiftKey = key % 10 data = data ^ key if len(str(ShiftKey)) == 1: data = data << ShiftKey return data def Dcrypt(self, data): key = self._privateKey ShiftKey = key % 10 if len(str(ShiftKey)) == 1: data = data >> ShiftKey data = data ^ key return data
class Bluetooth(object): characteristicsPath = "Characteristics/Bluetooth.json" _inputVoltage = 0 _coreCurrent = 0 _batteryEvent = EventHook() _uartEvent = EventHook() _socketClient = SocketClient() _isSingleHop = True _currentPort = 63342 Memory = [] def __init__(self, inputVoltage, timerVal, isSingleHop=True, txPorts=[], serverPort=63342): self._timerVal = timerVal self.jsonHandler = JsonHandler() self.BleChar = self.jsonHandler.LoadJson(self.characteristicsPath) self.serverPort = serverPort self._socketServer = SocketServer(serverPort) self._inputVoltage = inputVoltage self._txPorts = txPorts if len(self._txPorts) > 0: dict_ = self._txPorts[0] _, port = list(dict_.items())[0] self._currentPort = port self._isSingleHop = isSingleHop self.TurnOn() self.ConnectHandlers() def __del__(self): self.TurnOff() def ConnectHandlers(self): self._socketServer._socketHandler.addHandler(self.Rx) def ToIdleMode(self): self._coreCurrent = self.BleChar['Current']['CoreIdle'] if self._socketServer._isSocketUp: self._socketServer.SocketClosing() def ToActiveMode(self): self._coreCurrent = self.BleChar['Current']['CoreActive'] if self._socketServer._isSocketUp: self._socketServer.SocketClosing() def ToRxMode(self): self._coreCurrent = self.BleChar['Current']['RX'] self._socketServer = SocketServer(self.serverPort) self._socketServer.Setup() def TurnOff(self): self._timer.cancel() def TurnOn(self): self.StartTimer() self.ToActiveMode() def PowerConsumedUART(self, data): dataSize = getsizeof(data) / 8 time = (dataSize / self.BleChar['BitRate']['UART'] ) / 3600.0 # bitrate is in seconds, convert it to hours power = time * self._inputVoltage * self.BleChar['Current']['UART'] self._batteryEvent.fire(powerDischarged=power, reason=('Bluetooth UART')) def PowerConsumed(self, data, isTX=True): type_ = 'TX' if isTX else 'RX' dataSize = getsizeof(data) / 8 time = (dataSize / self.BleChar['BitRate']['BLE'] ) / 3600.0 # bitrate is in seconds, convert it to hours power = time * self._inputVoltage * self.BleChar['Current'][type_] self._batteryEvent.fire(powerDischarged=power, reason=('Bluetooth ' + type_)) def TimerHit(self): time = 30 / 3600 power = time * self._inputVoltage * self._coreCurrent self._batteryEvent.fire(powerDischarged=power, reason='Bluetooth Timer') self.StartTimer() def StartTimer(self): self._timer = Timer(self._timerVal, self.TimerHit) self._timer.start() def Tx(self, data): self.PowerConsumedUART(data) time.sleep(0.25) self.PowerConsumed(data) #encode it print("Tx --->>> " + str(data)) try: self._socketClient.Transmit(str(data), self._currentPort) except ConnectionRefusedError: DataTransferAttempts = 0 print("Tx------>>> connection failed port: ", self._currentPort) for node in self._txPorts: nodeId, port = list(node.items())[0] print("Tx------>>> Trying id : " + nodeId + " port: ", port) if port == self._currentPort: continue else: try: DataTransferAttempts += 1 #if there is memory in storage transfer it if (len(self.Memory) > 0): for storedData in self.Memory: self._socketClient.Transmit( str(storedData), port) else: self._socketClient.Transmit(str(data), port) self._currentPort = port return except ConnectionRefusedError: print("Tx------>>> connection failed port: ", port) continue print("No Node available to receive data") print("Saving data to buffer") #chekcs if buffer is full if (len(self.Memory) < 5): self.Memory.append(data) else: print("Buffer is full oldest data point is now lost") del self.Memory[0] self.Memory.append(data) def Rx(self, **kwargs): data = kwargs.get('data') self.PowerConsumed(data, False) self.PowerConsumedUART(data) self._uartEvent.fire(data=data)