Esempio n. 1
0
    def __init__(self,
                 logger,
                 config_file,
                 server_addr,
                 N=0,
                 tt=None,
                 encrypt_flag=0,
                 self_addr=None):
        super(Dev, self).__init__(logger)
        module_name = "protocol.config.%s" % config_file
        mod = import_module(module_name)
        self.sim_config = mod
        self.LOG = logger
        self.N = N
        self.tt = tt
        self.encrypt_flag = encrypt_flag
        self.attribute_initialization()
        self.sdk_obj = SDK(logger=logger,
                           addr=server_addr,
                           encrypt_flag=self.encrypt_flag,
                           self_addr=self_addr)
        self.sdk_obj.sim_obj = self
        self.sdk_obj.device_id = self._deviceID
        self.need_stop = False

        # state data:
        self.task_obj = Task('Washer-task', self.LOG)
        self.dev_register = False
        self.command_list = getattr(self.sim_config, "Command_list")
        self.create_tasks()
Esempio n. 2
0
    def __init__(self, config_file, logger, N=0, tt=None, encrypt_flag=0):
        super(Door, self).__init__(logger, encrypt_flag=encrypt_flag)
        module_name = "protocol.config.%s" % config_file
        mod = import_module(module_name)
        self.sim_config = mod
        self.LOG = logger
        self.N = N
        self.tt = tt
        self.encrypt_flag = encrypt_flag
        self.attribute_initialization()
        self.device_id = self._deviceID
        self.msgst = defaultdict(lambda: {})

        # state data:
        self.task_obj = Task('Washer-task', self.LOG)
        self.dev_register = False
        self.command_list = getattr(self.sim_config, "Command_list")
        # self.create_tasks()

        self.msgs = []
        for msg_name in self.test_msgs["msgs"]:
            tmp_msg = msg_name.split('.')
            if tmp_msg[0] == 'COM_UPLOAD_DEV_STATUS':
                msg = self.get_upload_status()
            elif tmp_msg[0] == 'COM_UPLOAD_RECORD':
                msg = self.get_upload_record(tmp_msg[-1])
            elif tmp_msg[0] == 'COM_UPLOAD_EVENT':
                msg = self.get_upload_event(tmp_msg[-1])

            for i in range(self.test_msgs["msgs"][msg_name]):
                self.msgs.append(msg)
        self.msgs *= self.test_msgs["round"]
        random.shuffle(self.msgs)
Esempio n. 3
0
    def __init__(self, logger):
        self.LOG = logger
        self.sdk_obj = None
        self.need_stop = False

        # state data:
        self.task_obj = Task('common-task', self.LOG)
        self.create_tasks()
Esempio n. 4
0
    def __init__(self, logger):
        self.LOG = logger
        self.sdk_obj = None
        self.need_stop = False

        # state data:
        self.task_obj = Task('Washer-task', self.LOG)
        self.create_tasks()
        self.alarm_dict = defaultdict(dict)
Esempio n. 5
0
    def __init__(self, logger, config_file, server_addr, self_addr=None, N=0):
        super(Door, self).__init__(logger)
        module_name = "protocol.config.%s" % config_file
        mod = __import__(module_name)
        components = module_name.split('.')
        for comp in components[1:]:
            mod = getattr(mod, comp)
        self.sim_config = mod
        self.LOG = logger
        self.N = N
        self.attribute_initialization()
        self.sdk_obj = SDK(addr=server_addr,
                           logger=logger,
                           time_delay=0,
                           self_addr=self_addr)
        self.sdk_obj.sim_obj = self
        self.sdk_obj.device_id = self._deviceID
        self.need_stop = False

        # state data:
        self.task_obj = Task('Washer-task', self.LOG)
        self.dev_register = False
        self.command_list = getattr(self.sim_config, "Command_list")
        self.create_tasks()
