cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
Showing results for 
Search instead for 
Did you mean: 

Community Tip - Did you get called away in the middle of writing a post? Don't worry you can find your unfinished post later in the Drafts section of your profile page. X

unable to connect esp8266 board to ThingWorx

NH_shree
12-Amethyst

unable to connect esp8266 board to ThingWorx

Hi , 

i am using  ESP8266  board.,  i followed the tutorial name "Connect an Arduino Developer Board"  and used the code given in it. By using Arduino IDE  i compiled and upload the code in it with necessary changes in code like WIFI  SSID name,  WIFI password, and in place of 

const char TWPlatformBaseURL[] = "https://pp-2007011431nt.devportal.ptc.io";

the above code i have replaced it with my thing Worx server address which i am usually going to access it using url https://xxxxxxxx.thingworx.com

and app key. also i have created AND  i have permitted the visibility of the resources to everyone  in the thing Worx composer and i have followed each and every step given in the ptc tutorial  but still my esp8266 board is not connecting to thing Worx, please help me still what changes I need to do in my code or what needs to be done in thing Worx ......

 

here is the code which i have compiled in my Arduino ide 

/**
 * 
 * ESP8266_ThingWorx_REST_Demo.ino
 *
 *  
 *  (c) PTC, Inc. 2016-2020
 *
 */

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>

//////////////////////
// WiFi Definitions //
//////////////////////
const char WiFiSSID[] = "shree"; // WiFi access point SSID
const char WiFiPSK[] = "shreeexxxxx"; // WiFi password - empty string for open access points

//////////////////////////////////////////////
// ThingWorx server definitions            //
//  modify for a specific platform instance //
//////////////////////////////////////////////
const char TWPlatformBaseURL[] = "https://xxxx-dev-twx.es.Thingworx.com";
const char appKey[] = "26e717cf-b1f0-466d-8d86-403de15xxxxxx";

////////////////////////////////////////////////////////
// Pin Definitions - board specific for Adafruit board//
////////////////////////////////////////////////////////
const int RED_LED = 0; // Thing's onboard, red LED - 
const int BLUE_LED = 2; // Thing's onboard, blue LED
const int ANALOG_PIN = A0; // The only analog pin on the Thing

const int OFF = HIGH;
const int ON = LOW;

// this will set as the Accept header for all the HTTP requests to the ThingWorx server
// valid values are: application/json, text/xml, text/csv, text/html (default)
#define ACCEPT_TYPE "text/csv"  

/////////////////////
//Attempt to make a WiFi connection. Checks if connection has been made once per second until timeout is reached
//returns TRUE if successful or FALSE if timed out
/////////////////////
boolean connectToWiFi(int timeout){

  Serial.println("Connecting to: " + String(WiFiSSID));
  WiFi.begin(WiFiSSID, WiFiPSK);

  // loop while WiFi is not connected waiting one second between checks
  uint8_t tries = 0; // counter for how many times we have checked
  while ((WiFi.status() != WL_CONNECTED) && (tries < timeout) ){ // stop checking if connection has been made OR we have timed out
    tries++;
    Serial.printf(".");// print . for progress bar
    Serial.println(WiFi.status());
    delay(2000);
  }
  Serial.println("*"); //visual indication that board is connected or timeout

  if (WiFi.status() == WL_CONNECTED){ //check that WiFi is connected, print status and device IP address before returning
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
    return true;
  } else { //if WiFi is not connected we must have exceeded WiFi connection timeout
    return false;
  }

}

//////////////////////////
//create a name for the board that is probably unique by appending last two bytes of MAC address
//return name as a String
///////////////////////////////
String getUniqueDeviceName(){ 

    String uniqueName;
    uint8_t mac[WL_MAC_ADDR_LENGTH];
    WiFi.macAddress(mac); // WiFi does NOT need to be connected for this call
    String macID = String(mac[WL_MAC_ADDR_LENGTH - 2], HEX) +
                    String(mac[WL_MAC_ADDR_LENGTH - 1], HEX);
    macID.toUpperCase();
    uniqueName = "ESP8266Board-" + macID;
    Serial.println("DeviceID>" + uniqueName);
    return uniqueName;
}

///////////////////////////////
// make HTTP GET to a specific Thing and Propertry on a ThingWorx server
// thingName - Name of Thing on server to make GET from
// property - Property of thingName to make GET from
// returns HTTP response code from server and prints full response
///////////////////////////////
int httpGetPropertry(String thingName, String property){
    std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
    client->setInsecure();
    HTTPClient https;
        int httpCode = -1;
        String response = "";
        Serial.print("[httpsGetPropertry] begin...");
        String fullRequestURL = String(TWPlatformBaseURL) + "/Thingworx/Things/"+ thingName +"/Properties/"+ property +"?appKey=" + String(appKey);

        https.begin(*client,fullRequestURL);
        https.addHeader("Accept",ACCEPT_TYPE,false,false);
        Serial.println("GET URL>" + fullRequestURL +"<");
        // start connection and send HTTP header
        httpCode = https.GET();
        // httpCode will be negative on error
        if(httpCode > 0) {
            response = https.getString();
            Serial.printf("[httpGetPropertry] response code:%d body>",httpCode);
            Serial.println(response + "<\n");
        } else {
            Serial.printf("[httpGetPropertry] failed, error: %s\n\n", https.errorToString(httpCode).c_str());
        }
        https.end();
        return httpCode;

}

