コード例 #1
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
コード例 #2
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)