server.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. .. _server:
  2. ======
  3. Server
  4. ======
  5. If you are implementing an OpenADR Server ("Virtual Top Node") using OpenLEADR, read this page.
  6. .. _server_example:
  7. 1-minute VTN example
  8. ====================
  9. Here's an example of a server that accepts registrations from a VEN named
  10. 'ven_123', requests all reports that it offers, and creates an Event for this
  11. VEN.
  12. .. code-block:: python3
  13. import asyncio
  14. from datetime import datetime, timezone, timedelta
  15. from openleadr import OpenADRServer
  16. async def on_create_party_registration(registration_info):
  17. """
  18. Inspect the registration info and return a ven_id and registration_id.
  19. """
  20. if registration_info['ven_name'] == 'ven123':
  21. ven_id = 'ven_id_123'
  22. registration_id = 'reg_id_123'
  23. return ven_id, registration_id
  24. else:
  25. return False
  26. async def on_register_report(ven_id, resource_id, measurement, unit, scale,
  27. min_sampling_interval, max_sampling_interval):
  28. """
  29. Inspect a report offering from the VEN and return a callback and sampling interval for receiving the reports.
  30. """
  31. callback = partial(on_update_report, ven_id=ven_id, resource_id=resource_id, measurement=measurement)
  32. sampling_interval = min_sampling_interval
  33. return callback, sampling_interval
  34. async def on_update_report(data, ven_id, resource_id, measurement):
  35. """
  36. Callback that receives report data from the VEN and handles it.
  37. """
  38. for time, value in data:
  39. print(f"Ven {ven_id} reported {measurement} = {value} at time {time} for resource {resource_id}")
  40. # Create the server object
  41. server = OpenADRServer(vtn_id='myvtn')
  42. # Add the handler for client (VEN) registrations
  43. server.add_handler('on_create_party_registration', on_create_party_registration)
  44. # Add the handler for report registrations from the VEN
  45. server.add_handler('on_register_report', on_register_report)
  46. # Add a prepared event for a VEN that will be picked up when it polls for new messages.
  47. server.add_event(ven_id='ven_id_123',
  48. event_name='simple',
  49. event_type='level',
  50. intervals=[{'dtstart': datetime(2021, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
  51. 'duration': timedelta(minutes=10),
  52. 'signal_payload': 1}])
  53. # Run the server on the asyncio event loop
  54. loop = asyncio.get_event_loop()
  55. loop.create_task(server.run())
  56. loop.run_forever()
  57. Read on for more details!
  58. .. _server_registration:
  59. Registration
  60. ============
  61. If a client (VEN) wants to register for the first time, it will go through a Registration procedure.
  62. .. admonition:: Implementation Checklist
  63. 1. Create a handler that decides what to do with new registrations, based on their registration info.
  64. The client will send a :ref:`oadrQueryRegistration` message. The server will respond with a :ref:`oadrCreatedPartyRegistration` message containing a list of its capabilities, notably the implemented OpenADR protocol versions and the available Transport Mechanisms (HTTP and/or XMPP).
  65. The client will then usually send a :ref:`oadrCreatePartyRegistration` message, in which it registers to a specific OpenADR version and Transport Method. The server must then decide what it wants to do with this registration.
  66. In the case that the registration is accepted, the VTN will generate a venID and a RegistrationID for this VEN and respond with a :ref:`oadrCreatedPartyRegistration` message.
  67. In your application, when a VEN sends a :ref:`oadrCreatePartyRegistration` request, it will call your ``on_create_party_registration`` handler. This handler must somehow look up what to do with this request, and respond with a ``ven_id, registration_id`` tuple.
  68. Example implementation:
  69. .. code-block:: python3
  70. from openleadr.utils import generate_id
  71. async def on_create_party_registration(payload):
  72. ven_name = payload['ven_name']
  73. # Check whether or not this VEN is allowed to register
  74. result = await database.query("""SELECT COUNT(*)
  75. FROM vens
  76. WHERE ven_name = ?""",
  77. (payload['ven_name'],))
  78. if result == 1:
  79. # Generate an ID for this registration
  80. ven_id = generate_id()
  81. registration_id = generate_id()
  82. # Store the registration in a database (pseudo-code)
  83. await database.query("""UPDATE vens
  84. SET ven_id = ?
  85. registration_id = ?
  86. WHERE ven_name = ?""",
  87. (ven_id, registration_id, ven_name))
  88. # Return the registration ID.
  89. # This will be put into the correct form by the OpenADRServer.
  90. return ven_id, registration_id
  91. .. _server_events:
  92. Events
  93. ======
  94. The server (VTN) is expected to know when it needs to inform the clients (VENs) of certain events that they must respond to. This could be a predicted shortage or overage of available power in a certain electricity grid area, for example.
  95. The easiest way to supply events to a VEN is by using OpenLEADR's built-in message queing system. You simply add an event for a ven using the ``server.add_event`` method. You supply the ven_id for which the event is required, as well as the ``signal_name``, ``signal_type``, ``intervals`` and ``targets``. This will build an event object with a single signal for a VEN. If you need more flexibility, you can alternatively construct the event dictionary yourself and supply it directly to the ``add_raw_event`` method.
  96. The VEN can decide whether to opt in or opt out of the event. To be notified of their opt status, you supply a callback handler which will be called when the VEN has responded to the event request.
  97. .. code-block:: python3
  98. from openleadr import OpenADRServer
  99. from functools import partial
  100. from datetime import datetime, timezzone
  101. async def event_callback(ven_id, event_id, opt_status):
  102. print(f"VEN {ven_id} responded {opt_status} to event {event_id}")
  103. server = OpenADRServer(vtn_id='myvtn')
  104. event_id = server.add_event(ven_id='ven123',
  105. signal_name='simple',
  106. signal_type='level',
  107. intervals=[{'dtstart': datetime(2020. 1, 1, 12, 0, 0, tzinfo=timezone.utc),
  108. 'signal_payload': 1},
  109. {'dtstart': datetime(2020. 1, 1, 12, 15, 0, tzinfo=timezone.utc),
  110. 'signal_payload': 0}],
  111. target=[{'resource_id': 'Device001'}],
  112. callback=event_callback)
  113. Alternatively, you can use the handy constructors in ``openleadr.objects`` to format parts of the event:
  114. .. code-block:: python3
  115. from openleadr import OpenADRServer
  116. from openleadr.objects import Target, Interval
  117. from datetime import datetime, timezone
  118. from functools import partial
  119. async def event_callback(ven_id, event_id, opt_status):
  120. print(f"VEN {ven_id} responded {opt_status} to event {event_id}")
  121. server = OpenADRServer(vtn_id='myvtn')
  122. event_id = server.add_event(ven_id='ven123',
  123. signal_name='simple',
  124. signal_type='level',
  125. intervals=[Interval(dtstart=datetime(2020, 1, 1, 12, 15, 0, tzinfo=timezone.utc),
  126. signal_payload=0),
  127. Interval(dtstart=datetime(2020, 1, 1, 12, 15, 0, tzinfo=timezone.utc),
  128. signal_payload=1)]
  129. target=[Target(resource_id='Device001')],
  130. callback=event_callback)
  131. If you want to add a "raw" event directly, you can use this example as a guid:
  132. .. code-block:: python3
  133. from openleadr import OpenADRServer
  134. from openleadr.objects import Event, EventDescriptor, EventSignal, Target, Interval
  135. from datetime import datetime, timezone
  136. from functools import partial
  137. async def event_callback(ven_id, event_id, opt_status):
  138. print(f"VEN {ven_id} responded {opt_status} to event {event_id}")
  139. server = OpenADRServer(vtn_id='myvtn')
  140. event = Event(event_descriptor=EventDescriptor(event_id='event001',
  141. modification_number=0,
  142. event_status='far',
  143. market_context='http://marketcontext01'),
  144. event_signals=[EventSignal(signal_id='signal001',
  145. signal_type='level',
  146. signal_name='simple',
  147. intervals=[Interval(dtstart=now,
  148. duration=datetime.timedelta(minutes=10),
  149. signal_payload=1)]),
  150. EventSignal(signal_id='signal002',
  151. signal_type='price',
  152. signal_name='ELECTRICITY_PRICE',
  153. intervals=[Interval(dtstart=now,
  154. duration=datetime.timedelta(minutes=10),
  155. signal_payload=1)])],
  156. targets=[objects.Target(ven_id='ven123')])
  157. server.add_raw_event(ven_id='ven123', event=event, callback=event_callback)
  158. If you want to add an event and wait for the response in a single coroutine, you can pass an asyncio Future instead of a function or coroutine as the callback argument:
  159. .. code-block:: python3
  160. import asyncio
  161. ...
  162. async def generate_event():
  163. loop = asyncio.get_event_loop()
  164. opt_status_future = loop.create_future()
  165. server.add_event(..., callback=opt_status_future)
  166. opt_status = await opt_status_future
  167. print(f"The opt status for this event is {opt_status}")
  168. A word on event targets
  169. ~~~~~~~~~~~~~~~~~~~~~~~
  170. The Target of your Event is an indication for the VEN which resources or devices should be affected. You can supply the target of the event in serveral ways:
  171. - Assigning the ``target`` parameter with a single ``objects.Target`` object.
  172. - Assigning the ``targets`` parameter with a list of ``objects.Target`` objects.
  173. - Assigning the ``targets_by_type`` parameters with a dict, that lists targets grouped by their type, like this:
  174. .. code-block:: python3
  175. server.add_event(...
  176. targets_by_type={'resource_id': ['resource01', 'resource02'],
  177. 'group_id': ['group01', 'group02']}
  178. )
  179. If you dont assign any Target, the target will be set to the ``ven_id`` that you specified.
  180. .. _server_reports:
  181. Reports
  182. =======
  183. Please see the :ref:`reporting` section.
  184. .. _server_implement:
  185. Things you should implement
  186. ===========================
  187. You should implement the following handlers:
  188. - ``on_create_party_registration(registration_info)``
  189. - ``on_register_report(ven_id, resource_id, measurement, unit, scale, min_sampling_interval, max_sampling_interval)``
  190. Optionally:
  191. - ``on_poll(ven_id)``; only if you don't want to use the internal message queue.
  192. .. _server_signing_messages:
  193. Signing Messages
  194. ================
  195. The OpenLEADR can sign your messages and validate incoming messages. For some background, see the :ref:`message_signing`.
  196. Example implementation:
  197. .. code-block:: python3
  198. from openleadr import OpenADRServr
  199. def fingerprint_lookup(ven_id):
  200. # Look up the certificate fingerprint that is associated with this VEN.
  201. fingerprint = database.lookup('certificate_fingerprint').where(ven_id=ven_id) # Pseudo code
  202. return fingerprint
  203. server = OpenADRServer(vtn_id='MyVTN',
  204. cert='/path/to/cert.pem',
  205. key='/path/to/private/key.pem',
  206. passphrase='mypassphrase',
  207. fingerprint_lookup=fingerprint_lookup)
  208. The VEN's fingerprint should be obtained from the VEN outside of OpenADR.
  209. .. _server_message_handlers:
  210. Message Handlers
  211. ================
  212. Your server has to deal with the different OpenADR messages. The way this works is that OpenLEADR will expose certain modules at the appropriate endpoints (like /oadrPoll and /EiRegister), and figure out what type of message is being sent. It will then call your handler with the contents of the message that are relevant for you to handle. This section provides an overview with examples for the different kinds of messages that you can expect and what should be returned.
  213. .. _server_on_register_report:
  214. on_register_report
  215. ------------------
  216. The VEN informs you which reports it has available. If you want to periodically receive any of these reports, you should return a list of the r_ids that you want to receive.
  217. Signature:
  218. .. code-block:: python3
  219. async def on_register_report(ven_id, resource_id, measurement, unit, scale,
  220. min_sampling_interval, max_sampling_interval):
  221. # If we want this report:
  222. return (callback, requested_sampling_interval)
  223. # or
  224. return None
  225. .. _server_on_query_registration:
  226. on_query_registration
  227. ---------------------
  228. A prospective VEN is requesting information about your VTN, like the versions and transports you support. You should not implement this handler and let OpenLEADR handle this response.
  229. .. _server_on_create_party_registration:
  230. on_create_party_registration
  231. ----------------------------
  232. The VEN tries to register with you. You will receive a registration_info dict that contains, among other things, a field `ven_name` which is how the VEN identifies itself. If the VEN is accepted, you return a ``ven_id, registration_id`` tuple. If not, return ``False``:
  233. .. code-block:: python3
  234. async def on_create_party_registration(registration_info):
  235. ven_name = registration_info['ven_name']
  236. ...
  237. if ven_is_known:
  238. return ven_id, registration_id
  239. else
  240. return None
  241. During this step, the VEN probably does not have a ``venID`` yet. If they connected using a secure TLS connection, the ``registration_info`` dict will contain the fingerprint of the public key that was used for this connection (``registration_info['fingerprint']``). Your ``on_create_party_registration`` handler should check this fingerprint value against a value that you received offline, to be sure that the ven with this venName is the correct VEN.
  242. .. _server_on_cancel_party_registration:
  243. on_cancel_party_registration
  244. ----------------------------
  245. The VEN informs you that they are cancelling their registration and no longer wish to be contacted by you.
  246. You should deregister the VEN internally, and return `None`.
  247. Return: ``None``
  248. .. _server_on_poll:
  249. on_poll
  250. -------
  251. You only need to implement this if you don't want to use the automatic internal message queue. If you add this handler to the server, the internal message queue will be automatically disabled.
  252. The VEN is requesting the next message that you have for it. You should return a tuple of message_type and message_payload as a dict. If there is no message for the VEN, you should return `None`.
  253. Signature:
  254. .. code-block:: python3
  255. async def on_poll(ven_id):
  256. ...
  257. return message_type, message_payload
  258. If you implement your own on_poll handler, you should also include your own ``on_created_event`` handler that retrieves the opt status for a distributed event.
  259. .. _server_on_created_event:
  260. on_created_event
  261. ----------------
  262. You only need to implement this if you don't want to use the automatic internal message queue. Otherwise, you supply a per-event callback function when you add the event to the internal queue.
  263. Signature:
  264. .. code-block:: python3
  265. async def on_created_event(ven_id, event_id, opt_status):
  266. print("Ven {ven_id} returned {opt_status} for event {event_id}")
  267. # return None