-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathpandafieldpart.py
75 lines (65 loc) · 2.24 KB
/
pandafieldpart.py
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from typing import Any, Callable, Optional
from annotypes import Anno
from malcolm.core import (
Alarm,
BooleanMeta,
Part,
PartRegistrar,
TimeStamp,
VMeta,
snake_to_camel,
)
from ..pandablocksclient import PandABlocksClient
with Anno("Client for setting and getting field"):
AClient = PandABlocksClient
with Anno("Meta object to create attribute from"):
AMeta = VMeta
with Anno("Name of Block in TCP server"):
ABlockName = str
with Anno("Name of Field in TCP server"):
AFieldName = str
with Anno("Initial value of attribute"):
AInitialValue = Any
class PandAFieldPart(Part):
"""This will normally be instantiated by the PandABox assembly, not created
in yaml"""
def __init__(
self,
client: AClient,
meta: AMeta,
block_name: ABlockName,
field_name: AFieldName,
initial_value: AInitialValue = None,
) -> None:
part_name = field_name.replace(".", "_")
super().__init__(part_name)
self.client = client
self.meta = meta
self.block_name = block_name
self.field_name = field_name
self.attr = self.meta.create_attribute_model(initial_value)
self.pending_change = False
def setup(self, registrar: PartRegistrar) -> None:
super().setup(registrar)
attr_name = snake_to_camel(self.field_name.replace(".", "_"))
writeable_func: Optional[Callable]
if self.meta.writeable:
writeable_func = self.set_field
else:
writeable_func = None
registrar.add_attribute_model(attr_name, self.attr, writeable_func)
def handle_change(self, value: str, ts: TimeStamp) -> None:
value = self.attr.meta.validate(value)
if self.pending_change:
self.pending_change = False
if value == self.attr.value:
# Ignore this change
return
self.attr.set_value_alarm_ts(value, Alarm.ok, ts)
def set_field(self, value):
if isinstance(self.meta, BooleanMeta):
value = int(value)
# Mark the next change as a possible duplicate
self.pending_change = True
self.client.set_field(self.block_name, self.field_name, value)
self.attr.set_value(value)