class CloudantDB: def __init__(self): self.database = None self.acl_db = None # try to open the db, if not, create it... try: self.vcap = json.loads( os.getenv("VCAP_SERVICES"))['cloudantNoSQLDB'] self.cl_username = self.vcap[0]['credentials']['username'] self.cl_password = self.vcap[0]['credentials']['password'] self.url = self.vcap[0]['credentials']['url'] self.auth = (self.cl_username, self.cl_password) self.client = Cloudant(self.cl_username, self.cl_password, url=self.url) self.client.connect() self.database = self.client[USER_DB] self.acl_db = self.client[ACL_DB] logger.info('Starting cloudant db at %s' % self.url) except: logger.error('Unable to load database...') def create_db(self): self.database = self.client.create_database(USER_DB) if self.database.exists(): return None, False return 'Unable to create %s' % USER_DB, True def get_all_documents(self): documents = [] for document in self.database: documents.append(document) if not documents: logger.error('Unable to load documents...') return None, True return {'documents': documents}, False def get_all_acl_db(self): documents = [] for document in self.acl_db: documents.append(document) if not documents: logger.error('Unable to load documents...') return None, True return {'documents': documents}, False def delete_db(self): if self.database.exists(): self.client.delete_database(USER_DB) def insert_document(self, key, data): # First retrieve the document document, err = self.get_document(key) if err: logger.info('Document not found, will create it with key=%s' % key) return self.create_document(data) # Update the document content # This can be done as you would any other dictionary for key in data: try: document[key] = data[key] except: logger.warning('Key %s missing in document %s' % (key, document)) # You must save the document in order to update it on the database document.save() logger.info('Success, document id=%s, new rev=%s' % (document['_id'], document['_rev'])) return '{"_id"="%s", "_rev":"%s"}' % (document['_id'], document['_rev']), False def create_document(self, data): if '_id' not in data: logger.error('No "_id" field in document') return 'No "_id" field in document', True document = self.database.create_document(data) if document.exists(): return document['_id'], False logger.error('Failed to create document %s' % data) return 'Failed to create document', True def create_report_metadata(self, data): if '_id' not in data: logger.error('No "_id" field in document') return 'No "_id" field in document', True document = self.acl_db.create_document(data) if document.exists(): return document['_id'], False logger.error('Failed to create document %s' % data) return 'Failed to create document', True def get_document(self, key): try: document = self.database[key] except: logger.error('Failed to retrieve document with key=%s' % key) return 'Failed to retrieve document with key=%s' % key, True logger.info('Got document %s' % document) return document, False def get_report_metadata(self, key): try: document = self.acl_db[key] except: logger.error('Failed to retrieve document with key=%s' % key) return 'Failed to retrieve document with key=%s' % key, True logger.info('Got document %s' % document) return document, False def update_document(self, key, data): # First retrieve the document document, err = self.get_document(key) if err: logger.error('Failed to update document with key=%s' % key) return 'Failed to update document with key=%s' % key, True # Update the document content # This can be done as you would any other dictionary for key in data: try: document[key] = data[key] except: logger.warning('Key %s missing in document %s' % (key, document)) # You must save the document in order to update it on the database document.save() logger.info('Success, document id=%s, new rev=%s' % (document['_id'], document['_rev'])) return '{"_id"="%s", "_rev":"%s"}' % (document['_id'], document['_rev']), False def delete_document(self, key): # First retrieve the document document, err = self.get_document(key) if err: logger.error('Failed to delete document with key=%s' % key) return 'Failed to delete document with key=%s' % key, True document.delete() logger.info('Success, deleted document key=%s' % key) return 'Success, deleted document key=%s' % key, False
class db: dataLabel = "data" timeLabel = "stamp" statusLabel = "state" lastUpdateLabel = 'lastUpdate' commandLabel = "command" def __init__(self): if 'VCAP_SERVICES' in os.environ: vcap = json.loads(os.getenv('VCAP_SERVICES')) print('Found VCAP_SERVICES') if 'cloudantNoSQLDB' in vcap: self.creds = vcap['cloudantNoSQLDB'][0]['credentials'] self.user = self.creds['username'] self.password = self.creds['password'] elif os.path.isfile('vcap-local.json'): with open('vcap-local.json') as f: vcap = json.load(f) print('Found local VCAP_SERVICES') self.creds = vcap['services']['cloudantNoSQLDB'][0][ 'credentials'] self.user = self.creds['username'] self.password = self.creds['password'] def connect(self, name=constant.prodDb): self.dbName = name self.client = Cloudant(self.user, self.password, url='https://' + self.creds['host'], connect=True) self.db = self.client.create_database(self.dbName, throw_on_exists=False) def createNewDevice(self): doc = self.db.create_document({self.dataLabel: []}) doc[self.lastUpdateLabel] = str(datetime.datetime.now()) doc[self.commandLabel] = [] doc[constant.hour_frequency] = [] doc.save() return doc["_id"] def addData(self, id, state, time=datetime.datetime.now()): doc = self.db[id] Document.list_field_append(doc, self.dataLabel, { self.timeLabel: str(time), self.statusLabel: state }) doc[self.lastUpdateLabel] = str(time) doc.save() """ dataArray is an array of tuple each tuple has in fist position the data and in second position the timestamp """ def addDataArray(self, id, dataArray): doc = self.db[id] for i in dataArray: Document.list_field_append(doc, self.dataLabel, { self.timeLabel: str(i[1]), self.statusLabel: i[0] }) doc[self.lastUpdateLabel] = str(datetime.datetime.now()) doc.save() def clearDatabase(self): self.client.delete_database(self.dbName) self.db = None def disconnect(self): self.client.disconnect() self.client = None self.db = None def getDataFromId(self, id): doc = self.db[id] return (doc[self.dataLabel], doc[constant.hour_frequency]) def getDeviceList(self): return self.db.keys(remote=True) def resetConnection(self): self.disconnect() self.connect() def getIdLastUpdate(self, id): doc = self.db[id] return doc[self.lastUpdateLabel] def addCommand(self, id, command): doc = self.db[id] doc[self.commandLabel].append(command) doc.save() def getCommandList(self, id): doc = self.db[id] return doc[self.commandLabel] def deleteCommands(self, id): doc = self.db[id] doc[self.commandLabel] = [] doc.save() def computeOccupancy(self, measurementFrequency, numGraphLabels, computedHours, deviceID): doc = self.db[deviceID] dataToCompute = doc[constant.dataLabel] numEntriesToCompute = (constant.minutesInHour // measurementFrequency) * computedHours lenPerLabel = numEntriesToCompute // numGraphLabels print(numEntriesToCompute) dataToCompute = dataToCompute[-numEntriesToCompute:] frequencyPerLabel = [] def chunks(arr, n): for i in range(0, len(arr), n): yield arr[i:i + n] dataPerLabel = list(chunks(dataToCompute, lenPerLabel)) print(dataPerLabel) for label in range(numGraphLabels): frequencyPerLabel.append(0) for el in dataPerLabel[label]: if el[constant.db_entry_state_label]: frequencyPerLabel[label] += 1 hours = doc[constant.hour_frequency] + frequencyPerLabel doc[constant.hour_frequency] = hours doc.save()