All Classes Namespaces Files Functions Variables Enumerations Enumerator
libs/connection/c/serial_utils.c
Go to the documentation of this file.
00001 
00010 #include "serial_utils.h"
00011 #include "serial_ctrl.h"
00012 
00013 #include <stdio.h>
00014 #include <ctype.h>
00015 
00016 
00017 /* 改行かの判定 */
00018 int serial_isLF(const char ch)
00019 {
00020   return ((ch == '\r') || (ch == '\n')) ? 1 : 0;
00021 }
00022 
00023 
00024 /* 受信データの読み飛ばし */
00025 void serial_skip(serial_t *serial, int total_timeout, int each_timeout)
00026 {
00027   char recv_ch;
00028 
00029   /* 書き戻した文字をクリア */
00030   serial->last_ch_ = '\0';
00031 
00032   if (each_timeout <= 0) {
00033     each_timeout = total_timeout;
00034   }
00035 
00036   // !!! total_timeout をこのループ条件に適用すべき
00037   while (1) {
00038     int n = serial_recv(serial, &recv_ch, 1, each_timeout);
00039     if (n <= 0) {
00040       break;
00041     }
00042   }
00043 }
00044 
00045 
00046 /* 改行までの読みだし */
00047 int serial_getLine(serial_t *serial, char* data, int data_size_max,
00048                    int timeout)
00049 {
00050   /* 1文字ずつ読みだして評価する */
00051   int filled = 0;
00052   int is_timeout = 0;
00053 
00054   while (filled < data_size_max) {
00055     char recv_ch;
00056     int n = serial_recv(serial, &recv_ch, 1, timeout);
00057     if (n <= 0) {
00058       is_timeout = 1;
00059       break;
00060     } else if (serial_isLF(recv_ch)) {
00061       break;
00062     }
00063     data[filled++] = recv_ch;
00064   }
00065   if (filled == data_size_max) {
00066     --filled;
00067     serial_ungetc(serial, data[filled]);
00068   }
00069   data[filled] = '\0';
00070 
00071   if ((filled == 0) && is_timeout) {
00072     return -1;
00073   } else {
00074     return filled;
00075   }
00076 }