-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcanlib.py
More file actions
53 lines (32 loc) · 1.45 KB
/
canlib.py
File metadata and controls
53 lines (32 loc) · 1.45 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
import can
from siromlib import SiromCommand
class CanBusTransport:
def __init__(self, identifier:str):
raise NotImplemented()
def sendCommand(self, command: SiromCommand):
raise NotImplemented()
def shutdown(self):
raise NotImplemented()
class LinuxCanBusTransport(CanBusTransport):
def __init__(self, identifier:str):
targetCan = f"/sys/class/net/{identifier}/flags"
try:
with open(targetCan, 'r') as file:
data = file.read().replace('\n', '')
if not list(data).pop() == '1':
raise Exception(f"Network adapter {identifier} is not configured")
except:
raise Exception(f"Network adapter {identifier} is not configured")
self.__canBus = can.interface.Bus(channel = identifier, bustype = 'socketcan')
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.shutdown()
def sendCommand(self, canbusTargetIdentifer:int, command: SiromCommand, timeoutSeconds:int = 2, verbose=False):
canMessage = can.Message(arbitration_id=canbusTargetIdentifer, extended_id=False, data=command.toByteArray())
self.__canBus.send(canMessage, timeoutSeconds)
if verbose:
print("Sent message:" )
print(canMessage)
def shutdown(self):
self.__canBus.shutdown()