|
| 1 | +""" |
| 2 | +Demonstration of implementing a custom Rule |
| 3 | +""" |
| 4 | + |
| 5 | +import logging |
| 6 | + |
| 7 | +from p4p import Value |
| 8 | +from p4p.server import Server |
| 9 | + |
| 10 | +from p4pillon.nt import NTScalar |
| 11 | +from p4pillon.rules import ( |
| 12 | + AlarmRule, |
| 13 | + BaseRule, |
| 14 | + RulesFlow, |
| 15 | + TimestampRule, |
| 16 | +) |
| 17 | +from p4pillon.rules.rules import check_applicable_init |
| 18 | +from p4pillon.thread.sharednt import SharedNT |
| 19 | + |
| 20 | +logger = logging.getLogger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +class IMatchRule(BaseRule): |
| 24 | + name = "imatch" |
| 25 | + fields = ["alarm"] |
| 26 | + |
| 27 | + def __init__(self, imatch: int | None = None): |
| 28 | + self._imatch = imatch |
| 29 | + |
| 30 | + @property |
| 31 | + def imatch(self): |
| 32 | + return self._imatch |
| 33 | + |
| 34 | + @imatch.setter |
| 35 | + def imatch(self, newval: int | None): |
| 36 | + self._imatch = newval |
| 37 | + |
| 38 | + @check_applicable_init |
| 39 | + def init_rule(self, newpvstate: Value) -> RulesFlow: |
| 40 | + # Check if imatch alarms are present and active! |
| 41 | + if not self._imatch: |
| 42 | + logger.debug("imatch not active") |
| 43 | + return RulesFlow.CONTINUE |
| 44 | + |
| 45 | + if self._imatch == newpvstate["value"]: |
| 46 | + newpvstate["alarm.severity"] = 2 |
| 47 | + newpvstate["alarm.message"] = "IMATCH" |
| 48 | + else: |
| 49 | + newpvstate["alarm.severity"] = 0 |
| 50 | + newpvstate["alarm.message"] = "" |
| 51 | + |
| 52 | + return RulesFlow.CONTINUE |
| 53 | + |
| 54 | + |
| 55 | +def main(): |
| 56 | + registered_handlers = [ |
| 57 | + AlarmRule, |
| 58 | + IMatchRule, # <-- This is the new rule |
| 59 | + TimestampRule, |
| 60 | + ] |
| 61 | + |
| 62 | + pv1 = SharedNT(nt=NTScalar("i"), initial=5, imatch={"imatch": 5}, registered_handlers=registered_handlers) |
| 63 | + |
| 64 | + pv2 = SharedNT(nt=NTScalar("i"), initial=5, imatch={"imatch": 3}, registered_handlers=registered_handlers) |
| 65 | + pv2.handler["imatch"].rule.imatch = 5 |
| 66 | + |
| 67 | + pv3 = SharedNT(nt=NTScalar("i"), initial=5, imatch={"imatch": 3}, registered_handlers=registered_handlers) |
| 68 | + pv3.handler["imatch"].rule.imatch = 5 |
| 69 | + pv3.post(5) |
| 70 | + |
| 71 | + Server.forever( |
| 72 | + providers=[ |
| 73 | + { |
| 74 | + "demo:pv:name1": pv1, |
| 75 | + "demo:pv:name2": pv2, |
| 76 | + "demo:pv:name3": pv3, |
| 77 | + } |
| 78 | + ] |
| 79 | + ) # runs until KeyboardInterrupt |
| 80 | + |
| 81 | + |
| 82 | +if __name__ == "__main__": |
| 83 | + main() |
0 commit comments