We have already achieved the initial configuration of the device through the O2IOTServer class. Now we need to use the configuration information to connect to the available WiFi and log in to the O2OA server.

Create O2IOTClient class

Create file o2iotClient. h in o2iot directory as follows:

# ifNdef O2IOTCLIENT_H_ #define O2IOTCLIENT_H_ #include < esp8266wifimulti. h < esp8266httpClient. h> // references ESP8266's HttpClient library #include <EEPROM. H > // references EEPROM library #include "Arduinojson. h" // references ArduinoJson library Class O2IOTClient {public: // Config information variable String xtoken=""; String o2host=""; String o2port=""; String o2user=""; String o2pass=""; bool begin(); O2OA bool connect(); String _doGet(String url); // Initiate http-get request String _doPost(String URL, String data); // Initiate an HTTP-POST request. String _doPut(String URL, String data); // Initiate http-put request void getConfig(); // Obtain the device configuration information void parseConfig(); Private: ESP8266WiFiMulti WiFiMulti; //esp8266WiFi object void blink(char n); // Chip LED light flashing bool _getToken(); // Log in to O2OA and obtain token char _ssidConfig[128]; // Store 128 bytes of configuration information char *ssid_name; // Hotspot name char *ssid_pass; // Hot password}; extern O2IOTClient O2_IOTClient; #endif /* O2IOTCLIENT_H_ */Copy the code

Then we need to create.cpp to implement the methods defined in the header file, so create file o2iotClient.cpp in the o2iot directory as follows:

#include "o2iotClient. h" void O2IOTClient::blink(char n){// This method is used to make the chip LED blink n times for (char I = 0; i < n; i++) { digitalWrite(LED_BUILTIN, LOW); delay(100); digitalWrite(LED_BUILTIN, HIGH); delay(100); }} bool O2IOTClient::begin() {// Start connecting to WiFi and logging in to EEPROM. Begin (512); Begin (size) {if (connect()){// Connect the device to the WiFi hotspot blink(2); If (_getToken()){// Log in to O2OA server and obtain toekN blink(3); // If the login is successful and the token is obtained, let the device LED blink 3 times}} return false; } void O2IOTClient::getConfig() {// Get device configuration information from EEPROM for (int I = 0; i < 128; i++) { _ssidConfig[i] = EEPROM.read(i); }} void O2IOTClient: : parseConfig () {/ / analytical equipment configuration information, stored in the variable the if (STRCHR (_ssidConfig, '|')! =NULL){ if (_ssidConfig[0] ! = NULL) { ssid_name = strtok(_ssidConfig, "|"); ssid_pass = strtok(NULL, "|"); o2user = strtok(NULL, "|"); o2pass = strtok(NULL, "|"); o2host = strtok(NULL, "|"); o2port = strtok(NULL, "|"); }} bool O2IOTClient::connect() {// Connect to WiFi hotspot getConfig(); parseConfig(); if (ssid_name[0] ! = NULL && ssid_pass[0] ! = NULL) { WiFiMulti.addAP(ssid_name, ssid_pass); // Connect to WiFi hotspot int n = 0; while (WiFiMulti.run() ! = WL_CONNECTED &&n <20) {// If there is no link, retry 20 times delay(500); // reconnection every 500 ms n++; } if (wifimulti.run () == WL_CONNECTED) {// If (wifimulti.run () == WL_CONNECTED) {return true; } return false; } return false; } bool O2IOTClient::_getToken(){// Initiate Post request for login. o2host.equalsIgnoreCase("") && ! O2port.equalsignorecase ("")){// Get the url of the login token, here is an interface of the O2OA service platform, And we will create the interface service String url = "http://" + + ":" + o2port o2host + "/ x_program_center/jaxrs/invoke/getToken/execute"; / / a post request, transfer the user name and password String content = _doPost (url, "{' user ', '" + o2user +"', 'pass' : '" + o2pass + "} "); if (payload.equalsIgnoreCase("")) return false; // StaticJsonDocument<256> doc; DeserializationError error = deserializeJson(doc, payload); JsonObject = doc["data"]. As <JsonObject>(); xtoken = json["token"].as<String>(); doc.clear(); return true; } return false; } String O2IOTClient::_doGet(String URL){// This method initiates a get request HTTPClient HTTP; // Create the HTTP object http.begin(url); HTTP. AddHeader (" Content-type ", "application/json; charset=utf-8"); http.addHeader("Origin", "http://"+o2host); String payload=""; Int httpCode = http.get (); if (httpCode > 0) { if (httpCode == HTTP_CODE_OK) { payload = http.getString(); payload.trim(); } } http.end(); return payload; } String O2IOTClient::_doPost(String URL, String data) {// This method makes a POST request HTTPClient HTTP; http.begin(url); //HTTP http.addHeader("Content-Type", "application/json; charset=utf-8"); http.addHeader("Origin", "http://"+o2host); String payload=""; int httpCode = http.POST(data); if (httpCode > 0) { if (httpCode == HTTP_CODE_OK) { payload = http.getString(); payload.trim(); } } http.end(); return payload; } String O2IOTClient::_doPut(String URL, String data) {// This method initiates a POST request HTTPClient HTTP; http.begin(url); //HTTP http.addHeader("Content-Type", "application/json; charset=utf-8"); http.addHeader("Origin", "http://"+o2host); String payload=""; int httpCode = http.sendRequest("put", data); if (httpCode > 0) { if (httpCode == HTTP_CODE_OK) { payload = http.getString(); payload.trim(); } } http.end(); return payload; } O2IOTClient O2_IOTClient;Copy the code

