All Classes Namespaces Files Functions Variables Enumerations Enumerator
libs/range_sensor/scip_samples/ScipUtils.cpp
Go to the documentation of this file.
00001 
00011 #include "ScipUtils.h"
00012 #include "Connection.h"
00013 #include "ConnectionUtils.h"
00014 #include <cstdlib>
00015 
00016 using namespace qrk;
00017 using namespace std;
00018 
00019 
00020 int decode(const char code[], int byte)
00021 {
00022   int value = 0;
00023   int i;
00024 
00025   for (i = 0; i < byte; ++i) {
00026     value <<= 6;
00027     value &= ~0x3f;
00028     value |= code[i] - 0x30;
00029   }
00030   return value;
00031 }
00032 
00033 
00034 static char addSum(const char* buf, size_t count)
00035 {
00036   char sum = 0;
00037   for (size_t i = 0; i < count; ++i) {
00038     sum += buf[i];
00039   }
00040   return sum;
00041 }
00042 
00043 
00044 int recvReply(qrk::Connection* con, int timeout,
00045               std::vector<std::string>* lines)
00046 {
00047   // Read echo back
00048   enum { LineMax = 64 + 1};
00049   char buffer[LineMax];
00050   int n = readline(con, buffer, LineMax, timeout);
00051   if (n <= 0) {
00052     return ReceiveTimeout;
00053   }
00054 
00055   // Read the response
00056   n = readline(con, buffer, LineMax, timeout);
00057   if (n <= 0) {
00058     return ReceiveTimeout;
00059   }
00060 
00061   // Check the checksum
00062   char checksum = (addSum(buffer, n - 1) & 0x3f) + 0x30;
00063   if (buffer[n - 1] != checksum) {
00064     return -3;
00065   }
00066   // Get status
00067   buffer[2] = '\0';
00068   int reply_code = strtol(buffer, NULL, 16);
00069 
00070   // read the new line character (1byte)
00071   char last_ch;
00072   n = con->receive(&last_ch, 1, timeout);
00073   if (n != 1) {
00074     return -4;
00075   }
00076   if (! isLF(last_ch)) {
00077     // If the character is not a line feed, then that character may be data.
00078     //  So write back that character.
00079     con->ungetc(last_ch);
00080   }
00081 
00082   // If "lines" is not a NULL, store as string data till the linefeed character.
00083   if (lines != NULL) {
00084     while (true) {
00085       n = readline(con, buffer, LineMax, timeout);
00086       lines->push_back(buffer);
00087       if ((n == 1) && isLF(buffer[0])) {
00088         break;
00089 
00090       } else if (n <= 0) {
00091         return -1;
00092       }
00093     }
00094   }
00095 
00096 #if defined(WINDOWS_OS)
00097   getchar();
00098 #endif
00099 
00100   return reply_code;
00101 }