def get_figPath(): figPath = os.path.join(sys.path[0], 'config', ModuleObj.get_chipId() + '.fig') if not os.path.exists(figPath) or not os.path.isfile(figPath): log(LogLevel.error, 'Can not find %s.fig file!' %(ModuleObj.get_chipId())) sys.exit(-1) return figPath
def delete_command(self, cid): try: self.curs.execute("DELETE FROM commands WHERE cid=?;", (cid,)) self.conn.commit() util.log("Command %s was deleted" % str(cid)) except sqlite3.OperationalError as oe: util.log(oe.message)
def gen_custDtsi(self): log(LogLevel.info, 'Start to generate cust_dtsi file...') fp = open(os.path.join(ModuleObj.get_genPath(), 'cust.dtsi'), 'w') gen_str = ModuleObj.writeComment() # if early porting, gen empty dtsi file for kernel if self.__epFlag: fp.write(gen_str) fp.close() return #sorted_list = sorted(self.__objs.keys()) #for tag in sorted_list: for tag in self.__objs.keys(): if cmp(tag, 'gpio') == 0: gpioObj = self.create_obj(tag) gen_str += ModuleObj.writeHeader(gpioObj.get_dtsiFileName()) gen_str += gpioObj.fill_mapping_dtsiFile() gen_str += gpioObj.fill_init_default_dtsiFile() else: obj = self.create_obj(tag) gen_str += ModuleObj.writeHeader(obj.get_dtsiFileName()) gen_str += obj.fill_dtsiFile() gen_str += '''\n\n''' fp.write(gen_str) fp.close() log(LogLevel.info, 'Generate cust_dtsi file successfully!')
def register_command(self, cid, message, data, commander, status='NEW', schedule=None, result=''): com = Command(cid, message, data, commander, status=status, schedule=schedule, result=result) if com.cid == 0: reason = 'Invalid command' elif com.cid == -1: reason = 'You are not authorized to perform this command.' elif com.cid == -2: reason = 'Invalid schedule time. Please respect the given format and make sure that the date is in the future' elif com.cid == -3: reason = 'Not enough arguments provided for command' else: return self.insert_command(com), 'Error within the database' util.log(reason) return -1, reason
def delete_command(self, cid): try: self.curs.execute("DELETE FROM commands WHERE cid=?;", (cid, )) self.conn.commit() util.log("Command %s was deleted" % str(cid)) except sqlite3.OperationalError as oe: util.log(oe.message)
def register_latest_commands(): global mid lid = max(db.get_latest_id(), mid) # max id / registered commands if (lid > 0): try: new_messages = tweet.get_direct_messages(since_id=lid) except TwythonError as te: util.log(te.message) return status = constants.STATUS_NEW else: new_messages = tweet.get_direct_messages(count=1) status = constants.STATUS_NOTIFIED for message in new_messages: # Take commands only from authorized users # These users must be stored in a list called USERS in the keys file # print message['sender']['location'] text = message['text'].strip().lower() if text.split()[0] == 'help': text = 'show ' + text username = message['sender']['screen_name'] data = datetime.datetime.strptime(message['created_at'], '%a %b %d %H:%M:%S +%f %Y') mid = max(message['id'], mid) res, reas = db.register_command(mid, text, str(data), username, status) if res != 0: return notify(reas, username)
def get_cfgInfo(self): cp = ConfigParser.ConfigParser(allow_no_value=True) cp.read(ModuleObj.get_cmpPath()) PmicData._var_list = cp.options('APPLICATION') if self.__chipName == '': return #parse the pmic config file cmpPath = os.path.join(sys.path[0], 'config', self.__chipName + '.cmp') if not os.path.exists(cmpPath) or not os.path.isfile(cmpPath): log(LogLevel.error, 'Can not find %s pmic config file!' % (self.__chipName)) sys.exit(-1) cp.read(cmpPath) self.__defLdo = cp.get('PMIC_TABLE', 'LDO_APPNAME_DEFAULT') self.__headerList = cp.get('PMIC_TABLE', 'INCLUDE_HEADER').split(':') self.__func = cp.get('PMIC_TABLE', 'FUNCTION') for i in range(1, cp.getint('PMIC_TABLE', 'NUM_LDO') + 1): key = 'LDO_NAME%d' % (i) self.__paraList.append(cp.get(key, 'PARAMETER_NAME')) #parse app count in fig file cp.read(ModuleObj.get_chipId() + '.fig') cp.read(ModuleObj.get_figPath()) self.__appCount = cp.getint('Chip Type', 'PMIC_APP_COUNT')
def register_latest_commands(): global mid lid = max(db.get_latest_id(), mid) # max id / registered commands if(lid > 0): try: new_messages = tweet.get_direct_messages(since_id=lid) except TwythonError as te: util.log(te.message) return status = constants.STATUS_NEW else: new_messages = tweet.get_direct_messages(count=1) status = constants.STATUS_NOTIFIED for message in new_messages: # Take commands only from authorized users # These users must be stored in a list called USERS in the keys file # print message['sender']['location'] text = message['text'].strip().lower() if text.split()[0] == 'help': text = 'show ' + text username = message['sender']['screen_name'] data = datetime.datetime.strptime(message['created_at'], '%a %b %d %H:%M:%S +%f %Y') mid = max(message['id'], mid) res, reas = db.register_command(mid, text, str(data), username, status) if res != 0: return notify(reas, username)
def update_command_result(self, cid, result): q = (result, cid) try: self.curs.execute('UPDATE commands SET result=? WHERE cid=?', q) self.conn.commit() util.log("Command %s result was updated to %s" % (cid, result)) except sqlite3.OperationalError as oe: util.log(oe.message)
def update_command_status(self, cid, status): q = (status, cid) try: self.curs.execute('UPDATE commands SET status=? WHERE cid=?', q) self.conn.commit() util.log("Command %s was marked as %s" % (cid, status)) except sqlite3.OperationalError as oe: util.log(oe.message)
def get_completed_commands(self): res = [] try: for row in self.curs.execute("SELECT * FROM commands WHERE status='COMPLETED';").fetchall(): res.append(self.to_command(row)) except sqlite3.OperationalError as oe: util.log(oe.message) return res
def get_latest_id(self): self.curs.execute('select max(cid) from commands;') try: lid = int(self.curs.fetchone()[0]) except TypeError: lid = 0 util.log("New deployment") return lid
def get_cmpPath(): cmpPath = os.path.join(sys.path[0], 'config', 'YuSu.cmp') if not os.path.exists(cmpPath) or not os.path.isfile(cmpPath): log(LogLevel.error, 'Can not find YuSu.cmp file!') sys.exit(-1) return cmpPath
def get_static_id(self): self.curs.execute('SELECT cid FROM commands WHERE cid < 10000000 \ ORDER BY cid DESC LIMIT 1;') try: sid = int(self.curs.fetchone()[0]) except TypeError: sid = 0 util.log("New deployment") return sid + 1
def read_next_commands(self, number): res = [] try: for row in self.curs.execute("SELECT * FROM commands WHERE status='NEW' ORDER BY schedule LIMIT ?;", (number,)).fetchall(): res.append(self.to_command(row)) except sqlite3.OperationalError as oe: util.log(oe.message) return res
def run(): util.log('Twitter process started') i = 1 while True: respond() sleep(3) i += 1 if i == 10: register_latest_commands() i = 1
def get_chipId(path): if not os.path.exists(path): msg = '%s is not a available path!' % (path) log(LogLevel.error, msg) return False data = xml.dom.minidom.parse(path) root = data.documentElement # get 'general' node node = root.getElementsByTagName('general') return node[0].getAttribute('chip')
def execute_command(command): util.log("Command {} will be executed now".format(command.order)) com = {constants.COMMAND_SHOW: show, constants.COMMAND_LIGHTS: lights, constants.COMMAND_CANCEL: cancel } res = com[command.order](command.args) util.log(res) db.update_command_result(command.cid, res) return res
def read_next_commands(self, number): res = [] try: for row in self.curs.execute( "SELECT * FROM commands WHERE status='NEW' ORDER BY schedule LIMIT ?;", (number, )).fetchall(): res.append(self.to_command(row)) except sqlite3.OperationalError as oe: util.log(oe.message) return res
def get_completed_commands(self): res = [] try: for row in self.curs.execute( "SELECT * FROM commands WHERE status='COMPLETED';" ).fetchall(): res.append(self.to_command(row)) except sqlite3.OperationalError as oe: util.log(oe.message) return res
def read_current_commands(self): res = [] now = str(datetime.now()) try: for row in self.curs.execute("SELECT * FROM commands WHERE status='NEW' AND schedule<? ;", (now,)).fetchall(): res.append(self.to_command(row)) except sqlite3.OperationalError as oe: util.log(oe.message) return res
def insert_reading(self, values): val = tuple(values) try: self.curs.execute('INSERT INTO thin VALUES (?, ?, ?, ?, ?)', val) self.conn.commit() return 0 except sqlite3.IntegrityError: util.log('thin primary key violation') except sqlite3.OperationalError as oe: util.log(oe.message) return 1
def read_current_commands(self): res = [] now = str(datetime.now()) try: for row in self.curs.execute( "SELECT * FROM commands WHERE status='NEW' AND schedule<? ;", (now, )).fetchall(): res.append(self.to_command(row)) except sqlite3.OperationalError as oe: util.log(oe.message) return res
def get_all(self): try: t = self.get_temperature() p = self.get_pressure() h = self.get_humidity() return t, h, p except BTLEException as bte: util.log(bte.message) if 'disconnected' or 'connect()' in bte.message: if self.init(): self.get_all() return 0, 0, 0
def cancel_command(self, text): try: if text == 'all': for cid in self.curs.execute("SELECT cid FROM commands WHERE status='NEW'").fetchall(): self.update_command_status(cid[0], 'CANCELLED') else: cid = self.curs.execute("SELECT cid FROM commands WHERE message IS ? AND status='NEW' LIMIT 1", (text,)).fetchone() self.update_command_status(cid[0], 'CANCELLED') return 0 except sqlite3.OperationalError as oe: util.log(oe.message) return 1
def notify(message, username): ''' Notifies the user by sending a direct message on Twitter Parameters: message: notification text (string) username: the twitter name of the user to notify (string) ''' try: status = tweet.send_direct_message(user=username, text=message) util.log("Successfully sent message with id = " + str(status['id'])) return status['id'] except TwythonError as te: util.log("Could not send message due to Twython Error: " + te.msg) return 0
def get_reading(self, source='inside'): now = datetime.now() now = now.replace(hour=now.hour - 1) self.curs.execute('SELECT AVG(temp), AVG(hum) FROM thin WHERE source is ? AND date > ?\ ORDER BY date DESC LIMIT 3;', (source, str(now))) try: x = self.curs.fetchone() t, h = x except TypeError as te: util.log(te.message) return "No sensor readings recorded!" if t is None or h is None: raise ValueError return t, h
def parse(self): if not os.path.exists(self.__path): msg = '%s is not a available path!' % (self.__path) log(LogLevel.error, msg) return False data = xml.dom.minidom.parse(self.__path) root = data.documentElement # get 'general' node node = root.getElementsByTagName('general') # get chip name and project name ModuleObj.set_chipId(node[0].getAttribute('chip')) msg = 'Chip ID : %s' % (node[0].getAttribute('chip')) log(LogLevel.info, msg) msg = 'Project Info: %s' % ( node[0].getElementsByTagName('proj')[0].childNodes[0].nodeValue) log(LogLevel.info, msg) # initialize the objects mapping table self.init_objs() # get module nodes from DWS file nodes = node[0].getElementsByTagName('module') for node in nodes: tag = node.getAttribute('name') obj = self.create_obj(tag) if obj == None: msg = 'can not find %s node in DWS!' % (tag) log(LogLevel.error, msg) return False obj.parse(node) return True
def register_reading(source, t, h, p): if (t, h, p) != (0, 0, 0): if t > sc.TEMPERATURE_THRESHOLD: alarm_all_users("{} temperature of {}*C registered!".format(t, source)) if h > sc.HUMIDITY_THRESHOLD: alarm_all_users("{} humidity over {}%!".format(h, source)) values = [] values.append(str(dt.now())) values.append(t) values.append(h) values.append(p) values.append(source) return db.insert_reading(values) else: util.log("Invalid readings from {} sensor ".format(source))
def get_reading(self, source='inside'): now = datetime.now() now = now.replace(hour=now.hour - 1) self.curs.execute( 'SELECT AVG(temp), AVG(hum) FROM thin WHERE source is ? AND date > ?\ ORDER BY date DESC LIMIT 3;', (source, str(now))) try: x = self.curs.fetchone() t, h = x except TypeError as te: util.log(te.message) return "No sensor readings recorded!" if t is None or h is None: raise ValueError return t, h
def run(): util.log('Executor process started') while True: commands = db.read_current_commands() for command in commands: db.update_command_status(command.cid, constants.STATUS_IN_PROGRESS) res = execute_command(command) if res is not None: db.update_command_status(command.cid, constants.STATUS_COMPLETED) else: db.update_command_status(command.cid, constants.STATUS_FAILED) if command.order == constants.COMMAND_CANCEL: break util.log('Command {} executed successfully'.format(command.order)) sleep(1)
def cancel_command(self, text): try: if text == 'all': for cid in self.curs.execute( "SELECT cid FROM commands WHERE status='NEW'" ).fetchall(): self.update_command_status(cid[0], 'CANCELLED') else: cid = self.curs.execute( "SELECT cid FROM commands WHERE message IS ? AND status='NEW' LIMIT 1", (text, )).fetchone() self.update_command_status(cid[0], 'CANCELLED') return 0 except sqlite3.OperationalError as oe: util.log(oe.message) return 1
def read(self, node): nodes = node.childNodes try: for node in nodes: if node.nodeType == xml.dom.Node.ELEMENT_NODE: if cmp(node.nodeName, 'count') == 0: self.__count = node.childNodes[0].nodeValue continue varNode = node.getElementsByTagName('varName') detNode = node.getElementsByTagName('debounce_time') polNode = node.getElementsByTagName('polarity') senNode = node.getElementsByTagName('sensitive_level') deeNode = node.getElementsByTagName('debounce_en') dedNode = node.getElementsByTagName('dedicated_en') srcNode = node.getElementsByTagName('srcPin') sktNode = node.getElementsByTagName('socketType') data = Md1EintData() if len(varNode): data.set_varName(varNode[0].childNodes[0].nodeValue) if len(detNode): data.set_debounceTime( detNode[0].childNodes[0].nodeValue) if len(polNode): data.set_polarity(polNode[0].childNodes[0].nodeValue) if len(senNode): data.set_sensitiveLevel( senNode[0].childNodes[0].nodeValue) if len(deeNode): data.set_debounceEnable( deeNode[0].childNodes[0].nodeValue) if len(dedNode): data.set_dedicatedEn( dedNode[0].childNodes[0].nodeValue) if len(srcNode) and len(srcNode[0].childNodes): data.set_srcPin(srcNode[0].childNodes[0].nodeValue) if len(sktNode) and len(sktNode[0].childNodes): data.set_socketType(sktNode[0].childNodes[0].nodeValue) ModuleObj.set_data(self, node.nodeName, data) except: msg = 'read md1_eint content fail!' util.log(LogLevel.error, msg) return False return True
def read(self, node): nodes = node.childNodes try: for node in nodes: if node.nodeType == xml.dom.Node.ELEMENT_NODE: if node.nodeName == 'count': count = node.childNodes[0].nodeValue continue subNode = node.getElementsByTagName('varName') if len(subNode): ModuleObj.set_data(self, node.nodeName, subNode[0].childNodes[0].nodeValue) except: msg = 'read adc content fail!' log(LogLevel.error, msg) return False return True
def run(): util.log('Reader process started') tag_connected = sensortag.init() minutar = 0 while True: if minutar % sc.RECORDING_FREQUENCY == 0: minutar = 0 t, h, p = dth.instant_th() register_reading(dth.location, t, h, p) if tag_connected: t, h, p = sensortag.get_all() register_reading(sensortag.location, t, h, p) if gas.alarm() == 1: alarm_all_users('High levels of gas/smoke detected!') gas.read() sleep(60) minutar += 1
def fill_dtsiFile(self): gen_str = ClkObj.fill_dtsiFile(self) gen_str += '''\n''' gen_str += '''&rf_clock_buffer_ctrl {\n''' gen_str += '''\tmediatek,clkbuf-quantity = <%d>;\n''' % ( len(ModuleObj.get_data(self)) - ClkData._count) msg = 'rf clk buff count : %d' % (len(ModuleObj.get_data(self)) - ClkData._count) log(LogLevel.info, msg) gen_str += '''\tmediatek,clkbuf-config = <''' #sorted_list = sorted(ModuleObj.get_data(self).keys()) for key in sorted_key(ModuleObj.get_data(self).keys()): value = ModuleObj.get_data(self)[key] if key.find(self.__rf) != -1: gen_str += '''%d ''' % (ClkData._varList.index( value.get_varName())) gen_str = gen_str.rstrip() gen_str += '''>;\n''' gen_str += '''\tmediatek,clkbuf-driving-current = <''' for key in sorted_key(ModuleObj.get_data(self).keys()): value = ModuleObj.get_data(self)[key] if key.find(self.__rf) != -1: idx = value.get_curList().index(value.get_current()) if cmp(value.get_curList()[0], DEFAULT_AUTOK) == 0: idx -= 1 gen_str += '''%d ''' % (idx) gen_str.rstrip() gen_str += '''>;\n''' gen_str += '''\tstatus = \"okay\";\n''' gen_str += '''};\n''' return gen_str
def gen_spec(self, paras): # if cmp(paras[0], 'cust_dtsi') == 0: # self.gen_custDtsi() # return True for para in paras: if cmp(para, 'cust_dtsi') == 0: self.gen_custDtsi() continue idx = 0 name = '' if para.strip() != '': for value in para_map.values(): if para in value: name = para_map.keys()[idx] break idx += 1 if name != '': log(LogLevel.info, 'Start to generate %s file...' % (para)) obj = self.__objs[name] obj.gen_spec(para) log(LogLevel.info, 'Generate %s file successfully!' % (para)) else: log(LogLevel.warn, '%s can not be recognized!' % (para)) # sys.exit(-1) return True
def insert_command(self, com): c = (int(com.cid), com.order, str(com.data), str(com.schedule), com.commander, com.status, com.result) try: self.curs.execute("INSERT INTO commands VALUES(?, ?, ?, ?, ?, ?, ?);", c) self.conn.commit() util.log('Command %s registered successfully' % com.order) return 0 except sqlite3.IntegrityError as ie: util.log(ie.message) util.log('Command already in the database.') except sqlite3.OperationalError as oe: util.log(oe.message) return 1