client.rst 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. ======
  2. Client
  3. ======
  4. An OpenADR Client (Virtual End Node or VEN) usually represents an entity that owns controllable devices. This can be electric vehicles, generators, wind turbines, refrigerated warehouses, et cetera. The client connects to a server, usualy representing a utility company, to discuss possible cooperation on energy usage throughout the day.
  5. .. _client_example:
  6. Example VEN
  7. ===========
  8. A straightforward example of an OpenADR VEN, which has one report and an event handler, would look like this:
  9. .. code-block:: python3
  10. import asyncio
  11. from datetime import timedelta
  12. from openleadr import OpenADRClient
  13. async def collect_report_value():
  14. # This callback is called when you need to collect a value for your Report
  15. return 1.23
  16. async def handle_event(event):
  17. # This callback receives an Event dict.
  18. # You should include code here that sends control signals to your resources.
  19. return 'optIn'
  20. # Create the client object
  21. client = OpenADRClient(ven_name='myven', vtn_url='http://some-vtn.com/OpenADR2/Simple/2.0b')
  22. # Add the report capability to the client
  23. client.add_report(callback=collect_report_value,
  24. resource_id='device001',
  25. measurement='voltage',
  26. sampling_rate=timedelta(seconds=10))
  27. # Add event handling capability to the client
  28. client.add_handler('on_event', handle_event)
  29. # Run the client in the Python AsyncIO Event Loop
  30. loop = asyncio.get_event_loop()
  31. loop.create_task(client.run())
  32. loop.run_forever()
  33. In the sections below, we'll go into more detail.
  34. .. _client_events:
  35. Dealing with Events
  36. ===================
  37. Events are informational or instructional messages from the server (VTN) which inform you of price changes, request load reduction, et cetera. Whenever there is an Event for your VEN, your ``on_event`` handler will be called with the event is dict-form as its first parameter.
  38. The Event consists of three main sections:
  39. 1. A time period for when this event is supposed to be active (``active_period``)
  40. 2. A list of Targets to which the Event applies (``targets``). This can be the VEN as a whole, or specific groups, assets, geographic areas, et cetera that this VEN represents.
  41. 3. A list of Signals (``signals``), which form the content of the Event. This can be price signals, load reduction signals, et cetera. Each signal has a name, a type, multiple Intervals that contain the relative start times, and some payload value for the client to interpret.
  42. After you evaluate all these properties, you have only one decision to make: Opt In or Opt Out. Your handler must return either the string ``optIn`` or ``optOut``, and OpenLEADR will see to it that your response is correctly formatted for the server.
  43. Example implementation:
  44. .. code-block:: python3
  45. async def on_event(event):
  46. # Check if we can opt in to this event
  47. first_signal = event['event_signals'][0]
  48. intervals = first_signal['intervals']
  49. target = event['target']
  50. ...
  51. return 'optIn'
  52. An example event dict might look like this:
  53. .. code-block:: python3
  54. {
  55. 'event_id': '123786-129831',
  56. 'active_period': {'dtstart': datetime.datetime(2020, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
  57. 'duration': datetime.timedelta(minutes=30)}
  58. 'event_signals': [{'signal_name': 'simple',
  59. 'signal_type': 'level',
  60. 'intervals': [{'dtstart': datetime.datetime(2020, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
  61. 'duration': datetime.timedelta(minutes=10),
  62. 'signal_payload': 1},
  63. {'dtstart': datetime.datetime(2020, 1, 1, 12, 10, 0, tzinfo=timezone.utc),
  64. 'duration': datetime.timedelta(minutes=10),
  65. 'signal_payload': 0},
  66. {'dtstart': datetime.datetime(2020, 1, 1, 12, 20, 0, tzinfo=timezone.utc),
  67. 'duration': datetime.timedelta(minutes=10),
  68. 'signal_payload': 1}],
  69. 'targets': [{'resource_id': 'Device001'}],
  70. 'targets_by_type': {'resource_id': ['Device001']}
  71. }
  72. Please note that you can access the targets in two ways, which may be useful if there are more than one target:
  73. 1. As a list of Target dicts
  74. 2. As a dictionary of targets, grouped by target type.
  75. For example:
  76. .. code-block:: python3
  77. {
  78. 'event_id': 'event123',
  79. # ...
  80. # As a list of Target dicts
  81. 'targets': [{'resource_id': 'resource01'},
  82. {'resource_id': 'resource02'},
  83. {'group_id': 'group01'},
  84. {'group_id': 'group02'}],
  85. # Grouped by target type
  86. 'targets_by_type': {'resource_id': ['resource01', 'resource02'],
  87. 'group_id': ['group01', 'group02']}
  88. }
  89. It is up to you which you want to use.
  90. .. _client_reports:
  91. Dealing with Reports
  92. ====================
  93. The VTN Server will most likely want to receive some reports like metering values or availability status from you.
  94. You can easily add reporting capabilities to your OpenADRClient object using the ``client.add_report`` method. In this method, you supply a callback function that will retrieve the current value for that measurement, as well as the resource_id, the measurement (like 'voltage', 'power', 'temperature', et cetera), optionally a unit and scale, and a sampling rate at which you can support this metervalue.
  95. OpenLEADR will then offer this report to the VTN, and if they request this report from you, your callback function will automatically be called when needed.
  96. Please see the :ref:`reporting` section for detailed information.
  97. .. _client_signing_messages:
  98. Signing outgoing messages
  99. =========================
  100. You can sign your outgoing messages using a public-private key pair in PEM format. This allows the receiving party to verify that the messages are actually coming from you.
  101. If you want you client to automatically sign your outgoing messages, use the following configuration:
  102. .. code-block:: python3
  103. async def main():
  104. client = OpenADRClient(ven_name='MyVEN',
  105. vtn_url='https://localhost:8080/',
  106. cert='/path/to/cert.pem',
  107. key='/path/to/key.pem',
  108. passphrase='my-key-password')
  109. ...
  110. .. _client_validating_messages:
  111. Validating incoming messages
  112. ============================
  113. You can validate incoming messages against a public key.
  114. .. code-block:: python3
  115. async def main():
  116. client = OpenADRClient(ven_name='MyVEN',
  117. vtn_url='https://localhost:8080/',
  118. vtn_fingerprint='AA:BB:CC:DD:EE:FF:11:22:33:44')
  119. This will automatically validate check that incoming messages are signed by the private key that belongs to the provided (public) certificate. If validation fails, you will see a Warning emitted, but the message will not be delivered to your handlers, protecting you from malicious messages being processed by your system. The sending party will see an error message returned.
  120. You should use both of the previous examples combined to secure both the incoming and the outgoing messages.