Debian Codegraph @

docs/source/usage/server_side.rst

raw
1 Server side usage
2 =================
3
4 This document explains how to create a central system and how to model a charge point at server side.
5
6
7 Create a websocket server
8 -------------------------
9
10 The following snippet creates a simple websocket server that listens on port 9000.
11 For every new websocket connection, the server prints *'Charge point connected'*.
12
13 .. code-block:: python
14
15 # server.py
16 import asyncio
17 import websockets
18
19 async def on_connect(connection: websockets.ServerConnection):
20 await connection.send('Connection made successfully')
21 print(f'Charge point connected: {connection.request.path}')
22
23 async def main():
24 server = await websockets.serve(
25 on_connect,
26 '0.0.0.0',
27 9000,
28 subprotocols=['ocpp1.6'],
29 )
30 await server.wait_closed()
31
32 if __name__ == '__main__':
33 asyncio.run(main())
34
35 A few things to note about the above code:
36
37 - The ``on_connect()`` handler receives an instance of `websockets.ServerConnection`_.
38 This is the handler that is executed on every new connection.
39
40 You can access the request URI of the connection using `connection.request`_.
41 The request URI is used as identifier for the charge point that made the connection.
42 To quote a snippet from section 3.1.1 of the OCPP-J specification:
43
44 *"The charge point's connection URL contains the charge point identity so that the Central System knows which charge point a Websocket connection belongs to."*
45
46 - The subprotocols parameter is used to specify the OCPP version that the server supports.
47 You can specify multiple subprotocols as follows:
48
49 .. code-block:: python
50
51 subprotocols=['ocpp1.6', 'ocpp2.0.1']
52
53 After you have started the server, connect a websocket client to it by using the websockets interactive client:
54
55 .. code-block:: bash
56
57 $ python -m websockets ws://localhost:9000/cp_id_1
58 Connected to ws://localhost:9000/cp_id_1.
59 < Connection made successfully
60 Connection closed: 1000 (OK).
61
62 OCPP compliant handler
63 ----------------------
64
65 The above example is a simple websocket server that does not implement the OCPP protocol.
66 Remove the ``on_connect()`` handler from the code above and replace it by the following snippet:
67
68 .. code-block:: python
69
70 # server.py
71 from datetime import datetime, timezone
72 import websockets
73
74 from ocpp.routing import on
75 from ocpp.v16 import ChargePoint as cp
76 from ocpp.v16 import call_result
77 from ocpp.v16.enums import Action, RegistrationStatus
78
79
80 class MyChargePoint(cp):
81 @on(Action.boot_notification)
82 async def on_boot_notification(
83 self, charge_point_vendor, charge_point_model, **kwargs
84 ):
85 return call_result.BootNotification(
86 current_time=datetime.now(tz=timezone.utc).isoformat(),
87 interval=10,
88 status=RegistrationStatus.accepted,
89 )
90
91
92 async def on_connect(connection: websockets.ServerConnection):
93 """
94 For every new connection, create a new ChargePoint instance,
95 and start listening for messages.
96 """
97 charge_point_id = connection.request.path.split("/")[-1]
98 charge_point = MyChargePoint(charge_point_id, connection)
99
100 await charge_point.start()
101
102
103 The ``on_connect()`` handler has been updated and now creates an instance of a ``MyChargePoint`` class and calls the `start()`_ coroutine.
104
105 The ``MyChargePoint`` class subclasses the `ocpp.v16.ChargePoint`_ class which is the core of the ocpp package.
106 This class implements the routing of messages from the client to the correct handler. It also validates the messages are are being sent and received.
107
108 In the above example, the `MyChargePoint` class implements a method ``on_boot_notification`` that handles the ocpp ``BootNotification`` message.
109 The `@on()`_ decorator which takes a string with the name of an action as a required argument, is responsible for registering the handler for the `BootNotification` message.
110 This package also provides an `@after()`_ decorator that can be used to register a post request handler.
111
112 According to the OCPP specification a payload of a ``BootNotification`` request must contain two required arguments: ``chargePointModel`` and ``chargePointVendor``, as well as an seven optional arguments.
113 The handler reflects this by having two required arguments, ``charge_point_vendor`` and ``charge_point_model``.
114 The handler uses ``**kwargs`` for the optional arguments.
115
116 The handler returns an instance of `ocpp.v16.call_result.BootNotification`_.
117 This object is used to create a valid response that is to be sent back to the client.
118
119 .. important::
120
121 OCPP uses a camelCase naming scheme for the keys in the JSON payload. Python, on the other hand, uses snake_case.
122 Therefore this package converts all the keys in messages from camelCase to snake_case and vice versa to make sure that the code is Pythonic.
123
124 Now start the websocket server and connect a websocket client to it.
125 If the client is connected, send the following BootNotification message to the server:
126
127 .. code-block:: shell
128
129 `[2, "12345", "BootNotification", {"chargePointVendor": "The Mobility House", "chargePointModel": "Optimus"}]`
130
131 The server should response and you should see something like this:
132
133 .. code-block:: shell
134
135 $ python -m websockets ws://localhost:9000/cp_id_1
136 Connected to ws://localhost:9000/cp_id_1.
137 cp_id_1: receive message [2, "12345", "BootNotification", {"chargePointVendor": "The Mobility House", "chargePointModel": "Optimus"}]
138 cp_id_1: send [3, "12345", {"currentTime": "2025-05-10T12:00:00+00:00", "interval": 10, "status": "Accepted"}]
139
140 .. _websockets.ServerConnection: https://websockets.readthedocs.io/en/stable/reference/asyncio/server.html#websockets.asyncio.server.ServerConnection
141 .. _connection.request: https://websockets.readthedocs.io/en/stable/reference/datastructures.html#websockets.http11.Request
142 .. _start(): https://github.com/search?q=repo%3Amobilityhouse%2Focpp+%22def+start%22&type=code
143 .. _ocpp.v16.ChargePoint: https://github.com/search?q=repo%3Amobilityhouse%2Focpp+%22class+ChargePoint%28%22+path%3A%2F%5Eocpp%5C%2Fv16%5C%2F%2F&type=code
144 .. _@on(): https://github.com/search?q=repo%3Amobilityhouse%2Focpp+%22def+on%28%22&type=code
145 .. _@after(): https://github.com/search?q=repo%3Amobilityhouse%2Focpp+%22def+after%28%22&type=code
146 .. _ocpp.v16.call_result.BootNotification: https://github.com/search?q=repo%3Amobilityhouse%2Focpp+%22class+BootNotification%22+path%3A%2F%5Eocpp%5C%2Fv16%5C%2Fcall_result%2F&type=code
147
148
149 Congratulations!
150 You have successfully created a simple websocket server that implements the OCPP protocol.
151 You can now start implementing the other messages that are required for your application.