Esempio n. 6
0
class Door(BaseSim):
    def __init__(self, config_file, logger, N=0, tt=None, encrypt_flag=0):
        super(Door, self).__init__(logger, encrypt_flag=encrypt_flag)
        module_name = "protocol.config.%s" % config_file
        mod = import_module(module_name)
        self.sim_config = mod
        self.LOG = logger
        self.N = N
        self.tt = tt
        self.encrypt_flag = encrypt_flag
        self.attribute_initialization()
        self.device_id = self._deviceID
        self.msgst = defaultdict(lambda: {})

        # state data:
        self.task_obj = Task('Washer-task', self.LOG)
        self.dev_register = False
        self.command_list = getattr(self.sim_config, "Command_list")
        # self.create_tasks()

        self.msgs = []
        for msg_name in self.test_msgs["msgs"]:
            tmp_msg = msg_name.split('.')
            if tmp_msg[0] == 'COM_UPLOAD_DEV_STATUS':
                msg = self.get_upload_status()
            elif tmp_msg[0] == 'COM_UPLOAD_RECORD':
                msg = self.get_upload_record(tmp_msg[-1])
            elif tmp_msg[0] == 'COM_UPLOAD_EVENT':
                msg = self.get_upload_event(tmp_msg[-1])

            for i in range(self.test_msgs["msgs"][msg_name]):
                self.msgs.append(msg)
        self.msgs *= self.test_msgs["round"]
        random.shuffle(self.msgs)

    async def run_forever(self):
        while True:
            await self.msg_dispatch()
            await self.schedule()
            await self.send_data_once()
            if self.tt:
                await asyncio.sleep(self.tt / 1000.0)
            else:
                await asyncio.sleep(self.test_msgs["interval"] / 1000.0)

    def create_tasks(self):
        self.task_obj.add_task(
            'status maintain', self.status_maintain, 10000000, 100)

        self.task_obj.add_task('monitor status report',
                               self.status_report_monitor, 10000000, 1)

        self.task_obj.add_task(
            'heartbeat', self.to_send_heartbeat, 1000000, 6000)

    async def msg_dispatch(self):
        try:
            msg = self.msgs.pop()
            if self.dev_register == False:
                pass
            else:
                self.to_to_send_msg(msg, ack=b'\x00')
        except:
            pass

    def status_maintain(self):
        for item in self.SPECIAL_ITEM:
            if "maintain" not in self.SPECIAL_ITEM[item]["use"]:
                continue
            if self.__dict__[item] != self.SPECIAL_ITEM[item]["init_value"]:
                tmp_item = '_current_time_' + item
                if '_current_time_' + item in self.__dict__:
                    if self.__dict__[tmp_item] > 0:
                        self.set_item(tmp_item, self.__dict__[tmp_item] - 1)
                        if self.__dict__[tmp_item] <= 0:
                            self.set_item(
                                tmp_item, self.SPECIAL_ITEM[item]["wait_time"])
                            self.set_item(
                                item, self.SPECIAL_ITEM[item]["init_value"])
                    else:
                        self.set_item(
                            item, self.SPECIAL_ITEM[item]["init_value"])
                else:
                    self.add_item('_current_time_' + item,
                                  self.SPECIAL_ITEM[item]["wait_time"])

    def status_report_monitor(self):
        need_send_report = False
        if not hasattr(self, 'old_status'):
            self.old_status = defaultdict(lambda: {})
            for item in self.__dict__:
                if item in self.SPECIAL_ITEM and "report" in self.SPECIAL_ITEM[item]["use"]:
                    self.LOG.yinfo("need check item: %s" % (item))
                    self.old_status[item] = copy.deepcopy(self.__dict__[item])

        for item in self.old_status:
            if self.old_status[item] != self.__dict__[item]:
                need_send_report = True
                self.old_status[item] = copy.deepcopy(self.__dict__[item])

        if need_send_report:
            self.send_msg(self.get_upload_status(), ack=b'\x00')

    def to_register_dev(self):
        if self.dev_register:
            self.LOG.info(common_APIs.chinese_show("设备已经注册"))
        else:
            self.LOG.info(common_APIs.chinese_show("发送设备注册"))
            self.to_to_send_msg(json.dumps(
                self.get_send_msg('COM_DEV_REGISTER')), ack=b'\x00')

    async def to_send_heartbeat(self):
        await asyncio.sleep(60)
        self.to_to_send_msg(json.dumps(
            self.get_send_msg('COM_HEARTBEAT')), ack=b'\x00')

    def get_upload_status(self):
        # self.LOG.info(common_APIs.chinese_show("设备状态上报"))
        return json.dumps(self.get_send_msg('COM_UPLOAD_DEV_STATUS'))

    def get_upload_record(self, record_type):
        # self.LOG.info(common_APIs.chinese_show("记录上传"))
        report_msg = self.get_send_msg('COM_UPLOAD_RECORD')
        report_msg["Data"][0]["RecordType"] = record_type
        report_msg["EventCode"] = record_type
        return json.dumps(report_msg)

    def get_upload_event(self, event_type):
        # self.LOG.info(common_APIs.chinese_show("事件上报"))
        report_msg = self.get_send_msg('COM_UPLOAD_EVENT')
        report_msg["Data"][0]["EventType"] = event_type
        report_msg["EventCode"] = event_type
        return json.dumps(report_msg)

    def dev_protocol_handler(self, msg, ack=False):
        if ack:
            self.update_msgst(msg['Command'], 'rsp')
            if msg['Command'] == 'COM_DEV_REGISTER':
                if msg['Result'] == 0:
                    self.dev_register = True
                    # decrypt
                    if self.encrypt_flag:
                        self.add_item('_encrypt_key', msg['Data'][0]['aeskey'])
                    self.LOG.warn(common_APIs.chinese_show("设备已经注册"))
                    return None
                else:
                    self.dev_register = False
                    self.LOG.warn(common_APIs.chinese_show("设备注册失败"))
                    return None
            else:
                return None
        else:
            self.update_msgst(msg['Command'], 'req')

        if msg['Command'] == 'COM_HEARTBEAT':
            pass
        elif msg['Command'] in self.command_list:
            self.set_items(msg['Command'], msg)
            rsp_msg = self.get_rsp_msg(msg['Command'])
            self.update_msgst(msg['Command'], 'rsp')
            return json.dumps(rsp_msg)
        else:
            self.LOG.warn('Unknow msg: %s!' % (msg['Command']))
            return None

    def get_msg_by_command(self, command):
        command = getattr(self.sim_config, command)
        command_str = str(command)
        command_str = re.sub(r'\'TIMENOW\'', '"%s"' % datetime.datetime.now().strftime(
            '%Y-%m-%d %H:%M:%S'), command_str)
        command_str = re.sub(r'\'randint1\'', '"%s"' %
                             random.randint(0, 1), command_str)
        return eval(command_str.replace("'##", "").replace("##'", ""))

    def get_record_list(self):
        return getattr(self.sim_config, "defined_record")

    def get_event_list(self):
        return getattr(self.sim_config, "defined_event")

    def get_send_msg(self, command):
        return self.get_msg_by_command(command)['send_msg']

    def get_rsp_msg(self, command):
        return self.get_msg_by_command(command)['rsp_msg']

    def set_items(self, command, msg):
        item_dict = self.get_msg_by_command(command)['set_item']
        for item, msg_param in item_dict.items():
            msg_param_list = msg_param.split('.')
            tmp_msg = msg[msg_param_list[0]]
            for i in msg_param_list[1:]:
                if re.match(r'\d+', i):
                    i = int(i)
                tmp_msg = tmp_msg[i]
            self.set_item(item, tmp_msg)

    def attribute_initialization(self):
        attribute_params_dict = getattr(
            self.sim_config, "Attribute_initialization")
        for attribute_params, attribute_params_value in attribute_params_dict.items():
            self.add_item(attribute_params, attribute_params_value)

        self._mac = self.mac_list[self.N]
        #"_deviceID": "1005200958FCDBDA5380",
        #"_subDeviceID": "301058FCDBDA53800001",
        self._deviceID = str(self.DeviceFacturer) + \
            str(self.DeviceType) + self._mac.replace(":", '')
        self._encrypt_key = self._deviceID[-16:].encode('utf-8')
        #self._decrypt_key = self._deviceID[-16:].encode('utf-8')
        self._subDeviceID = str(self.subDeviceType) + \
            self._mac.replace(":", '') + "%04d" % (self.N + 1)
