Search code examples
linuxlinux-kernelusblinux-device-driverusbserial

How to make an/a (API or driver) to handle all the USB serial request on the USB-device side in Linux?


For two days I have been looking for a way to write programs or make a driver to handle the USB serial request on my USB device side. I have specially made USB device and the only way to connect to it is through USB serial port, on my PC I am using the Webusb API from Google to access a terminal console on the device. So I can send Linux commands (i.e ifconfig), so what I would like to do is to build something that can run on the device to listen to requests coming through the USB serial and send a proper response. For example, I have a C code that runs on the Arduino do exactly what I want, but the problem is the code only work for Arduino not on my device, here is the c code:

// Third-party WebUSB Arduino library
#include <WebUSB.h>

WebUSB WebUSBSerial(1 /* https:// */, "webusb.github.io/arduino/demos");

#define Serial WebUSBSerial

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // Wait for serial port to connect.
  }
  Serial.write("WebUSB FTW!");
  Serial.flush();
}

void loop()
{
  if (webUsbSerial)
  {
    if (webUsbSerial.available())
    {
      int byte = webUsbSerial.read();
      if (byte == 'h')
      {
        webUsbSerial.write("hallo from Arduino");
      }
      else
        webUsbSerial.write("sorry not a function yet!!!!");
      webUsbSerial.flush();
    }
  }
}

As you see in this example I check if the command is “h” and I send hello world. I would like to do the same on my device which have Linux OS, I tried libusb, but I think it is a USB-host API not USB-Device. Thank you in advance.


Solution

  • I think you could use something like this (and if you're ok with using Python):

    import serial
    #Assuming you're connecting an Arduino
    try:
       ser = serial.Serial("/dev/ttyACM0",9600)
    except:
       ser = serial.Serial("/dev/ttyACM1",9600)
    
    while True:   
        print("Start")
        print("Waiting...")
    
        command = ser.read()
        try: command = str(command, "utf-8")
        except: command = str(command, "utf-16")
    
        if (command =="h"): print("Hello")
    

    Hope it helped.