Fake serial communication under Linux

后端 未结 3 990
予麋鹿
予麋鹿 2020-12-29 07:43

I have an application where I want to simulate the connection between a device and a \"modem\". The device will be connected to a serial port and will talk to the software m

3条回答
  •  别那么骄傲
    2020-12-29 07:56

    You are on the right track with pseudo-terminals. To do this, your mock software device needs to first open a pseudo-terminal master - this is the file descriptor it will read from and write to, when it is talking to the serial software that you're testing. It then needs to grant access to and unlock the pseudo-terminal slave, and obtain the name of the slave device. It should then print out the name of the slave device somewhere, so that you can tell the other software to open that as it's serial port (ie. that software will be opening a name like /dev/pts/0 instead of /dev/ttyS1).

    The simulator software then just reads and writes from the master side of the pseudoterminal. In C, it would look like this:

    #define _XOPEN_SOURCE
    #include 
    #include 
    #include 
    
    int main(int argc, char *argv[])
    {
        int pt;
    
        pt = open("/dev/ptmx", O_RDWR | O_NOCTTY);
        if (pt < 0)
        {
            perror("open /dev/ptmx");
            return 1;
        }
    
        grantpt(pt);
        unlockpt(pt);
    
        fprintf(stderr, "Slave device: %s\n", ptsname(pt));
    
        /* Now start pretending to be a modem, reading and writing "pt" */
        /* ... */
        return 0;
    }
    

    Hopefully that is easy enough to convert to Python.

提交回复
热议问题