对于时间来说可以写一个线程单独运行每一秒给显示终端推送当前的时间就好了,但是如果这个时候要显示别的内容该如何解决呢。
这里采取了有限自动机的思路
这样就可以在系统内维护一个有限自动机,然后通过对于当前状态的判断显示正确的内容。
class ShowSys: def __init__(self): # 0 for time mode 1 for recipe mode # 自动机设计 self.mode = 0 self.mode2index = {'time_s': 0, 'recipe_s': 1, 'clear_s': 2} self.index2mode = {0: 'time_s', 1: 'recipe_s', 2: 'clear_s'} self.update_map = [{'recipe': 'recipe_s'}, {'clear': 'clear_s'}, {'recipe': 'recipe_s', 'time': 'time_s'}] self.string_map = {} for item in self.mode2index: self.string_map.update({item: ''}) self.show_driver = ShowDriver() self.timer = Timer(self) self.handler = partial(ShowHandler, self) server_address = ('', 9999) self.httpd = HTTPServer(server_address, self.handler) self.httpd_thread = HTTPServerThread(self.httpd) def run(self): self.httpd_thread.start() self.timer.start() def show(self): cur_state = self.index2mode.get(self.mode) show_string = self.string_map.get(cur_state) self.show_driver.show(show_string) def deal_message(self, me_type, string): self.update_string_map(me_type, string) self.change_mode(me_type) self.show() def action_to_situation(self, action): return action + '_s' def update_string_map(self, me_type, string): self.string_map.update({self.action_to_situation(me_type): string}) def change_mode(self, action): future_state = self.update_map[self.mode].get(action) if future_state: self.mode = self.mode2index.get(future_state)