from hub import methods, Global import threading import time import json class MessageListener(object): """ """ @staticmethod def decorate_method(client, userdata, message): """消息处理方法""" file_name = methods.now_string('%Y-%m-%d.log') log_file_path = f"/home/server/logs/{file_name}" log_dict = json.loads(message.payload) # methods.debug_log(f"MessageListener.20", f"#log_dict: {log_dict}") log_list = list() for i in range(1, 5): v = str(log_dict.get(str(i))) log_list.append(v) methods.write_text(log_file_path, '|'.join(log_list) + '\n', 'a') methods.debug_log(f"MessageListener.24", f"#message.payload: {json.loads(message.payload)}") @classmethod def start_check_loop(cls): # --- check --- save_dir = f"/home/server/logs" if not methods.is_dir(save_dir): out = methods.run_command(f'mkdir -p {save_dir}', callback=True) methods.debug_log('MessageListener.33', f"#out: {out}") Global.emqx.start_subscribe_loop( decorate_method=MessageListener.decorate_method, subscribe_topic='bg/log' ) @classmethod def run_background(cls, background_is=True): """""" p1 = threading.Thread(target=cls.start_check_loop) p1.start() if __name__ == '__main__': # --- test --- MessageListener.run_background()