client.py 17 KB

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