Now we have completed the O2IOTClient class, which can connect WiFi and log in to O2OA and obtain token, but there is still a lack of O2OA login interface.

Create O2OA login interface

Next, we will create an interface service on the O2OA server for the device to log in and get the token. This is the getToken service called in the above code. Log in to the O2OA server as the service administrator, enter the service Management platform, create an interface, name it “getToken”, and enter the following code:

/ / will be resolved as a json request message body var. Res = json parse (this. RequestText. ToString ()); Var o = {"credential":res.user,"codeAnswer":res.pass}; / / by the AuthenticationAction x_organization_assemble_authentication codeLogin method login system this.Actions.load("x_organization_assemble_authentication").AuthenticationAction.codeLogin(o, Function (json){var token = json.data.token; var token = json.data.token; // Return the token as a response to the client this.response.setBody({"data": {"token": token}}, "application/json"); }.bind(this));Copy the code

Create a user in O2OA

We need to create a user on the O2OA server for device login, create a user process, please consult the documentation. Here I created a user called iot.

Called in the device main program

Let’s go back to the o2iot.ino file and update the code to call the O2IOTClient class.

#include "arduino.h" // reference Arduino core library #include "o2iotServer. h" // reference O2IOTServer class #include" o2iotClient. h" // reference O2IOTClient class void setup() { pinMode(LED_BUILTIN, OUTPUT); // configure the LED_BUILTIN pin to output digitalWrite(LED_BUILTIN, HIGH); O2_IOTServer.begin(); // Start the AP access point and start the Web service o2_iotClient.begin (); O2OA} void loop() {o2_iotServer.listening (); // Listen for HTTP requests}Copy the code

Validation and upload procedures

This step is the same as in the previous chapter.

See the effect

At this point, we have started to run our program on the development board, according to the previous chapter, set up the WiFi to connect, O2OA center server address, port, and login user name and password. Power the device back on, and we should see the results. The LED blinks 2 times when connected to WiFi and 3 times when logged in to O2OA server.

f19a837c83bff925292dd9a68578b532.mp4

The debugger

Arduino debugging

Of course, not many programs can run correctly at once, so we can add some serial output statements to the code for debugging.

Now initialize the serial port in the main program, adding the code to setup:

Serial.begin(115200);
Copy the code

The entire code is as follows:

#include "arduino.h" // reference Arduino core library #include "o2iotServer. h" // reference O2IOTServer class #include" o2iotClient. h" // reference O2IOTServer class void setup() { Serial.begin(115200); // Initialize the serial port with baud rate of 115200 pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, HIGH); O2_IOTServer.begin(); // Start the AP access point and start the Web service o2_iotClient.begin (); O2OA} void loop() {o2_iotServer.listening (); // Listen for HTTP requests}Copy the code

You can then use serial.print () or serial.println () anywhere to print information on the Serial port for debugging purposes. As in the _getToken method:

Bool O2IOTClient::_getToken(){// Initiate Post request for login. o2host.equalsIgnoreCase("") && ! O2port.equalsignorecase ("")){serial. print("url:"); Serial.println("http://"+o2host+":"+o2port+"/x_program_center/jaxrs/invoke/getToken/execute"); // Get the url of the login token, here is an interface of the O2OA service platform, And we will create the interface service String url = "http://" + + ":" + o2port o2host + "/ x_program_center/jaxrs/invoke/getToken/execute"; / / a post request, transfer the user name and password String content = _doPost (url, "{' user ', '" + o2user +"', 'pass' : '" + o2pass + "} "); if (payload.equalsIgnoreCase("")) return false; // StaticJsonDocument<256> doc; DeserializationError error = deserializeJson(doc, payload); JsonObject = doc["data"]. As <JsonObject>(); xtoken = json["token"].as<String>(); Serial.print("xtoken:" ); Serial.println(xtoken); doc.clear(); return true; } return false; }Copy the code

You can then use any serial port tool, connect to the device serial port, set the same baud rate (115200 in this column), and see the output.

VS Code already has the serial port tool integrated, so just click on the icon in the lower right corner to open the serial port tool.

After opening the serial port tool, you can adjust the baud rate in the lower right corner.

Here you can see the output of the request URL, and I also output the token information.

O2OA interface debugging

For interface debugging, we can also use the print() method to output debugging information, and then view it in the platform log. If the request body content is output in the interface, the code is as follows:

/ / output request message body print (this. RequestText. ToString ()); / / will be resolved as a json request message body var. Res = json parse (this. RequestText. ToString ()); Var o = {"credential":res.user,"codeAnswer":res.pass}; / / by the AuthenticationAction x_organization_assemble_authentication codeLogin method login system this.Actions.load("x_organization_assemble_authentication").AuthenticationAction.codeLogin(o, Function (json){var token = json.data.token; var token = json.data.token; // Return the token as a response to the client this.response.setBody({"data": {"token": token}}, "application/json"); }.bind(this));Copy the code

Then open the log, wait for the request, and you can see the output.

That’s it for this chapter. In the next chapter, we’ll connect to webSockets.