reader_station.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. from data_models.mqtt_message import MqttMessage
  2. from pypdevs.DEVS import AtomicDEVS
  3. from pypdevs.infinity import INFINITY
  4. from dataclasses import dataclass, field
  5. from loguru import logger
  6. from data_models.workpiece import Workpiece, WorkpieceColor
  7. from utils.get_timestamp import get_timestamp
  8. from utils.timed_phase_enum import TimedPhaseEnum
  9. from fdir.mixins import TurnedOffMixin
  10. class InputRoutine(TimedPhaseEnum):
  11. """
  12. Routine when a new workpiece enters the factory
  13. (Steps along with their timings)
  14. """
  15. IDLE = ('IDLE', INFINITY)
  16. NFC_READING = ('NFC_READING', 1.367)
  17. IDLE_WAIT = ('IDLE_WAIT', INFINITY) # wait for VGR to move to color sensor
  18. COLOR_READING = ('COLOR_READING', 0.100)
  19. IDLE_WAIT_2 = ('IDLE_WAIT_2', INFINITY) # wait for VGR to move to NFC reader
  20. NFC_WRITING = ('NFC_WRITING', 7.603) # yes, this takes a while
  21. class OutputRoutine(TimedPhaseEnum):
  22. """
  23. Routine before a workpiece gets delivered to the output
  24. (Steps along with their timings)
  25. """
  26. IDLE = ('IDLE', INFINITY)
  27. NFC_WRITING = ('NFC_WRITING', 3.902)
  28. @dataclass
  29. class ReaderStationState:
  30. phase: InputRoutine | OutputRoutine = InputRoutine.IDLE
  31. delta_t: float = INFINITY
  32. workpiece: Workpiece | None = None
  33. color_read: WorkpieceColor = WorkpieceColor.NONE # color read by the color sensor
  34. visual_update_pending: bool = False
  35. class ReaderStation(AtomicDEVS):
  36. """ Station which holds both the NFC reader/writer and the color sensor to detect workpiece color """
  37. def __init__(self, name: str):
  38. # name needs to be unique to refer to it
  39. super(ReaderStation, self).__init__(name)
  40. self.nfc_in = self.addInPort("nfc_in")
  41. self.nfc_out = self.addOutPort("nfc_out")
  42. self.color_in = self.addInPort("color_in")
  43. self.color_out = self.addOutPort("color_out")
  44. self.mqtt_in = self.addInPort("mqtt_in")
  45. self.mqtt_out = self.addOutPort("mqtt_out")
  46. self.state = ReaderStationState()
  47. def change_phase(self, new_phase: InputRoutine | OutputRoutine):
  48. """ Wrapper for changing the phase and time associated with it, helps with logging """
  49. self.state.phase = new_phase
  50. self.state.delta_t = new_phase.timing
  51. logger.trace(f"{type(self).__name__} '{self.name}' phase changed to {new_phase}")
  52. self.state.visual_update_pending = True
  53. def get_visual_update_data(self) -> MqttMessage:
  54. """ Get visual update data for the animation, contains the action taken and the duration of that action left """
  55. message = MqttMessage()
  56. message.topic = "visualization/nfc"
  57. duration = self.state.delta_t
  58. if duration == INFINITY: duration = None
  59. message.payload = {
  60. "action": self.state.phase.value,
  61. "duration": duration, # should be equal to the timing of the phase
  62. "workpiece": self.state.workpiece.to_dict() if self.state.workpiece else None,
  63. }
  64. return message
  65. def get_nfc_message(self) -> MqttMessage:
  66. """ Get the nfc message for the workpiece """
  67. message = MqttMessage()
  68. message.topic = "f/i/nfc/ds"
  69. message.payload = {
  70. "history": [], # TODO: history of NFC reading
  71. "ts": get_timestamp(),
  72. "workpiece": {
  73. "id": self.state.workpiece.id,
  74. "state": self.state.workpiece.state,
  75. "type": self.state.color_read.value,
  76. }
  77. }
  78. return message
  79. def extTransition(self, inputs):
  80. self.state.delta_t -= self.elapsed
  81. if self.mqtt_in in inputs:
  82. msg = inputs[self.mqtt_in][0]
  83. if msg.topic == "simulation/ctrl/nfc":
  84. #print(msg)
  85. if self.state.workpiece and msg.payload["action"] == "id_update":
  86. self.state.workpiece.id = msg.payload["workpiece"]["id"]
  87. elif self.state.workpiece and msg.payload["action"] == "color_update":
  88. self.state.workpiece.color = WorkpieceColor[msg.payload["workpiece"]["type"]]
  89. if msg.topic == "simulation/ctrl/all" and msg.payload.get("action") == "refresh":
  90. self.state.visual_update_pending = True
  91. return self.state
  92. elif not self.state.phase in [InputRoutine.IDLE, InputRoutine.IDLE_WAIT, InputRoutine.IDLE_WAIT_2, OutputRoutine.IDLE]:
  93. logger.error(f"{type(self).__name__} '{self.name}' received workpiece while not Idle!")
  94. if self.nfc_in in inputs:
  95. wp: Workpiece = inputs[self.nfc_in][0]
  96. logger.trace(f"{type(self).__name__} '{self.name}' NFC received: {wp}")
  97. if wp.state == "BAKED":
  98. self.change_phase(OutputRoutine.NFC_WRITING)
  99. self.state.color_read = wp.color
  100. wp.state = "PROCESSED" # TODO: check if this logic is correct
  101. elif self.state.phase in [InputRoutine.IDLE, OutputRoutine.IDLE]:
  102. self.change_phase(InputRoutine.NFC_READING) # new, read
  103. elif self.state.phase == InputRoutine.IDLE_WAIT_2:
  104. self.change_phase(InputRoutine.NFC_WRITING) # seen, write nfc
  105. self.state.workpiece = wp
  106. if self.color_in in inputs:
  107. wp: Workpiece = inputs[self.color_in][0]
  108. logger.trace(f"{type(self).__name__} '{self.name}' COLOR_SENSOR received: {wp}")
  109. self.change_phase(InputRoutine.COLOR_READING)
  110. self.state.workpiece = wp
  111. return self.state # important, return state
  112. def timeAdvance(self):
  113. if self.state.visual_update_pending:
  114. return 0.0
  115. return self.state.delta_t
  116. def outputFnc(self):
  117. if self.state.visual_update_pending:
  118. return {self.mqtt_out: [self.get_visual_update_data()]}
  119. if self.state.phase in [InputRoutine.NFC_READING, InputRoutine.NFC_WRITING, OutputRoutine.NFC_WRITING]:
  120. return {self.nfc_out: [self.state.workpiece], self.mqtt_out: [self.get_nfc_message()]}
  121. elif self.state.phase == InputRoutine.COLOR_READING:
  122. return {self.color_out: [self.state.workpiece]}
  123. return {}
  124. def intTransition(self):
  125. if self.state.visual_update_pending:
  126. self.state.visual_update_pending = False
  127. return self.state
  128. if self.state.phase == InputRoutine.COLOR_READING:
  129. self.state.color_read = self.state.workpiece.color
  130. if self.state.phase in [InputRoutine.NFC_WRITING, OutputRoutine.NFC_WRITING]:
  131. self.state.color_read = WorkpieceColor.NONE # reset for next input
  132. # Transition to next phase (idle phase)
  133. self.state.workpiece = None # We have just output the workpiece, so mark it as empty again
  134. self.change_phase(self.state.phase.next())
  135. return self.state
  136. class FaultyReaderStation(TurnedOffMixin, ReaderStation):
  137. """ A reader station which is turned off, does nothing """
  138. pass