client.py 41 KB

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