New project
New iot
  • Project Name:
  • Type:
  • Private Code:
    2881-3137-3841
  • Auth Key:
    Project not saved
  • Public Code:
    2279-8791-8097
  • IoT Name:
//*****************************************************************************
//** by dataino www.dataino.it                                               **
//** modified 07 Dec 2015                                                    **
//** by G. Carmelo                                                           **
//*****************************************************************************
//* MQTT dataino.it Server                                                   **
//* http://mosquitto.org                                                     **
//*****************************************************************************
// Dataino Network - MQTT - version 001                                      **
// Copyright (c) 2015 Carmelo G.                                             **
// If you require a license, see                                             **
//     http://www.opensource.org/licenses/bsd-license.php                    **
//*****************************************************************************
//                                LIBRARY                                    **
//*****************************************************************************
#include <SPI.h>                  //
#include <Ethernet.h>             //
#include <PubSubClient.h>         //
//*****************************************************************************
//                            PROGRAM VAR - CONST                            **
//*****************************************************************************
unsigned int count = 0;           //
char rqs[6] = "00000";            // IOT requester iD
char *topic;                      // Topic Var
boolean VAR_IN = false;           // switch fon incoming variable
boolean VAL_IN = false;           // switch fon incoming value
int valId = 0;                    // Variable iD (Integer from 1 to 10000)
const int MAX_STRING_LEN = 128 ;  // The largest string you will process
char strBuf[MAX_STRING_LEN];      // Static buffer for computation
char inData[MAX_STRING_LEN];      // Allocate some space for the string
char myConc[MAX_STRING_LEN];      // Static buffer for MQTT Message computation
//*****************************************************************************
#define IntValue 0                //
#define FloatValue 1              //
#define CharValue 2               //
//*****************************************************************************
#define Alive 0                   // The alive id for incoming request
char aliveMsg[8] = "";            // Alive msg
//*****************************************************************************
#define GetConfig 1               // The get config id for incoming request
//*****************************************************************************
#define GetValues 2               // The getvalues id for incoming request
//*****************************************************************************
#define GetAuth 3                 // 
char authkey[41] = ""; // Auth key
char msgAuth[20];                 //
char *y;                          //
int pointer = -1;                 // Pointer auth code
int insertSql = -1;               // Id insert sql DB
//*****************************************************************************
char EndSend[3]   = "*E";         //
char Empty[1]     = "";           //
char str_float[6];                // Static buffer for float to char conversion
char *dtostrf(double val, signed char width, unsigned char prec, char *s);
//*****************************************************************************
//            Update these with values suitable for your network.            **
//*****************************************************************************
//byte iotMac[]     = { 0x90, 0xA2, 0xDA, 0x0D, 0x82, 0x39 };// iot mac Uno
byte iotMac[]     = { 0x90, 0xA2, 0xDA, 0x0E, 0x80, 0x2A };// iot Mac Mega
byte iotIp[]      = { 192, 168, 88, 252};                  // iot ip
byte iotGateway[] = { 192, 168, 88, 1 };                   // iot Gateway
byte iotDns[]     = { 192, 168, 88, 1 };                   // iot dns
byte iotSubnet[]  = { 255, 255, 255, 0};                   // iot subnet
//*****************************************************************************
//                               MQTT dataino IP                             **
//*****************************************************************************
byte server[]={37,59,113,1}; // MQTT ip
char userName[] = "";        // Reserved not divulgate (your username)
char password[] = "";        // Reserved not divulgate (see user data)
//*****************************************************************************
//                         Project and iot iD values                         **
//*****************************************************************************
// 
char ProjectTopic[15] = "";                   // Project iD
// 
char IOT[6]           = "";                            // IOT iD
// ProjectTopic (14) + / + IOT (5)
char IotTopic[21]     = ""; // Channel iot

//*****************************************************************************
//                              Gauge variable                               **
//*****************************************************************************

//*****************************************************************************
//**                            IoT Configuration                            **
//*****************************************************************************

