client.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  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. import asyncio
  13. import inspect
  14. import logging
  15. import ssl
  16. import sys
  17. import random
  18. from datetime import datetime, timedelta, timezone
  19. from functools import partial
  20. from http import HTTPStatus
  21. import aiohttp
  22. from lxml.etree import XMLSyntaxError
  23. from signxml.exceptions import InvalidSignature
  24. from apscheduler.schedulers.asyncio import AsyncIOScheduler
  25. from openleadr import enums, objects, errors
  26. from openleadr.messaging import create_message, parse_message, \
  27. validate_xml_schema, validate_xml_signature
  28. from openleadr import utils
  29. logger = logging.getLogger('openleadr')
  30. class OpenADRClient:
  31. """
  32. Main client class. Most of these methods will be called automatically, but
  33. you can always choose to call them manually.
  34. """
  35. def __init__(self, ven_name, vtn_url, debug=False, cert=None, key=None,
  36. passphrase=None, vtn_fingerprint=None, show_fingerprint=True, ca_file=None,
  37. allow_jitter=True):
  38. """
  39. Initializes a new OpenADR Client (Virtual End Node)
  40. :param str ven_name: The name for this VEN
  41. :param str vtn_url: The URL of the VTN (Server) to connect to
  42. :param bool debug: Whether or not to print debugging messages
  43. :param str cert: The path to a PEM-formatted Certificate file to use
  44. for signing messages.
  45. :param str key: The path to a PEM-formatted Private Key file to use
  46. for signing messages.
  47. :param str fingerprint: The fingerprint for the VTN's certificate to
  48. verify incomnig messages
  49. :param str show_fingerprint: Whether to print your own fingerprint
  50. on startup. Defaults to True.
  51. :param str ca_file: The path to the PEM-formatted CA file for validating the VTN server's
  52. certificate.
  53. """
  54. self.ven_name = ven_name
  55. if vtn_url.endswith("/"):
  56. vtn_url = vtn_url[:-1]
  57. self.vtn_url = vtn_url
  58. self.ven_id = None
  59. self.registration_id = None
  60. self.poll_frequency = None
  61. self.vtn_fingerprint = vtn_fingerprint
  62. self.debug = debug
  63. self.reports = []
  64. self.report_callbacks = {} # Holds the callbacks for each specific report
  65. self.report_requests = [] # Keep track of the report requests from the VTN
  66. self.incomplete_reports = {} # Holds reports that are being populated over time
  67. self.pending_reports = asyncio.Queue() # Holds reports that are waiting to be sent
  68. self.scheduler = AsyncIOScheduler()
  69. self.client_session = None
  70. self.report_queue_task = None
  71. self.responded_events = {} # Holds the events that we already saw.
  72. self.cert_path = cert
  73. self.key_path = key
  74. self.passphrase = passphrase
  75. self.ca_file = ca_file
  76. self.allow_jitter = allow_jitter
  77. if cert and key:
  78. with open(cert, 'rb') as file:
  79. cert = file.read()
  80. with open(key, 'rb') as file:
  81. key = file.read()
  82. if show_fingerprint:
  83. print("")
  84. print("*" * 80)
  85. print("Your VEN Certificate Fingerprint is ".center(80))
  86. print(f"{utils.certificate_fingerprint(cert).center(80)}".center(80))
  87. print("Please deliver this fingerprint to the VTN.".center(80))
  88. print("You do not need to keep this a secret.".center(80))
  89. print("*" * 80)
  90. print("")
  91. self._create_message = partial(create_message,
  92. cert=cert,
  93. key=key,
  94. passphrase=passphrase)
  95. async def run(self):
  96. """
  97. Run the client in full-auto mode.
  98. """
  99. # if not hasattr(self, 'on_event'):
  100. # raise NotImplementedError("You must implement on_event.")
  101. self.loop = asyncio.get_event_loop()
  102. await self.create_party_registration()
  103. if not self.ven_id:
  104. logger.error("No VEN ID received from the VTN, aborting.")
  105. await self.stop()
  106. return
  107. if self.reports:
  108. await self.register_reports(self.reports)
  109. self.report_queue_task = self.loop.create_task(self._report_queue_worker())
  110. await self._poll()
  111. # Set up automatic polling
  112. if self.poll_frequency > timedelta(hours=24):
  113. logger.warning("Polling with intervals of more than 24 hours is not supported. "
  114. "Will use 24 hours as the logging interval.")
  115. self.poll_frequency = timedelta(hours=24)
  116. cron_config = utils.cron_config(self.poll_frequency, randomize_seconds=self.allow_jitter)
  117. self.scheduler.add_job(self._poll,
  118. trigger='cron',
  119. **cron_config)
  120. self.scheduler.start()
  121. async def stop(self):
  122. """
  123. Cleanly stops the client. Run this coroutine before closing your event loop.
  124. """
  125. if self.scheduler.running:
  126. self.scheduler.shutdown()
  127. if self.report_queue_task:
  128. self.report_queue_task.cancel()
  129. if sys.version_info.minor > 8:
  130. delayed_call_tasks = [task for task in asyncio.all_tasks() if task.get_name().startswith('DelayedCall')]
  131. for task in delayed_call_tasks:
  132. task.cancel()
  133. await self.client_session.close()
  134. await asyncio.sleep(0)
  135. def add_handler(self, handler, callback):
  136. """
  137. Add a callback for the given situation
  138. """
  139. if handler not in ('on_event', 'on_update_event'):
  140. logger.error("'handler' must be either on_event or on_update_event")
  141. return
  142. setattr(self, handler, callback)
  143. def add_report(self, callback, resource_id, measurement=None,
  144. data_collection_mode='incremental',
  145. report_specifier_id=None, r_id=None,
  146. report_name=enums.REPORT_NAME.TELEMETRY_USAGE,
  147. reading_type=enums.READING_TYPE.DIRECT_READ,
  148. report_type=enums.REPORT_TYPE.READING, sampling_rate=None, data_source=None,
  149. scale="none", unit=None, power_ac=True, power_hertz=50, power_voltage=230,
  150. market_context=None, end_device_asset_mrid=None, report_data_source=None):
  151. """
  152. Add a new reporting capability to the client.
  153. :param callable callback: A callback or coroutine that will fetch the value for a specific
  154. report. This callback will be passed the report_id and the r_id
  155. of the requested value.
  156. :param str resource_id: A specific name for this resource within this report.
  157. :param str measurement: The quantity that is being measured (openleadr.enums.MEASUREMENTS).
  158. Optional for TELEMETRY_STATUS reports.
  159. :param str data_collection_mode: Whether you want the data to be collected incrementally
  160. or at once. If the VTN requests the sampling interval to be
  161. higher than the reporting interval, this setting determines
  162. if the callback should be called at the sampling rate (with
  163. no args, assuming it returns the current value), or at the
  164. reporting interval (with date_from and date_to as keyword
  165. arguments). Choose 'incremental' for the former case, or
  166. 'full' for the latter case.
  167. :param str report_specifier_id: A unique identifier for this report. Leave this blank for a
  168. random generated id, or fill it in if your VTN depends on
  169. this being a known value, or if it needs to be constant
  170. between restarts of the client.
  171. :param str r_id: A unique identifier for a datapoint in a report. The same remarks apply as
  172. for the report_specifier_id.
  173. :param str report_name: An OpenADR name for this report (one of openleadr.enums.REPORT_NAME)
  174. :param str reading_type: An OpenADR reading type (found in openleadr.enums.READING_TYPE)
  175. :param str report_type: An OpenADR report type (found in openleadr.enums.REPORT_TYPE)
  176. :param datetime.timedelta sampling_rate: The sampling rate for the measurement.
  177. :param str unit: The unit for this measurement.
  178. :param boolean power_ac: Whether the power is AC (True) or DC (False).
  179. Only required when supplying a power-related measurement.
  180. :param int power_hertz: Grid frequency of the power.
  181. Only required when supplying a power-related measurement.
  182. :param int power_voltage: Voltage of the power.
  183. Only required when supplying a power-related measurement.
  184. :param str market_context: The Market Context that this report belongs to.
  185. :param str end_device_asset_mrid: the Meter ID for the end device that is measured by this report.
  186. :param report_data_source: A (list of) target(s) that this report is related to.
  187. """
  188. # Verify input
  189. if report_name not in enums.REPORT_NAME.values and not report_name.startswith('x-'):
  190. raise ValueError(f"{report_name} is not a valid report_name. Valid options are "
  191. f"{', '.join(enums.REPORT_NAME.values)}",
  192. " or any name starting with 'x-'.")
  193. if reading_type not in enums.READING_TYPE.values and not reading_type.startswith('x-'):
  194. raise ValueError(f"{reading_type} is not a valid reading_type. Valid options are "
  195. f"{', '.join(enums.READING_TYPE.values)}"
  196. " or any name starting with 'x-'.")
  197. if report_type not in enums.REPORT_TYPE.values and not report_type.startswith('x-'):
  198. raise ValueError(f"{report_type} is not a valid report_type. Valid options are "
  199. f"{', '.join(enums.REPORT_TYPE.values)}"
  200. " or any name starting with 'x-'.")
  201. if scale not in enums.SI_SCALE_CODE.values:
  202. raise ValueError(f"{scale} is not a valid scale. Valid options are "
  203. f"{', '.join(enums.SI_SCALE_CODE.values)}")
  204. if sampling_rate is None:
  205. sampling_rate = objects.SamplingRate(min_period=timedelta(seconds=10),
  206. max_period=timedelta(hours=24),
  207. on_change=False)
  208. elif isinstance(sampling_rate, timedelta):
  209. sampling_rate = objects.SamplingRate(min_period=sampling_rate,
  210. max_period=sampling_rate,
  211. on_change=False)
  212. if data_collection_mode not in ('incremental', 'full'):
  213. raise ValueError("The data_collection_mode should be 'incremental' or 'full'.")
  214. if data_collection_mode == 'full':
  215. args = inspect.signature(callback).parameters
  216. if not ('date_from' in args and 'date_to' in args and 'sampling_interval' in args):
  217. raise TypeError("Your callback function must accept the 'date_from', 'date_to' "
  218. "and 'sampling_interval' arguments if used "
  219. "with data_collection_mode 'full'.")
  220. # Determine the correct item name, item description and unit
  221. if report_name == 'TELEMETRY_STATUS':
  222. item_base = None
  223. elif isinstance(measurement, objects.Measurement):
  224. item_base = measurement
  225. elif isinstance(measurement, dict):
  226. utils.validate_report_measurement_dict(measurement)
  227. power_attributes = object.PowerAttributes(**measurement.get('power_attributes')) or None
  228. item_base = objects.Measurement(name=measurement['name'],
  229. description=measurement['description'],
  230. unit=measurement['unit'],
  231. scale=measurement.get('scale'),
  232. power_attributes=power_attributes)
  233. elif measurement.upper() in enums.MEASUREMENTS.members:
  234. item_base = enums.MEASUREMENTS[measurement.upper()]
  235. else:
  236. item_base = objects.Measurement(name='customUnit',
  237. description=measurement,
  238. unit=unit,
  239. scale=scale)
  240. if report_name != 'TELEMETRY_STATUS' and scale is not None:
  241. if item_base.scale is not None:
  242. if scale in enums.SI_SCALE_CODE.values:
  243. item_base.scale = scale
  244. else:
  245. raise ValueError("The 'scale' argument must be one of '{'. ',join(enums.SI_SCALE_CODE.values)}")
  246. # Check if unit is compatible
  247. if unit is not None and unit != item_base.unit and unit not in item_base.acceptable_units:
  248. logger.warning(f"The supplied unit {unit} for measurement {measurement} "
  249. f"will be ignored, {item_base.unit} will be used instead. "
  250. f"Allowed units for this measurement are: "
  251. f"{', '.join(item_base.acceptable_units)}")
  252. # Get or create the relevant Report
  253. if report_specifier_id:
  254. report = utils.find_by(self.reports,
  255. 'report_name', report_name,
  256. 'report_specifier_id', report_specifier_id)
  257. else:
  258. report = utils.find_by(self.reports, 'report_name', report_name)
  259. if not report:
  260. report_specifier_id = report_specifier_id or utils.generate_id()
  261. report = objects.Report(created_date_time=datetime.now(),
  262. report_name=report_name,
  263. report_specifier_id=report_specifier_id,
  264. data_collection_mode=data_collection_mode)
  265. self.reports.append(report)
  266. # Add the new report description to the report
  267. target = objects.Target(resource_id=resource_id)
  268. r_id = utils.generate_id()
  269. report_description = objects.ReportDescription(r_id=r_id,
  270. reading_type=reading_type,
  271. report_data_source=target,
  272. report_subject=target,
  273. report_type=report_type,
  274. sampling_rate=sampling_rate,
  275. measurement=item_base,
  276. market_context='Market01')
  277. self.report_callbacks[(report.report_specifier_id, r_id)] = callback
  278. report.report_descriptions.append(report_description)
  279. ###########################################################################
  280. # #
  281. # POLLING METHODS #
  282. # #
  283. ###########################################################################
  284. async def poll(self):
  285. """
  286. Request the next available message from the Server. This coroutine is called automatically.
  287. """
  288. service = 'OadrPoll'
  289. message = self._create_message('oadrPoll', ven_id=self.ven_id)
  290. response_type, response_payload = await self._perform_request(service, message)
  291. return response_type, response_payload
  292. ###########################################################################
  293. # #
  294. # REGISTRATION METHODS #
  295. # #
  296. ###########################################################################
  297. async def query_registration(self):
  298. """
  299. Request information about the VTN.
  300. """
  301. request_id = utils.generate_id()
  302. service = 'EiRegisterParty'
  303. message = self._create_message('oadrQueryRegistration', request_id=request_id)
  304. response_type, response_payload = await self._perform_request(service, message)
  305. return response_type, response_payload
  306. async def create_party_registration(self, http_pull_model=True, xml_signature=False,
  307. report_only=False, profile_name='2.0b',
  308. transport_name='simpleHttp', transport_address=None,
  309. ven_id=None):
  310. """
  311. Take the neccessary steps to register this client with the server.
  312. :param bool http_pull_model: Whether to use the 'pull' model for HTTP.
  313. :param bool xml_signature: Whether to sign each XML message.
  314. :param bool report_only: Whether or not this is a reporting-only client
  315. which does not deal with Events.
  316. :param str profile_name: Which OpenADR profile to use.
  317. :param str transport_name: The transport name to use. Either 'simpleHttp' or 'xmpp'.
  318. :param str transport_address: Which public-facing address the server should use
  319. to communicate.
  320. :param str ven_id: The ID for this VEN. If you leave this blank,
  321. a VEN_ID will be assigned by the VTN.
  322. """
  323. request_id = utils.generate_id()
  324. service = 'EiRegisterParty'
  325. payload = {'ven_name': self.ven_name,
  326. 'http_pull_model': http_pull_model,
  327. 'xml_signature': xml_signature,
  328. 'report_only': report_only,
  329. 'profile_name': profile_name,
  330. 'transport_name': transport_name,
  331. 'transport_address': transport_address}
  332. if ven_id:
  333. payload['ven_id'] = ven_id
  334. message = self._create_message('oadrCreatePartyRegistration',
  335. request_id=request_id,
  336. **payload)
  337. response_type, response_payload = await self._perform_request(service, message)
  338. if response_type is None:
  339. return
  340. if response_payload['response']['response_code'] != 200:
  341. status_code = response_payload['response']['response_code']
  342. status_description = response_payload['response']['response_description']
  343. logger.error(f"Got error on Create Party Registration: "
  344. f"{status_code} {status_description}")
  345. return
  346. self.ven_id = response_payload['ven_id']
  347. self.registration_id = response_payload['registration_id']
  348. self.poll_frequency = response_payload.get('requested_oadr_poll_freq',
  349. timedelta(seconds=10))
  350. logger.info(f"VEN is now registered with ID {self.ven_id}")
  351. logger.info(f"The polling frequency is {self.poll_frequency}")
  352. return response_type, response_payload
  353. async def cancel_party_registration(self):
  354. raise NotImplementedError("Cancel Registration is not yet implemented")
  355. ###########################################################################
  356. # #
  357. # EVENT METHODS #
  358. # #
  359. ###########################################################################
  360. async def request_event(self, reply_limit=1):
  361. """
  362. Request the next Event from the VTN, if it has any.
  363. """
  364. payload = {'request_id': utils.generate_id(),
  365. 'ven_id': self.ven_id,
  366. 'reply_limit': reply_limit}
  367. message = self._create_message('oadrRequestEvent', **payload)
  368. service = 'EiEvent'
  369. response_type, response_payload = await self._perform_request(service, message)
  370. return response_type, response_payload
  371. async def created_event(self, request_id, event_id, opt_type, modification_number=1):
  372. """
  373. Inform the VTN that we created an event.
  374. """
  375. service = 'EiEvent'
  376. payload = {'ven_id': self.ven_id,
  377. 'response': {'response_code': 200,
  378. 'response_description': 'OK',
  379. 'request_id': request_id},
  380. 'event_responses': [{'response_code': 200,
  381. 'response_description': 'OK',
  382. 'request_id': request_id,
  383. 'event_id': event_id,
  384. 'modification_number': modification_number,
  385. 'opt_type': opt_type}]}
  386. message = self._create_message('oadrCreatedEvent', **payload)
  387. response_type, response_payload = await self._perform_request(service, message)
  388. ###########################################################################
  389. # #
  390. # REPORTING METHODS #
  391. # #
  392. ###########################################################################
  393. async def register_reports(self, reports):
  394. """
  395. Tell the VTN about our reports. The VTN miht respond with an
  396. oadrCreateReport message that tells us which reports are to be sent.
  397. """
  398. request_id = utils.generate_id()
  399. payload = {'request_id': request_id,
  400. 'ven_id': self.ven_id,
  401. 'reports': reports}
  402. service = 'EiReport'
  403. message = self._create_message('oadrRegisterReport', **payload)
  404. response_type, response_payload = await self._perform_request(service, message)
  405. # Handle the subscriptions that the VTN is interested in.
  406. if 'report_requests' in response_payload:
  407. for report_request in response_payload['report_requests']:
  408. await self.create_report(report_request)
  409. message_type = 'oadrCreatedReport'
  410. message_payload = {}
  411. return message_type, message_payload
  412. async def create_report(self, report_request):
  413. """
  414. Add the requested reports to the reporting mechanism.
  415. This is called when the VTN requests reports from us.
  416. :param report_request dict: The oadrReportRequest dict from the VTN.
  417. """
  418. # Get the relevant variables from the report requests
  419. report_request_id = report_request['report_request_id']
  420. report_specifier_id = report_request['report_specifier']['report_specifier_id']
  421. report_back_duration = report_request['report_specifier'].get('report_back_duration')
  422. granularity = report_request['report_specifier']['granularity']
  423. # Check if this report actually exists
  424. report = utils.find_by(self.reports, 'report_specifier_id', report_specifier_id)
  425. if not report:
  426. logger.error(f"A non-existant report with report_specifier_id "
  427. f"{report_specifier_id} was requested.")
  428. return False
  429. # Check and collect the requested r_ids for this report
  430. requested_r_ids = []
  431. for specifier_payload in report_request['report_specifier']['specifier_payloads']:
  432. r_id = specifier_payload['r_id']
  433. # Check if the requested r_id actually exists
  434. rd = utils.find_by(report.report_descriptions, 'r_id', r_id)
  435. if not rd:
  436. logger.error(f"A non-existant report with r_id {r_id} "
  437. f"inside report with report_specifier_id {report_specifier_id} "
  438. f"was requested.")
  439. continue
  440. # Check if the requested measurement exists and if the correct unit is requested
  441. if 'measurement' in specifier_payload:
  442. measurement = specifier_payload['measurement']
  443. if measurement['description'] != rd.measurement.description:
  444. logger.error(f"A non-matching measurement description for report with "
  445. f"report_request_id {report_request_id} and r_id {r_id} was given "
  446. f"by the VTN. Offered: {rd.measurement.description}, "
  447. f"requested: {measurement['description']}")
  448. continue
  449. if measurement['unit'] != rd.measurement.unit:
  450. logger.error(f"A non-matching measurement unit for report with "
  451. f"report_request_id {report_request_id} and r_id {r_id} was given "
  452. f"by the VTN. Offered: {rd.measurement.unit}, "
  453. f"requested: {measurement['unit']}")
  454. continue
  455. if granularity is not None:
  456. if not rd.sampling_rate.min_period <= granularity <= rd.sampling_rate.max_period:
  457. logger.error(f"An invalid sampling rate {granularity} was requested for report "
  458. f"with report_specifier_id {report_specifier_id} and r_id {r_id}. "
  459. f"The offered sampling rate was between "
  460. f"{rd.sampling_rate.min_period} and "
  461. f"{rd.sampling_rate.max_period}")
  462. continue
  463. else:
  464. # If no granularity is specified, set it to the lowest sampling rate.
  465. granularity = rd.sampling_rate.max_period
  466. requested_r_ids.append(r_id)
  467. callback = partial(self.update_report, report_request_id=report_request_id)
  468. reporting_interval = report_back_duration or granularity
  469. job = self.scheduler.add_job(func=callback,
  470. trigger='cron',
  471. **utils.cron_config(reporting_interval))
  472. self.report_requests.append({'report_request_id': report_request_id,
  473. 'report_specifier_id': report_specifier_id,
  474. 'report_back_duration': report_back_duration,
  475. 'r_ids': requested_r_ids,
  476. 'granularity': granularity,
  477. 'job': job})
  478. async def create_single_report(self, report_request):
  479. """
  480. Create a single report in response to a request from the VTN.
  481. """
  482. async def update_report(self, report_request_id):
  483. """
  484. Call the previously registered report callback and send the result as a message to the VTN.
  485. """
  486. logger.debug(f"Running update_report for {report_request_id}")
  487. report_request = utils.find_by(self.report_requests, 'report_request_id', report_request_id)
  488. granularity = report_request['granularity']
  489. report_back_duration = report_request['report_back_duration']
  490. report_specifier_id = report_request['report_specifier_id']
  491. report = utils.find_by(self.reports, 'report_specifier_id', report_specifier_id)
  492. data_collection_mode = report.data_collection_mode
  493. if report_request_id in self.incomplete_reports:
  494. logger.debug("We were already compiling this report")
  495. outgoing_report = self.incomplete_reports[report_request_id]
  496. else:
  497. logger.debug("There is no report in progress")
  498. outgoing_report = objects.Report(report_request_id=report_request_id,
  499. report_specifier_id=report.report_specifier_id,
  500. report_name=report.report_name,
  501. intervals=[])
  502. intervals = outgoing_report.intervals or []
  503. if data_collection_mode == 'full':
  504. if report_back_duration is None:
  505. report_back_duration = granularity
  506. date_to = datetime.now(timezone.utc)
  507. date_from = date_to - max(report_back_duration, granularity)
  508. for r_id in report_request['r_ids']:
  509. report_callback = self.report_callbacks[(report_specifier_id, r_id)]
  510. result = report_callback(date_from=date_from,
  511. date_to=date_to,
  512. sampling_interval=granularity)
  513. if asyncio.iscoroutine(result):
  514. result = await result
  515. for dt, value in result:
  516. report_payload = objects.ReportPayload(r_id=r_id, value=value)
  517. intervals.append(objects.ReportInterval(dtstart=dt,
  518. report_payload=report_payload))
  519. else:
  520. for r_id in report_request['r_ids']:
  521. report_callback = self.report_callbacks[(report_specifier_id, r_id)]
  522. result = report_callback()
  523. if asyncio.iscoroutine(result):
  524. result = await result
  525. if isinstance(result, (int, float)):
  526. result = [(datetime.now(timezone.utc), result)]
  527. for dt, value in result:
  528. logger.info(f"Adding {dt}, {value} to report")
  529. report_payload = objects.ReportPayload(r_id=r_id, value=value)
  530. intervals.append(objects.ReportInterval(dtstart=dt,
  531. report_payload=report_payload))
  532. outgoing_report.intervals = intervals
  533. logger.info(f"The number of intervals in the report is now {len(outgoing_report.intervals)}")
  534. # Figure out if the report is complete after this sampling
  535. if data_collection_mode == 'incremental' and report_back_duration is not None\
  536. and report_back_duration > granularity:
  537. report_interval = report_back_duration.total_seconds()
  538. sampling_interval = granularity.total_seconds()
  539. expected_len = len(report_request['r_ids']) * int(report_interval / sampling_interval)
  540. if len(outgoing_report.intervals) == expected_len:
  541. logger.info("The report is now complete with all the values. Will queue for sending.")
  542. if self.allow_jitter:
  543. delay = random.uniform(0, min(30, report_interval / 2))
  544. if sys.version_info.minor >= 8:
  545. name = {'name': f'DelayedCall-OutgoingReport-{utils.generate_id()}'}
  546. else:
  547. name = {}
  548. self.loop.create_task(utils.delayed_call(func=self.pending_reports.put(outgoing_report),
  549. delay=delay), **name)
  550. else:
  551. await self.pending_reports.put(self.incomplete_reports.pop(report_request_id))
  552. else:
  553. logger.debug("The report is not yet complete, will hold until it is.")
  554. self.incomplete_reports[report_request_id] = outgoing_report
  555. else:
  556. logger.info("Report will be sent now.")
  557. if self.allow_jitter:
  558. delay = random.uniform(0, min(30, granularity.total_seconds() / 2))
  559. if sys.version_info.minor >= 8:
  560. name = {'name': f'DelayedCall-OutgoingReport-{utils.generate_id()}'}
  561. else:
  562. name = {}
  563. self.loop.create_task(utils.delayed_call(func=self.pending_reports.put(outgoing_report),
  564. delay=delay), **name)
  565. else:
  566. await self.pending_reports.put(outgoing_report)
  567. async def cancel_report(self, payload):
  568. """
  569. Cancel this report.
  570. """
  571. async def _report_queue_worker(self):
  572. """
  573. A Queue worker that pushes out the pending reports.
  574. """
  575. while True:
  576. report = await self.pending_reports.get()
  577. service = 'EiReport'
  578. message = self._create_message('oadrUpdateReport', reports=[report])
  579. try:
  580. response_type, response_payload = await self._perform_request(service, message)
  581. except Exception as err:
  582. logger.error(f"Unable to send the report to the VTN. Error: {err}")
  583. else:
  584. if 'cancel_report' in response_payload:
  585. await self.cancel_report(response_payload['cancel_report'])
  586. ###########################################################################
  587. # #
  588. # PLACEHOLDER #
  589. # #
  590. ###########################################################################
  591. async def on_event(self, event):
  592. """
  593. Placeholder for the on_event handler.
  594. """
  595. logger.warning("You should implement your own on_event handler. This handler receives "
  596. "an Event dict and should return either 'optIn' or 'optOut' based on your "
  597. "choice. Will opt out of the event for now.")
  598. return 'optOut'
  599. async def on_update_event(self, event):
  600. """
  601. Placeholder for the on_update_event handler.
  602. """
  603. logger.warning("You should implement your own on_update_event handler. This handler receives "
  604. "an Event dict and should return either 'optIn' or 'optOut' based on your "
  605. "choice. Will re-use the previous opt status for this event_id for now")
  606. if event['event_descriptor']['event_id'] in self.events:
  607. return self.responded_events['event_id']
  608. async def on_register_report(self, report):
  609. """
  610. Placeholder for the on_register_report handler.
  611. """
  612. ###########################################################################
  613. # #
  614. # LOW LEVEL #
  615. # #
  616. ###########################################################################
  617. async def _perform_request(self, service, message):
  618. await self._ensure_client_session()
  619. logger.debug(f"Client is sending {message}")
  620. url = f"{self.vtn_url}/{service}"
  621. try:
  622. async with self.client_session.post(url, data=message) as req:
  623. content = await req.read()
  624. if req.status != HTTPStatus.OK:
  625. logger.warning(f"Non-OK status {req.status} when performing a request to {url} "
  626. f"with data {message}: {req.status} {content.decode('utf-8')}")
  627. return None, {}
  628. logger.debug(content.decode('utf-8'))
  629. except aiohttp.client_exceptions.ClientConnectorError as err:
  630. # Could not connect to server
  631. logger.error(f"Could not connect to server with URL {self.vtn_url}:")
  632. logger.error(f"{err.__class__.__name__}: {str(err)}")
  633. return None, {}
  634. except Exception as err:
  635. logger.error(f"Request error {err.__class__.__name__}:{err}")
  636. return None, {}
  637. try:
  638. tree = validate_xml_schema(content)
  639. if self.vtn_fingerprint:
  640. validate_xml_signature(tree)
  641. message_type, message_payload = parse_message(content)
  642. except XMLSyntaxError as err:
  643. logger.warning(f"Incoming message did not pass XML schema validation: {err}")
  644. return None, {}
  645. except errors.FingerprintMismatch as err:
  646. logger.warning(err)
  647. return None, {}
  648. except InvalidSignature:
  649. logger.warning("Incoming message had invalid signature, ignoring.")
  650. return None, {}
  651. except Exception as err:
  652. logger.error(f"The incoming message could not be parsed or validated: {err}")
  653. return None, {}
  654. if 'response' in message_payload and 'response_code' in message_payload['response']:
  655. if message_payload['response']['response_code'] != 200:
  656. logger.warning("We got a non-OK OpenADR response from the server: "
  657. f"{message_payload['response']['response_code']}: "
  658. f"{message_payload['response']['response_description']}")
  659. return message_type, message_payload
  660. async def _on_event(self, message):
  661. logger.debug("The VEN received an event")
  662. events = message['events']
  663. try:
  664. results = []
  665. for event in message['events']:
  666. event_id = event['event_descriptor']['event_id']
  667. event_status = event['event_descriptor']['event_status']
  668. if event_id in self.responded_events:
  669. result = self.on_update_event(event)
  670. else:
  671. result = self.on_event(event)
  672. if asyncio.iscoroutine(result):
  673. result = await result
  674. results.append(result)
  675. if event_status == 'completed':
  676. self.responded_events.pop(event_id)
  677. else:
  678. self.responded_events[event_id] = result
  679. for i, result in enumerate(results):
  680. if result not in ('optIn', 'optOut') and events[i]['response_required'] == 'always':
  681. logger.error("Your on_event or on_update_event handler must return 'optIn' or 'optOut'; "
  682. f"you supplied {result}. Please fix your on_event handler.")
  683. results[i] = 'optOut'
  684. except Exception as err:
  685. logger.error("Your on_event handler encountered an error. Will Opt Out of the event. "
  686. f"The error was {err.__class__.__name__}: {str(err)}")
  687. results = ['optOut'] * len(events)
  688. event_responses = [{'response_code': 200,
  689. 'response_description': 'OK',
  690. 'opt_type': results[i],
  691. 'request_id': message['request_id'],
  692. 'modification_number': 1,
  693. 'event_id': events[i]['event_descriptor']['event_id']}
  694. for i, event in enumerate(events) if event['response_required'] == 'always']
  695. if len(event_responses) > 0:
  696. response = {'response_code': 200,
  697. 'response_description': 'OK',
  698. 'request_id': message['request_id']}
  699. message = self._create_message('oadrCreatedEvent',
  700. response=response,
  701. event_responses=event_responses,
  702. ven_id=self.ven_id)
  703. service = 'EiEvent'
  704. response_type, response_payload = await self._perform_request(service, message)
  705. logger.info(response_type, response_payload)
  706. else:
  707. logger.info("Not sending any event responses, because a response was not required/allowed by the VTN.")
  708. async def _poll(self):
  709. logger.debug("Now polling for new messages")
  710. response_type, response_payload = await self.poll()
  711. if response_type is None:
  712. return
  713. if response_type == 'oadrResponse':
  714. logger.debug("No events or reports available")
  715. return
  716. if response_type == 'oadrRequestReregistration':
  717. logger.info("The VTN required us to re-register. Calling the registration procedure.")
  718. await self.create_party_registration()
  719. if response_type == 'oadrDistributeEvent':
  720. if len(response_payload['events']) > 0:
  721. await self._on_event(response_payload)
  722. elif response_type == 'oadrUpdateReport':
  723. await self._on_report(response_payload)
  724. elif response_type == 'oadrCreateReport':
  725. if 'report_requests' in response_payload:
  726. for report_request in response_payload['report_requests']:
  727. await self.create_report(report_request)
  728. elif response_type == 'oadrRegisterReport':
  729. if 'reports' in response_payload and len(response_payload['reports']) > 0:
  730. for report in response_payload['reports']:
  731. await self.register_report(report)
  732. else:
  733. logger.warning(f"No handler implemented for incoming message "
  734. f"of type {response_type}, ignoring.")
  735. # Immediately poll again, because there might be more messages
  736. await self._poll()
  737. async def _ensure_client_session(self):
  738. if not self.client_session:
  739. if self.cert_path:
  740. ssl_context = ssl.create_default_context(cafile=self.ca_file,
  741. purpose=ssl.Purpose.CLIENT_AUTH)
  742. ssl_context.load_cert_chain(self.cert_path, self.key_path, self.passphrase)
  743. ssl_context.check_hostname = False
  744. connector = aiohttp.TCPConnector(ssl=ssl_context)
  745. self.client_session = aiohttp.ClientSession(connector=connector)
  746. else:
  747. self.client_session = aiohttp.ClientSession()