nht_cntt

MSP430 To Server

Apr 4th, 2018
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.13 KB | None | 0 0
  1. #include <Arduino.h>
  2. #include <ESP8266WiFi.h>
  3. #include <ESP8266HTTPClient.h>
  4. #include "SoftwareSerial.h"
  5.  
  6. const char* ssid = "nhtcntt";
  7. const char* pass = "123456789";
  8. String URL = "http://192.168.123.1:80/update";
  9. SoftwareSerial sw(D1, D2, false, 128); //rx, tx
  10.  
  11. void SendInfo2Server(uint8_t *buff, size_t size);
  12. void RecvFromMSP430();
  13.  
  14. void setup() {
  15.     Serial.begin(115200);
  16.     Serial.println("debug");
  17.     Serial.print("Connectting to");
  18.     sw.begin(115200);
  19.     Serial.println(ssid);
  20.     WiFi.mode(WIFI_STA);
  21.     WiFi.begin(ssid, pass);
  22.     while( WiFi.status() != WL_CONNECTED)
  23.     {
  24.         delay(2000);
  25.         Serial.println("Failed - Try connect");
  26.     }    
  27.     Serial.println("WiFi connected");
  28.     Serial.print("IP address: ");
  29.     Serial.println(WiFi.localIP());
  30.     Serial.print("MAC: ");
  31.     Serial.println(WiFi.macAddress());
  32. }
  33.  
  34. void loop()
  35. {
  36.     RecvFromMSP430();
  37.     delay(1000);
  38. }
  39. /*
  40.     Message format:
  41.         {"nhietdo":"xx.xx", "doam": "yy.yy"}| message | ...
  42. */
  43.  
  44. void RecvFromMSP430()
  45. {
  46.     uint8_t buff[50];
  47.     if(sw.available() > 0)
  48.     {
  49.         size_t len = sw.readBytesUntil('|', buff, sizeof(buff));
  50.         if(len > 0)
  51.         {              
  52.             SendInfo2Server(buff, len);
  53.         }
  54.     }
  55. }
  56.  
  57. /*
  58.  URL: http://IPorName:80/update
  59.  method: POST
  60.  http header:
  61.              User-Agent: MAC Address
  62.              Content-Type: application/json
  63.              Content-Length: length(http body)
  64.              Connection: close
  65.  http body:  
  66.              {
  67.                  "nhietdo" : float,
  68.                  "doam"    : float
  69.              }
  70. */
  71.  
  72. void SendInfo2Server(uint8_t *buff, size_t size)
  73. {
  74.     HTTPClient http;
  75.     http.begin(URL);
  76.     http.addHeader("Content-Type", "application/json");
  77.     http.setUserAgent(WiFi.macAddress());
  78.     //int statuscode = http.POST("{\"nhietdo\" : " + String(Nhietdo) + ", \"doam\" : \"" + String(DoAm) + "\"}");
  79.     int statuscode = http.POST(buff, size);
  80.     if(statuscode > 0)
  81.     {
  82.         String payload = http.getString();
  83.         Serial.print("payload: ");
  84.         Serial.println(payload);
  85.     }
  86.     http.end();
  87. }
Advertisement
Add Comment
Please, Sign In to add comment