Skip to content

Commit 725bbd0

Browse files
committed
cleanup the examples; they now pass the linter and formatter and always close the bus by using a context manager
1 parent d321bb4 commit 725bbd0

9 files changed

+131
-103
lines changed

examples/asyncio_demo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,4 +58,4 @@ async def main():
5858
LOOP.close()
5959

6060
# or on Python 3.7+ simply
61-
#asyncio.run(main())
61+
# asyncio.run(main())

examples/cyclic.py

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,14 @@ def simple_periodic_send(bus):
3434

3535

3636
def limited_periodic_send(bus):
37+
"""Send using LimitedDurationCyclicSendTaskABC."""
3738
print("Starting to send a message every 200ms for 1s")
3839
msg = can.Message(
3940
arbitration_id=0x12345678, data=[0, 0, 0, 0, 0, 0], is_extended_id=True
4041
)
4142
task = bus.send_periodic(msg, 0.20, 1, store_task=False)
4243
if not isinstance(task, can.LimitedDurationCyclicSendTaskABC):
43-
print("This interface doesn't seem to support a ")
44+
print("This interface doesn't seem to support LimitedDurationCyclicSendTaskABC")
4445
task.stop()
4546
return
4647

@@ -53,7 +54,8 @@ def limited_periodic_send(bus):
5354

5455

5556
def test_periodic_send_with_modifying_data(bus):
56-
print("Starting to send a message every 200ms. Initial data is ones")
57+
"""Send using ModifiableCyclicTaskABC."""
58+
print("Starting to send a message every 200ms. Initial data is four consecutive 1s")
5759
msg = can.Message(arbitration_id=0x0CF02200, data=[1, 1, 1, 1])
5860
task = bus.send_periodic(msg, 0.20)
5961
if not isinstance(task, can.ModifiableCyclicTaskABC):
@@ -106,19 +108,13 @@ def test_periodic_send_with_modifying_data(bus):
106108
# print("done")
107109

108110

109-
if __name__ == "__main__":
110-
111+
def main():
112+
"""Test different cyclic sending tasks."""
111113
reset_msg = can.Message(
112114
arbitration_id=0x00, data=[0, 0, 0, 0, 0, 0], is_extended_id=False
113115
)
114116

115-
for interface, channel in [
116-
("socketcan", "vcan0"),
117-
# ('ixxat', 0)
118-
]:
119-
print("Carrying out cyclic tests with {} interface".format(interface))
120-
121-
bus = can.Bus(interface=interface, channel=channel, bitrate=500000)
117+
with can.Bus(interface="virtual") as bus:
122118
bus.send(reset_msg)
123119

124120
simple_periodic_send(bus)
@@ -133,6 +129,8 @@ def test_periodic_send_with_modifying_data(bus):
133129
# can.rc['interface'] = interface
134130
# test_dual_rate_periodic_send()
135131

136-
bus.shutdown()
137-
138132
time.sleep(2)
133+
134+
135+
if __name__ == "__main__":
136+
main()

examples/cyclic_multiple.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -131,14 +131,10 @@ def cyclic_multiple_send_modify(bus):
131131

132132
if __name__ == "__main__":
133133
for interface, channel in [("socketcan", "vcan0")]:
134-
print("Carrying out cyclic multiple tests with {} interface".format(interface))
134+
print(f"Carrying out cyclic multiple tests with {interface} interface")
135135

136-
bus = can.Bus(interface=interface, channel=channel, bitrate=500000)
137-
138-
cyclic_multiple_send(bus)
139-
140-
cyclic_multiple_send_modify(bus)
141-
142-
bus.shutdown()
136+
with can.Bus(interface=interface, channel=channel, bitrate=500000) as BUS:
137+
cyclic_multiple_send(BUS)
138+
cyclic_multiple_send_modify(BUS)
143139

144140
time.sleep(2)

examples/receive_all.py

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,33 @@
11
#!/usr/bin/env python
22

3+
"""
4+
Shows how the receive messages via polling.
5+
"""
6+
37
import can
48
from can.bus import BusState
59

610

711
def receive_all():
12+
"""Receives all messages and prints them to the console until Ctrl+C is pressed."""
13+
14+
with can.interface.Bus(
15+
bustype="pcan", channel="PCAN_USBBUS1", bitrate=250000
16+
) as bus:
17+
# bus = can.interface.Bus(bustype='ixxat', channel=0, bitrate=250000)
18+
# bus = can.interface.Bus(bustype='vector', app_name='CANalyzer', channel=0, bitrate=250000)
819

9-
bus = can.interface.Bus(bustype="pcan", channel="PCAN_USBBUS1", bitrate=250000)
10-
# bus = can.interface.Bus(bustype='ixxat', channel=0, bitrate=250000)
11-
# bus = can.interface.Bus(bustype='vector', app_name='CANalyzer', channel=0, bitrate=250000)
20+
# set to read-only, only supported on some interfaces
21+
bus.state = BusState.PASSIVE
1222

