File: lightswitch.py

package info (click to toggle)
automat 25.4.16-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 492 kB
  • sloc: python: 3,657; makefile: 15
file content (60 lines) | stat: -rw-r--r-- 1,340 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from operator import itemgetter

from automat import MethodicalMachine


class LightSwitch(object):
    machine = MethodicalMachine()

    @machine.state(serialized="on")
    def on_state(self):
        "the switch is on"

    @machine.state(serialized="off", initial=True)
    def off_state(self):
        "the switch is off"

    @machine.input()
    def flip(self):
        "flip the switch"

    on_state.upon(flip, enter=off_state, outputs=[])
    off_state.upon(flip, enter=on_state, outputs=[])

    @machine.input()
    def query_power(self):
        "return True if powered, False otherwise"

    @machine.output()
    def _is_powered(self):
        return True

    @machine.output()
    def _not_powered(self):
        return False

    on_state.upon(
        query_power, enter=on_state, outputs=[_is_powered], collector=itemgetter(0)
    )
    off_state.upon(
        query_power, enter=off_state, outputs=[_not_powered], collector=itemgetter(0)
    )

    @machine.serializer()
    def save(self, state):
        return {"is-it-on": state}

    @machine.unserializer()
    def _restore(self, blob):
        return blob["is-it-on"]

    @classmethod
    def from_blob(cls, blob):
        self = cls()
        self._restore(blob)
        return self


if __name__ == "__main__":
    l = LightSwitch()
    print(l.query_power())