Esempio n. 7
0
class BaseSim():
    __metaclass__ = ABCMeta
    status_lock = threading.Lock()

    def __init__(self, logger):
        self.LOG = logger
        self.sdk_obj = None
        self.need_stop = False

        # state data:
        self.task_obj = Task('common-task', self.LOG)
        self.create_tasks()

    @common_APIs.need_add_lock(status_lock)
    def set_item(self, item, value):
        if item in self.__dict__:
            self.__dict__[item] = value
        else:
            self.LOG.error("Unknow item: %s" % (item))

    @common_APIs.need_add_lock(status_lock)
    def add_item(self, item, value):
        try:
            setattr(self, item, value)
        except:
            self.LOG.error("add item fail: %s" % (item))

    def status_show(self):
        for item in sorted(self.__dict__):
            if item.startswith('_'):
                self.LOG.warn("%s: %s" % (item, str(self.__dict__[item])))

    def send_msg(self, msg):
        return self.sdk_obj.add_send_data(self.sdk_obj.msg_build(msg))

    @abstractmethod
    def protocol_handler(self, msg, ack=False):
        pass

    def stop(self):
        self.need_stop = True
        self.sdk_obj.stop()
        if self.task_obj:
            self.task_obj.stop()
        self.LOG.warn('Thread %s stoped!' % (__name__))

    def run_forever(self):
        thread_list = []
        thread_list.append([self.task_obj.task_proc])
        thread_list.append([self.status_report_monitor])
        thread_ids = []
        for th in thread_list:
            thread_ids.append(threading.Thread(target=th[0], args=th[1:]))

        for th in thread_ids:
            th.setDaemon(True)
            th.start()

    def create_tasks(self):
        self.task_obj.add_task('status maintain', self.status_maintain,
                               10000000, 1)

        # self.task_obj.add_task('monitor event report',
        #                       self.status_report_monitor, 10000000, 1)

    def status_maintain(self):
        pass

    def status_report_monitor(self):
        while self.need_stop == False:
            need_send_report = []
            if not hasattr(self, 'old_status'):
                self.old_status = defaultdict(lambda: {})
                for item in self.__dict__:
                    if item.startswith('_'):
                        self.LOG.yinfo("need check item: %s" % (item))
                        self.old_status[item] = copy.deepcopy(
                            self.__dict__[item])

            for item in self.old_status:
                if self.old_status[item] != self.__dict__[item]:
                    need_send_report.append(item)
                    self.old_status[item] = copy.deepcopy(self.__dict__[item])

            for item in need_send_report:
                self.LOG.warn('Device report: %s' % (item))
                self.event_report_proc(item)

    def get_default_response(self, datas):
        def_rsp = {
            'control': bit_set(datas['control'], 7),
            'seq': datas['seq'],
            'addr': self.sdk_obj.src_addr,
            'cmd': datas['cmd'],
            'reserve': b'',
            'data': b'',
        }
        return def_rsp

    def add_seq(self):
        seq = struct.unpack('B', self.seq)[0]
        seq += 1
        if seq >= 255:
            seq = 0
        self.seq = struct.pack('B', seq)

    def set_seq(self, seq):
        self.seq = seq

    def convert_to_dictstr(self, src):
        ret_str = ''
        ret_str += '\n{\n'
        for item in src:
            ret_str += protocol_data_printB(src[item],
                                            title="    %s," % (item))
            ret_str += '\n'
        ret_str += '}'
        return ret_str

    def get_event_report(self,
                         req_cmd_word=b'\x0a' + b'\x06\x00' + b'\x00\x00',
                         data=b'\x10\x01'):
        self.add_seq()
        send_datas = {
            'control': b'\x00',
            'seq': self.seq,
            'addr': self.addr,
            'cmd': req_cmd_word,
            'reserve': b'',
            'data': data,
        }
        return send_datas
