tty2midi.c (1937B)
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<fcntl.h> 4 #include<unistd.h> 5 #include<termio.h> 6 #include<alsa/asoundlib.h> 7 8 int 9 main(void) 10 { 11 int tf, portid; 12 struct termios tty; 13 snd_seq_t *seq; 14 snd_seq_event_t ev; 15 snd_midi_event_t *midi; 16 17 /* serial setup */ 18 tf = open("/dev/ttyACM0", O_RDWR); 19 if (tf < 0) { 20 fprintf(stderr, "can't open\n"); 21 exit(-1); 22 } 23 if (tcgetattr(tf, &tty) != 0) { 24 fprintf(stderr, "tcgetattr failed\n"); 25 exit(-1); 26 } 27 if (cfsetspeed(&tty, B115200) != 0) { 28 fprintf(stderr, "cfsetspeed failed\n"); 29 exit(-1); 30 } 31 tty.c_cflag &= ~(PARENB|CSTOPB|CSIZE|CRTSCTS); 32 tty.c_cflag |= CS8|CREAD|CLOCAL; 33 tty.c_lflag &= ~(ICANON|ECHO|ECHOE|ECHONL|ISIG); 34 tty.c_iflag &= ~(IXON |IXOFF| IXANY|IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL); 35 tty.c_oflag &= ~(OPOST|ONLCR); 36 tty.c_cc[VTIME] = 0; 37 tty.c_cc[VMIN] = 1; 38 tcsetattr(tf, TCSANOW, &tty); 39 40 /* ALSA MIDI setup */ 41 if (snd_seq_open(&seq, "default", SND_SEQ_OPEN_OUTPUT, 0) != 0) exit(-1); 42 if (snd_seq_set_client_name(seq, "tty2midi") != 0) { 43 fprintf(stderr, "set client name failed\n"); 44 exit(-1); 45 } 46 portid = snd_seq_create_simple_port( 47 seq, 48 "tty2midi out", 49 SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ, 50 SND_SEQ_PORT_TYPE_APPLICATION 51 ); 52 if (portid < 0) { 53 fprintf(stderr, "create simple port failed\n"); 54 exit(-1); 55 } 56 if (snd_midi_event_new(16, &midi) != 0) { 57 fprintf(stderr, "midi event new failed\n"); 58 exit(-1); 59 } 60 while(1) { 61 unsigned char buf[1024]; 62 int n, r; 63 if ((n = read(tf, buf, 1)) == 0) continue; 64 65 snd_seq_ev_clear(&ev); 66 snd_seq_ev_set_subs(&ev); 67 snd_seq_ev_set_direct(&ev); 68 snd_seq_ev_set_source(&ev, portid); 69 70 r = snd_midi_event_encode_byte(midi, *buf, &ev); 71 if (r < 0) { 72 fprintf(stderr, "event encode failed\n"); 73 } 74 if (r != 1) continue; 75 76 r = snd_seq_event_output_direct(seq, &ev); 77 if (r < 0) { 78 fprintf(stderr, "event output failed: %s\n", snd_strerror(r)); 79 } 80 } 81 return 0; 82 }