def prepare_machine(num_nodes, single_edges, start, finish, alphabet): nodes = {'s' + str(i) for i in range(num_nodes)} edges = {'s' + str(i): dict() for i in range(num_nodes)} for from_, letter, to_ in single_edges: edges[from_].update({letter: to_}) return StateMachine(nodes, edges, start, finish, alphabet)
def test_machine(): m = StateMachine() assert 3 == m.execute(Command("c1", "x", 3)) assert 4 == m.execute(Command("c2", "x", 4)) assert 4 == m.execute(Command("c3", "x", None)) assert 3 == m.execute(Command("c1", None, None)) assert m.lookup(Command("c1", None, None)) == 3 assert m.lookup(Command("new", None, None)) is None
def __init__(self, id, config, queue_maxsize=10): self.logger.info( f"Setting up raft server with id {id}, configuration {config}.") directory = pathlib.Path( config[id]["dir"]) if config[id]["dir"] else None # persistent (log is internally persisted, so just need to persist the others) # Note: the log assumes all integer named files are log entries if directory and not directory.is_dir(): directory.mkdir() self.config_file = directory / "server-config.yaml" if directory else None if self.config_file and self.config_file.is_file(): with open(self.config_file) as f: config_from_file = yaml.load(f) if config_from_file["config"] != config or config_from_file[ "id"] != id: raise RaftServerInconsistentConfigError( config_from_file, id, config) else: config_from_file = {} self.id = config_from_file.get("id", id) self.config = config_from_file.get("config", config) self.currentTerm = config_from_file.get("currentTerm", 0) self.votedFor = config_from_file.get("votedFor", None) self.persist() self.log = (RaftLog(directory) if directory else RaftLog() ) # persists itself; but by above dir has been created # volatile self.commitIndex = 0 self.lastApplied = -1 self.state = Follower(self) self.leaderId = None self.clientsockets = {i: None for i, _ in self.config.items()} self.sendQueue = Queue(queue_maxsize) self.recvQueue = Queue(queue_maxsize) self.isRunning = True self.lock = threading.Lock() self.server_str = f"RaftServer({self.id})" self.slow_step = 0 self.machine = StateMachine()
def main(args): # Initialize main transport transport = get_transport(args.transport, args.path) # Initialize hardware (screen, buttons) but = Buttons(hw=args.shield, stdin=not args.shield, pygame=not args.shield) buff = DisplayBuffer(DISPLAY_WIDTH, DISPLAY_HEIGHT) display = Display(buff, spi=args.shield, virtual=not args.shield) display.init() # Initialize layout driver layout = Layout(buff) # Startup state machine and switch it to default state machine = StateMachine(args.keyfile, layout) display.refresh() # Main cycle while True: # Set True if device does something # False = device will sleep for a moment is_active = False try: # Read button states button = but.read() except KeyboardInterrupt: # User requested to close the app break if button is not None: print "Button", button is_active = True resp = machine.press_button(button) if resp is not None: print "Sending", resp transport.write(resp) # Handle main connection msg = transport.read() if msg is not None: print "Received", msg.__class__.__name__ # , msg resp = machine.process_message(msg) if resp is not None: print "Sending", resp.__class__.__name__, resp transport.write(resp) is_active = True # Display scrolling is_active |= layout.update() if layout.need_refresh: # Update display display.refresh() if not is_active: # Nothing to do, sleep for a moment time.sleep(0.1) # Close transports transport.close()
def main(args): # Initialize debuglink transport if args.debuglink: print "Starting debug connection on '%s'" % args.debuglink_path print "Debug connection is for unit tests only. NEVER use debug connection with real wallet!" debug_transport = get_transport(args.debuglink_transport, args.debuglink_path) else: debug_transport = get_transport('fake', None) # Initialize main transport transport = get_transport(args.transport, args.path) # Load persisted data. Create new wallet if file doesn't exist print "Loading wallet..." wallet = Wallet(args.wallet) print wallet.struct # Initialize hardware (screen, buttons) but = Buttons(hw=args.shield, stdin=not args.shield, pygame=not args.shield) buff = DisplayBuffer(DISPLAY_WIDTH, DISPLAY_HEIGHT) display = Display(buff, spi=args.shield, virtual=not args.shield) display.init() # Initialize layout driver layout = Layout(buff) # Startup state machine and switch it to default state machine = StateMachine(wallet, layout) #tx1 = proto.TxOutput(address='1BRMLAB7nryYgFGrG8x9SYaokb8r2ZwAsX', amount=112000000) #tx2 = proto.TxOutput(address='1MarekMKDKRb6PEeHeVuiCGayk9avyBGBB', amount=12340123400) #layout.show_transactions([tx1, tx2 ], False) display.refresh() # Main cycle while True: #d=datetime.now() #layout.show_message([d.strftime("%d %B %Y %H:%M:%S")],question=False) # Set True if device does something # False = device will sleep for a moment is_active = False try: # Read button states button = but.read() except KeyboardInterrupt: # User requested to close the app break # Handle debug link connection msg = debug_transport.read() if msg is not None: print "Received debuglink", msg.__class__.__name__, msg if isinstance(msg, proto.DebugLinkDecision): # Press the button button = msg.yes_no else: resp = machine.process_message(msg) if resp is not None: print "Sending debuglink", resp.__class__.__name__, resp debug_transport.write(resp) is_active = True ''' elif isinstance(msg, proto.DebugLinkGetState): # Report device state resp = machine.get_state(msg) print "Sending debuglink", resp.__class__.__name__, resp debug_transport.write(resp) else: raise Exception("Got unexpected object %s" % msg.__class__.__name__) ''' if button is not None: print "Button", button is_active = True resp = machine.press_button(button) if resp is not None: print "Sending", resp transport.write(resp) ''' if button == True: layout.show_transactions([tx1, tx2 ], False) layout.show_question_dummy() if button == False: layout.show_logo(logo) ''' # Handle main connection msg = transport.read() if msg is not None: print "Received", msg.__class__.__name__, msg resp = machine.process_message(msg) if resp is not None: print "Sending", resp.__class__.__name__, resp transport.write(resp) is_active = True # Display scrolling is_active |= layout.update() if layout.need_refresh: # Update display display.refresh() if not is_active: # Nothing to do, sleep for a moment time.sleep(0.1) # Save wallet file wallet.save() # Close transports transport.close() debug_transport.close()
import pygame from machine import StateMachine, State class Example(State): def __init__(self): # This will save the this instance to state machine State.__init__(self) # All draw code goes here def draw(self, surface): surface.fill((0, 40, 0)) # Process all event here def event(self, event): if event.type == pygame.QUIT: # call state machine self.state.machine.quit() if __name__ == '__main__': pygame.init() StateMachine.screen_center() # Create the state machine StateMachine('Example', 800, 600) # Create Example and set it to first state StateMachine.main_loop(Example()) pygame.quit()
def parse_machine(machine_info): return StateMachine(machine_info['nodes'], machine_info['edges'], machine_info['start'], machine_info['final'], machine_info['alphabet'])
def main(args): monkeypatch_google_protobuf_text_format() # Initialize debuglink transport if args.debuglink: print "Starting debug connection on '%s'" % args.debuglink_path print "Debug connection is for unit tests only. NEVER use debug connection with real wallet!" debug_transport = get_transport(args.debuglink_transport, args.debuglink_path) else: debug_transport = get_transport('fake', None) # Initialize main transport transport = get_transport(args.transport, args.path) # Load persisted data. Create new wallet if file doesn't exist print "Loading wallet..." storage = Storage(args.wallet, bootloader_mode=args.bootloader_mode) # storage.struct.settings.label = 'Slushova penezenka' print storage.struct # Initialize hardware (screen, buttons) but = Buttons(hw=args.shield, stdin=not args.shield, pygame=not args.shield) buff = DisplayBuffer(DISPLAY_WIDTH, DISPLAY_HEIGHT) display = Display(buff, spi=args.shield, virtual=not args.shield) display.init() # Initialize layout driver layout = Layout(buff, display) # Process exponential backoff if there was unsuccesfull PIN attempts if storage.get_pin_delay(): delay = storage.get_pin_delay() print "Waiting %s seconds until boot up" % delay layout.show_pin_backoff_progress(delay) # Startup state machine and switch it to default state machine = StateMachine(storage, layout) display.refresh() # Main cycle while True: try: # Read button states button = but.read() except KeyboardInterrupt: # User requested to close the app break # Set is_active=True if device does something # False = device will sleep for a moment to prevent CPU load # Set button=None to use event only for rendering # and hide it against state machine (is_active, button) = layout.update(button) # Handle debug link connection msg = debug_transport.read() if msg is not None: print "Received debuglink", msg.__class__.__name__, msg if isinstance(msg, proto.DebugLinkDecision): # Press the button button = msg.yes_no else: resp = machine.process_debug_message(msg) if resp is not None: print "Sending debuglink", resp.__class__.__name__, resp debug_transport.write(resp) is_active = True if button is not None: print "Button", button is_active = True resp = machine.press_button(button) if resp is not None: print "Sending", resp transport.write(resp) # Handle main connection msg = transport.read() if msg is not None: print "Received", msg.__class__.__name__, msg resp = machine.process_message(msg) if resp is not None: print "Sending", resp.__class__.__name__, resp transport.write(resp) is_active = True if not is_active: # Nothing to do, sleep for a moment time.sleep(0.05) # Close transports transport.close() debug_transport.close()
# This will save the this instance to state machine BaseState.__init__(self, 'Intro') # All draw code goes here def draw(self, surface): surface.fill((0, 0, 40)) surface.blit(self.text, self.text_rect) class Intro(BaseState): def __init__(self): # This will save the this instance to state machine BaseState.__init__(self, 'Game') # All draw code goes here def draw(self, surface): surface.fill((0, 40, 0)) surface.blit(self.text, self.text_rect) if __name__ == '__main__': pygame.init() StateMachine.screen_center() # Create the state machine StateMachine('Example Flip', 800, 600) # Create states Game() # Create Intro and set it to first state StateMachine.main_loop(Intro()) pygame.quit()
def main(args): # Initialize debuglink transport if args.debuglink: print "Starting debug connection on '%s'" % args.debuglink_path print "Debug connection is for unit tests only. NEVER use debug connection with real wallet!" debug_transport = get_transport(args.debuglink_transport, args.debuglink_path) else: debug_transport = get_transport('fake', None) # Initialize main transport transport = get_transport(args.transport, args.path) # Load persisted data. Create new wallet if file doesn't exist print "Loading wallet..." wallet = Wallet(args.wallet) print wallet.struct # Initialize hardware (screen, buttons) but = Buttons(hw=args.shield, stdin=not args.shield, pygame=not args.shield) buff = DisplayBuffer(DISPLAY_WIDTH, DISPLAY_HEIGHT) display = Display(buff, spi=args.shield, virtual=not args.shield) display.init() # Initialize layout driver layout = Layout(buff) # Startup state machine and switch it to default state machine = StateMachine(wallet, layout) #tx1 = proto.TxOutput(address='1BRMLAB7nryYgFGrG8x9SYaokb8r2ZwAsX', amount=112000000) #tx2 = proto.TxOutput(address='1MarekMKDKRb6PEeHeVuiCGayk9avyBGBB', amount=12340123400) #layout.show_transactions([tx1, tx2 ], False) display.refresh() # Main cycle while True: # Set True if device does something # False = device will sleep for a moment is_active = False try: # Read button states button = but.read() except KeyboardInterrupt: # User requested to close the app break # Handle debug link connection msg = debug_transport.read() if msg != None: print "Received debuglink", msg.__class__.__name__, msg if isinstance(msg, proto.DebugLinkDecision): # Press the button button = msg.yes_no else: resp = machine.process_debug_message(msg) if resp != None: print "Sending debuglink", resp.__class__.__name__, resp debug_transport.write(resp) is_active = True ''' elif isinstance(msg, proto.DebugLinkGetState): # Report device state resp = machine.get_state(msg) print "Sending debuglink", resp.__class__.__name__, resp debug_transport.write(resp) else: raise Exception("Got unexpected object %s" % msg.__class__.__name__) ''' if button != None: print "Button", button is_active = True resp = machine.press_button(button) if resp != None: print "Sending", resp transport.write(resp) ''' if button == True: layout.show_transactions([tx1, tx2 ], False) layout.show_question_dummy() if button == False: layout.show_logo(logo) ''' # Handle main connection msg = transport.read() if msg != None: print "Received", msg.__class__.__name__, msg resp = machine.process_message(msg) if resp != None: print "Sending", resp.__class__.__name__, resp transport.write(resp) is_active = True # Display scrolling is_active |= layout.update() if layout.need_refresh: # Update display display.refresh() if not is_active: # Nothing to do, sleep for a moment time.sleep(0.1) # Save wallet file wallet.save() # Close transports transport.close() debug_transport.close()
def main(): pygame.init() StateMachine.screen_center() StateMachine("Test", 800, 600) Test2() StateMachine.main_loop(Test())