Esempio n. 8
0
    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"
                }
            }
        }
Esempio n. 9
0
class Door(BaseSim):
    def __init__(self, logger, config_file, server_addr, self_addr=None, N=0):
        super(Door, self).__init__(logger)
        module_name = "protocol.config.%s" % config_file
        mod = __import__(module_name)
        components = module_name.split('.')
        for comp in components[1:]:
            mod = getattr(mod, comp)
        self.sim_config = mod
        self.LOG = logger
        self.N = N
        self.attribute_initialization()
        self.sdk_obj = SDK(addr=server_addr,
                           logger=logger,
                           time_delay=0,
                           self_addr=self_addr)
        self.sdk_obj.sim_obj = self
        self.sdk_obj.device_id = self._deviceID
        self.need_stop = False

        # state data:
        self.task_obj = Task('Washer-task', self.LOG)
        self.dev_register = False
        self.command_list = getattr(self.sim_config, "Command_list")
        self.create_tasks()

    def run_forever(self):
        thread_list = []
        thread_list.append([self.sdk_obj.schedule_loop])
        thread_list.append([self.sdk_obj.send_data_loop])
        thread_list.append([self.sdk_obj.recv_data_loop])
        thread_list.append([self.sdk_obj.heartbeat_loop])
        thread_list.append([self.task_obj.task_proc])
        thread_list.append([self.msg_dispatch])
        thread_ids = []
        for th in thread_list:
            thread_ids.append(threading.Thread(target=th[0], args=th[1:]))

        for th in thread_ids:
            th.setDaemon(True)
            th.start()

    def create_tasks(self):
        self.task_obj.add_task('status maintain', self.status_maintain,
                               10000000, 100)

        self.task_obj.add_task('monitor status report',
                               self.status_report_monitor, 10000000, 1)

        self.task_obj.add_task('dev register', self.to_register_dev, 1, 100)

        # self.task_obj.add_task(
        #    'check register', self.check_register_dev, 1, 10)

        self.task_obj.add_task('heartbeat', self.to_send_heartbeat, 1000000,
                               6000)

    def msg_dispatch(self):
        msgs = []

        for msg in self.test_msgs["msgs"]:
            for i in range(self.test_msgs["msgs"][msg]):
                msgs.append(msg)
        random.shuffle(msgs)
        for msg in msgs:
            self.LOG.debug(msg)

        count = 0
        while self.need_stop == False and count < self.test_msgs["round"]:
            count += 1
            for msg in msgs:
                time.sleep(self.test_msgs["interval"] / 1000.0)
                tmp_msg = msg.split('.')
                if tmp_msg[0] == 'COM_UPLOAD_DEV_STATUS':
                    self.send_msg(self.get_upload_status())
                elif tmp_msg[0] == 'COM_UPLOAD_RECORD':
                    self.send_msg(self.get_upload_record(tmp_msg[-1]))
                elif tmp_msg[0] == 'COM_UPLOAD_EVENT':
                    self.send_msg(self.get_upload_event(tmp_msg[-1]))
                else:
                    self.LOG.error("Unknow msg to dispatch: %s" % (msg))

    def status_maintain(self):
        for item in self.SPECIAL_ITEM:
            if "maintain" not in self.SPECIAL_ITEM[item]["use"]:
                continue
            if self.__dict__[item] != self.SPECIAL_ITEM[item]["init_value"]:
                tmp_item = '_current_time_' + item
                if '_current_time_' + item in self.__dict__:
                    if self.__dict__[tmp_item] > 0:
                        self.set_item(tmp_item, self.__dict__[tmp_item] - 1)
                        if self.__dict__[tmp_item] <= 0:
                            self.set_item(tmp_item,
                                          self.SPECIAL_ITEM[item]["wait_time"])
                            self.set_item(
                                item, self.SPECIAL_ITEM[item]["init_value"])
                    else:
                        self.set_item(item,
                                      self.SPECIAL_ITEM[item]["init_value"])
                else:
                    self.add_item('_current_time_' + item,
                                  self.SPECIAL_ITEM[item]["wait_time"])

    def status_report_monitor(self):
        need_send_report = False
        if not hasattr(self, 'old_status'):
            self.old_status = defaultdict(lambda: {})
            for item in self.__dict__:
                if item in self.SPECIAL_ITEM and "report" in self.SPECIAL_ITEM[
                        item]["use"]:
                    self.LOG.yinfo("need check item: %s" % (item))
                    self.old_status[item] = copy.deepcopy(self.__dict__[item])

        for item in self.old_status:
            if self.old_status[item] != self.__dict__[item]:
                need_send_report = True
                self.old_status[item] = copy.deepcopy(self.__dict__[item])

        if need_send_report:
            self.send_msg(self.get_upload_status())

    def to_register_dev(self):
        if self.dev_register:
            self.LOG.debug(common_APIs.chinese_show("设备已经注册"))
        else:
            self.LOG.debug(common_APIs.chinese_show("发送设备注册"))
            self.send_msg(json.dumps(self.get_send_msg('COM_DEV_REGISTER')))
            time.sleep(4)
            if self.dev_register:
                self.LOG.warn(common_APIs.chinese_show("设备已经注册"))
            else:
                self.LOG.error(common_APIs.chinese_show("设备注册失败"))
                sys.exit()

    def to_send_heartbeat(self):
        self.send_msg(json.dumps(self.get_send_msg('COM_HEARTBEAT')))

    def check_register_dev(self):
        if self.dev_register:
            self.LOG.yinfo(common_APIs.chinese_show("设备已经注册"))
        else:
            self.LOG.error(common_APIs.chinese_show("设备注册失败"))
            sys.exit()

    def get_upload_status(self):
        self.LOG.warn(common_APIs.chinese_show("设备状态上报"))
        return json.dumps(self.get_send_msg('COM_UPLOAD_DEV_STATUS'))

    def get_upload_record(self, record_type):
        self.LOG.warn(common_APIs.chinese_show("记录上传"))
        report_msg = self.get_send_msg('COM_UPLOAD_RECORD')
        report_msg["Data"][0]["RecordType"] = record_type
        report_msg["EventCode"] = record_type
        return json.dumps(report_msg)

    def get_upload_event(self, event_type):
        self.LOG.warn(common_APIs.chinese_show("事件上报"))
        report_msg = self.get_send_msg('COM_UPLOAD_EVENT')
        report_msg["Data"][0]["EventType"] = event_type
        report_msg["EventCode"] = event_type
        return json.dumps(report_msg)

    def protocol_handler(self, msg, ack=False):
        coding = sys.getfilesystemencoding()
        if ack:
            self.update_msgst(msg['Command'], 'rsp')
            if msg['Command'] == 'COM_DEV_REGISTER':
                if msg['Result'] == 0:
                    self.dev_register = True
                    return None
                else:
                    pass
            else:
                #self.LOG.warn('Unknow msg: %s!' % (msg['Command']))
                return None
        else:
            self.update_msgst(msg['Command'], 'req')

        if msg['Command'] in self.command_list:
            self.set_items(msg['Command'], msg)
            rsp_msg = self.get_rsp_msg(msg['Command'])
            self.update_msgst(msg['Command'], 'rsp')
            return json.dumps(rsp_msg)
        else:
            self.LOG.warn('Unknow msg: %s!' % (msg['Command']))
            return None

    def get_msg_by_command(self, command):
        command = getattr(self.sim_config, command)
        command_str = str(command)
        command_str = re.sub(
            r'\'TIMENOW\'',
            '"%s"' % datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            command_str)
        command_str = re.sub(r'\'randint1\'', '"%s"' % random.randint(0, 1),
                             command_str)
        return eval(command_str.replace("'##", "").replace("##'", ""))

    def get_record_list(self):
        return getattr(self.sim_config, "defined_record")

    def get_event_list(self):
        return getattr(self.sim_config, "defined_event")

    def get_send_msg(self, command):
        return self.get_msg_by_command(command)['send_msg']

    def get_rsp_msg(self, command):
        return self.get_msg_by_command(command)['rsp_msg']

    def set_items(self, command, msg):
        item_dict = self.get_msg_by_command(command)['set_item']
        for item, msg_param in item_dict.items():
            msg_param_list = msg_param.split('.')
            tmp_msg = msg[msg_param_list[0]]
            for i in msg_param_list[1:]:
                tmp_msg = tmp_msg[i]
            self.set_item(item, tmp_msg)

    def attribute_initialization(self):
        attribute_params_dict = getattr(self.sim_config,
                                        "Attribute_initialization")
        for attribute_params, attribute_params_value in attribute_params_dict.items(
        ):
            self.add_item(attribute_params, attribute_params_value)

        self._mac = self.mac_list[self.N]
        #"_deviceID": "1005200958FCDBDA5380",
        #"_subDeviceID": "301058FCDBDA53800001",
        self._deviceID = str(self.DeviceFacturer) + \
            str(self.DeviceType) + self._mac.replace(":", '')
        self._subDeviceID = str(self.subDeviceType) + \
            self._mac.replace(":", '') + "%04d" % (self.N + 1)
