report_service.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. # SPDX-License-Identifier: Apache-2.0
  2. # Copyright 2020 Contributors to OpenLEADR
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. from . import service, handler, VTNService
  13. from asyncio import iscoroutine, gather
  14. from openleadr import objects, utils
  15. import logging
  16. import inspect
  17. logger = logging.getLogger('openleadr')
  18. # ╔══════════════════════════════════════════════════════════════════════════╗
  19. # ║ REPORT SERVICE ║
  20. # ╚══════════════════════════════════════════════════════════════════════════╝
  21. # ┌──────────────────────────────────────────────────────────────────────────┐
  22. # │ The VEN can register its reporting capabilities. │
  23. # │ │
  24. # │ ┌────┐ ┌────┐ │
  25. # │ │VEN │ │VTN │ │
  26. # │ └─┬──┘ └─┬──┘ │
  27. # │ │───────────────oadrRegisterReport(METADATA Report)──────────────▶│ │
  28. # │ │ │ │
  29. # │ │◀ ─ ─ ─ ─oadrRegisteredReport(optional oadrReportRequest) ─ ─ ─ ─│ │
  30. # │ │ │ │
  31. # │ │ │ │
  32. # │ │─────────────oadrCreatedReport(if report requested)─────────────▶│ │
  33. # │ │ │ │
  34. # │ │◀ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ oadrResponse()─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─│ │
  35. # │ │ │ │
  36. # │ │
  37. # └──────────────────────────────────────────────────────────────────────────┘
  38. # ┌──────────────────────────────────────────────────────────────────────────┐
  39. # │ A report can also be canceled │
  40. # │ │
  41. # │ ┌────┐ ┌────┐ │
  42. # │ │VEN │ │VTN │ │
  43. # │ └─┬──┘ └─┬──┘ │
  44. # │ │───────────────oadrRegisterReport(METADATA Report)──────────────▶│ │
  45. # │ │ │ │
  46. # │ │◀ ─ ─ ─ ─oadrRegisteredReport(optional oadrReportRequest) ─ ─ ─ ─│ │
  47. # │ │ │ │
  48. # │ │ │ │
  49. # │ │─────────────oadrCreatedReport(if report requested)─────────────▶│ │
  50. # │ │ │ │
  51. # │ │◀ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ oadrResponse()─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─│ │
  52. # │ │ │ │
  53. # │ │
  54. # └──────────────────────────────────────────────────────────────────────────┘
  55. @service('EiReport')
  56. class ReportService(VTNService):
  57. def __init__(self, vtn_id, message_queues=None):
  58. super().__init__(vtn_id)
  59. self.report_callbacks = {}
  60. self.message_queues = message_queues
  61. self.registered_reports = {}
  62. @handler('oadrRegisterReport')
  63. async def register_report(self, payload):
  64. """
  65. Handle the VENs reporting capabilities.
  66. """
  67. report_requests = []
  68. args = inspect.signature(self.on_register_report).parameters
  69. if all(['ven_id' in args, 'resource_id' in args, 'measurement' in args,
  70. 'min_sampling_interval' in args, 'max_sampling_interval' in args,
  71. 'unit' in args, 'scale' in args]):
  72. for report in payload['reports']:
  73. if report['report_name'] == 'METADATA_TELEMETRY_STATUS':
  74. result = [self.on_register_report(ven_id=payload['ven_id'],
  75. resource_id=rd.get('report_data_source', {}).get('resource_id'),
  76. measurement='Status',
  77. unit=None,
  78. scale=None,
  79. min_sampling_interval=rd['sampling_rate']['min_period'],
  80. max_sampling_interval=rd['sampling_rate']['max_period'])
  81. for rd in report['report_descriptions']]
  82. elif report['report_name'] == 'METADATA_TELEMETRY_USAGE':
  83. result = [self.on_register_report(ven_id=payload['ven_id'],
  84. resource_id=rd.get('report_data_source', {}).get('resource_id'),
  85. measurement=rd['measurement']['description'],
  86. unit=rd['measurement']['unit'],
  87. scale=rd['measurement']['scale'],
  88. min_sampling_interval=rd['sampling_rate']['min_period'],
  89. max_sampling_interval=rd['sampling_rate']['max_period'])
  90. for rd in report['report_descriptions']]
  91. elif report['report_name'] in ('METADATA_HISTORY_USAGE', 'METADATA_HISTORY_GREENBUTTON'):
  92. if payload['ven_id'] not in self.available_reports:
  93. self.available_reports[payload['ven_id']] = []
  94. self.registered_reports[payload['ven_id']].append(report)
  95. else:
  96. logger.warning("Reports other than TELEMETRY_USAGE, TELEMETRY_STATUS, "
  97. "HISTORY_USAGE and HISTORY_GREENBUTTON are not yet supported. "
  98. f"Skipping report with name {report['report_name']}.")
  99. report_requests.append(None)
  100. continue
  101. if iscoroutine(result[0]):
  102. result = await gather(*result)
  103. for i, r in enumerate(result):
  104. if not isinstance(r, tuple):
  105. logger.error(f"Your on_register_report handler must return a tuple; it returned '{r}' ({r.__class__.__name__}).")
  106. result[i] = None
  107. result = [(report['report_descriptions'][i]['r_id'], *result[i])
  108. for i in range(len(report['report_descriptions'])) if isinstance(result[i], tuple)]
  109. report_requests.append(result)
  110. else:
  111. # Use the 'full' mode for openADR reporting
  112. result = [self.on_register_report(report) for report in payload['reports']]
  113. if iscoroutine(result[0]):
  114. result = await gather(*result) # Now we have r_id, callback, sampling_rate
  115. for i, r in enumerate(result):
  116. if not isinstance(r, list):
  117. logger.error(f"Your on_register_report handler must return a list of tuples. It returned '{r}' ({r.__class__.__name__}).")
  118. result[i] = None
  119. report_requests = result
  120. # Validate the report requests for being of the proper type and lengs
  121. utils.validate_report_request_tuples(report_requests)
  122. for i, report_request in enumerate(report_requests):
  123. if report_request is None or len(report_request) == 0:
  124. continue
  125. # Check if all sampling rates per report_request are the same
  126. sampling_interval = min(rrq[2] for rrq in report_request if rrq is not None)
  127. if not all(rrq is not None and report_request[0][2] == sampling_interval for rrq in report_request):
  128. logger.error("OpenADR does not support multiple different sampling rates per "
  129. "report. OpenLEADR will set all sampling rates to "
  130. f"{sampling_interval}")
  131. # Form the report request
  132. oadr_report_requests = []
  133. for i, report_request in enumerate(report_requests):
  134. if report_request is None or len(report_request) == 0:
  135. continue
  136. orig_report = payload['reports'][i]
  137. report_specifier_id = orig_report['report_specifier_id']
  138. report_request_id = utils.generate_id()
  139. specifier_payloads = []
  140. for rrq in report_request:
  141. if len(rrq) == 3:
  142. r_id, callback, sampling_interval = rrq
  143. report_interval = sampling_interval
  144. elif len(rrq) == 4:
  145. r_id, callback, sampling_interval, report_interval = rrq
  146. report_description = utils.find_by(orig_report['report_descriptions'], 'r_id', r_id)
  147. reading_type = report_description['reading_type']
  148. specifier_payloads.append(objects.SpecifierPayload(r_id=r_id,
  149. reading_type=reading_type))
  150. # Append the callback to our list of known callbacks
  151. self.report_callbacks[(report_request_id, r_id)] = callback
  152. # Add the ReportSpecifier to the ReportRequest
  153. report_specifier = objects.ReportSpecifier(report_specifier_id=report_specifier_id,
  154. granularity=sampling_interval,
  155. report_back_duration=report_interval,
  156. specifier_payloads=specifier_payloads)
  157. # Add the ReportRequest to our outgoing message
  158. oadr_report_requests.append(objects.ReportRequest(report_request_id=report_request_id,
  159. report_specifier=report_specifier))
  160. # Put the report requests back together
  161. response_type = 'oadrRegisteredReport'
  162. response_payload = {'report_requests': oadr_report_requests}
  163. return response_type, response_payload
  164. async def on_register_report(self, payload):
  165. """
  166. Pre-handler for a oadrOnRegisterReport message. This will call your own handler (if defined)
  167. to allow for requesting the offered reports.
  168. """
  169. logger.warning("You should implement and register your own on_register_report handler "
  170. "if you want to receive reports from a VEN. This handler will receive the "
  171. "following arguments: ven_id, resource_id, measurement, unit, scale, "
  172. "min_sampling_interval, max_sampling_interval and should return either "
  173. "None or (callback, sampling_interval) or "
  174. "(callback, sampling_interval, reporting_interval).")
  175. return None
  176. @handler('oadrUpdateReport')
  177. async def update_report(self, payload):
  178. """
  179. Handle a report that we received from the VEN.
  180. """
  181. for report in payload['reports']:
  182. report_request_id = report['report_request_id']
  183. if not self.report_callbacks:
  184. result = self.on_update_report(report)
  185. if iscoroutine(result):
  186. result = await result
  187. continue
  188. for r_id, values in utils.group_by(report['intervals'], 'report_payload.r_id').items():
  189. # Find the callback that was registered.
  190. if (report_request_id, r_id) in self.report_callbacks:
  191. # Collect the values
  192. values = [(ri['dtstart'], ri['report_payload']['value']) for ri in values]
  193. # Call the callback function to deliver the values
  194. result = self.report_callbacks[(report_request_id, r_id)](values)
  195. if iscoroutine(result):
  196. result = await result
  197. response_type = 'oadrUpdatedReport'
  198. response_payload = {}
  199. return response_type, response_payload
  200. async def on_update_report(self, payload):
  201. """
  202. Placeholder for the on_update_report handler.
  203. """
  204. logger.warning("You should implement and register your own on_update_report handler "
  205. "to deal with reports that your receive from the VEN. This handler will "
  206. "receive either a complete oadrReport dict, or a list of (datetime, value) "
  207. "tuples that you can then process how you see fit. You don't "
  208. "need to return anything from that handler.")
  209. return None