13-
bus.state = BusState.ACTIVE # or BusState.PASSIVE
23+
try:
24+
while True:
25+
msg = bus.recv(1)
26+
if msg is not None:
27+
print(msg)
1428

15-
try:
16-
while True:
17-
msg = bus.recv(1)
18-
if msg is not None:
19-
print(msg)
20-
except KeyboardInterrupt:
21-
pass
29+
except KeyboardInterrupt:
30+
pass # exit normally
2231

2332

2433
if __name__ == "__main__":

examples/send_one.py

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,27 +8,28 @@
88

99

1010
def send_one():
11+
"""Sends a single message."""
1112

1213
# this uses the default configuration (for example from the config file)
1314
# see https://python-can.readthedocs.io/en/stable/configuration.html
14-
bus = can.interface.Bus()
15-
16-
# Using specific buses works similar:
17-
# bus = can.interface.Bus(bustype='socketcan', channel='vcan0', bitrate=250000)
18-
# bus = can.interface.Bus(bustype='pcan', channel='PCAN_USBBUS1', bitrate=250000)
19-
# bus = can.interface.Bus(bustype='ixxat', channel=0, bitrate=250000)
20-
# bus = can.interface.Bus(bustype='vector', app_name='CANalyzer', channel=0, bitrate=250000)
21-
# ...
22-
23-
msg = can.Message(
24-
arbitration_id=0xC0FFEE, data=[0, 25, 0, 1, 3, 1, 4, 1], is_extended_id=True
25-
)
26-
27-
try:
28-
bus.send(msg)
29-
print("Message sent on {}".format(bus.channel_info))
30-
except can.CanError:
31-
print("Message NOT sent")
15+
with can.interface.Bus() as bus:
16+
17+
# Using specific buses works similar:
18+
# bus = can.interface.Bus(bustype='socketcan', channel='vcan0', bitrate=250000)
19+
# bus = can.interface.Bus(bustype='pcan', channel='PCAN_USBBUS1', bitrate=250000)
20+
# bus = can.interface.Bus(bustype='ixxat', channel=0, bitrate=250000)
21+
# bus = can.interface.Bus(bustype='vector', app_name='CANalyzer', channel=0, bitrate=250000)
22+
# ...
23+
24+
msg = can.Message(
25+
arbitration_id=0xC0FFEE, data=[0, 25, 0, 1, 3, 1, 4, 1], is_extended_id=True
26+
)
27+
28+
try:
29+
bus.send(msg)
30+
print(f"Message sent on {bus.channel_info}")
31+
except can.CanError:
32+
print("Message NOT sent")
3233

3334

3435
if __name__ == "__main__":

examples/serial_com.py

Lines changed: 36 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#!/usr/bin/env python
22

