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()
class Battery(object): logPath = "Characteristics/BatteryLog.json" def __init__(self, currentBatteryPower): self._currentBatteryPower = currentBatteryPower self.jsonHandler = JsonHandler() self.BatteryLog = self.jsonHandler.LoadJson(self.logPath) self._logs = self.BatteryLog['Log'] def __del__(self): self.BatteryLog['Log'] = self._logs self.jsonHandler.WriteJson(self.logPath, self.BatteryLog) def Discharging(self, **kwargs): powerDischarged = kwargs.get('powerDischarged') self._currentBatteryPower = self._currentBatteryPower - powerDischarged log = { 'CurrentPower': self._currentBatteryPower, 'PowerConsumed': powerDischarged, 'Reason': kwargs.get('reason'), 'TimeStamp': (datetime.datetime.now()).strftime('%m/%d/%Y %I:%M:%S %p') } self._logs.append(log) def Charging(self, **kwargs): powerCharging = kwargs.get('powerDischarged') self._currentBatteryPower = self._currentBatteryPower + powerCharging def GetCurrentCharge(self): return self._currentBatteryPower
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 __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()
class oximeterController(MicroController): _characteristicsPath = "Characteristics/oximeterController.json" def Setup(self): self.bt = Battery( self._ControllerChar['Battery']['CurrentState']['Power']) self.ble = Bluetooth(3.0, 30) self.ts = oximeterSensor(3.0) def __init__(self): self.jsonHandler = JsonHandler() self._ControllerChar = self.jsonHandler.LoadJson( self._characteristicsPath) self.Setup() self.ConnectHandlers() super().__init__(3.0) try: while (True): self.Run() except KeyboardInterrupt: self._ControllerChar['Battery']['CurrentState'][ 'Power'] = self.bt.GetCurrentCharge() self.__del__() exit(1) def __del__(self): self.jsonHandler.WriteJson(self._characteristicsPath, self._ControllerChar) self.ble.__del__() self.ts.__del__() self.bt.__del__() super().__del__() def ConnectHandlers(self): self.ble._batteryEvent.addHandler(self.bt.Discharging) self.ts._batteryEvent.addHandler(self.bt.Discharging) self._batteryEvent.addHandler(self.bt.Discharging) def Run(self): time.sleep(3) temp = self.ReadOxygenLevel() #time.sleep(3) print("Oximeter---->" + str(temp)) if (temp < 90): self.WriteBluetooth(temp) time.sleep(3) def ReadOxygenLevel(self): self.I2CRead() return self.ts.I2CRead() def WriteBluetooth(self, data): super().I2CWrite() data = str(data) + '| OxygenLevel' self.ble.Tx(data)
def __init__(self): self.jsonHandler = JsonHandler() self._ControllerChar = self.jsonHandler.LoadJson(self._characteristicsPath) self.Setup() self.ConnectHandlers() super().__init__(3.0) try: while(True): self.Run() except KeyboardInterrupt: self._ControllerChar['Battery']['CurrentState']['Power'] = self.bt.GetCurrentCharge() self.__del__() exit(1)
def __init__(self, inputVoltage, timerVal, SensorID): self.jsonHandler = JsonHandler() routingTable = self.jsonHandler.LoadJson(self._characteristicsPath) self._routingTable = routingTable[SensorID] super().__init__(inputVoltage, timerVal, False, self._routingTable['Tx'], self._routingTable['Port']) self._sensorID = SensorID print(self._routingTable) if 'Flooding' in self._routingTable: self.NodePortList = self._routingTable['Flooding'] self.NodeBatteryLevelList = [] self._broadCasting = False self._broadCastingNodes = self._routingTable['BroadCastingNodes'] self.P2pConnectHandlers()
class EdgeNodeController(EdgeController): _characteristicsPath = "Characteristics/TemperatureController.json" def Setup(self): self.bt = Battery( self._ControllerChar['Battery']['CurrentState']['Power']) self.ble = Bluetooth(3.0, 30) self.ble.ToRxMode() def __init__(self): self.jsonHandler = JsonHandler() self._ControllerChar = self.jsonHandler.LoadJson( self._characteristicsPath) self.Setup() self.ConnectHandlers() self._mqttService = MqttPublisher("EdgeNode", "DS/Node1/Temperature") super().__init__(3.0) try: while (True): self.Run() except KeyboardInterrupt: self._ControllerChar['Battery']['CurrentState'][ 'Power'] = self.bt.GetCurrentCharge() self.__del__() exit(1) def __del__(self): self.jsonHandler.WriteJson(self._characteristicsPath, self._ControllerChar) self.ble.__del__() self.bt.__del__() super().__del__() def ConnectHandlers(self): self.ble._batteryEvent.addHandler(self.bt.Discharging) self._batteryEvent.addHandler(self.bt.Discharging) self.ble._uartEvent.addHandler(self.UartRx) def Run(self): pass def UartRx(self, **kwargs): data = kwargs.get('data') self.UartPowerConsumed(data) print('RX --->>>', str(data)) self.WifiPowerConsumed(data) self._mqttService.Publish(data)
def __init__(self): self.jsonHandler = JsonHandler() self._ControllerChar = self.jsonHandler.LoadJson(self._characteristicsPath) self.Setup() self.ConnectHandlers() self._mqttService = MqttPublisher("EdgeNode","PatientMonitoring/Edge3/") super().__init__(3.0) try: while(True): self.Run() except KeyboardInterrupt: self._ControllerChar['Battery']['CurrentState']['Power'] = self.bt.GetCurrentCharge() self.__del__() exit(1)
def __init__(self): self.jsonHandler = JsonHandler() self._ControllerChar = self.jsonHandler.LoadJson(self._characteristicsPath) self.Setup() self.ConnectHandlers() self._privateKey = self._ControllerChar['PrivateKey'] mqtt = self._ControllerChar['Mqtt'] self._mqttService = MqttPublisher(mqtt['Name'],mqtt['Topic']) self._LogData = [] super().__init__(3.0,self._sensorId) try: while(True): self.Run() except KeyboardInterrupt: self._ControllerChar['Battery']['CurrentState']['Power'] = self.bt.GetCurrentCharge() self.__del__() exit(1)
class Battery(object): characteristicsPath = "Characteristics/Battery.json" def __init__(self): self.jsonHandler = JsonHandler() self.BatteryChar = self.jsonHandler.LoadJson(self.characteristicsPath) self.InitialState() def __del__(self): self.BatteryChar['Logs'] = self._logs self.jsonHandler.WriteJson(self.characteristicsPath, self.BatteryChar) def InitialState(self): #battery power usually in mAh # Voltage * Amps * hours = Wh InitialState = self.BatteryChar['InitialState'] wattHr = InitialState['AmpHours'] * InitialState['Voltage'] self.BatteryChar['InitialState']['Power'] = wattHr self._logs = self.BatteryChar['Logs'] def Discharging(self, **kwargs): powerDischarged = kwargs.get('powerDischarged') currentPower = self.BatteryChar['State']['Power'] self.BatteryChar['State']['Power'] = currentPower - powerDischarged currentTimeStamp = datetime.datetime.now() date = currentTimeStamp.strftime( '%m/%d/%Y') + " " + currentTimeStamp.strftime('%I:%M:%S %p') log = { 'Power': self.BatteryChar['State']['Power'], 'Reason': kwargs.get('reason'), 'TimeStamp': date } self._logs.append(log) def Charging(self, **kwargs): powerCharging = kwargs.get('powerDischarged') currentPower = self.BatteryChar['State']['Power'] self.BatteryChar['State']['Power'] = currentPower + powerCharging def GetOutputVoltage(self): return self.BatteryChar['InitialState']['Voltage']
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()
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 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 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 P2pBluetooth(Bluetooth): _characteristicsPath = "Characteristics/RoutingTable.json" def __init__(self, inputVoltage, timerVal, SensorID): self.jsonHandler = JsonHandler() routingTable = self.jsonHandler.LoadJson(self._characteristicsPath) self._routingTable = routingTable[SensorID] super().__init__(inputVoltage, timerVal, False, self._routingTable['Tx'], self._routingTable['Port']) self._sensorID = SensorID print(self._routingTable) if 'Flooding' in self._routingTable: self.NodePortList = self._routingTable['Flooding'] self.NodeBatteryLevelList = [] self._broadCasting = False self._broadCastingNodes = self._routingTable['BroadCastingNodes'] self.P2pConnectHandlers() def __del__(self): super().__del__() def P2pConnectHandlers(self): self._socketServer._p2pHandler.addHandler(self.P2pRx) def P2pRx(self, **kwargs): data = kwargs.get('data') dataArray = str(data).split('-') print(self.NodePortList) result, nodeId, port = self.GetNodeId(dataArray[1]) print(result, nodeId, port) if result: self.NodeBatteryLevelList.append({ 'Id': nodeId, 'Port': port, 'BatteryLevel': dataArray[0] }) if self._broadCastingNodes == len(self.NodeBatteryLevelList): a = sorted(self.NodeBatteryLevelList, key=itemgetter('BatteryLevel'), reverse=True) a = a[0] print("Chossen Sensor is ", a['Id']) if a['Id'] != self._sensorID: self.ToActiveMode() def GenearteBatteryLevelDict(self, index): array = [] for node in self.NodePortList: nodeId, port = list(node.items())[0] array.append({'Id': nodeId, 'Port': port, 'BatteryLevel': 0}) return array def GetNodeId(self, key): nodeId = '' port = '' result = False for node in self.NodePortList: if key in node: nodeId, port = list(node.items())[0] result = True return result, nodeId, port return result, nodeId, port def BroadCasting(self, Batterydata): self._broadCasting = True self.NodeBatteryLevelList = [] self._broadCastingNodes = self._routingTable['BroadCastingNodes'] if not self._socketServer._isSocketUp: self.ToRxMode() time.sleep(0.25) #loops through each port in priority list and contacts them # for node in self.NodePortList: _, port = list(node.items())[0] data = str(Batterydata) + "-" + self._sensorID self.PowerConsumed(data) try: self._socketClient.Transmit(data, port) except ConnectionRefusedError: self._broadCastingNodes -= self._broadCastingNodes print("failed on port " + str(port)) if self._broadCastingNodes == 0: pass self._broadCasting = False
class OxyMeterController (EdgeController) : _characteristicsPath = "Characteristics/TemperatureController.json" _sensorId = 'OxyMeter' def Setup(self): self.bt = Battery(self._ControllerChar['Battery']['CurrentState']['Power']) self.ble = P2pBluetooth(3.0,30,self._sensorId) self.SetP2P() self.sensor = HeartRateSensor(3.0) self.ble.ToRxMode() def __init__(self): self.jsonHandler = JsonHandler() self._ControllerChar = self.jsonHandler.LoadJson(self._characteristicsPath) self.Setup() self.ConnectHandlers() self._privateKey = self._ControllerChar['PrivateKey'] mqtt = self._ControllerChar['Mqtt'] self._mqttService = MqttPublisher(mqtt['Name'],mqtt['Topic']) self._LogData = [] self._bulkPushTimer = Timer(150,self.BulkPushTimerHit) self._bulkPushTimer.start() super().__init__(3.0,self._sensorId) try: while(True): self.Run() except KeyboardInterrupt: self.BulkPushTimerHit() self._ControllerChar['Battery']['CurrentState']['Power'] = self.bt.GetCurrentCharge() self.__del__() exit(1) def __del__(self): self.jsonHandler.WriteJson(self._characteristicsPath,self._ControllerChar) self.ble.__del__() self.bt.__del__() super().__del__() def SetP2P(self): self._p2pTimer = Timer(10,self.P2pTimerHit) self._p2pTimer.start() def P2pTimerHit(self): self.ble.BroadCasting(self.bt.GetCurrentCharge()) self._p2pTimer = Timer(10,self.P2pTimerHit) self._p2pTimer.start() def ConnectHandlers(self): self.ble._batteryEvent.addHandler(self.bt.Discharging) self.sensor._batteryEvent.addHandler(self.bt.Discharging) self._batteryEvent.addHandler(self.bt.Discharging) self.ble._uartEvent.addHandler(self.UartRx) def Run(self): self.PushAll() def PushAll(self): time.sleep(3) temp = self.ReadTemperature() print('OxyMeter--->>',temp) time.sleep(1) #time.sleep(3) self.WifiTx(self.Encrypt(temp),'HeartRate') def Push(self): pass def UartRx(self,**kwargs): data = kwargs.get('data') self.UartPowerConsumed(data) print('RX --->>>', str(data)) dataArray = str(data).split('|') if dataArray[2] == '0' : self.WifiTx(dataArray[0],dataArray[1]) else: self._LogData.append(data) pass def WifiTx(self,data,topic): self.WifiPowerConsumed(data) self._mqttService.Publish(data,topic) def WifiBulkPush(self): data = self._LogData self.WifiPowerConsumed(data,True,False) data = {"Data" : data} self._mqttService.Publish(json.dumps(data),'BulkPush') self._LogData = [] def BulkPushTimerHit(self): if len(self._LogData) > 0 : self.WifiBulkPush() self._bulkPushTimer = Timer(150,self.BulkPushTimerHit) self._bulkPushTimer.start() def ReadTemperature(self): self.I2CRead() return self.sensor.I2CRead()
class EdgeNodeController(EdgeController): _characteristicsPath = "Characteristics/ECGController.json" def Setup(self): self.bt = Battery( self._ControllerChar['Battery']['CurrentState']['Power']) self.ble = Bluetooth(3.0, 30) self.ble.ToRxMode() def __init__(self): self.jsonHandler = JsonHandler() self._ControllerChar = self.jsonHandler.LoadJson( self._characteristicsPath) self.Setup() self.ConnectHandlers() self._mqttService = MqttPublisher("EdgeNode", "PatientMonitoring/Edge3/") super().__init__(3.0) try: while (True): self.Run() except KeyboardInterrupt: self._ControllerChar['Battery']['CurrentState'][ 'Power'] = self.bt.GetCurrentCharge() self.__del__() exit(1) def __del__(self): self.jsonHandler.WriteJson(self._characteristicsPath, self._ControllerChar) self.ble.__del__() self.bt.__del__() super().__del__() def ConnectHandlers(self): self.ble._batteryEvent.addHandler(self.bt.Discharging) self._batteryEvent.addHandler(self.bt.Discharging) self.ble._uartEvent.addHandler(self.UartRx) def Run(self): pass def Encript(self, data): password_provided = "password" # This is input in the form of a string password = password_provided.encode() # Convert to type bytes salt = b'salt_' # CHANGE THIS - recommend using a key from os.urandom(16), must be of type bytes kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=default_backend()) key = base64.urlsafe_b64encode( kdf.derive(password)) # Can only use kdf once message = data.encode() f = Fernet(key) encrypted = f.encrypt(message) #print('RX --->>>', str(encrypted)) return encrypted def UartRx(self, **kwargs): data = kwargs.get('data') self.UartPowerConsumed(data) print('RX --->>>', str(data)) data = str(data).split('| ') #temp = int(data[0]) encdata = self.Encript(data[0]) self.WifiPowerConsumed(encdata) #if(temp>400 or temp<70): self._mqttService.Publish(encdata, data[1])
def __init__(self, inputVoltage): self.jsonHandler = JsonHandler() self.SensorChar = self.jsonHandler.LoadJson(self.characteristicsPath) self.sensingRange = self.SensorChar['SensingRange'] self._inputVoltage = inputVoltage self.TurnOn()
class HeartRateController (MicroController) : _characteristicsPath = "Characteristics/TemperatureController.json" _sensorId = 'HeartRate' def Setup(self): self.bt = Battery(self._ControllerChar['Battery']['CurrentState']['Power']) self.ble = P2pBluetooth(3.0,30,self._sensorId) self.SetP2P() self.sensor = HeartRateSensor(3.0) self.ble.ToRxMode() def __init__(self): self.jsonHandler = JsonHandler() self._ControllerChar = self.jsonHandler.LoadJson(self._characteristicsPath) self.Setup() self.ConnectHandlers() self._privateKey = self._ControllerChar['PrivateKey'] mqtt = self._ControllerChar['Mqtt'] self._mqttService = MqttPublisher(mqtt['Name'],mqtt['Topic']) self._LogData = [] super().__init__(3.0,self._sensorId) try: while(True): self.Run() except KeyboardInterrupt: self._ControllerChar['Battery']['CurrentState']['Power'] = self.bt.GetCurrentCharge() self.__del__() exit(1) def __del__(self): self.jsonHandler.WriteJson(self._characteristicsPath,self._ControllerChar) self.ble.__del__() self.bt.__del__() super().__del__() def SetP2P(self): self._p2pTimer = Timer(10,self.P2pTimerHit) self._p2pTimer.start() def P2pTimerHit(self): self.ble.BroadCasting(self.bt.GetCurrentCharge()) self._p2pTimer = Timer(10,self.P2pTimerHit) self._p2pTimer.start() def ConnectHandlers(self): self.ble._batteryEvent.addHandler(self.bt.Discharging) self.ble._uartEvent.addHandler(self.UartRx) self.sensor._batteryEvent.addHandler(self.bt.Discharging) self._batteryEvent.addHandler(self.bt.Discharging) def Run(self): self.PushAll() def PushAll(self): time.sleep(3) temp = self.ReadTemperature() print('HEartRate--->>',temp) time.sleep(1) #time.sleep(3) self.WriteBluetooth(temp) def Push(self): pass def ReadTemperature(self): self.I2CRead() return self.sensor.I2CRead() def WriteBluetooth(self,data): data = self.Encrypt(data) data = str(data) + '|HeartRate|0' self.UartPowerConsumed(data) self.ble.Tx(data) def UartRx(self,**kwargs): data = kwargs.get('data') self.UartPowerConsumed(data) self.UartPowerConsumed(data) self.ble.Tx(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()
def __init__(self, inputVoltage): self.jsonHandler = JsonHandler() self.ControllerChar = self.jsonHandler.LoadJson( self.characteristicsPath) self._inputVoltage = inputVoltage self.TurnOn()
def __init__(self): self.jsonHandler = JsonHandler() self.BatteryChar = self.jsonHandler.LoadJson(self.characteristicsPath) self.InitialState()
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)
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 TemperatureController(MicroController): _characteristicsPath = "Characteristics/TemperatureController.json" _sensorId = 'Temperature' def Setup(self): self.bt = Battery( self._ControllerChar['Battery']['CurrentState']['Power']) self.ble = P2pBluetooth(3.0, 30, self._sensorId) self.ts = TemperatureSensor(3.0) def __init__(self): self.jsonHandler = JsonHandler() self._ControllerChar = self.jsonHandler.LoadJson( self._characteristicsPath) self.Setup() self.ConnectHandlers() super().__init__(3.0, self._sensorId) #Change Mode -->> self.ts.SetRegister() try: while (True): self.Run() except KeyboardInterrupt: self._ControllerChar['Battery']['CurrentState'][ 'Power'] = self.bt.GetCurrentCharge() self.__del__() exit(1) def __del__(self): self.jsonHandler.WriteJson(self._characteristicsPath, self._ControllerChar) self.ble.__del__() self.ts.__del__() self.bt.__del__() super().__del__() def ConnectHandlers(self): self.ble._batteryEvent.addHandler(self.bt.Discharging) self.ts._batteryEvent.addHandler(self.bt.Discharging) self.ts._interupt.addHandler(self.ReceiveInterupt) self._batteryEvent.addHandler(self.bt.Discharging) def Run(self): pass def ReceiveInterupt(self): self.I2CRead() data = self.ts.RI2CRead() self.WriteBluetooth(data) def ReadTemperature(self): self.I2CRead() return self.ts.I2CRead() def WriteBluetooth(self, data): data = self.Encrypt(data) data = str(data) + '|Temperature|1' self.UartPowerConsumed(data) self.ble.Tx(data)
def __init__(self, currentBatteryPower): self._currentBatteryPower = currentBatteryPower self.jsonHandler = JsonHandler() self.BatteryLog = self.jsonHandler.LoadJson(self.logPath) self._logs = self.BatteryLog['Log']
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)