Repository navigation
Expand file tree
/
Copy pathnetwork.py
More file actions
382 lines (316 loc) · 12.1 KB
/
Copy pathnetwork.py
File metadata and controls
382 lines (316 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
try:
from collections.abc import MutableMapping
except ImportError:
from collections import MutableMapping
import logging
import threading
import struct
try:
import can
from can import Listener
from can import CanError
except ImportError:
# Do not fail if python-can is not installed
can = None
Listener = object
CanError = Exception
from .node import RemoteNode, LocalNode
from .sync import SyncProducer
from .timestamp import TimeProducer
from .nmt import NmtMaster
from .lss import LssMaster
from .objectdictionary.eds import import_from_node
logger = logging.getLogger(__name__)
class Network(MutableMapping):
"""Representation of one CAN bus containing one or more nodes."""
def __init__(self, bus=None):
"""
:param can.BusABC bus:
A python-can bus instance to re-use.
"""
#: A python-can :class:`can.BusABC` instance which is set after
#: :meth:`canopen.Network.connect` is called
self.bus = bus
#: A :class:`~canopen.network.NodeScanner` for detecting nodes
self.scanner = NodeScanner(self)
#: List of :class:`can.Listener` objects.
#: Includes at least MessageListener.
self.listeners = [MessageListener(self)]
self.notifier = None
self.nodes = {}
self.subscribers = {}
self.send_lock = threading.Lock()
self.sync = SyncProducer(self)
self.time = TimeProducer(self)
self.nmt = NmtMaster(0)
self.nmt.network = self
self.lss = LssMaster()
self.lss.network = self
self.subscribe(self.lss.LSS_RX_COBID, self.lss.on_message_received)
def subscribe(self, can_id, callback):
"""Listen for messages with a specific CAN ID.
:param int can_id:
The CAN ID to listen for.
:param callback:
Function to call when message is received.
"""
self.subscribers.setdefault(can_id, list())
if callback not in self.subscribers[can_id]:
self.subscribers[can_id].append(callback)
def unsubscribe(self, can_id, callback=None):
"""Stop listening for message.
:param int can_id:
The CAN ID from which to unsubscribe.
:param callback:
If given, remove only this callback. Otherwise all callbacks for
the CAN ID.
"""
if callback is None:
del self.subscribers[can_id]
else:
self.subscribers[can_id].remove(callback)
def connect(self, *args, **kwargs):
"""Connect to CAN bus using python-can.
Arguments are passed directly to :class:`can.BusABC`. Typically these
may include:
:param channel:
Backend specific channel for the CAN interface.
:param str bustype:
Name of the interface. See
`python-can manual <https://python-can.readthedocs.io/en/latest/configuration.html#interface-names>`__
for full list of supported interfaces.
:param int bitrate:
Bitrate in bit/s.
:raises can.CanError:
When connection fails.
"""
# If bitrate has not been specified, try to find one node where bitrate
# has been specified
if "bitrate" not in kwargs:
for node in self.nodes.values():
if node.object_dictionary.bitrate:
kwargs["bitrate"] = node.object_dictionary.bitrate
break
self.bus = can.interface.Bus(*args, **kwargs)
logger.info("Connected to '%s'", self.bus.channel_info)
self.notifier = can.Notifier(self.bus, self.listeners, 1)
return self
def disconnect(self):
"""Disconnect from the CAN bus.
Must be overridden in a subclass if a custom interface is used.
"""
for node in self.nodes.values():
if hasattr(node, "pdo"):
node.pdo.stop()
self.notifier.stop()
self.bus.shutdown()
self.bus = None
self.check()
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.disconnect()
def add_node(self, node, object_dictionary=None, upload_eds=False):
"""Add a remote node to the network.
:param node:
Can be either an integer representing the node ID, a
:class:`canopen.RemoteNode` or :class:`canopen.LocalNode` object.
:param object_dictionary:
Can be either a string for specifying the path to an
Object Dictionary file or a
:class:`canopen.ObjectDictionary` object.
:param bool upload_eds:
Set ``True`` if EDS file should be uploaded from 0x1021.
:return:
The Node object that was added.
:rtype: canopen.RemoteNode
"""
if isinstance(node, int):
if upload_eds:
logger.info("Trying to read EDS from node %d", node)
object_dictionary = import_from_node(node, self)
node = RemoteNode(node, object_dictionary)
self[node.id] = node
return node
def create_node(self, node, object_dictionary=None):
"""Create a local node in the network.
:param node:
An integer representing the node ID.
:param object_dictionary:
Can be either a string for specifying the path to an
Object Dictionary file or a
:class:`canopen.ObjectDictionary` object.
:return:
The Node object that was added.
:rtype: canopen.LocalNode
"""
if isinstance(node, int):
node = LocalNode(node, object_dictionary)
self[node.id] = node
return node
def send_message(self, can_id, data, remote=False):
"""Send a raw CAN message to the network.
This method may be overridden in a subclass if you need to integrate
this library with a custom backend.
It is safe to call this from multiple threads.
:param int can_id:
CAN-ID of the message
:param data:
Data to be transmitted (anything that can be converted to bytes)
:param bool remote:
Set to True to send remote frame
:raises can.CanError:
When the message fails to be transmitted
"""
if not self.bus:
raise RuntimeError("Not connected to CAN bus")
msg = can.Message(is_extended_id=can_id > 0x7FF,
arbitration_id=can_id,
data=data,
is_remote_frame=remote)
with self.send_lock:
self.bus.send(msg)
self.check()
def send_periodic(self, can_id, data, period, remote=False):
"""Start sending a message periodically.
:param int can_id:
CAN-ID of the message
:param data:
Data to be transmitted (anything that can be converted to bytes)
:param float period:
Seconds between each message
:param bool remote:
indicates if the message frame is a remote request to the slave node
:return:
An task object with a ``.stop()`` method to stop the transmission
:rtype: canopen.network.PeriodicMessageTask
"""
return PeriodicMessageTask(can_id, data, period, self.bus, remote)
def notify(self, can_id, data, timestamp):
"""Feed incoming message to this library.
If a custom interface is used, this function must be called for each
message read from the CAN bus.
:param int can_id:
CAN-ID of the message
:param bytearray data:
Data part of the message (0 - 8 bytes)
:param float timestamp:
Timestamp of the message, preferably as a Unix timestamp
"""
if can_id in self.subscribers:
callbacks = self.subscribers[can_id]
for callback in callbacks:
callback(can_id, data, timestamp)
self.scanner.on_message_received(can_id)
def check(self):
"""Check that no fatal error has occurred in the receiving thread.
If an exception caused the thread to terminate, that exception will be
raised.
"""
if self.notifier is not None:
exc = self.notifier.exception
if exc is not None:
logger.error("An error has caused receiving of messages to stop")
raise exc
def __getitem__(self, node_id):
return self.nodes[node_id]
def __setitem__(self, node_id, node):
assert node_id == node.id
self.nodes[node_id] = node
node.associate_network(self)
def __delitem__(self, node_id):
self.nodes[node_id].remove_network()
del self.nodes[node_id]
def __iter__(self):
return iter(self.nodes)
def __len__(self):
return len(self.nodes)
class PeriodicMessageTask(object):
"""
Task object to transmit a message periodically using python-can's
CyclicSendTask
"""
def __init__(self, can_id, data, period, bus, remote=False):
"""
:param int can_id:
CAN-ID of the message
:param data:
Data to be transmitted (anything that can be converted to bytes)
:param float period:
Seconds between each message
:param can.BusABC bus:
python-can bus to use for transmission
"""
self.bus = bus
self.period = period
self.msg = can.Message(is_extended_id=can_id > 0x7FF,
arbitration_id=can_id,
data=data, is_remote_frame=remote)
self._task = None
self._start()
def _start(self):
self._task = self.bus.send_periodic(self.msg, self.period)
def stop(self):
"""Stop transmission"""
self._task.stop()
def update(self, data):
"""Update data of message
:param data:
New data to transmit
"""
new_data = bytearray(data)
old_data = self.msg.data
self.msg.data = new_data
if hasattr(self._task, "modify_data"):
self._task.modify_data(self.msg)
elif new_data != old_data:
# Stop and start (will mess up period unfortunately)
self._task.stop()
self._start()
class MessageListener(Listener):
"""Listens for messages on CAN bus and feeds them to a Network instance.
:param canopen.Network network:
The network to notify on new messages.
"""
def __init__(self, network):
self.network = network
def on_message_received(self, msg):
if msg.is_error_frame or msg.is_remote_frame:
return
try:
self.network.notify(msg.arbitration_id, msg.data, msg.timestamp)
except Exception as e:
# Exceptions in any callbaks should not affect CAN processing
logger.error(str(e))
class NodeScanner(object):
"""Observes which nodes are present on the bus.
Listens for the following messages:
- Heartbeat (0x700)
- SDO response (0x580)
- TxPDO (0x180, 0x280, 0x380, 0x480)
- EMCY (0x80)
:param canopen.Network network:
The network to use when doing active searching.
"""
#: Activate or deactivate scanning
active = True
SERVICES = (0x700, 0x580, 0x180, 0x280, 0x380, 0x480, 0x80)
def __init__(self, network=None):
self.network = network
#: A :class:`list` of nodes discovered
self.nodes = []
def on_message_received(self, can_id):
service = can_id & 0x780
node_id = can_id & 0x7F
if node_id not in self.nodes and node_id != 0 and service in self.SERVICES:
self.nodes.append(node_id)
def reset(self):
"""Clear list of found nodes."""
self.nodes = []
def search(self, limit=127):
"""Search for nodes by sending SDO requests to all node IDs."""
if self.network is None:
raise RuntimeError("A Network is required to do active scanning")
sdo_req = b"\x40\x00\x10\x00\x00\x00\x00\x00"
for node_id in range(1, limit + 1):
self.network.send_message(0x600 + node_id, sdo_req)