QtSerialBus virtualcan connect using socket and python

22 Views Asked by At

Following the documentation of https://doc.qt.io/qt-5/qtserialbus-virtualcan-overview.html I was able to launch an app listening on incoming TCP packets at the default port of 35468.

  • I was able to monitor the traffic using wireshark with port 35468 command on Adapter for loopback traffic capture
  • I was also able to send "CAN" data to the Qt C++ app using python and socket socket.sendall(f'{args.interface}:{can_id}#{flags}#{data}\n'.encode("utf-8"))
  • I was not able to read data processed by the server from external, e.g. python using socket.recv

So I came up with another approach: Given the documentation it says "To connect to a remote server, use the following fully qualified URL as interface name": I was not able to do so:

In python I run:

import socket

def main():
    # Define the host and port to listen on
    host = 'localhost'  # localhost
    port = 35469
    
    # Create a TCP socket
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
        # Bind the socket to the host and port
        server_socket.bind((host, port))
        
        # Start listening for incoming connections
        server_socket.listen()
        print(f"Server is listening on {host}:{port}")
        
        while True:
            # Accept a new connection
            client_socket, client_address = server_socket.accept()
            print(f"Connection from {client_address}")
            
            # Handle the client's request
            handle_client(client_socket)

def handle_client(client_socket):
    # Receive data from the client
    data = client_socket.recv(1024).decode('utf-8')
    print(f"Received data: {data}")
    
    # Echo back the received data
    client_socket.sendall(data.encode('utf-8'))
    
    # Close the client socket
    client_socket.close()

if __name__ == "__main__":
    main()

and on Qt C++ side I set:

QCanBusDevice *device = QCanBus::instance()->createDevice(
    QStringLiteral("virtualcan"), QStringLiteral("tcp://localhost:35468/can0"));
device->connectDevice();

But it looks like the Qt App cannot connect to the server. I cannot see any sending of messages.

Was anyone able to make something similar work?

My initial goal was to process "raw" CAN data from the Qt C++ app within a python script on the other end.

0

There are 0 best solutions below