KSduino 

 The Device Network
Your IP Address is: 54.161.130.145

DOCUMENTATION

KSduino.cpp
Go to the documentation of this file.
00001 /* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 2; tab-width: 2 -*- */
00002 /*
00003  * KSduino.cpp
00004  *
00005  * KSduino-library for Arduino ver 0.0.1
00006  *
00007  * Copyright (C) Kirill Scherba 2012-2013 <kirill@scherba.ru>
00008  * 
00009  * KSduino Library is free software: you can redistribute it and/or modify it
00010  * under the terms of the GNU Lesser General Public License  as published by 
00011  * the Free Software Foundation, either version 2.1 of the License, or
00012  * (at your option) any later version.
00013  * 
00014  * KSduino-library is distributed in the hope that it will be useful, but
00015  * WITHOUT ANY WARRANTY; without even the implied warranty of
00016  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00017  * See the GNU General Public License for more details.
00018  * 
00019  * You should have received a copy of the GNU General Public License along
00020  * with this program.  If not, see <http://opensource.org/licenses/LGPL-2.1>
00021  *
00022  */
00023 
00031 #include "KSduino.h" 
00032 
00033 #ifdef __arduino__
00034 # 
00035 #ifdef __W5100__
00036 #include <SPI.h>
00037 #include <Ethernet.h>
00038 #include <EthernetUdp.h>
00039 #
00040 #include <utility/w5100.h>
00041 #include <utility/socket.h>
00042 #endif
00043 #
00044 #ifdef __ENC28J60__
00045 #include <EtherCard.h>
00046 #endif
00047 #
00048 #endif
00049 
00050 #ifdef __linux__
00051 #
00052 #include <stdio.h>
00053 #include <string.h>
00054 #include "KSduinoEthernet.h"
00055 #include "KSduinoEthernetUdp.h"
00056 #
00057 #endif
00058 
00059 #define BUF_SIZE 40*2
00060 #define XBUF_SIZE 32
00061 #define MAX_WAIT_TIME 2500
00062 #define MAX_NUM_TO_REPEAT_IN_WAIT_PACKET 5
00063 
00064 #define TIMEOUT_BEFORE_RESET 300
00065 
00066 #if PRINT_SERIAL_MESSAGES
00067 #ifdef __arduino__
00068 #define ksd_print(text) Serial.print(text)
00069 #define ksd_println(text) Serial.println(text)
00070 #endif
00071 #ifdef __linux__
00072 #include <iostream>
00073 using namespace std; 
00074 #define ksd_print(text) cout << text
00075 #define ksd_println(text) cout << text; cout << "\n"
00076 #endif
00077 #else
00078 #define ksd_print(text)   
00079 #define ksd_println(text)
00080 #endif
00081 
00082 #ifdef __arduino__W5100__
00083   #define _parsePacket() parsePacket()
00084 #else 
00085 #ifdef __arduino__ENC28J60__
00086     #define _parsePacket() Udp.parsePacket(&_len, &_pos)  
00087 #else
00088     #define _parsePacket() Udp.parsePacket()
00089 #endif    
00090 #endif
00091 
00092 void(* resetArduino) (void) = 0;                                  
00093 
00107 KSduino::KSduino (unsigned int devID, unsigned int devPwd, byte *serverAddr, 
00108                   unsigned int serverP)
00109 {
00110     deviceID = devID; 
00111     devicePasswd = devPwd;
00112     serverIpAddr = serverAddr;
00113     serverPort = serverP;  
00114     _loopTime = MAX_WAIT_TIME;
00115     _receptionFunc = NULL;
00116     #ifdef __arduino__W5100__
00117     _beforeResetFunc = NULL;
00118     #endif
00119     _lostPacketCallback = NULL;
00120     _totalPackets = 0;
00121     _lostPackets = 0;
00122     _wrongAnswer = 0;
00123     _lastSend = 0;
00124     _idx = 0;
00125 }
00126 
00127 
00128 /*
00129  * Get W5100 socket & set timeout
00130  */
00131 #ifdef __arduino__W5100__
00132 #define getSocket() \
00133   for (int i = 0; i < MAX_SOCK_NUM; i++) { \
00134     uint8_t s = W5100.readSnSR(i); \
00135     if (s == SnSR::CLOSED || s == SnSR::FIN_WAIT) { \
00136       _s = i; \
00137       break; \
00138     } \
00139   } \
00140   uint16_t _timeout = 2000; \
00141   W5100.setRetransmissionTime (_timeout);
00142 #else
00143   #define getSocket()
00144 #endif
00145 
00146 #ifdef __arduino__ENC28J60__
00147 #define Ethernet Ethernet_ethercard 
00148 #endif
00149 
00150 
00185 void KSduino::begin (byte *mac, byte *ip, byte *dns, byte *gateway, 
00186                                       unsigned int port)
00187 {
00188   Ethernet.begin (mac, ip, dns, gateway);
00189   getSocket();
00190   _port = port;
00191   Udp.begin (port);
00192 }
00193 void KSduino::begin (byte *mac, byte *ip, byte *dns, unsigned int port)
00194 {
00195   Ethernet.begin (mac, ip, dns);
00196   getSocket();
00197   _port = port;
00198   Udp.begin (port);
00199 }
00200 void KSduino::begin (byte *mac, byte *ip, unsigned int port)
00201 {
00202   Ethernet.begin (mac, ip);
00203   getSocket();
00204   _port = port;
00205   Udp.begin (port);
00206 }
00207 void KSduino::begin (byte *mac, unsigned int port)
00208 {
00209   Ethernet.begin (mac);
00210   getSocket();
00211   _port = port;
00212   Udp.begin (port);
00213 }
00214 #ifndef __arduino__ENC28J60__
00215 void KSduino::begin (byte *mac, byte *ip, byte *dns, byte *gateway, 
00216                                        byte* subnet, unsigned int port)
00217 {
00218   Ethernet.begin (mac, ip, dns, gateway, subnet);
00219   getSocket();
00220   _port = port;
00221   Udp.begin (port);
00222 }
00223 #endif
00224 
00256 void KSduino::sendBuffer (const char *userData, int checkAnswer)
00257 { 
00258   beginPacket ();                       // Start (init) Packet
00259   Udp.write (",");
00260   Udp.write (userData);           // Write User data
00261   endPacket (checkAnswer);  // Send Packet to server 
00262 }
00263 #ifdef __arduino__
00264 
00292 void KSduino::sendBuffer (String userData, int checkAnswer)
00293 { 
00294   int i, len = userData.length();
00295   beginPacket ();           // Start (init) Packet
00296   Udp.write (",");
00297   for (i=0; i < len; i++)  Udp.write (userData.charAt(i));  // Write User data
00298   Udp.write ((byte)0);
00299   endPacket (checkAnswer);  // Send Packet to server 
00300 }
00301 #endif
00302 
00303 
00327 void KSduino::sendOne (const char *parameter, const char *value, 
00328                        const char *message, int checkAnswer)
00329 {
00330   beginPacket ();                               // Start (init) Packet
00331   addParameter (parameter, value);              // Add parameter
00332   if (message != NULL) addMessage (message);    // Add message
00333   endPacket (checkAnswer);                      // Send Packet to server   
00334 }
00335 
00336 void KSduino::sendOne (const char *parameter, float value, const char *message, 
00337                        int checkAnswer )
00338 {
00339   char fBuf [XBUF_SIZE];
00340   
00341   dtostrf (value, 1, 2, fBuf); 
00342   if (strstr(fBuf,"INF") != NULL) strcpy (fBuf,"0.00");
00343   sendOne (parameter, fBuf, message, checkAnswer);
00344 }
00345 
00346 void KSduino::sendOne (const char *parameter, byte value, const char *message, 
00347                        int checkAnswer )
00348 {
00349   char dBuf [XBUF_SIZE];
00350   
00351   //snprintf (dBuf, XBUF_SIZE, "%d", value); 
00352   dtostrf (value, 1, 0, dBuf);
00353   sendOne (parameter, dBuf, message, checkAnswer);
00354 }
00355 
00356 void KSduino::sendOne (const char *parameter, int value, const char *message, 
00357                        int checkAnswer )
00358 {
00359   char dBuf [XBUF_SIZE];
00360   
00361   //snprintf (dBuf, XBUF_SIZE, "%d", value); 
00362   dtostrf (value, 1, 0, dBuf);
00363   sendOne (parameter, dBuf, message, checkAnswer);
00364 }
00365 
00366 void KSduino::sendOne (const char *parameter, unsigned int value, 
00367                        const char *message, int checkAnswer )
00368 {
00369   char dBuf [XBUF_SIZE];
00370   
00371   //snprintf (dBuf, XBUF_SIZE, "%u", value); 
00372   dtostrf (value, 1, 0, dBuf);
00373   sendOne (parameter, dBuf, message, checkAnswer);
00374 }
00375 
00376 void KSduino::sendOne (const char *parameter, unsigned long value, 
00377                        const char *message, int checkAnswer )
00378 {
00379   char dBuf [XBUF_SIZE*2];
00380   
00381   //snprintf (dBuf, XBUF_SIZE*2, "%ul", value); 
00382   dtostrf (value, 1, 0, dBuf);
00383   sendOne (parameter, dBuf, message, checkAnswer);
00384 }
00385 
00386 
00406 void KSduino::beginPacket (void)
00407 {
00408   char xBuf [XBUF_SIZE]; 
00409 
00410   _startTime = millis();
00411   packet++; if (!packet) packet = 1;
00412     
00413   ksd_print ("Sending packet ");
00414   ksd_println ((int)packet);
00415 
00416   Udp.beginPacket(serverIpAddr, serverPort);
00417   // Write ID
00418   snprintf (xBuf, XBUF_SIZE, "id=%d,", deviceID); 
00419   Udp.write (xBuf);   
00420   // Write Package number
00421   snprintf (xBuf, XBUF_SIZE, "pkg=%d,", packet); 
00422   Udp.write (xBuf);    
00423   // Write password
00424   snprintf (xBuf, XBUF_SIZE, "pwd=%d", devicePasswd+deviceID+packet); 
00425   Udp.write (xBuf);    
00426 }
00427 
00428 
00461 // char value for any parameters or for messager 
00462 void KSduino::addParameter (const char *parameter, const char *value)
00463 {
00464   Udp.write (",");
00465   Udp.write (parameter);
00466   Udp.write ("=");
00467   Udp.write (value);
00468 }
00469 // float value for f-type
00470 void KSduino::addParameter (const char *parameter, float value)
00471 {
00472   char fBuf [XBUF_SIZE];
00473   
00474   /* ERRROR: If float value ~= 0.00 the dtostrf - returns INF!!! 
00475      This code does not work:
00476      if (value == 0.0) strcpy (fBuf,"0.00");
00477      else dtostrf (value, 1, 2, fBuf);
00478   */
00479   dtostrf (value, 1, 2, fBuf);
00480   if (strstr(fBuf,"INF") != NULL) strcpy (fBuf,"0.00"); 
00481   addParameter (parameter, fBuf);
00482 }
00483 // byte value for d-type and b-type
00484 void KSduino::addParameter (const char *parameter, byte value)
00485 {
00486   char dBuf [XBUF_SIZE];
00487   
00488   //snprintf (dBuf, XBUF_SIZE, "%d", value);
00489   dtostrf (value, 1, 0, dBuf);
00490   addParameter (parameter, dBuf);
00491 }
00492 // int value for i-type
00493 void KSduino::addParameter (const char *parameter, int value)
00494 {
00495   char dBuf [XBUF_SIZE];
00496   
00497   //snprintf (dBuf, XBUF_SIZE, "%d", value);
00498   dtostrf (value, 1, 0, dBuf);
00499   addParameter (parameter, dBuf);
00500 }
00501 // unsigned int value for u-type
00502 void KSduino::addParameter (const char *parameter, unsigned int value)
00503 {
00504   char dBuf [XBUF_SIZE];
00505   
00506   //snprintf (dBuf, XBUF_SIZE, "%u", value);
00507   dtostrf (value, 1, 0, dBuf);
00508   addParameter (parameter, dBuf);
00509 }
00510 // unsigned long value for unsigned long
00511 void KSduino::addParameter (const char *parameter, unsigned long value)
00512 {
00513   char dBuf [XBUF_SIZE*2];
00514   
00515   //snprintf (dBuf, XBUF_SIZE*2, "%ul", value);
00516   dtostrf (value, 1, 0, dBuf);
00517   addParameter (parameter, dBuf);
00518 }
00519 
00520 
00540 void KSduino::addMessage (const char *message)
00541 {
00542   if (message[0] != 0)
00543   {
00544     Udp.write (",");
00545     Udp.write ("msg");
00546     Udp.write ("=\"");
00547     Udp.write (message);
00548     Udp.write ("\"");
00549   }
00550 }
00551 
00552 
00553 #ifdef __arduino__W5100__
00554 int KSduino::_Udp_endPacket()
00555 {
00556   unsigned long st = millis();
00557   W5100.execCmdSn(_s, Sock_SEND);
00558   while ( (W5100.readSnIR(_s) & SnIR::SEND_OK) != SnIR::SEND_OK ) 
00559   {
00560     if (W5100.readSnIR(_s) & SnIR::TIMEOUT)
00561     {
00562       W5100.writeSnIR(_s, (SnIR::SEND_OK|SnIR::TIMEOUT));
00563       /* Timeout */
00564       return 0;
00565     }
00566     
00567     /* W5100 error - try to reconnect */
00568     if ( (millis() - st) >= TIMEOUT_BEFORE_RESET )
00569     {
00570       int doReset = 1;
00571       
00572       if (_beforeResetFunc != NULL) doReset  =  _beforeResetFunc ();      
00573       
00574       if (doReset == 1) resetArduino ();
00575       
00576       return -1;
00577     }
00578   }
00579   W5100.writeSnIR(_s, SnIR::SEND_OK);
00580 
00581   /* Sent ok */
00582   return 1;
00583 }
00584 #define Udp_endPacket() _Udp_endPacket()
00585 #else
00586   #define Udp_endPacket() Udp.endPacket()
00587 #endif
00588 
00589 
00613 int KSduino::endPacket (int checkAnswer)
00614 {
00615   int retval = 1;
00616 
00617   #ifdef __arduino__W5100__
00618   W5100.getRXReceivedSize(_s);
00619   #endif
00620   
00621   Udp_endPacket(); 
00622   
00623   _totalPackets++;
00624   _lastSend = millis();
00625   
00626   // read ansver from server
00627   if (checkAnswer == 1) retval = waitPacketAnswer (packet);  // Return 1 if success
00628   else if (checkAnswer == 2)
00629   {
00630     // add packet to Packets Queue
00631     _packetsQueue [_idx].packet = packet;
00632     _packetsQueue [_idx].num = 0;
00633     if (_idx < PACKETS_QUEUE_SIZE-1) _idx++;
00634     else
00635     {
00636       _idx++;
00637       // remove old records from queue
00638       if (!checkPacketsQueue ())
00639       {
00640         // remove first record from queue
00641         _packetsQueue[0].num = OLD_QUEUES_PACKET;
00642         checkPacketsQueue ();
00643       }
00644     }
00645   }
00646 
00647   // calculate one loops time
00648   _loopTime = millis() - _startTime;
00649   
00650   // print messages
00651   #if PRINT_SERIAL_MESSAGES
00652   ksd_print ("Total packets = ");
00653   ksd_println (_totalPackets);    
00654   if (_lostPackets)
00655   {
00656     ksd_print ("Total lost packets = ");
00657     ksd_println (_lostPackets);    
00658   }  
00659   if (_wrongAnswer)
00660   {
00661     ksd_print("Total wrong answer = ");
00662     ksd_println(_wrongAnswer);    
00663   }  
00664   if (_idx)
00665   {
00666     ksd_print ("Bytes in packets Queue = ");
00667     ksd_println ((int)_idx);    
00668   }  
00669   ksd_print ("After ");
00670   ksd_print (_loopTime);
00671   ksd_println (" ms");
00672   ksd_println (""); 
00673   #endif
00674 
00675   return retval;
00676 }
00677 
00678 
00711 void KSduino::sendToOther (int device_id, int device_passwd, 
00712                            const char *parameter, const char *value, 
00713                            const char *message, int checkAnswer)
00714 {
00715   beginPacket ();                             // Start (init) Packet
00716   addParameter ("T1", device_id);             // Add T1 transit parameter
00717   addParameter ("P1", device_passwd);         // Add P1 transit parameter
00718   addParameter (parameter, value);            // Add parameter
00719   if (message != NULL) addMessage (message);  // Add message
00720   endPacket (checkAnswer);                    // Send Packet to server   
00721 }
00722 void KSduino::sendToOther (int device_id, int device_passwd, 
00723                            const char *parameter, byte value, 
00724                            const char *message, int checkAnswer)
00725 {
00726   char fBuf [XBUF_SIZE];
00727   
00728   dtostrf (value, 1, 0, fBuf);
00729   sendToOther (device_id, device_passwd, parameter, fBuf, message, checkAnswer);
00730 }
00731 void KSduino::sendToOther (int device_id, int device_passwd, 
00732                            const char *parameter, int value, 
00733                            const char *message, int checkAnswer)
00734 {
00735   char fBuf [XBUF_SIZE];
00736   
00737   dtostrf (value, 1, 0, fBuf); 
00738   sendToOther (device_id, device_passwd, parameter, fBuf, message, checkAnswer);
00739 }
00740 void KSduino::sendToOther (int device_id, int device_passwd, 
00741                            const char *parameter, unsigned int value, 
00742                            const char *message, int checkAnswer)
00743 {
00744   char fBuf [XBUF_SIZE];
00745   
00746   dtostrf (value, 1, 0, fBuf); 
00747   sendToOther (device_id, device_passwd, parameter, fBuf, message, checkAnswer);
00748 }
00749 void KSduino::sendToOther (int device_id, int device_passwd, 
00750                            const char *parameter, unsigned long value, 
00751                            const char *message, int checkAnswer)
00752 {
00753   char fBuf [XBUF_SIZE];
00754   
00755   dtostrf (value, 1, 0, fBuf); 
00756   sendToOther (device_id, device_passwd, parameter, fBuf, message, checkAnswer);
00757 }
00758 void KSduino::sendToOther (int device_id, int device_passwd, 
00759                            const char *parameter, float value, 
00760                            const char *message, int checkAnswer)
00761 {
00762   char fBuf [XBUF_SIZE];
00763   
00764   dtostrf (value, 1, 2, fBuf); 
00765   if (strstr(fBuf,"INF") != NULL) strcpy (fBuf,"0.00");
00766   sendToOther (device_id, device_passwd, parameter, fBuf, message, checkAnswer);
00767 }
00768 
00769 
00782 void KSduino::update()
00783 {
00784   getAnswer ();
00785   pingServer ();
00786 }
00787 
00788 
00789 // Check reception and select wrong answer
00790 #define         _checkReception(packetNum, buf)  \
00791         {  \
00792           if (!checkReception (packetNum, buf)) \
00793           {  \
00794             _wrongAnswer++;  \
00795             if (_lostPacketCallback != NULL) { _lostPacketCallback (2, packetNum); } \
00796             \
00797             ksd_print ("Wrong Answer#: "); \
00798             ksd_println (packetNum); \
00799             ksd_print ("Data: "); \
00800             ksd_println (buf); \
00801             ksd_println (""); \
00802           }  \
00803         }
00804         
00805 
00806 /* *
00807  * Wait answer from server to selected packet
00808  */
00809 int KSduino::waitPacketAnswer (byte packet)
00810 {
00811   int retval = 0;
00812   int packetSize = 0;
00813   int numToRepeate = 0;
00814   char buf [BUF_SIZE];       // Buffer to hold incoming packet  
00815 
00816   #ifdef __arduino__W5100__
00817   _readbuf = buf;
00818   _readbufSize = BUF_SIZE;
00819   #endif
00820         
00821   // Wait for answer
00822   while (1)
00823   {
00824     int packetNum = 0;
00825     unsigned long waitTime = millis();
00826 
00827     while ( (packetSize = _parsePacket()) > 0 )
00828     {
00829       int maxWaitTime=(_loopTime <= MAX_WAIT_TIME)?_loopTime+50:MAX_WAIT_TIME;
00830         
00831       if (millis() - waitTime > maxWaitTime)
00832       {
00833         ksd_print("The Packet ");
00834         ksd_print(packet);
00835         ksd_println(" was lost ");
00836         break;
00837       }
00838      }
00839 
00840      // Check reseived  data
00841      if(packetSize)
00842      {    
00843        packetNum = readPacket (packetSize, buf, BUF_SIZE);
00844         
00845        if (packetNum != packet)
00846        {
00847          _checkReception (packetNum, buf);
00848        }
00849        else { retval = 1; break; }
00850       }
00851       
00852       if (++numToRepeate > MAX_NUM_TO_REPEAT_IN_WAIT_PACKET) 
00853       {         
00854         _lostPackets++; 
00855         if (_lostPacketCallback != NULL) _lostPacketCallback(1, packetNum);
00856         break; 
00857       }
00858     }  
00859     
00860     return retval;
00861 }
00862 
00863 
00867 #ifdef __arduino__W5100__
00868 int KSduino::parsePacket ()
00869 {
00870   _readLen = 0;
00871   
00872   if (W5100.getRXReceivedSize(_s) > 0)
00873   {
00874     _readLen = recvfrom(_s, (uint8_t *)_readbuf, _readbufSize, 
00875                             _si_recvIP,
00876                             &_si_recvPort);  
00877   }
00878   
00879   if (_readLen > 0) return _readLen; 
00880   else return 0;        
00881 }
00882 #endif
00883 
00884 
00888 int KSduino::readPacket (int packetSize, char *buf, int bufferSize)
00889 {
00890   
00891   int packetNum = 0;
00892 
00893   // print message
00894   ksd_print("Received ");
00895   ksd_print(packetSize);
00896   ksd_print(" byte packet from: ");
00897   #if PRINT_SERIAL_MESSAGES
00898   #ifdef __arduino__W5100__
00899   IPAddress ip = _si_recvIP;
00900   word port = _si_recvPort;
00901   #endif
00902   #ifdef __arduino__ENC28J60__
00903   char *ip = "";
00904   word port = 0;
00905   #endif
00906   #ifdef __linux__
00907   char *ip = Udp.remoteIP();
00908   word port = Udp.remotePort();
00909   #endif
00910   #endif
00911   ksd_print(ip);
00912   ksd_print(":");
00913   ksd_println(port);
00914         
00915   // read the packet into packetBufffer & check it packet number
00916   #ifdef __arduino__W5100__
00917   if (_readLen > 0)
00918   #else
00919   buf[0] = 0;
00920   if (Udp.read (buf, bufferSize) > 0)
00921   #endif        
00922   {     
00923     buf [packetSize<bufferSize ? packetSize:(bufferSize-1)] = 0;
00924     packetNum = getPacketNum ((const unsigned char*)buf, bufferSize);
00925   }     
00926 
00927   // print message
00928   ksd_print("Packet #: ");
00929   ksd_println(packetNum);
00930   ksd_print("Data: ");
00931   ksd_println(buf);
00932   ksd_println("");
00933         
00934   return packetNum;
00935 }
00936 
00937 
00946 int KSduino::checkPacketsQueue (int packet)
00947 {
00948   int retval = 0;
00949 
00950   // Check current packet
00951   if (packet)
00952   {
00953     // Check queue & Mark record if packet found or not found
00954     int i = 0;
00955     for (i = 0; i < _idx; i++)
00956     {
00957       if (_packetsQueue[i].packet == packet) 
00958       { 
00959         // Packet found. Mark the record to remove from Queue
00960         _packetsQueue[i].num = FOUND_QUEUES_PACKET; 
00961         retval++; 
00962       }
00963       // Packet not found. Mark the record as not found - increment it's wait variavle
00964       else _packetsQueue[i].num++;
00965      }
00966   }
00967 
00968   // Remove old packects from queue
00969   int i = 0;
00970   while (i < _idx)
00971   {
00972     if (_packetsQueue[i].num >= OLD_QUEUES_PACKET)
00973     {
00974       if (_packetsQueue[i].num != FOUND_QUEUES_PACKET)
00975       { 
00976         ksd_print ("Lost packet #: ");
00977         ksd_println ((int)_packetsQueue[i].packet);
00978         _lostPackets++;
00979         if (_lostPacketCallback != NULL) _lostPacketCallback (1, (int)_packetsQueue[i].packet);
00980       } 
00981       if (!packet) retval++;
00982 
00983       // remove one first packet from queue (if queue holds only one packet)
00984       if (i == 0 && _idx == 1)
00985       { 
00986         _idx = 0;
00987         break;
00988       }
00989       // remove a packet from queue
00990       else
00991       { 
00992         if (i < (_idx-1) )
00993         {       
00994           memmove (&_packetsQueue[i], &_packetsQueue[i+1], 
00995           sizeof(ksdPacketsQueue)*(_idx-(i+1)) );
00996         }       
00997         _idx--;
00998       }
00999     }
01000     else i++;
01001   }
01002 
01003   return retval;
01004 }
01005 
01006 
01013 int KSduino::getAnswer ()
01014 {
01015   int packetNum = -1;
01016   int packetSize = 0;
01017   char buf [BUF_SIZE];       // Buffer to hold incoming packet  
01018 
01019   #ifdef __arduino__W5100__
01020   _readbuf = buf;
01021   _readbufSize = BUF_SIZE;
01022   #endif
01023         
01024   // check for answer
01025   while ( (packetSize = _parsePacket()) > 0)
01026   {
01027     packetNum = readPacket (packetSize, buf, BUF_SIZE);
01028     
01029     // find the packet number in the packet queue
01030     int success = checkPacketsQueue (packetNum);
01031                 
01032     if (!success)
01033     {
01034       _checkReception (packetNum, buf);
01035     }
01036   }
01037     
01038   return packetNum;
01039 }
01040 
01041 
01054 int KSduino::getPacketNum (const unsigned char *buffer, unsigned int bufferSize)
01055 {
01056   int packet = 0, i = 0;
01057   
01058   while(1)
01059   {
01060     unsigned char c = buffer[i];
01061     if (i >= bufferSize);
01062     else if (c == 0) break;
01063     else if (c == ',')
01064     {
01065       for(int j = 0; j < i; j++) packet = packet * 10 + (int) (buffer[j] - '0');
01066       break;
01067     }
01068     else if ( !(c>='0' && c <= '9') ) break;
01069     i++;
01070   }
01071   
01072   return packet;
01073 }
01074 
01075 
01082 unsigned long KSduino::getLostPackets (void)
01083 {
01084   return _lostPackets;
01085 }
01086 
01087 
01094 unsigned long KSduino::getWrongAnswer (void)
01095 {
01096   return _wrongAnswer;
01097 }
01098 
01099 
01106 unsigned long KSduino::getTotalPackets(void)
01107 {
01108   return _totalPackets;
01109 }
01110 
01111 
01118 unsigned long KSduino::getLoopTime (void)
01119 {
01120   return _loopTime;
01121 }
01122 
01123 
01130 int KSduino::getBytesInQueue(void)
01131 {
01132   return (int)_idx;
01133 }
01134 
01135 
01147 void KSduino::setReceptionCallback (ksdReceptionFunc receptionFunc)
01148 {
01149   _receptionFunc = receptionFunc;
01150 }
01151 
01152 
01153 #ifdef __arduino__W5100__
01154 
01166 void KSduino::setBeforeResetCallback (ksdBeforeReset beforeResetFunc)
01167 {
01168   _beforeResetFunc = beforeResetFunc;
01169 }
01170 #endif
01171 
01172 
01183 void KSduino::setLostPacketCallback (ksdLostPacketCallback lostPacketCallback)
01184 {
01185   _lostPacketCallback = lostPacketCallback;
01186 }
01187 
01188 
01192 int KSduino::checkReception (int packet_code, char *packet_data)
01193 {       
01194   int retval=0;
01195         
01196   if (_receptionFunc != NULL)
01197   {
01198     char *msg = NULL;
01199     char param;
01200     int  num;
01201     float value_float;
01202     int   value_int;
01203     unsigned int   value_uint;
01204     unsigned long  value_ulong;
01205     int   id;
01206     char  *i, *i2;
01207 
01208     // Packets data example: 7701,T1:id=3300,d1=1,msg="Test message" 
01209     if (packet_code == 7701)
01210     {   
01211       ksd_print ("Received T1 packet: ");
01212       ksd_println (packet_data);
01213                         
01214       // Parse the packet and call user function
01215       const char *fs = "7701,T1:id=";
01216       int fsLen = strlen(fs);
01217       if (strstr(packet_data,fs) == packet_data)
01218       {
01219         // Get id
01220         i = &packet_data[fsLen];
01221         if ( (i = strchr(i,',')) != NULL)
01222         {       
01223           i[0] = 0;
01224           sscanf(&packet_data[fsLen],"%d",&id);
01225           i[0] = ',';
01226           // Get parameter
01227           i++;       
01228           param = i[0];
01229           if ( (i2 = strchr(i,'=')) != NULL) 
01230           {
01231             i2[0] = 0;
01232             sscanf(&i[1],"%d",&num);
01233             i2[0] = '=';
01234             // Get parametr value
01235             i2++;
01236             i = strstr(i2,",msg=\"");
01237             if (i != NULL ) i[0] = 0;
01238             switch (param)
01239             {   
01240               case 'f':
01241                 sscanf(i2,"%f",&value_float);
01242                 break;
01243                                                                 
01244               case 'u':
01245                 sscanf(i2,"%u",&value_uint);
01246                 break;
01247                                                                 
01248               case 'l':
01249                 sscanf(i2,"%lu",&value_ulong);
01250                 break;
01251                                                                 
01252               default:
01253                 sscanf(i2,"%d",&value_int);
01254             }   
01255             if (i != NULL )
01256             {   
01257               i[0] = ',';
01258               // Get message
01259               i += 6;
01260               msg=i;
01261                                 int msglen = strlen(msg);
01262                                 if (msglen) 
01263                                 if (msg[msglen-1] == '\"') msg[msglen-1] = 0;
01264             }
01265             retval = 1;
01266                                                 
01267             switch (param)
01268             {
01269               case 'f':
01270                 _receptionFunc (id, param, num, &value_float, msg);
01271                 break;
01272                                                                 
01273               case 'u':
01274                 _receptionFunc (id, param, num, &value_uint, msg);
01275                 break;
01276 
01277               case 'l':
01278                 _receptionFunc (id, param, num, &value_ulong, msg);
01279                 break;
01280 
01281               default:  
01282                 _receptionFunc (id, param, num, &value_int, msg);
01283             }
01284           }     
01285         }       
01286       }
01287     }
01288   }
01289 
01290   return retval;
01291 }
01292 
01293 
01294 /*
01295  * Send ping signal to server if program does not send something 1 second longer
01296  */
01297 int KSduino::pingServer ()
01298 {
01299   if ( (millis() - _lastSend) > 1000 ) sendBuffer ("ping");
01300         
01301   return 1;
01302 }
01303 
01307 #ifdef __arduino__
01308 void  KSduino::softReset ()
01309 {
01310   resetArduino ();
01311 }
01312 #endif
01313 
01314 
Created with KSNews

HOME | CONTACTS | INFORMER | SHORTENER | DOCUMENTATION | HELP

Copyright © 2012-2013, The KSduino Project