///////////////////////////////
// makes HTTP POST to platform to CreateThing service using input string as the new Things's name. 
// Returns server response code
///////////////////////////////
int createThing(String nameOfThing){
        std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
    client->setInsecure();
    HTTPClient https;
        int httpCode = -1;
        String response = "";
        Serial.print("[createThing] begin...");
        String fullRequestURL = String(TWPlatformBaseURL) + "/Thingworx/Resources/EntityServices/Services/CreateThing?appKey=" + String(appKey);
        https.begin(*client,fullRequestURL);
        https.addHeader("Accept",ACCEPT_TYPE,false,false);
        https.addHeader("Content-Type","application/json",false,false);
        Serial.println("POST URL>" + fullRequestURL + "<");
        // start connection and send HTTP header
        httpCode = https.POST("{\"name\": \""+ nameOfThing +"\",\"thingTemplateName\": \"GenericThing\"}");
        // httpCode will be negative on error
        if(httpCode > 0) {
            response = https.getString();
            Serial.printf("[createThing] response code:%d body>",httpCode);
            Serial.println(response + "<\n");

        } else {
            Serial.printf("[createThing] POST... failed, error: %s\n\n", https.errorToString(httpCode).c_str());
        }
        https.end();
        return httpCode;
}

///////////////////////////////
// make HTTP POST to ThingWorx server Thing service
// nameOfThing - Name of Thing to POST to
// endPoint - Services URL to invoke
// postBody - Body of POST to send to ThingWorx platform
// returns HTTP response code from server
///////////////////////////////
int postToThing(String nameOfThing, String endPoint, String postBody){
        std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
    client->setInsecure();
    HTTPClient https;
        int httpCode = -1;
        String response = "";
        Serial.print("[postToThing] begin...");
        String fullRequestURL = String(TWPlatformBaseURL) + "/Thingworx/Things/"+ nameOfThing +"/Services/"+ endPoint +"?appKey=" + String(appKey);
        Serial.println("URL>" + fullRequestURL + "<");
        https.begin(*client,fullRequestURL);
        https.addHeader("Accept",ACCEPT_TYPE,false,false);
        https.addHeader("Content-Type","application/json",false,false);
        Serial.println("[postToThing] POST body>" + postBody + "<");
        // start connection and send HTTP header
        httpCode = https.POST(postBody);
        // httpCode will be negative on error
        if(httpCode > 0) {

            response = https.getString();
            Serial.printf("[postToThing] response code:%d body>",httpCode);
            Serial.println(response + "<\n");

        } else {
            Serial.printf("[postToThing] POST... failed, error: %s\n\n", https.errorToString(httpCode).c_str());
        }
        https.end();
        return httpCode;
}

void setup() {

    pinMode(RED_LED, OUTPUT);
    pinMode(BLUE_LED, OUTPUT);

    Serial.begin(115200);
    Serial.setDebugOutput(true);
    Serial.println();
    Serial.println();
    Serial.println();

    Serial.printf("Starting...\n");

    for(uint8_t t = 4; t > 0; t--) {
        Serial.printf("   WAIT %d...\n", t);
        Serial.flush();
        delay(1000);
    }

    connectToWiFi(10);

}

void loop() {

    String thingName = getUniqueDeviceName(); //unique name for this Thing so many work on one ThingWorx server

    while (WiFi.status() == WL_CONNECTED) { //confirm WiFi is connected before looping as long as WiFi is connected

      int getResponseCode = httpGetPropertry(thingName, "SomeNumber");

      if (getResponseCode == 404){ // a 404 means connected, but either no Thing or no property

        // first we will try to create a new Thing on the platform
        int postResp = createThing(thingName); // saving the response code for retry logic in the future

        //  the newly crated Thing has to be enabled
        postResp = postToThing(thingName,"EnableThing","");  //POST to EnableThing endpoint with no body

        // after the new Thing is enabled it must be restarted
        postResp = postToThing(thingName,"RestartThing","");  //POST to RestartThing endpoint with no body

        // add a property to the Thing 3rd parameter is ugly because required quotes are escaped with backslashes
        postResp = postToThing(thingName,"AddPropertyDefinition", "{\"name\":\"SomeNumber\",\"type\":\"NUMBER\"}"); 
        //POST body contains JSON object with property name and property type 

        // after changes to a Thing's structure it must be restarted
        postResp = postToThing(thingName,"RestartThing",""); //POST to RestartThing endpoint with no body
      }

      delay(2000);

    }// end WiFi connected while loop
    Serial.printf("****Wifi connection dropped****\n");
    WiFi.disconnect(true);
    delay(10000);
    connectToWiFi(10);
}t 

 

1 ACCEPTED SOLUTION

Accepted Solutions
slangley
23-Emerald II
(To:NH_shree)

Hi @NH_shree.

 

Have you checked the logs for errors?  You will find the ThingWorx logs in ...\ThingworxStorage\logs.

 

If you're not seeing anything in the ThingWorx logs, you may have a network issue preventing the device from connecting.  

 

Let us know if you're not able to make any progress.

 

Regards.

 

--Sharon

View solution in original post

2 REPLIES 2
slangley
23-Emerald II
(To:NH_shree)

Hi @NH_shree.

 

Have you checked the logs for errors?  You will find the ThingWorx logs in ...\ThingworxStorage\logs.

 

If you're not seeing anything in the ThingWorx logs, you may have a network issue preventing the device from connecting.  

 

Let us know if you're not able to make any progress.

 

Regards.

 

--Sharon

NH_shree
12-Amethyst
(To:slangley)

Hi @slangley 

Thanks for your reply, the issue is solved.

 

Regards, 

Shree

Top Tags