Esempio n. 10
0
    def __init__(self, config_file, logger, N=0, tt=None, encrypt_flag=0, self_ip=None, lp=None,
                 to=None, disp_sleep_s=10, change_creno=False):
        super(Door, self).__init__(logger, encrypt_flag=encrypt_flag)
        module_name = "protocol.config.%s" % config_file
        mod = import_module(module_name)
        self.sim_config = mod
        self.LOG = logger
        self.N = N
        self.tt = tt
        self.encrypt_flag = encrypt_flag
        self.attribute_initialization()

        self.device_id = self._deviceID
        # self.msgst = defaultdict(lambda: {})
        if self_ip:
            self._ip = self_ip
        # 心跳间隔默认30秒
        self.hbInv = 30
        # 处理间隔默认0.1秒
        self.procInv = 0.1

        # state data:
        self.task_obj = Task('Washer-task', self.LOG)
        self.dev_register = False
        self.command_list = getattr(self.sim_config, "Command_list")
        # self.create_tasks()

        self.lp = lp
        self.tMsg = "Start"
        self.summaryDict = self.getSummaryDict()
        # self.sleep_s = self.tt
        self.disp_sleep_s = disp_sleep_s
        self.beginTime = time.time()
        self.breakTime = to
        # 偏移量是偶数的才改,奇数的不改车牌
        # 为了保证偏移为1,3,5...N的出口车牌号与0,2,4...N-1的车牌号一致
        if change_creno:
            # 出入口车牌要同步递增
            creno = self.__getattribute__('_credenceNo')
            # print("creno_0:{}".format(creno))
            creno = creno[:2] + str(int(creno[2:]) + N // 2)
            # print("creno_1:{}".format(creno))
            self.__setattr__('_credenceNo', creno)
            # 出口上报要延迟半个周期
            if N & 0x1 != 0:
                # print("creno_2:{}".format(self.__getattribute__('_credenceNo')))
                # 多延迟半个周期的启动 tt的单位是毫秒,sleep_s的单位是秒所以要除以1000
                self.disp_sleep_s += self.tt / 1000 * 0.5
            # print("ID:{} NO:{}".format(self._deviceID, self._credenceNo))
            # print(self._credenceNo[-4:])
        self.msgs = []
        for msg_name in self.test_msgs["msgs"]:
            tmp_msg = msg_name.split('.')
            if tmp_msg[0] == 'COM_UPLOAD_DEV_STATUS':
                msg = self.get_upload_status()
            elif tmp_msg[0] == 'COM_UPLOAD_RECORD':
                msg = self.get_upload_record(tmp_msg[-1])
            elif tmp_msg[0] == 'COM_UPLOAD_EVENT':
                msg = self.get_upload_event(tmp_msg[-1])
            elif tmp_msg[0] == 'ADS_UPLOAD_DEV_INFO':
                msg = self.get_ads_upload_dev_info()
            else:
                raise NotImplementedError("Not found msg:{}".format(tmp_msg))

            # for i in range(self.test_msgs["msgs"][msg_name]):
            #     self.msgs.append(msg)
            msgInfo = common_APIs.msgs_info(tmp_msg, msg, self.test_msgs["msgs"][msg_name])
            msgInfo.num *= self.test_msgs["round"]
            # num<0 means run forever
            if msgInfo.num != 0:
                self.msgs.append(msgInfo)
        # self.msgs *= self.test_msgs["round"]
        # random.shuffle(self.msgs)
        self.LOG.info("device start!")
Esempio n. 11
0
class BaseSim():
    __metaclass__ = ABCMeta
    status_lock = threading.Lock()

    def __init__(self, logger):
        self.LOG = logger
        self.sdk_obj = None
        self.need_stop = False

        # state data:
        self.task_obj = Task('Washer-task', self.LOG)
        self.create_tasks()
        self.alarm_dict = defaultdict(dict)

    @common_APIs.need_add_lock(status_lock)
    def set_item(self, item, value):
        if item in self.__dict__:
            self.__dict__[item] = value
        else:
            self.LOG.error("Unknow item: %s" % (item))

    @common_APIs.need_add_lock(status_lock)
    def add_item(self, item, value):
        try:
            setattr(self, item, value)
        except:
            self.LOG.error("add item fail: %s" % (item))

    def status_show(self):
        for item in sorted(self.__dict__):
            if item.startswith('_'):
                self.LOG.warn("%s: %s" % (item, str(self.__dict__[item])))

    def send_msg(self, msg):
        return self.sdk_obj.add_send_data(self.sdk_obj.msg_build(msg))

    @abstractmethod
    def protocol_handler(self, msg, ack=False):
        pass

    def stop(self):
        self.need_stop = True
        self.sdk_obj.stop()
        if self.task_obj:
            self.task_obj.stop()
        self.LOG.warn('Thread %s stoped!' % (__name__))

    def run_forever(self):
        thread_list = []
        thread_list.append([self.sdk_obj.schedule_loop])
        thread_list.append([self.sdk_obj.send_data_loop])
        thread_list.append([self.sdk_obj.recv_data_loop])
        thread_list.append([self.sdk_obj.heartbeat_loop, False])
        thread_list.append([self.task_obj.task_proc])
        thread_list.append([self.alarm_proc])
        thread_ids = []
        for th in thread_list:
            thread_ids.append(threading.Thread(target=th[0], args=th[1:]))

        for th in thread_ids:
            th.setDaemon(True)
            th.start()

    def create_tasks(self):
        self.task_obj.add_task('status maintain', self.status_maintain,
                               10000000, 100)

        self.task_obj.add_task('monitor event report',
                               self.status_report_monitor, 10000000, 1)

    def status_maintain(self):
        pass

    def status_report_monitor(self):
        need_send_report = False
        if not hasattr(self, 'old_status'):
            self.old_status = defaultdict(lambda: {})
            for item in self.__dict__:
                if item.startswith('_'):
                    self.LOG.yinfo("need check item: %s" % (item))
                    self.old_status[item] = copy.deepcopy(self.__dict__[item])

        for item in self.old_status:
            if self.old_status[item] != self.__dict__[item]:
                need_send_report = True
                self.old_status[item] = copy.deepcopy(self.__dict__[item])

        if need_send_report:
            self.send_msg(self.get_event_report())

    def alarm_proc(self):
        while self.need_stop == False:
            alarm_lock.acquire()
            for alarm in self.alarm_dict:
                if self.alarm_dict[alarm]['status'] == 'ready':
                    self.alarm_dict[alarm]['status'] = "over"
                    self.send_msg(
                        self.alarm_report(
                            self.alarm_dict[alarm]['error_code'],
                            self.alarm_dict[alarm]['error_status'],
                            self.alarm_dict[alarm]['error_level'],
                            self.alarm_dict[alarm]['error_msg']))

                elif self.alarm_dict[alarm]['status'] == 'over':
                    pass

            alarm_lock.release()
            time.sleep(3)

    def alarm_report(self,
                     error_code,
                     error_status,
                     error_level=1,
                     error_msg="test alarm"):
        report_msg = {
            "method": "alarm",
            "attribute": {
                "error_code": error_code,
                "error_msg": error_msg,
                "error_level": error_level,
                "error_status": error_status,
            }
        }
        return json.dumps(report_msg)

    @common_APIs.need_add_lock(alarm_lock)
    def add_alarm(self,
                  error_code,
                  error_status,
                  error_level=1,
                  error_msg="test alarm"):
        if error_code in self.alarm_dict and self.alarm_dict[error_code][
                'status'] != 'over':
            pass
        else:
            self.alarm_dict[error_code]['error_code'] = error_code
            self.alarm_dict[error_code]['error_status'] = error_status
            self.alarm_dict[error_code]['error_level'] = error_level
            self.alarm_dict[error_code]['error_msg'] = error_msg
            self.alarm_dict[error_code]['status'] = 'ready'

    @common_APIs.need_add_lock(alarm_lock)
    def set_alarm(self, error_code, status):
        if error_code in self.alarm_dict:
            self.alarm_dict[error_code]['status'] = status
        else:
            self.LOG.error('error code not exist!')

    @common_APIs.need_add_lock(alarm_lock)
    def del_alarm(self, error_code):
        if error_code in self.alarm_dict:
            self.alarm_dict[error_code]['status'] = status
            self.LOG.error('Del error code: %s' % str(error_code))

    def alarm_confirm_rsp(self, req, error_code):
        self.LOG.warn(("故障(解除)上报确认:").encode(coding))
        self.set_alarm(error_code, 'over')
        rsp_msg = {
            "method": "dm_set",
            "req_id": req,
            "msg": "success",
            "code": 0,
            "attribute": {
                "error_code": error_code,
                "error_status": self.alarm_dict[error_code]["error_status"]
            }
        }
        return json.dumps(rsp_msg)

    def dm_set_rsp(self, req):
        rsp_msg = {
            "method": "dm_set",
            "req_id": req,
            "msg": "success",
            "code": 0
        }
        return json.dumps(rsp_msg)