report_service.py 14 KB

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