33
"""
4-
This example sends every second a messages over the serial interface and also
4+
This example sends every second a messages over the serial interface and also
55
receives incoming messages.
66
77
python3 -m examples.serial_com
@@ -25,17 +25,19 @@
2525

2626

2727
def send_cyclic(bus, msg, stop_event):
28+
"""The loop for sending."""
2829
print("Start to send a message every 1s")
2930
start_time = time.time()
3031
while not stop_event.is_set():
3132
msg.timestamp = time.time() - start_time
3233
bus.send(msg)
33-
print("tx: {}".format(tx_msg))
34+
print(f"tx: {msg}")
3435
time.sleep(1)
3536
print("Stopped sending messages")
3637

3738

3839
def receive(bus, stop_event):
40+
"""The loop for receiving."""
3941
print("Start receiving messages")
4042
while not stop_event.is_set():
4143
rx_msg = bus.recv(1)
@@ -44,30 +46,36 @@ def receive(bus, stop_event):
4446
print("Stopped receiving messages")
4547

4648

47-
if __name__ == "__main__":
48-
server = can.interface.Bus(bustype="serial", channel="/dev/ttyS10")
49-
client = can.interface.Bus(bustype="serial", channel="/dev/ttyS11")
50-
51-
tx_msg = can.Message(
52-
arbitration_id=0x01, data=[0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]
53-
)
54-
55-
# Thread for sending and receiving messages
56-
stop_event = threading.Event()
57-
t_send_cyclic = threading.Thread(
58-
target=send_cyclic, args=(server, tx_msg, stop_event)
59-
)
60-
t_receive = threading.Thread(target=receive, args=(client, stop_event))
61-
t_receive.start()
62-
t_send_cyclic.start()
63-
64-
try:
65-
while True:
66-
pass
67-
except KeyboardInterrupt:
68-
pass
69-
70-
stop_event.set()
71-
server.shutdown()
72-
client.shutdown()
49+
def main():
50+
"""Controles the sender and receiver."""
51+
with can.interface.Bus(bustype="serial", channel="/dev/ttyS10") as server:
52+
with can.interface.Bus(bustype="serial", channel="/dev/ttyS11") as client:
53+
54+
tx_msg = can.Message(
55+
arbitration_id=0x01,
56+
data=[0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88],
57+
)
58+
59+
# Thread for sending and receiving messages
60+
stop_event = threading.Event()
61+
t_send_cyclic = threading.Thread(
62+
target=send_cyclic, args=(server, tx_msg, stop_event)
63+
)
64+
t_receive = threading.Thread(target=receive, args=(client, stop_event))
65+
t_receive.start()
66+
t_send_cyclic.start()
67+
68+
try:
69+
while True:
70+
time.sleep(0) # yield
71+
except KeyboardInterrupt:
72+
pass # exit normally
73+
74+
stop_event.set()
75+
time.sleep(0.5)
76+
7377
print("Stopped script")
78+
79+
80+
if __name__ == "__main__":
81+
main()

examples/simple_log_converter.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,25 @@
22

33
"""
44
Use this to convert .can/.asc files to .log files.
5+
Can be easily adapted for all sorts of files.
56
6-
Usage: simpleLogConvert.py sourceLog.asc targetLog.log
7+
Usage: python3 simple_log_convert.py sourceLog.asc targetLog.log
78
"""
89

910
import sys
1011

11-
import can.io.logger
12-
import can.io.player
12+
import can
1313

14-
reader = can.io.player.LogReader(sys.argv[1])
15-
writer = can.io.logger.Logger(sys.argv[2])
1614

17-
for msg in reader:
18-
writer.on_message_received(msg)
15+
def main():
16+
"""The transcoder"""
17+
18+
with can.LogReader(sys.argv[1]) as reader:
19+
with can.Logger(sys.argv[2]) as writer:
20+
21+
for msg in reader:
22+
writer.on_message_received(msg)
23+
24+
25+
if __name__ == "__main__":
26+
main()

examples/vcan_filtered.py

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,25 @@
88

99
import can
1010

11+
12+
def main():
13+
"""Send some messages to itself and apply filtering."""
14+
with can.Bus(bustype="virtual", receive_own_messages=True) as bus:
15+
16+
can_filters = [{"can_id": 1, "can_mask": 0xF, "extended": True}]
17+
bus.set_filters(can_filters)
18+
19+
# print all incoming messages, wich includes the ones sent,
20+
# since we set receive_own_messages to True
21+
# assign to some variable so it does not garbage collected
22+
notifier = can.Notifier(bus, [can.Printer()]) # pylint: disable=unused-variable
23+
24+
bus.send(can.Message(arbitration_id=1, is_extended_id=True))
25+
bus.send(can.Message(arbitration_id=2, is_extended_id=True))
26+
bus.send(can.Message(arbitration_id=1, is_extended_id=False))
27+
28+
time.sleep(1.0)
29+
30+
1131
if __name__ == "__main__":
12-
bus = can.interface.Bus(
13-
bustype="socketcan", channel="vcan0", receive_own_messages=True
14-
)
15-
16-
can_filters = [{"can_id": 1, "can_mask": 0xF, "extended": True}]
17-
bus.set_filters(can_filters)
18-
notifier = can.Notifier(bus, [can.Printer()])
19-
bus.send(can.Message(arbitration_id=1, is_extended_id=True))
20-
bus.send(can.Message(arbitration_id=2, is_extended_id=True))
21-
bus.send(can.Message(arbitration_id=1, is_extended_id=False))
22-
23-
time.sleep(10)
32+
main()

examples/virtual_can_demo.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,23 +10,22 @@
1010
import can
1111

1212

13-
def producer(id, message_count=16):
13+
def producer(thread_id, message_count=16):
1414
"""Spam the bus with messages including the data id.
1515
1616
:param int id: the id of the thread/process
1717
"""
18-
1918
with can.Bus(bustype="socketcan", channel="vcan0") as bus:
2019
for i in range(message_count):
2120
msg = can.Message(
22-
arbitration_id=0x0CF02200 + id, data=[id, i, 0, 1, 3, 1, 4, 1]
21+
arbitration_id=0x0CF02200 + id, data=[thread_id, i, 0, 1, 3, 1, 4, 1]
2322
)
2423
bus.send(msg)
2524
sleep(1.0)
2625

27-
print("Producer #{} finished sending {} messages".format(id, message_count))
26+
print(f"Producer #{thread_id} finished sending {message_count} messages")
2827

2928

3029
if __name__ == "__main__":
31-
with ProcessPoolExecutor(max_workers=4) as executor:
30+
with ProcessPoolExecutor() as executor:
3231
executor.map(producer, range(5))

0 commit comments

Comments
 (0)