Enhanced SIM for E2AP v1 for TS UC
[sim/e2-interface.git] / e2sim / e2apv1sim / test / Pendulum / Serial / adruino_serial.c
1 /*
2  *
3  * Copyright 2019 AT&T Intellectual Property
4  * Copyright 2019 Nokia
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  */
19
20 #include "stdio.h"
21 #include <string.h>
22 #include <unistd.h>
23
24 #include "adruino_serial.h"
25
26 int start_serial_inferface(int baudrate, char *serial_port)
27 {
28   int fd = -1;
29
30   fd = serialport_init(serial_port, baudrate);
31   if(fd == -1) {
32     fprintf(stderr, "couldn't open serial port %s\n", serial_port);
33     return -1;
34   } else {
35     fprintf(stderr, "Openning serial port: %s ...\n", serial_port);
36   }
37
38   serialport_flush(fd); // take 2 seconds
39   fprintf(stderr, "Serial port ready!\n");
40
41   return fd;
42
43 }
44
45 int serial_readline(int fd, char* buf, int buf_max)
46 {
47   if( fd == -1 ){
48     perror("serial port not opened");
49     return -1;
50   }
51
52   memset(buf, 0, buf_max);
53
54   do {
55      serialport_read_until(fd, buf, SERIAL_EOL_CHAR, buf_max, SERIAL_TIMEOUT);
56   } while( buf[0] == '\n' );
57
58   // serialport_read_until(fd, buf, SERIAL_EOL_CHAR, buf_max, SERIAL_TIMEOUT);
59
60   return 0;
61 }
62
63 int serial_writeline(int fd, char* buf)
64 {
65   if(buf[strlen(buf)-1] != SERIAL_EOL_CHAR){
66     //append EOL to buf
67     int len = strlen(buf);
68     buf[len] = SERIAL_EOL_CHAR;
69     buf[len+1] = '\0';
70   }
71
72   serialport_write(fd, buf);
73
74   return 0;
75 }
76
77 //For testing only
78 void test_adruino_serial(void)
79 {
80   int   fd;
81   char  buf[MAX_SERIAL_BUFFER];
82
83   fd = start_serial_inferface(DEFAULT_BAUDRATE, DEFAULT_SERIAL_PORT);
84
85   while(1){
86     fprintf(stderr, "[E2 Agent]: ");
87     fgets(buf, MAX_SERIAL_BUFFER, stdin);
88
89     // serialport_write(fd, "hello\n");
90     //serialport_write(fd, buf);
91     serial_writeline(fd, buf);
92
93     serial_readline(fd, buf, MAX_SERIAL_BUFFER);
94     fprintf(stderr, "[Adruino] %s", buf);
95   }
96
97   return;
98 }