python : statemachine

# -*- coding: utf-8 -*-
from statemachine import StateMachine, State
from glob import glob
import re

# regular
# https://www.cnblogs.com/wyh0923/p/13937138.html

current_supported_code = ('repeat', 'stv',)


class P750PatternDecode(StateMachine):
    state_start = State('start decode', initial=True)
    state_decode_import = State('decode import')
    state_decode_vector = State('decode vector')
    state_start_decode_content = State('start decode content')
    state_end_decode_content = State('end decode content')

    decode_import = state_start.to(state_decode_import)
    decode_vector = state_decode_import.to(state_decode_vector)
    start_decode_content = state_decode_vector.to(state_start_decode_content)
    end_decode = state_start_decode_content.to(state_end_decode_content)

    @staticmethod
    def read_fileline_generator(file, size=4096):
        while 1:
            # data = file.read(size)
            data = file.readline()
            if not data:
                break
            yield data

    def __init__(self, filename):
        super().__init__()
        self.filename = filename
        self.change = {}

    # iter(list), next
    def analysis(self):
        with open(self.filename, 'r+', encoding='utf-8') as f:
            for line in self.read_fileline_generator(f):
                newline = line.strip()
                if 0 == len(newline):
                    continue
                if newline.startswith('import'):
                    self.decode_import(newline)
                    continue
                if newline.startswith('{'):
                    self.start_decode_content(newline)
                    continue
                if newline.startswith('}'):
                    self.end_decode(newline)
                    continue
                if newline.startswith('vector'):
                    self.decode_vector(line)
                    continue
                if newline.startswith('//'):
                    continue
                if newline.find(';') == -1:
                    for newline2 in self.read_fileline_generator(f):
                        break
                    newline = newline + newline2.strip()
                self.decode_vectors(newline)

    def on_decode_import(self, line):
        rimport = re.match('^import[\s]+(\w+)[\s]+(\w+);$', line)
        if rimport is not None:
            tset = rimport.group(1)
            data = rimport.group(2)
            self[tset] = data
            # print(tset, data)

    def on_decode_vector(self, line):
        rimport = re.match('^vector[\s]+\((.+)\)[\n]$', line)
        if rimport is not None:
            rlist = rimport.group(1)
            result = [item.strip() for item in rlist.split(',')]
            self['pins'] = result[1:]

    def on_start_decode_content(self, line):
        print('received {')

    def on_end_decode(self, line):
        print('received }')

    def decode_vectors(self, line):
        if line.startswith('start_label'):
            self.decode_startlabel(line)
            return
        if line.startswith('>'):
            self.decode_one_vector(line)
            return
        if line.startswith(current_supported_code):
            print(line)
            pass
        # handle jump-label

    def decode_vector_with_code(self, line):
        pass

    def __getitem__(self, item):
        return self.change[item]

    def __setitem__(self, key, value):
        self.change[key] = value

    def decode_startlabel(self, line):
        rss = re.match('^start_label[\s]+(.*)[:](.*)', line)
        if rss is not None:
            value = rss.group(1)
            self['start_label'] = value
            value = rss.group(2)
            self.decode_one_vector(value)

    def decode_one_vector(self, line):
        rss = re.match('^>(.*);$', line)
        if rss is not None:
            result = rss.group(1).split()
            print(str(result))

    def __str__(self):
        # return self.change.__str__()
        return str(self.change)


# file_path = "craneL_idcode_20211109_module_0_750.atp"
file_path = "2.atp"

# multiprocess handling files
if __name__ == '__main__':
    # get all the files under a directory
    roots = glob('*.py')
    print(roots)

    decode = P750PatternDecode(file_path)
    # print(decode.current_state)
    # print(decode.current_state_value)

    if decode.current_state_value == decode.state_start.value:
        # print(decode.current_state_value)
        pass

    if decode.current_state == decode.state_start:
        print(decode.current_state_value)
        pass

    decode.analysis()
    print(decode)

状态机(state machine)是一种模型,用于描述对象在不同状态之间转换的行为。在软件开发中,状态机被广泛应用于事件驱动的应用程序中,如游戏开发、自动控制、通信协议等领域。 下面是一个简单的状态机模型: ![state machine model](https://cdn.jsdelivr.net/gh/tsyj8102/tuchuang/images/statemachine.png) 上图中,状态机包含三个状态:A、B、C,以及两个事件:event1、event2。状态机的初始状态为A,当事件event1发生时,状态机会从状态A转换到状态B;当事件event2发生时,状态机会从状态B转换到状态C。 在实际开发中,可以使用各种编程语言来实现状态机。下面是一个使用Python语言实现状态机的例子: ```python class StateMachine: def __init__(self, states, initial_state): self.states = states self.current_state = initial_state def transition(self, event): transitions = self.states[self.current_state] next_state = transitions.get(event, None) if next_state is None: raise ValueError("Invalid event") self.current_state = next_state # Example usage states = { "A": {"event1": "B"}, "B": {"event2": "C"}, "C": {} } machine = StateMachine(states, "A") machine.transition("event1") machine.transition("event2") ``` 在上面的例子中,我们首先定义了一个StateMachine类,用于表示状态机。在StateMachine类的构造函数中,我们传入了状态列表states和初始状态initial_state。在transition方法中,我们根据当前状态和传入的事件event来获取下一个状态,并将当前状态更新为下一个状态。 以上是状态机的简单介绍和Python实现例子,希望对你有所帮助。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值