client.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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 xmltodict
  16. import random
  17. import aiohttp
  18. from openleadr.utils import peek, generate_id, certificate_fingerprint
  19. from openleadr.messaging import create_message, parse_message
  20. from openleadr import enums
  21. from datetime import datetime, timedelta, timezone
  22. from http import HTTPStatus
  23. from apscheduler.schedulers.asyncio import AsyncIOScheduler
  24. import asyncio
  25. from asyncio import iscoroutine
  26. from functools import partial
  27. import warnings
  28. MEASURANDS = {'power_real': 'power_quantity',
  29. 'power_reactive': 'power_quantity',
  30. 'power_apparent': 'power_quantity',
  31. 'energy_real': 'energy_quantity',
  32. 'energy_reactive': 'energy_quantity',
  33. 'energy_active': 'energy_quantity'}
  34. class OpenADRClient:
  35. """
  36. Main client class. Most of these methods will be called automatically, but
  37. you can always choose to call them manually.
  38. """
  39. def __init__(self, ven_name, vtn_url, debug=False, cert=None, key=None, passphrase=None, vtn_fingerprint=None):
  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 for signing messages
  46. :param str key: The path to a PEM-formatted Private Key file to use for signing messages
  47. :param str fingerprint: The fingerprint for the VTN's certificate to verify incomnig messages
  48. """
  49. self.ven_name = ven_name
  50. self.vtn_url = vtn_url
  51. self.ven_id = None
  52. self.poll_frequency = None
  53. self.debug = debug
  54. self.reports = {} # Mapping of all available reports from the VEN
  55. self.report_requests = {} # Mapping of the reports requested by the VTN
  56. self.report_schedulers = {} # Mapping between reportRequestIDs and our internal report schedulers
  57. self.scheduler = AsyncIOScheduler()
  58. self.client_session = aiohttp.ClientSession()
  59. if cert and key:
  60. with open(cert, 'rb') as file:
  61. cert = file.read()
  62. with open(key, 'rb') as file:
  63. key = file.read()
  64. print("*" * 80)
  65. print("Your VEN Certificate Fingerprint is", certificate_fingerprint(cert))
  66. print("Please deliver this fingerprint to the VTN you are connecting to.")
  67. print("You do not need to keep this a secret.")
  68. print("*" * 80)
  69. self._create_message = partial(create_message,
  70. cert=cert,
  71. key=key,
  72. passphrase=passphrase)
  73. self._parse_message = partial(parse_message,
  74. fingerprint=vtn_fingerprint)
  75. async def run(self):
  76. """
  77. Run the client in full-auto mode.
  78. """
  79. if not hasattr(self, 'on_event'):
  80. raise NotImplementedError("You must implement an on_event function or coroutine.")
  81. await self.create_party_registration()
  82. if not self.ven_id:
  83. print("No VEN ID received from the VTN, aborting registration.")
  84. return
  85. if self.reports:
  86. await self.register_report()
  87. # Set up automatic polling
  88. if self.poll_frequency.total_seconds() < 60:
  89. cron_second = f"*/{self.poll_frequency.seconds}"
  90. cron_minute = "*"
  91. cron_hour = "*"
  92. elif self.poll_frequency.total_seconds() < 3600:
  93. cron_second = "0"
  94. cron_minute = f'*/{int(self.poll_frequency.total_seconds() / 60)}'
  95. cron_hour = "*"
  96. elif self.poll_frequency.total_seconds() < 86400:
  97. cron_second = "0"
  98. cron_minute = "0"
  99. cron_hour = f'*/{int(self.poll_frequency.total_seconds() / 3600)}'
  100. elif self.poll_frequency.total_seconds() > 86400:
  101. print("Polling with intervals of more than 24 hours is not supported.")
  102. return
  103. self.scheduler.add_job(self._poll, trigger='cron', second=cron_second, minute=cron_minute, hour=cron_hour)
  104. self.scheduler.start()
  105. def add_report(self, callable, report_id, report_name, reading_type, report_type,
  106. sampling_rate, resource_id, measurand, unit, scale="none",
  107. power_ac=True, power_hertz=50, power_voltage=230, market_context=None):
  108. """
  109. Add a new reporting capability to the client.
  110. :param callable callable: A callable or coroutine that will fetch the value for a specific report. This callable will be passed the report_id and the r_id of the requested value.
  111. :param str report_id: A unique identifier for this report.
  112. :param str report_name: An OpenADR name for this report (one of openleadr.enums.REPORT_NAME)
  113. :param str reading_type: An OpenADR reading type (found in openleadr.enums.READING_TYPE)
  114. :param str report_type: An OpenADR report type (found in openleadr.enums.REPORT_TYPE)
  115. :param datetime.timedelta sampling_rate: The sampling rate for the measurement.
  116. :param resource_id: A specific name for this resource within this report.
  117. :param str unit: The unit for this measurement.
  118. """
  119. if report_name not in enums.REPORT_NAME.values:
  120. raise ValueError(f"{report_name} is not a valid report_name. Valid options are {', '.join(enums.REPORT_NAME.values)}.")
  121. if reading_type not in enums.READING_TYPE.values:
  122. raise ValueError(f"{reading_type} is not a valid reading_type. Valid options are {', '.join(enums.READING_TYPE.values)}.")
  123. if report_type not in enums.REPORT_TYPE.values:
  124. raise ValueError(f"{report_type} is not a valid report_type. Valid options are {', '.join(enums.REPORT_TYPE.values)}.")
  125. if measurand not in MEASURANDS:
  126. raise ValueError(f"{measurand} is not a valid measurand. Valid options are 'power_real', 'power_reactive', 'power_apparent', 'energy_real', 'energy_reactive', 'energy_active', 'energy_quantity', 'voltage'")
  127. if scale not in enums.SI_SCALE_CODE.values:
  128. raise ValueError(f"{scale} is not a valid scale. Valid options are {', '.join(enums.SI_SCALE_CODE.values)}")
  129. report_description = {'market_context': market_context,
  130. 'r_id': resource_id,
  131. 'reading_type': reading_type,
  132. 'report_type': report_type,
  133. 'sampling_rate': {'max_period': sampling_rate,
  134. 'min_period': sampling_rate,
  135. 'on_change': False},
  136. measurand: {'item_description': measurand,
  137. 'item_units': unit,
  138. 'si_scale_code': scale}}
  139. if 'power' in measurand:
  140. report_description[measurand]['power_attributes'] = {'ac': power_ac, 'hertz': power_hertz, 'voltage': power_voltage}
  141. if report_id in self.reports:
  142. report = self.reports[report_id]['report_descriptions'].append(report_description)
  143. else:
  144. report = {'callable': callable,
  145. 'created_date_time': datetime.now(timezone.utc),
  146. 'report_id': report_id,
  147. 'report_name': report_name,
  148. 'report_request_id': generate_id(),
  149. 'report_specifier_id': report_id + "_" + report_name.lower(),
  150. 'report_descriptions': [report_description]}
  151. self.reports[report_id] = report
  152. self.report_ids[resource_id] = {'item_base': measurand}
  153. async def query_registration(self):
  154. """
  155. Request information about the VTN.
  156. """
  157. request_id = generate_id()
  158. service = 'EiRegisterParty'
  159. message = self._create_message('oadrQueryRegistration', request_id=request_id)
  160. response_type, response_payload = await self._perform_request(service, message)
  161. return response_type, response_payload
  162. async def create_party_registration(self, http_pull_model=True, xml_signature=False,
  163. report_only=False, profile_name='2.0b',
  164. transport_name='simpleHttp', transport_address=None, ven_id=None):
  165. """
  166. Take the neccessary steps to register this client with the server.
  167. :param bool http_pull_model: Whether to use the 'pull' model for HTTP.
  168. :param bool xml_signature: Whether to sign each XML message.
  169. :param bool report_only: Whether or not this is a reporting-only client which does not deal with Events.
  170. :param str profile_name: Which OpenADR profile to use.
  171. :param str transport_name: The transport name to use. Either 'simpleHttp' or 'xmpp'.
  172. :param str transport_address: Which public-facing address the server should use to communicate.
  173. :param str ven_id: The ID for this VEN. If you leave this blank, a VEN_ID will be assigned by the VTN.
  174. """
  175. request_id = generate_id()
  176. service = 'EiRegisterParty'
  177. payload = {'ven_name': self.ven_name,
  178. 'http_pull_model': http_pull_model,
  179. 'xml_signature': xml_signature,
  180. 'report_only': report_only,
  181. 'profile_name': profile_name,
  182. 'transport_name': transport_name,
  183. 'transport_address': transport_address}
  184. if ven_id:
  185. payload['ven_id'] = ven_id
  186. message = self._create_message('oadrCreatePartyRegistration', request_id=generate_id(), **payload)
  187. response_type, response_payload = await self._perform_request(service, message)
  188. if response_type is None:
  189. return
  190. if response_payload['response']['response_code'] != 200:
  191. status_code = response_payload['response']['response_code']
  192. status_description = response_payload['response']['response_description']
  193. print(f"Got error on Create Party Registration: {status_code} {status_description}")
  194. return
  195. self.ven_id = response_payload['ven_id']
  196. self.poll_frequency = response_payload.get('requested_oadr_poll_freq', timedelta(seconds=10))
  197. print(f"VEN is now registered with ID {self.ven_id}")
  198. print(f"The polling frequency is {self.poll_frequency}")
  199. return response_type, response_payload
  200. async def cancel_party_registration(self):
  201. raise NotImplementedError("Cancel Registration is not yet implemented")
  202. async def request_event(self, reply_limit=1):
  203. """
  204. Request the next Event from the VTN, if it has any.
  205. """
  206. payload = {'request_id': generate_id(),
  207. 'ven_id': self.ven_id,
  208. 'reply_limit': reply_limit}
  209. message = self._create_message('oadrRequestEvent', **payload)
  210. service = 'EiEvent'
  211. response_type, response_payload = await self._perform_request(service, message)
  212. return response_type, response_payload
  213. async def created_event(self, request_id, event_id, opt_type, modification_number=1):
  214. """
  215. Inform the VTN that we created an event.
  216. """
  217. service = 'EiEvent'
  218. payload = {'ven_id': self.ven_id,
  219. 'response': {'response_code': 200,
  220. 'response_description': 'OK',
  221. 'request_id': request_id},
  222. 'event_responses': [{'response_code': 200,
  223. 'response_description': 'OK',
  224. 'request_id': request_id,
  225. 'event_id': event_id,
  226. 'modification_number': modification_number,
  227. 'opt_type': opt_type}]}
  228. message = self._create_message('oadrCreatedEvent', **payload)
  229. response_type, response_payload = await self._perform_request(service, message)
  230. async def register_report(self):
  231. """
  232. Tell the VTN about our reporting capabilities.
  233. """
  234. request_id = generate_id()
  235. payload = {'request_id': generate_id(),
  236. 'ven_id': self.ven_id,
  237. 'reports': self.reports}
  238. service = 'EiReport'
  239. message = self._create_message('oadrRegisterReport', **payload)
  240. response_type, response_payload = await self._perform_request(service, message)
  241. # Remember which reports the VTN is interested in
  242. return response_type, response_payload
  243. async def created_report(self):
  244. pass
  245. async def poll(self):
  246. """
  247. Request the next available message from the Server. This coroutine is called automatically.
  248. """
  249. service = 'OadrPoll'
  250. message = self._create_message('oadrPoll', ven_id=self.ven_id)
  251. response_type, response_payload = await self._perform_request(service, message)
  252. return response_type, response_payload
  253. async def update_report(self, report_id, resource_id=None):
  254. """
  255. Calls the previously registered report callable, and send the result as a message to the VTN.
  256. """
  257. if not resource_id:
  258. resource_ids = self.reports[report_id]['report_descriptions'].keys()
  259. elif isinstance(resource_id, str):
  260. resource_ids = [resource_id]
  261. else:
  262. resource_ids = resource_id
  263. value = self.reports[report_id]['callable'](resource_id)
  264. if iscoroutine(value):
  265. value = await value
  266. report_type = self.reports[report_id][resource_id]['report_type']
  267. for measurand in MEASURAND:
  268. if measurand in self.reports[report_id][resource_id]:
  269. item_base = measurand
  270. break
  271. report = {'report_id': report_id,
  272. 'report_descriptions': {resource_id: {MEASURANDS[measurand]: {'quantity': value,
  273. measurand: self.reports[report_id][resource_id][measurand]},
  274. 'report_type': self.reports[report_id][resource_id]['report_type'],
  275. 'reading_type': self.reports[report_id][resource_id]['reading_type']}},
  276. 'report_name': self.report['report_id']['report_name'],
  277. 'report_request_id': self.reports['report_id']['report_request_id'],
  278. 'report_specifier_id': self.report['report_id']['report_specifier_id'],
  279. 'created_date_time': datetime.now(timezone.utc)}
  280. service = 'EiReport'
  281. message = self._create_message('oadrUpdateReport', report)
  282. response_type, response_payload = self._perform_request(service, message)
  283. if response_type is not None:
  284. # We might get a oadrCancelReport message in this thing:
  285. if 'cancel_report' in response_payload:
  286. print("TODO: cancel this report")
  287. async def _perform_request(self, service, message):
  288. if self.debug:
  289. print(f"Client is sending {message}")
  290. url = f"{self.vtn_url}/{service}"
  291. try:
  292. async with self.client_session.post(url, data=message) as req:
  293. if req.status != HTTPStatus.OK:
  294. warnings.warn(f"Non-OK status when performing a request to {url} with data {message}: {req.status}")
  295. return None, {}
  296. content = await req.read()
  297. if self.debug:
  298. print(content.decode('utf-8'))
  299. except:
  300. # Could not connect to server
  301. warnings.warn(f"Could not connect to server with URL {self.vtn_url}")
  302. return None, {}
  303. try:
  304. message_type, message_payload = self._parse_message(content)
  305. except Exception as err:
  306. warnings.warn(f"The incoming message could not be parsed or validated: {content}.")
  307. raise err
  308. return None, {}
  309. return message_type, message_payload
  310. async def _on_event(self, message):
  311. if self.debug:
  312. print("ON_EVENT")
  313. result = self.on_event(message)
  314. if iscoroutine(result):
  315. result = await result
  316. if self.debug:
  317. print(f"Now responding with {result}")
  318. request_id = message['request_id']
  319. event_id = message['events'][0]['event_descriptor']['event_id']
  320. await self.created_event(request_id, event_id, result)
  321. return
  322. async def _poll(self):
  323. print("Now polling")
  324. response_type, response_payload = await self.poll()
  325. if response_type is None:
  326. return
  327. if response_type == 'oadrResponse':
  328. print("No events or reports available")
  329. return
  330. if response_type == 'oadrRequestReregistration':
  331. await self.create_party_registration()
  332. if response_type == 'oadrDistributeEvent':
  333. await self._on_event(response_payload)
  334. elif response_type == 'oadrUpdateReport':
  335. await self._on_report(response_payload)
  336. else:
  337. print(f"No handler implemented for message type {response_type}, ignoring.")
  338. # Immediately poll again, because there might be more messages
  339. await self._poll()