class RoutingManager: def __init__(self): self._jsonHandler = JsonHandler() self._routes = self._jsonHandler.LoadJson('Routes.json') def __del__(self): self._jsonHandler.WriteJson('Routes.json', self._routes) def GetServiceUrl(self, path): try: pathArray = path.split("/") service = pathArray[1] serviceList = self._routes['services'] endpoint = next(endpoint for endpoint in serviceList if endpoint['Endpoint'] == service) path = path.replace("/" + service, "") return RoutingEndpoint(service, endpoint['Primary']['server'], endpoint['Port'], path) except Exception as ex: raise Exception(ex) def ChangePrimary(self, endpoint, replicaList): pass def GetReplicaList(self, endpoint): pass
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.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.BatteryChar['State']['Power'] = wattHr def Discharging(self, powerDischarged): currentPower = self.BatteryChar['State']['Power'] self.BatteryChar['State']['Power'] = currentPower - powerDischarged def Charging(self, powerCharging): currentPower = self.BatteryChar['State']['Power'] self.BatteryChar['State']['Power'] = currentPower + powerCharging def GetOutputVoltage(self): return self.BatteryChar['InitialState']['Voltage']
def __init__(self, producer: Producer): self._JsonHandler = JsonHandler() self.config = self._JsonHandler.LoadJson('Config.json') self._queue = producer._queue self.socketClosed = False self._thread = threading.Thread(target=self.Consume) self._thread.daemon = True self._thread.start()
def __init__(self): try: config = JsonHandler().LoadJson('Config.json') print(config) Client = pymongo.MongoClient("mongodb://localhost:27017/") dataBase = Client['DBB_db'] PostCollection = dataBase['PostCollection'] postList = [] cursor = PostCollection.find({}) for doc in cursor: postList.append(doc) sortedList = sorted(postList, key=lambda i: i['PayLoadToken'], reverse=True) print(str(len(sortedList))) token = sortedList[0]['PayLoadToken'] if len(sortedList) > 0 else 0 payload = {"PayLoadToken": token} client = http.client.HTTPConnection(config['CordinatorHost'], config['CordinatorHTTPPort']) client.request('POST', "/recovery", json.dumps(payload), {'Content-type': 'application/json'}) response = client.getresponse() if response.status == 200: responseData = response.read() responseJSon = json.loads(responseData) if len(responseJSon) > 0: PostCollection.insert_many(responseJSon) except Exception as ex: print(ex)
class Consumer: def __init__(self, producer: Producer): self._JsonHandler = JsonHandler() self.config = self._JsonHandler.LoadJson('Config.json') self._queue = producer._queue self.socketClosed = False self._thread = threading.Thread(target=self.Consume) self._thread.daemon = True self._thread.start() def Consume(self): print("Started consuming") client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((self.config['CordinatorHost'], self.config['CordinatorSocketPort'])) msg = {"type": "DataSource", "source": "participant"} client.send(bytes(json.dumps(msg), "utf8")) while True: try: item = self._queue.get() while True: try: if self.socketClosed: client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(('localhost', 7000)) client.send(bytes(json.dumps(item), "utf8")) break except: self.socketClosed = True client.close() continue self._queue.task_done() except: continue
class DbHandler: def __init__(self): self._jsonHandler = JsonHandler() self._config = self._jsonHandler.LoadJson('Config.json') self._polling = True def GetStatusCollection(self): print("--->In Db Handler") for attempts in range(self._config['dbReconnection']): try: Client = pymongo.MongoClient(self._config['connectionString']) dataBase = Client[self._config['dataBase']] collection = dataBase[self._config['collectionName']] self._polling = False return self._polling, collection except (AutoReconnect, NetworkTimeout) as ex: print("--->In Db Handler ex1") print(str(ex)) waitTime = 5.0 * attempts self._polling = True time.sleep(waitTime) except Exception as ex: print("--->In Db Handler ex2") print(str(ex)) self._polling = True break return self._polling, None
def __init__(self): self._JsonHandler = JsonHandler() config = self._JsonHandler.LoadJson('Config.json') # if config['IsPrimary'] : # self.Status = False # return print(config) try: self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client.connect((config['CordinatorHost'], config['CordinatorSocketPort'])) msg = {"type" : "connectRequest", "source" : "participant"} self.client.send(bytes(json.dumps(msg), "utf8")) #open mongo client self.mongoClient = pymongo.MongoClient("mongodb://localhost:27017/") dataBase = self.mongoClient['DBB_db'] self.PostCollection = dataBase['PostCollection'] except Exception as ex: print(ex) receive_thread = Thread(target=self.receive) receive_thread.daemon = True receive_thread.start()
def __init__(self, dataPipeline : Producer, twoPhaseManager : TwoPhaseCommitManager,log : LogHandler): self.State = False self._log = log self._dataPipeline = dataPipeline self._twoPhaseManager = twoPhaseManager jsonHandler = JsonHandler() socketConfig = jsonHandler.LoadJson('Config.json') self._socketAddress = (socketConfig['host'],socketConfig['port']) self._bufferSize = socketConfig['bufferSize'] if(self.CreateSocket()): self._socket.listen(10) self._hcrThread = threading.Thread(target=self.HandleConnectionRequest) self._hcrThread.daemon = True self._hcrThread.start() #Waiting for all the client to join #time.sleep(30) self._thread = threading.Thread(target=self.PiplineConsumer) self._thread.daemon = True self._thread.start() self.run()
class MicroController(object): characteristicsPath = "Characteristics/MicroController.json" _inputVoltage = 0 _coreCurrent = 0 def __init__(self, inputVoltage): self.jsonHandler = JsonHandler() self.ControllerChar = self.jsonHandler.LoadJson( self.characteristicsPath) self._inputVoltage = inputVoltage self._coreCurrent = self.ControllerChar['Current']['Mode']['Run'] def TurnOn(self): self.ToActiveMode() def TurnOff(self): #updatePower pass 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): Temp = 12 self.I2CPowerConsumed() return Temp def I2CWrite(self): self.I2CPowerConsumed() def I2CPowerConsumed(self): time = (self.ControllerChar['BitSize'] / self.ControllerChar['BitRate'] ) / 3600 # bitrate is in seconds, convert it to hours power = time * self._inputVoltage * self._coreCurrent return power
class Bluetooth(object): characteristicsPath = "Characteristics/Battery.json" _inputVoltage = 0 _coreCurrent = 0 def __init__(self, inputVoltage): self.jsonHandler = JsonHandler() self.BleChar = self.jsonHandler.LoadJson(self.characteristicsPath) self._inputVoltage = inputVoltage self._coreCurrent = self.BleChar['Current']['CoreActive'] def ToIdleMode(self): self._coreCurrent = self.BleChar['Current']['CoreIdle'] def ToActiveMode(self): self._coreCurrent = self.BleChar['Current']['CoreActive'] def TurnOff(self): #update power consumension pass def TurnOn(self): #power drop for pairing self.ToActiveMode() def PowerConsumedTx(self, dataSize): time = (self.BleChar['BitRate'] * dataSize) / 3600 # bitrate is in seconds, convert it to hours power = time * self._inputVoltage * self.BleChar['Current']['TX'] return power def PowerConsumedRx(self, dataSize): time = (self.BleChar['BitRate'] * dataSize) / 3600 # bitrate is in seconds, convert it to hours power = time * self._inputVoltage * self.BleChar['Current']['RX'] return power def Tx(self, data): bitSize = data.nbytes * 8 self.PowerConsumedTx(bitSize)
def __init__(self): self.jsonHandler = JsonHandler() self.BatteryChar = self.jsonHandler.LoadJson(self.characteristicsPath) self.InitialState()
def __init__(self): self._jsonHandler = JsonHandler() self._config = self._jsonHandler.LoadJson('Config.json') self._polling = True
def __init__(self, inputVoltage): self.jsonHandler = JsonHandler() self.ControllerChar = self.jsonHandler.LoadJson( self.characteristicsPath) self._inputVoltage = inputVoltage self._coreCurrent = self.ControllerChar['Current']['Mode']['Run']
class Participant: Status = True payload = None _currentTransationId = "" _currentState = "" def __init__(self): self._JsonHandler = JsonHandler() config = self._JsonHandler.LoadJson('Config.json') # if config['IsPrimary'] : # self.Status = False # return print(config) try: self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client.connect((config['CordinatorHost'], config['CordinatorSocketPort'])) msg = {"type" : "connectRequest", "source" : "participant"} self.client.send(bytes(json.dumps(msg), "utf8")) #open mongo client self.mongoClient = pymongo.MongoClient("mongodb://localhost:27017/") dataBase = self.mongoClient['DBB_db'] self.PostCollection = dataBase['PostCollection'] except Exception as ex: print(ex) receive_thread = Thread(target=self.receive) receive_thread.daemon = True receive_thread.start() # self.Run() def __del__(self): if self.Status: self.client.close() # def Run(self): # while Status: # continue def receive(self): while True: try: msg = self.client.recv(1024).decode("utf8") if msg: msgJson = json.loads(msg) print(msgJson) if msgJson['type'] == "ReadyToCommit": #if it has become primary it will replay no and close the socket _currentTransationId = msgJson['transactionId'] _currentState = "Prepare" payload = msgJson['payload'] msg = {"transactionId" : _currentTransationId, "type" : "ReadyToCommit", "response": True} self.client.send(bytes(json.dumps(msg), "utf8")) elif msgJson['type'] == "Commit": if msgJson['transactionId'] == _currentTransationId: try: _currentState = "Commit" #save in the db print("comitted" + str(payload)) querry = {'PayLoadToken' : payload['PayLoadToken']} result = self.PostCollection.find(querry) print("Result"+ str(result.count())) if result.count() != 0: msg = {"type" : "connectClose", "source" : "participant"} self.client.send(bytes(json.dumps(msg), "utf8")) self.client.close() self.mongoClient.close() self.Status = False break else: self.PostCollection.insert(payload) msg = {"transactionId" : _currentTransationId,"type" : "Commit", "response": True} self.client.send(bytes(json.dumps(msg), "utf8")) except Exception as ex: print(ex) elif msgJson['type'] == "Abort": _currentState = "Abort" msg = {"transactionId" : _currentTransationId,"type" : "Abort", "response": True} self.client.send(bytes(json.dumps(msg), "utf8"))
def __init__(self, inputVoltage): self.jsonHandler = JsonHandler() self.SensorChar = self.jsonHandler.LoadJson(self.characteristicsPath) self._inputVoltage = inputVoltage self._coreCurrent = self.SensorChar['Current']['AciveMode']
def __init__(self): self._jsonHandler = JsonHandler() self._routes = self._jsonHandler.LoadJson('Routes.json')
def __init__(self, inputVoltage): self.jsonHandler = JsonHandler() self.BleChar = self.jsonHandler.LoadJson(self.characteristicsPath) self._inputVoltage = inputVoltage self._coreCurrent = self.BleChar['Current']['CoreActive']