Ejemplo n.º 1
0
def parse_request(request):
    interface = request.get('bus')
    if interface == None:
        interface = CAN_SEND_INTERFACE
    else:
        interface = interface[0]
    try:
        bus = CAN.Bus(interface)
    except OSError:
        raise BadRequest("bus '" + interface + "' does not exist")
    id = request.get('id')
    if id == None:
      raise BadRequest("id not specified")
    id = int(id[0])
    data = request.get('data[]') # POST
    if data == None:
        data = request.get('data') # GET
        if data == None:
            data = [] # parse_url removes data field if empty array
        else:
            data = data[0].strip('[]').split(',')
    if len(data) == 1:
      if data[0] == '':
        data = []
    data = list(map(int, data))
    msg = CAN.Message(id, data)
    return (bus, msg)
Ejemplo n.º 2
0
def parse_net(net):
    global default_net
    if net == 'default':
        net = default_net
    else:
        net = CAN_INTERFACES[int(net) - 1]
    return CAN.Bus(net)
Ejemplo n.º 3
0
 def listen(self):
     bus = CAN.Bus(DEFAULT_CAN_INTERFACE)
     while True:
         rlist, _, _ = select([self.websocket, bus], [], [])
         for s in rlist:
             if isinstance(s, CAN.Bus):
                 msg = s.recv()
                 self.send(bytes(msg))
             elif isinstance(s, WebSocket):
                 msg = s.recv()
                 if msg is None:
                     return
                 bus.send(CAN.Message.from_bytes(msg))
Ejemplo n.º 4
0
#!/usr/bin/python3
import CAN
import CANopen

CAN_INTERFACE = "vcan0"

can_bus = CAN.Bus(CAN_INTERFACE)

node_id = 0x02

canopen_od = CANopen.ObjectDictionary.from_eds('node.eds')

node = CANopen.Node(can_bus, node_id, canopen_od)

while True:
    pass  # Run forever
Ejemplo n.º 5
0
CAN_SEND_INTERFACE = "vcan0"
UDP_LISTEN_IP = "127.0.0.1"
UDP_LISTEN_PORT = 5005
UDP_SEND_IP = "127.0.0.1"
UDP_SEND_PORT = 5006


def sigterm_handler(signum, frame):
    sys.exit()


signal.signal(signal.SIGTERM, sigterm_handler)

sockets = []
for interface in CAN_LISTEN_INTERFACES:
    can_socket = CAN.Bus(interface)
    sockets.append(can_socket)
for s in sockets:
    if s.getsockname()[0] == CAN_SEND_INTERFACE:
        can_socket = s
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp_socket.bind((UDP_LISTEN_IP, UDP_LISTEN_PORT))
sockets.append(udp_socket)

while True:
    try:
        rlist, _, _ = select(sockets, [], [])
        for s in rlist:
            socket_type = s.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)
            if isinstance(s, CAN.Bus):
                msg = s.recv()
Ejemplo n.º 6
0
    GPIO.cleanup()
    exit()

signal.signal(signal.SIGTERM, sigterm_handler)

GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN_ENABLE_N, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(PIN_ADDRESS_N, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(PIN_ADDRESS_PARITY_N, GPIO.IN, pull_up_down=GPIO.PUD_UP)

runled0 = CANopen.RunIndicator(PIN_RUNLED0)
errled0 = CANopen.ErrorIndicator(PIN_ERRLED0)
runled1 = CANopen.Indicator(PIN_RUNLED1, CANopen.Indicator.OFF)
errled1 = CANopen.Indicator(PIN_ERRLED1, CANopen.Indicator.ON)

default_bus = CAN.Bus(DEFAULT_CAN_INTERFACE)
redundant_bus = CAN.Bus(REDUNDANT_CAN_INTERFACE)
active_bus = default_bus

class ResetNode(Exception):
    pass

class ResetCommunication(Exception):
    pass

while True:
    try:
        if GPIO.input(PIN_ENABLE_N) == GPIO.HIGH:
            print("Enable_n is high")
            sleep(1)
            raise ResetNode
Ejemplo n.º 7
0
    def do_GET(self):
        parsed_path = urlparse(self.path)

        try:
            # Command
            if parsed_path.query != '':
                bus, msg = parse_request(parse_qs(parsed_path.query))
                bus.send(msg)
                self.send_response(204);
                self.send_header('Access-Control-Allow-Origin', '*')
                self.end_headers();
                return

            # Telemetry
            if parsed_path.path == '/':
                self.send_response(200)
                self.send_header('Content-type', 'text/event-stream')
                self.send_header('Cache-control', 'no-cache')
                self.send_header('Access-Control-Allow-Origin', '*')
                self.end_headers()

                busses = []
                for interface in CAN_LISTEN_INTERFACES:
                    bus = CAN.Bus(interface)
                    busses.append(bus)

                while True:
                    try:
                        rlist, _, _ = select(busses, [], [])
                        for bus in rlist:
                            msg = bus.recv()
                            id = msg.arbitration_id
                            data = msg.data
                            data = ",".join(map(str, data))
                            self.wfile.write(bytes('data: {"bus":"' + bus.name + '","id":' + str(id) + ',"data":[' + data + '],"ts":"' + datetime.fromtimestamp(msg.timestamp).isoformat() + '"}' + "\n\n", 'utf8'))
                    except CAN.BusDown:
                        self.wfile.write(bytes('event: error' + "\n" + 'data: ' + bus.name + ' is down.' + "\n\n", 'utf-8'))
                        sleep(1)
                        continue
                    except SystemExit:
                        # This doesn't get called. Find a way if possible
                        self.wfile.write(bytes('event: error' + "\n" + 'data: System is shutting down.' + "\n\n", 'utf-8'))
                        raise

            # File
            filepath = WWW_DIR + self.path
            if path.isfile(filepath):
                f = open(filepath)
                self.send_response(200)
                if self.path.endswith(".html"):
                    self.send_header('Content-type', 'text/html')
                elif self.path.endswith(".js"):
                    self.send_header('Content-type', 'text/javascript')
                elif self.path.endswith(".css"):
                  self.send_header('Content-type', 'text/css')
                self.end_headers()
                self.wfile.write(bytes(f.read(), 'UTF-8'))
                f.close()
                return

            self.send_response(404)
            self.end_headers()

        except BadRequest as e:
            self.send_response(400)
            self.send_error(400, 'Bad Request: %s' % str(e.args))
        except BrokenPipeError:
            print('Connection closed.')
        except IOError:
            self.send_response(500)
            print("\n*** do_GET except ***")
            print("Unexpected error:", sys.exc_info()[0])
            traceback.print_exc()