def start_sims(): if not os.path.exists(log_path): os.mkdir(log_path) if del_log_before_start: del_all_files(log_path) addr_len = 0 if bind_self: addr_list = get_connected_ipv4_list() addr_len = len(addr_list) mac_mid = "Air" # Ascii of "Air_" mac_head = ("%s%s" % (mac_prefix[0:1], mac_mid)) for i in range(0, sim_num): #mac_tmp = mac_prefix + sim_type+"mac"+str(i) mac_tmp = ("%s%02x" % (mac_head, i)) log = MyLogger(join(log_path, '%s-%s.log' % (sim_type, mac_tmp)), clevel=eval(cl_level), flevel=eval(fl_level)) log.warn("device mac:%s" % (mac_tmp, )) sim = eval(sim_type) if bind_self and addr_len > 0: if force_dev_num and i >= addr_len: log.error("devices should not more than net cards number!") break addr_index = i % (addr_len) sim_temp = sim(logger=log, mac=mac_tmp, addr=rout_addr, self_addr=(addr_list[addr_index], int(start_port))) else: log.error("no any net card is connected!") sys.exit(-666) #sim_temp = sim(logger=log, mac=mac_tmp) #sim_temp.sdk_obj.heartbeat_interval = heartbeat_interval sim_temp.run_forever() device_online_list.append(sim_temp) if start_one_by_one: log.warn("press any key to start next devices") raw_input()
class Task(): def __init__(self, name='default-task', logger=None): self.tasks = {} self.lock = threading.RLock() if logger: self.LOG = logger else: self.LOG = MyLogger(name + '.log', clevel=logging.DEBUG) self.need_stop = False def stop(self): self.need_stop = True self.LOG.warn('Thread %s stoped!' % (__name__)) def add_task(self, name, func, run_times=1, interval=5, *argv): self.lock.acquire() if name and func and int(run_times) >= 1 and int(interval) >= 1: pass else: self.LOG.error("Invalid task: %s, run_times: %d, internal: %d" % (name, int(run_times), int(interval))) self.LOG.info("To add task: %s, run_times: %d, internal: %d" % (name, int(run_times), int(interval))) self.tasks[name] = { 'func': func, 'run_times': int(run_times), 'interval': int(interval), 'now_seconds': 0, 'argv': argv, 'state': 'active', 'name': name } self.lock.release() def del_task(self, name): self.lock.acquire() self.LOG.warn("To delete task:%s" % (name)) if name in self.tasks: del self.tasks[name] self.lock.release() def show_tasks(self): if self.tasks: for task in self.tasks: self.LOG.info(task + ":") for item in sorted(self.tasks[task]): self.LOG.yinfo(" " + item.ljust(20) + ':' + str(self.tasks[task][item]).rjust(20)) else: self.LOG.warn("No task...") def task_proc(self): while self.need_stop == False: if len(self.tasks) == 0: self.LOG.debug("No task!\n") ''' for task in self.tasks: if self.tasks[task]['state'] == 'inactive': self.del_task(task) ''' try: self.lock.acquire() for task in self.tasks: if self.tasks[task]['state'] != 'active': continue self.tasks[task]['now_seconds'] += 1 if self.tasks[task]['now_seconds'] >= self.tasks[task][ 'interval']: if callable(self.tasks[task]['func']): # self.LOG.info("It is time to run %s: " % ( # task) + self.tasks[task]['func'].__name__ + str(self.tasks[task]['argv'])) self.tasks[task]['func']( *(self.tasks[task]['argv'])) elif callable(eval(self.tasks[task]['func'])): # self.LOG.info("It is time to run %s: " % ( # task) + self.tasks[task]['func'] + str(self.tasks[task]['argv'])) eval(self.tasks[task]['func'] + '(*' + str(self.tasks[task]['argv']) + ')') else: self.LOG.error( "Uncallable task: %s, will disable it!") self.tasks[task]['state'] = 'inactive' self.tasks[task]['now_seconds'] = 0 self.tasks[task]['run_times'] -= 1 if self.tasks[task]['run_times'] == 0: self.LOG.info("stop task:%s" % (task)) self.tasks[task]['state'] = 'inactive' else: pass self.lock.release() time.sleep(0.1) except RuntimeError: pass
j = 100000 req_id = i + 99000000 for uuid in uuids: req_id += j j += 1 msg = switch_control_msg(req_id, uuid, 'off') app.queue_out.put(msg) app.msgst[req_id]['send_time'] = datetime.datetime.now() app.queue_out.put(msg) LOG.info("send: " + msg.strip()) time.sleep(arg_handle.get_args('t2') / 1000.0) time.sleep(arg_handle.get_args('time_interval') / 1000.0) else: LOG.error('Not support device!') while not app.queue_out.empty(): time.sleep(1) time.sleep(5) pkg_lost = 0 pkg_lost_list = [] min_delay = 8888888888 max_delay = 0 total_delay = 0 for item in app.msgst: if 'delaytime' in app.msgst[item]: if app.msgst[item]['delaytime'] > max_delay: max_delay = app.msgst[item]['delaytime'] if app.msgst[item]['delaytime'] < min_delay:
#wifi_list = [('192.168.10.10',12345), ('192.168.10.13',12346), ('192.168.10.14',12347)] wifi_list = [('192.168.10.12', 12347)] mac_index = 0 for wk in wifi_list: try: mac_index += 1 newmac = arg_handle.get_args('mac') + str(mac_index) LOG.warn("mac:" + newmac + " bind IP:" + str(wk)) sim = Sim(logger=LOG, time_delay=arg_handle.get_args('time_delay'), mac=newmac, self_addr=wk) sim.run_forever() except Exception as e: LOG.error("bind rror:%s" % e) task_obj = Task('test-task', LOG) thread_list.append([task_obj.task_proc]) sys_proc() if arg_handle.get_args('debug'): dmsg = { "method": "dm_set", "req_id": 178237278, "nodeid": "wifi.main.alarm_confirm", "params": { "attribute": { "error_code": "3" } }
class TestCase(object): __metaclass__ = ABCMeta def _init_(self, name, log_dir): self.name = name self.log_dir = log_dir self.log_dir += os.path.sep + datetime.datetime.now().strftime('%Y%m%d_%H%M%S') + \ '-' + self.name + os.path.sep self.log_dir = common_APIs.dirit(self.log_dir) try: os.mkdir(self.log_dir) except Exception as er: print('Can not create log dir: %s\n[[%s]]' % ( self.log_dir, str(er))) sys.exit() # create the log obj self.LOG = MyLogger(self.log_dir + 'output.log', cenable=True, with_print=True) def setup(self): pass def teardown(self): pass #@istest #@with_setup(setup, teardown) def test(self): self.common_init() result = 0 try: result = self.run() # except Exception as e: # traceback.print_exc() # self.LOG.critical(str(e)) # assert False finally: self.common_cleanup() @abstractmethod def run(self): pass def common_init(self): pass def common_cleanup(self): pass def case_pass(self, success_info='pass'): self.LOG.info(success_info) assert True return True def case_fail(self, error_info='fail'): self.LOG.error(error_info) assert False return False def do_setup(self, config_data): self.LOG.info('call do_setup') if 'setup' in config_data: self.LOG.info('Maybe have data') setup_list = config_data['setup'] for i in setup_list: for k in i: self.LOG.info(k) def do_run(self, config_data): self.LOG.info('call core') def do_teardown(self, config_data): self.LOG.info('call do_teardown')
return (400, {}, {}) if __name__ == "__main__": global LOG global cprint global arg_handle cprint = cprint() arg_handle = ArgHandle() arg_handle.run() LOG = MyLogger(os.path.abspath(sys.argv[0]).replace( 'py', 'log'), clevel=logging.DEBUG, fenable=False) picpath = "pics" if not os.path.exists(picpath): LOG.error('no pics dir!!!') sys.exit() msg = { "name": "小狗狗test", "userType": "1", "sex": "1", "idenType": "111", "birth": "", "idenNum": "211223198708080088", "nation": "1", "origin": "阿富汗", "phone": "18888888888", "email": "", "company": "", "dept": "",
time_delay=arg_handle.get_args('time_delay')) zigbee_obj.run_forever() sys_proc() device_list = arg_handle.get_args( 'device_type') # ['Led','Curtain','Switch'] if isinstance(device_list, list): while True: for device_cls in device_list: Sim = eval(device_cls) zigbee_obj.set_device(Sim) time.sleep(arg_handle.get_args('switch_interval')) elif isinstance(device_list, str): Sim = eval(device_list) zigbee_obj.set_device(Sim) else: LOG.error("type of device_list is %s" % type(device_list)) if arg_handle.get_args('debug'): dmsg = b'\x55\xaa\x10\x27\x01\x11\x22\x33\x77\x88\x99\x11\x33\x55\x66\x22\x88\x11\x11' time.sleep(1) zigbee_obj.queue_in.put(dmsg) if True: # signal.signal(signal.SIGINT, lambda signal, # frame: cprint.notice_p('Exit SYSTEM: exit')) my_cmd = MyCmd(logger=LOG, sim_objs=zigbee_obj.devices) my_cmd.cmdloop() else: sys_join() sys_cleanup() sys.exit()