char buffer[128];
//*****************************************************************************
EthernetClient ethClient;
PubSubClient client( server, 1883, callback, ethClient );
// ****************************************************************************
// **                                SETUP                                   **
// ****************************************************************************
void setup()
{
 // Openf serial communications:
 Serial.begin( 57600 );
 // start the Ethernet connection:
 Ethernet.begin( iotMac, iotIp, iotDns, iotGateway, iotSubnet );
 Serial.println( );
 delay( 1000 );
 Serial.println( F( "MQTT Connecting..." ) );
 //***************************************************************************
 //                      Check if MQTT is connect                           **
 //***************************************************************************
 if ( client.connect(IOT, userName, password )) {
   subscribeChannels();
 } else {
   Serial.println( F( "MQTT ERROR" ) );
 }
}
// ****************************************************************************
// **                                LOOP                                    **
// ****************************************************************************
void loop()
{
 // *************************************************************************
 // **             Check if MQTT client is ok or try to reconnect          **
 // *************************************************************************
 if (!client.loop()) {
   Serial.print( F( "Client disconnected..." ) );
   if ( client.connect( IOT, userName, password ) ) {
     Serial.println( F ( "reconnected." ) );
     subscribeChannels();
   } else {
     Serial.println( F( "failed.") );
   }
 }

}
// ***************************************************************************
//                            Subscribe MQTT channels                       **
// ***************************************************************************
void subscribeChannels()
{
 Serial.print( F( "Connected As:" ) );
 Serial.println( IOT );
 client.subscribe( ProjectTopic );
 Serial.print( F( "subscribe:" ) );
 Serial.println( ProjectTopic );
 client.subscribe( IotTopic );
 Serial.print( F( "subscribe:" ) );
 Serial.println( IotTopic );
 sprintf( aliveMsg, "%s;!", IOT );
 client.publish( ProjectTopic , aliveMsg );
 Serial.println( F( "I'm Alive !" ) );
}
// ***************************************************************************
//                          Function Compare String                         **
// ***************************************************************************
char Comp(char* inData, char* This) {
 //-----------------------------------------------------------------------
 if ( strcmp( inData, This ) == 0 ) {
   return (0);
 } else {
   return (1);
 }
}
//****************************************************************************
//                         Handle message arrived                           **
//****************************************************************************
void callback( char* topicIn, byte * payload, unsigned int length ) {
  topic = topicIn;
  Serial.print( F( "payload:" ) );
  for ( unsigned int i = 0 ; i < length ; i++ ) {
    Serial.print( char( payload[i] ) );
    inData[i] = char( payload[i] );
  }// End For
  Serial.println( );
  split_value( inData );
  // Clear inData Array
  for (int i = 0 ; i < MAX_STRING_LEN ; i++ ) {
    inData[i] = 0;
  }// End For
}
//****************************************************************************
//                               SPLIT FUNCTION                             **
//****************************************************************************
void split_value( char* string )
{
  //-----------------------------------------------------------------------
  char *str;
  char *p;
  count = 0;
  //-----------------------------------------------------------------------
  strncpy( strBuf, string, MAX_STRING_LEN );      // copy source string
  //-----------------------------------------------------------------------
  // split using comma loop while str is not null get subsequent tokens
  //-----------------------------------------------------------------------
  for ( str = strtok_r(strBuf, ";", &p); str; str = strtok_r(NULL, ";", &p)) {
    //---------------------------------------------------------------------
    //
    //---------------------------------------------------------------------
    if ( Comp( str, EndSend ) == 0 ) {
      VAL_IN = false;
      VAR_IN = false;
    }
    //***********************************************************************
    //                             Value on Recive                         **
    //***********************************************************************
    if ( VAR_IN == false && VAL_IN == true ) {
      //
      switch ( valId ) {
        //*******************************************************************
        //                            GetConfig                            **
        //*******************************************************************
        case GetConfig:
          for (int i = 0; i < tableSize; i++)
          {
            // Necessary casts and dereferencing, just copy.
            strcpy_P(buffer, (char*)pgm_read_word(&(string_table[i])));
            SendConfig( buffer, rqs );
          }
          break;
        //*******************************************************************
        //                        Get Authorization code                   **
        //*******************************************************************
        case GetAuth:
          strncpy( rqs, IOT, 5 );
          pointer   = atoi( strtok_r( str, ":", &y ) ) + 1 ;
          insertSql = atoi( strtok_r( NULL, ":", &y ) );
          sprintf( msgAuth, "{\"aut\":%i,\"sql\":%i}", authkey[pointer], insertSql );
          client.publish( "dbServer" , msgAuth );
          break;
        //*******************************************************************
        //                            Get All Values                       **
        //*******************************************************************
        case GetValues:
          strncpy( rqs, IOT, 5 );
 
          break;
 
      }
    }
    //***********************************************************************
    //                      Variable on Recive                             **
    //***********************************************************************
    if ( VAR_IN == true && VAL_IN == false ) {
      valId  =  atoi( str );
      VAR_IN = false;
      VAL_IN = true;
    }
    //***********************************************************************
    //                    Incoming request From = rqs                      **
    //***********************************************************************
    if ( ( Comp( topic, IotTopic ) == 0
           || Comp( topic, ProjectTopic ) == 0 ) && count == 0  ) {

      strncpy( rqs, str, 5 );

      //*********************************************************************
      //                          Echo on channell                         **
      //*********************************************************************
      if ( Comp( rqs, IOT ) == 0 ) {
        VAR_IN = false;
        VAL_IN = false;
        break;
      }
      //*********************************************************************
      //                          Variable incoming                        **
      //*********************************************************************
      VAR_IN = true;
      VAL_IN = false;
    }
    count++;

  } // END for
  //*************************************************************************
  //
  //*************************************************************************
  if ( valId > 100 ) {
    //***********************************************************************
    // Replay value to other IoT
    //***********************************************************************
    SendValue( valId );
  }
} // END void
//***************************************************************************
//                          SEND VALUE TO MONITOR                          **
//***************************************************************************
void SendValue( int SendVar ) {
 // ProjectTopic (14) + / + IOT (5) + / + GaugeId (4)
  char GaugeTopic[26];
  sprintf( GaugeTopic, "%s/%i", IotTopic, SendVar );
  //*************************************************************************
  //* Switch value to send                                                 **
  //*************************************************************************
  switch ( SendVar )
  {

  }
}
//***************************************************************************
//                           Send configuration IoT                        **
//***************************************************************************
void SendConfig ( char* message , char* inquirer ) {
  sprintf( myConc, "%s;%s", IOT, message );
 // ProjectTopic (14) + / + IOT (5)
  char TopicDestination[21];
  sprintf( TopicDestination, "%s/%s", ProjectTopic, inquirer );
  client.publish( TopicDestination , myConc );
}
//***************************************************************************
//                       Pubblish value on channel                         **
//***************************************************************************
void PubblishValue( char* GaugeTopic  , int type , int valueI ,  float valueF , char* valueC ) {
  switch ( type ) {
    //*********************************************************************
    // Int case
    //*********************************************************************
    case IntValue:
      sprintf( myConc, "{\"value\":%i,\"rqs\":\"%s\"}", valueI, rqs );
      break;
    //*********************************************************************
    // Float case
    //*********************************************************************
    case FloatValue:
      dtostrf( valueF, 4, 2, str_float );
      sprintf( myConc, "{\"value\":\"%s\",\"rqs\":\"%s\"}", str_float, rqs );
      break;
    //*********************************************************************
    // Text case
    //*********************************************************************
    case CharValue:
      sprintf( myConc, "{\"value\":\"%s\",\"rqs\":\"%s\"}", valueC, rqs );
      break;
  }
  //---------------------------------------------------------------------
  //
  //---------------------------------------------------------------------
  client.publish( GaugeTopic , myConc );
}

X

Login




X

Register

captcha

X

Password Reset