Ga naar inhoud

event

Event dataclass #

Een Event is een gebeurtenis die plaatsvindt voor een bepaald toestel of component (device) op de micro:bit. Bijvoorbeeld een data update (event) van de accellerometer (toestel) of een druk (event) op een knop (toestel)

Zie kaspersmicrobit.services.v1_events voor de device ids en de event values voor de micro:bit v1, en kaspersmicrobit.services.v2_events voor de ids en valuesvan de micro:bit v2

Attributes:

  • device_id (int) –

    Het id van van het toestel of de component dat de gebeurtenis meldt

  • event_value (int) –

    De waarde van de gebeurtenis voor het gegeven toestel

Source code in src/kaspersmicrobit/services/event.py
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
@dataclass
class Event:
    """
    An Event takes place for a specific device or component (device) on the micro:bit.
    For example, a data update (event) from the accelerometer (device) or a press (event) on a button (device)

    See `kaspersmicrobit.services.v1_events` for the device ids and event values for the micro:bit v1, and
    `kaspersmicrobit.services.v2_events` for the ids and values of the micro:bit v2

    Attributes:
        device_id (int): The ID of the device or component reporting the event
        event_value (int): The value of the event for the given device
    """
    device_id: int
    event_value: int = 0

    @staticmethod
    def from_bytes(values: ByteData):
        return Event(
            int.from_bytes(values[0:2], "little"),
            int.from_bytes(values[2:4], "little")
        )

    def to_bytes(self) -> bytes:
        return self.device_id.to_bytes(2, "little") + self.event_value.to_bytes(2, "little")

    @staticmethod
    def list_from_bytes(values: ByteData) -> List['Event']:
        result = []
        for i in range(0, len(values), 4):
            result.append(Event.from_bytes(values[i:i + 4]))

        return result

    @staticmethod
    def list_to_bytes(values: List['Event']) -> bytes:
        result = bytes()
        for event in values:
            result += event.to_bytes()

        return result