return -3;
}
/* Empty read buffer (echo is on) */
- isp_serial_read(buf, strlen(SYNCHRO), strlen(SYNCHRO));
+ isp_serial_empty_buffer();
/* Read reply (OK) */
isp_serial_read(buf, REP_BUFSIZE, strlen(SYNCHRO_OK));
if (strncmp(SYNCHRO_OK, buf, strlen(SYNCHRO_OK)) != 0) {
/* Documentation says we should send crystal frequency .. sending anything is OK */
isp_serial_write(freq, strlen(freq));
/* Empty read buffer (echo is on) */
- isp_serial_read(buf, strlen(freq), strlen(freq));
+ isp_serial_empty_buffer();
/* Read reply (OK) */
isp_serial_read(buf, REP_BUFSIZE, strlen(SYNCHRO_OK));
if (strncmp(SYNCHRO_OK, buf, strlen(SYNCHRO_OK)) != 0) {
/* Turn off echo */
isp_serial_write(SYNCHRO_ECHO_OFF, strlen(SYNCHRO_ECHO_OFF));
/* Empty read buffer (echo still on) */
- isp_serial_read(buf, strlen(SYNCHRO_ECHO_OFF), strlen(SYNCHRO_ECHO_OFF));
+ isp_serial_empty_buffer();
/* Read eror code for command */
isp_serial_read(buf, REP_BUFSIZE, 3);
return nb;
}
+static char next_read_char = 0;
+void isp_serial_empty_buffer()
+{
+ int nb = 0;
+ char unused = 0;
+ unsigned int loops = 0; /* Used to create a timeout */
+
+ do {
+ nb = read(serial_fd, &unused, 1);
+ if (nb < 0) {
+ if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) {
+ if (loops++ > 100) {
+ break; /* timeout at 500ms */
+ }
+ usleep( 5000 );
+ continue;
+ }
+ perror("Serial read error");
+ return;
+ } else if (nb == 0) {
+ printf("serial_read: end of file !!!!\n");
+ return;
+ }
+ } while ((unused != '\r') && (unused != '\n'));
+
+ /* This should be improved by reading ALL \r and \n */
+ if (unused == '\r') {
+ nb = read(serial_fd, &unused, 1);
+ }
+ if (unused == '\n') {
+ return;
+ }
+ next_read_char = unused;
+}
+
/* Try to read at least "min_read" characters from the serial line.
* Returns -1 on error, 0 on end of file, or read count otherwise.
*/
printf("serial_read: buffer too small for min read value.\n");
return -3;
}
+ if (next_read_char != 0) {
+ buf[count++] = next_read_char;
+ next_read_char = 0;
+ }
do {
nb = read(serial_fd, &buf[count], (buf_size - count));
/* Simple write() wrapper, with trace if enabled */
int isp_serial_write(const char* buf, unsigned int buf_size);
+void isp_serial_empty_buffer();
/* Try to read at least "min_read" characters from the serial line.
* Returns -1 on error, 0 on end of file, or read count otherwise.
*/