-// really simple JSON helpers
-#define JSON_NUM(NAME) printf("\"" #NAME "\": %d", NAME)
-#define JSON_STR(NAME) printf("\"" #NAME "\": \"%s\"", NAME)
-#define JSON_START() printf("{\n")
-#define JSON_NEXT() printf(",\n")
-#define JSON_END() printf("\n}\n")
+int set_nonblock(int fd)
+{
+ int flags = fcntl(fd, F_GETFL, 0);
+ if (flags == -1){
+ perror("fcntl (get)");
+ return -1;
+ }
+ if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1){
+ perror("fcntl (set)");
+ return -1;
+ }
+ fprintf(stderr, "set non-blocking\n");
+ return 0;
+}
+
+int set_rts(int fd, int level) {
+ int uart_status;
+
+ if (ioctl(fd, TIOCMGET, &uart_status) == -1) {
+ perror("ioctl (TIOCMGET)");
+ return -1;
+ }
+
+ if (level) {
+ uart_status |= TIOCM_RTS;
+ } else {
+ uart_status &= ~TIOCM_RTS;
+ }
+
+ if (ioctl(fd, TIOCMSET, &uart_status) == -1) {
+ perror("TIOCMSET");
+ return -1;
+ }
+
+ fprintf(stderr, "set rts %d\n", level);
+
+ return 0;
+}
+
+void set_baud_rate(int fd, int br) {
+ struct termios options;
+
+ tcgetattr(fd, &options);
+ cfsetispeed(&options, br);
+ cfsetospeed(&options, br);
+ tcsetattr(fd, TCSANOW, &options);
+}
+
+int tty_open(const char *port, int baud_rate) {
+
+ int fd = open(port, O_RDONLY | O_NOCTTY);
+ if (fd < 0) {
+ perror("open");
+ return fd;
+ } else {
+ fprintf(stderr, "opened %s as %d\n", port, fd);
+ }
+
+ set_nonblock(fd);
+ set_rts(fd, 0);
+ set_baud_rate(fd, baud_rate);
+ usleep(1200000); //value by d-logic
+ tcflush(fd, TCIFLUSH);
+
+ return fd;
+}