1
- CANopen for Python
2
- ==================
1
+ CANopen for Python, asyncio port
2
+ ================================
3
3
4
4
A Python implementation of the CANopen _ standard.
5
5
The aim of the project is to support the most common parts of the CiA 301
@@ -8,6 +8,8 @@ automation tasks rather than a standard compliant master implementation.
8
8
9
9
The library supports Python 3.6+.
10
10
11
+ This library is the asyncio port of CANopen. See below for code example.
12
+
11
13
12
14
Features
13
15
--------
@@ -147,6 +149,74 @@ The :code:`n` is the PDO index (normally 1 to 4). The second form of access is f
147
149
network.disconnect()
148
150
149
151
152
+ Asyncio
153
+ -------
154
+
155
+ This library can be used with asyncio.
156
+
157
+ .. code-block :: python
158
+
159
+ import asyncio
160
+ import canopen
161
+ import can
162
+
163
+ async def my_node (network , nodeid , od ):
164
+
165
+ # Create the node object and load the OD
166
+ node = network.add_node(nodeid, od)
167
+
168
+ # Read the PDOs from the remote
169
+ await node.tpdo.aread()
170
+ await node.rpdo.aread()
171
+
172
+ # Set the module state
173
+ node.nmt.set_state(' OPERATIONAL' )
174
+
175
+ # Set motor speed via SDO
176
+ await node.sdo[' MotorSpeed' ].aset_raw(2 )
177
+
178
+ while True :
179
+
180
+ # Wait for RPDO 1
181
+ t = await tpdo.await_for_reception(1 )
182
+ if not t:
183
+ continue
184
+
185
+ # Get the PDO value
186
+ rpm = node.tpdo[1 ][' MotorSpeed Actual' ].get_raw()
187
+ print (f ' SPEED on motor { nodeid} : ' , rpm)
188
+
189
+ # Sleep a little
190
+ await asyncio.sleep(0.2 )
191
+
192
+ # Send PDO with
193
+ node.rpdo[1 ][' Some variable' ].set_phys(42 )
194
+ node.rpdo[1 ].transmit()
195
+
196
+ async def main ():
197
+
198
+ # Open CAN bus
199
+ # Arguments are passed to python-can's can.Bus() constructor
200
+ # (see https://python-can.readthedocs.io/en/latest/bus.html).
201
+ bus = can.BUS(interface = ' pcan' , bitrate = 1000000 )
202
+
203
+ # Create a network representing one CAN bus
204
+ network = canopen.Network(bus)
205
+
206
+ # Start the notifier to enable canopen to respond to incoming CAN message
207
+ loop = asyncio.get_event_loop()
208
+ network.notifier = can.Notifier(bus, network.listeners, 1 , loop = loop)
209
+
210
+ # Create two independent tasks for two nodes 51 and 52 which will run concurrently
211
+ task1 = asyncio.create_task(my_node(network, 51 , ' /path/to/object_dictionary.eds' ))
212
+ task2 = asyncio.create_task(my_node(network, 52 , ' /path/to/object_dictionary.eds' ))
213
+
214
+ # Wait for both to complete (which will never happen)
215
+ await asyncio.gather((task1, task2))
216
+
217
+ asyncio.run(main())
218
+
219
+
150
220
Debugging
151
221
---------
152
222
0 commit comments