Blame view

virtual_serial.c 1.36 KB
2dcf20ec   HAMEL   first program wit...
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
  /*
   * Virtual Serial library
   */
  
  ////
  // Include files
  ////
  #include <stdio.h>
  #include <stdlib.h>
  #include <unistd.h>
  #include <termios.h>
  #include <strings.h>
  #include <sys/types.h>
  #include <sys/ioctl.h>
  #include <sys/file.h>
  #include <linux/serial.h>
  #include <pty.h>
  
  #include "virtual_serial.h"
  
  ////
  // Functions
  ////
  
  //
  // Serial structure filling
  //
  static struct termios serialConfig(int speed){
  int fspeed;
  switch(speed){
    case 1200: fspeed=B1200; break;
    case 2400: fspeed=B2400; break;
    case 4800: fspeed=B4800; break;
    case 9600: fspeed=B9600; break;
    case 19200: fspeed=B19200; break;
    case 38400: fspeed=B38400; break;
    case 57600: fspeed=B57600; break;
    case 115200: fspeed=B115200; break;
    default: fprintf(stderr,"Unknown serial speed %d.\n",speed); exit(-1);
    }
  struct termios new;
  bzero(&new,sizeof(new));
  new.c_cflag=CLOCAL|CREAD|fspeed|CS8;
  new.c_iflag=0;
  new.c_oflag=0;
  new.c_lflag=0;     /* set input mode (non-canonical, no echo,...) */
  new.c_cc[VTIME]=0; /* inter-character timer unused */
  new.c_cc[VMIN]=1;  /* blocking read until 1 char received */
  return new;
  }
  
  //
  // Virtual serial creation
  //
  
  int virtualSerialOpen(char *name,int speed){
  int master;
  int slave;
  struct termios serial=serialConfig(speed);
  openpty(&master,&slave,name,&serial,NULL);
  return master;
  }
  
  //
  // Serial port termination
  //
  void virtualSerialClose(int fd){
  close(fd);
  }