Arduino REST call Example ThingWorx

    This document contains an example of calling the service and receiving a result using the REST ThingWorx. Example Arduino sketch in C language.

     

    #include <SPI.h>
    #include <Ethernet.h>
    #include <ArduinoJson.h>
    
    // Enter a MAC address and IP address for your controller below.
    // The IP address will be dependent on your local network:
    
    byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x03};
    
    char server[] = "tvsn.cloud.thingworx.com";
    
    EthernetClient client;
    
    //ThingWorx App key which replaces login credentials)
    char appKey[] = "b0b54023-3977-4670-8a0a-671ef412fe30";
    // ThingWorx Thing name for which you want to set properties values
    char thingName[] = "ExamleThing";
    //Interval of time at which you want the properties values to be sent to TWX server
    int timeBetweenRefresh = 5000;
    // ThingWorx service that will set values for the properties you need
    // See the documentation for this tutorial for more information
    char serviceName[] = "ExampleService";
    
    //How many values you will be pushing to ThingWorx
    #define propertyCount 2
    //Initialize Properties Names and Values Arrays
    const char* propertyNames[] = {"Example1", "Example2"};
    double propertyValues[propertyCount];
    
    // last time you connected to the server, in milliseconds
    unsigned long lastConnectionTime = 0;
    // timer waiting for the arrival of characters from the server
    unsigned long timer_iot_timeout = 0;
    // Receive buffer size
    #define BUFF_LENGTH 64
    
    
    void setup() {
      //shut down the SD Card pins
      pinMode(4, OUTPUT);
      digitalWrite(4, HIGH);
    
      // start serial port:
    
      Serial.begin(9600);
    
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }
    
      // start the Ethernet connection:
      Serial.println("Trying to get an IP address using DHCP");
      Ethernet.begin(mac);
      Serial.print("My IP address: ");
      Serial.print(Ethernet.localIP());
      Serial.println();
    }
    
    void loop() {
    
      // wait the established interval of time before
      // reading values from the sensor
      // and sending them to the TWX server again
      // delay(timeBetweenRefresh);
      if (millis() - lastConnectionTime > timeBetweenRefresh)
        updateServiceValues();
      else
        updateSensorsData();
    }
    
    void updateSensorsData()
    {
      // Aquire sensor values
      propertyValues[0] = 0;
    }
    
    void updateServiceValues()
    {
      // Connection to server Thingworx
      Serial.println("Connecting to IoT server...");
      if (client.connect(server, 80))
      {
        // Check connection
        if (client.connected())
        {
          // Sending a header of a network packet
          Serial.println("Sending data to IoT server...\n");
          Serial.print("POST /Thingworx/Things/");
          client.print("POST /Thingworx/Things/");
          Serial.print(thingName);
          client.print(thingName);
          Serial.print("/Services/");
          client.print("/Services/");
          Serial.print(serviceName);
          client.print(serviceName);
          Serial.print("?appKey=");
          client.print("?appKey=");
          Serial.print(appKey);
          client.print(appKey);
          Serial.print("&method=post&x-thingworx-session=true");
          client.print("&method=post&x-thingworx-session=true");
          // Sending data from sensors
          for (int idx = 0; idx < propertyCount; idx ++)
          {
            Serial.print("&");
            client.print("&");
            Serial.print(propertyNames[idx]);
            client.print(propertyNames[idx]);
            Serial.print("=");
            client.print("=");
            Serial.print(propertyValues[idx]);
            client.print(propertyValues[idx]);
          }
          // Close package
          Serial.println(" HTTP/1.1");
          client.println(" HTTP/1.1");
          Serial.println("Accept: application/json");
          client.println("Accept: application/json");
          Serial.print("Host: ");
          client.print("Host: ");
          Serial.println(server);
          client.println(server);
          Serial.println("Content-Type: application/json");
          client.println("Content-Type: application/json");
          Serial.println();
          client.println();
    
          // Waiting for a response from the server
          timer_iot_timeout = millis();
          while ((client.available() == 0) && (millis() < timer_iot_timeout + 5000));
    
          // Display the response on the server, and if a slow connection, wait for the timeout
          char buff[BUFF_LENGTH] = "";
          int iii = 0;
          bool flagJSON = false;
          timer_iot_timeout = millis();
          while ((millis() < timer_iot_timeout + 100) && (client.connected()))
          {
            while (client.available() > 0)
            {
              char symb = client.read();
              Serial.print(symb);
              if (symb == '{')
              {
                flagJSON = true;
              }
              else if (symb == '}')
              {
                flagJSON = false;
              }
              if (flagJSON == true)
              {
                buff[iii] = symb;
                iii ++;
              }
              timer_iot_timeout = millis();
            }
          }
          buff[iii] = '}';
          buff[iii + 1] = '\0';
          Serial.println(buff);
          // Close connection
          client.stop();
    
          // Decrypted parameters
          StaticJsonBuffer<BUFF_LENGTH> jsonBuffer;
          JsonObject& json_array = jsonBuffer.parseObject(buff);
          //Service result variable (return JSON)
          int result = json_array["result"];
          Serial.println("Result state:   " + String(result));
          Serial.println();
    
          // Device control
          //controlDevices();
    
          Serial.println("Packet successfully sent!");
          Serial.println();
          lastConnectionTime = millis();
        }
      }
      else {
        // if you didn't get a connection to the server:
        Serial.println("Connection could not be established");
        client.stop();
      }
    }
    
    

     

    Many thanks to the company MGBOT for the idea of this example.