Sming - Open Source framework for high efficiency native ESP8266 development

User avatar
By TobiasN82
#25967 Hello Guys,

I have some trubble with my little project. I want to send temperature values to thinkspeak.
I 've connected the sensor to the esp8266 an i get the temperatur in picocom.
I've connected the esp8266 to thinkspeak and I get figures like 1, 2, 3, 4, to .... in the chart. But no temperature.
I just copied the examples for thinkspeak and ds18b20 together.

Code: Select all#include <user_config.h>
#include <SmingCore/SmingCore.h>
#include <Libraries/OneWire/OneWire.h>
#include <AppSettings.h>
#include <unistd.h>

#define WORK_PIN 3 // GPIO0

OneWire ds(WORK_PIN);


Timer procTimer;
int sensorValue = 0;
float celsius = 0;
HttpClient thingSpeak;
HttpServer server;
FTPServer ftp;
BssList networks;
String network, password;
Timer connectionTimer;

//Thingspeak
void onDataSent(HttpClient& client, bool successful)
{
   if (successful)
      Serial.println("Success sent");
   else
      Serial.println("Failed");

   String response = client.getResponseString();
   Serial.println("Server response: '" + response + "'");
   if (response.length() > 0)
   {
      int intVal = response.toInt();

      if (intVal == 0)
         Serial.println("Sensor value wasn't accepted. May be we need to wait a little?");
   }
}



//DS18B20
void readData()
{

   byte i;
   byte present = 0;
   byte type_s;
   byte data[12];
   byte addr[8];
   float fahrenheit;

   ds.reset_search();
   if (!ds.search(addr))
   {
      Serial.println("No addresses found.");
      Serial.println();
      ds.reset_search();
      delay(250);
      return;
   }

   Serial.print("Thermometer ROM =");
   for( i = 0; i < 8; i++)
   {
      Serial.write(' ');
      Serial.print(addr[i], HEX);
   }

   if (OneWire::crc8(addr, 7) != addr[7])
   {
     Serial.println("CRC is not valid!");
     return;
   }
   Serial.println();

   // the first ROM byte indicates which chip
   switch (addr[0]) {
   case 0x10:
     Serial.println("  Chip = DS18S20");  // or old DS1820
     type_s = 1;
     break;
   case 0x28:
     Serial.println("  Chip = DS18B20");
     type_s = 0;
     break;
   case 0x22:
     Serial.println("  Chip = DS1822");
     type_s = 0;
     break;
   default:
     Serial.println("Device is not a DS18x20 family device.");
     return;
   }

   ds.reset();
   ds.select(addr);
   ds.write(0x44, 1);        // start conversion, with parasite power on at the end

   delay(1000);     // maybe 750ms is enough, maybe not
   // we might do a ds.depower() here, but the reset will take care of it.

   present = ds.reset();
   ds.select(addr);
   ds.write(0xBE);         // Read Scratchpad

   Serial.print("  Data = ");
   Serial.print(present, HEX);
   Serial.print(" ");
   for ( i = 0; i < 9; i++)
   {
      // we need 9 bytes
      data[i] = ds.read();
      Serial.print(data[i], HEX);
      Serial.print(" ");
   }
   Serial.print(" CRC=");
   Serial.print(OneWire::crc8(data, 8), HEX);
   Serial.println();

   // Convert the data to actual temperature
   // because the result is a 16 bit signed integer, it should
   // be stored to an "int16_t" type, which is always 16 bits
   // even when compiled on a 32 bit processor.
   int16_t raw = (data[1] << 8) | data[0];
   if (type_s)
   {
      raw = raw << 3; // 9 bit resolution default
      if (data[7] == 0x10)
      {
        // "count remain" gives full 12 bit resolution
        raw = (raw & 0xFFF0) + 12 - data[6];
      }
   } else {
      byte cfg = (data[4] & 0x60);
      // at lower res, the low bits are undefined, so let's zero them
      if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
      else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
      else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
      //// default is 12 bit resolution, 750 ms conversion time
   }

   celsius = (float)raw / 16.0;
   fahrenheit = celsius * 1.8 + 32.0;
   Serial.print("  Temperature = ");
   Serial.print(celsius);
   Serial.print(" Celsius, ");
   Serial.print(fahrenheit);
   Serial.println(" Fahrenheit");
   Serial.println();



   
}


//Thingspeak
void sendData()
{
   if (thingSpeak.isProcessing()) return; // We need to wait while request processing was completed

   // Read our sensor value :)
   sensorValue++;
   {
   
   thingSpeak.downloadString("http://api.thingspeak.com/update?key=7XQL253GLOXXXXXX&field1=" + String(celsius), onDataSent);
}

}

//Thingspeak
// Will be called when WiFi station was connected to AP
void connectOk()
{
   Serial.println("I'm CONNECTED");

   // Start send data loop
   procTimer.initializeMs(25 * 1000, sendData).start(); // every 25 seconds
}

// Will be called when WiFi station timeout was reached
void connectFail()
{
   Serial.println("I'm NOT CONNECTED. Need help :(");

   // Start soft access point
   WifiAccessPoint.enable(true);
   WifiAccessPoint.config("CONFIG ME PLEEEEASE...", "", AUTH_OPEN);

   // .. some you code for configuration ..
}

//HTTP Setting
void onIndex(HttpRequest &request, HttpResponse &response)
{
   TemplateFileStream *tmpl = new TemplateFileStream("index.html");
   auto &vars = tmpl->variables();
   response.sendTemplate(tmpl); // will be automatically deleted
}

void onIpConfig(HttpRequest &request, HttpResponse &response)
{
   if (request.getRequestMethod() == RequestMethod::POST)
   {
      AppSettings.dhcp = request.getPostParameter("dhcp") == "1";
      AppSettings.ip = request.getPostParameter("ip");
      AppSettings.netmask = request.getPostParameter("netmask");
      AppSettings.gateway = request.getPostParameter("gateway");
      debugf("Updating IP settings: %d", AppSettings.ip.isNull());
      AppSettings.save();
   }

   TemplateFileStream *tmpl = new TemplateFileStream("settings.html");
   auto &vars = tmpl->variables();

   bool dhcp = WifiStation.isEnabledDHCP();
   vars["dhcpon"] = dhcp ? "checked='checked'" : "";
   vars["dhcpoff"] = !dhcp ? "checked='checked'" : "";

   if (!WifiStation.getIP().isNull())
   {
      vars["ip"] = WifiStation.getIP().toString();
      vars["netmask"] = WifiStation.getNetworkMask().toString();
      vars["gateway"] = WifiStation.getNetworkGateway().toString();
   }
   else
   {
      vars["ip"] = "192.168.1.77";
      vars["netmask"] = "255.255.255.0";
      vars["gateway"] = "192.168.1.1";
   }

   response.sendTemplate(tmpl); // will be automatically deleted
}

void onFile(HttpRequest &request, HttpResponse &response)
{
   String file = request.getPath();
   if (file[0] == '/')
      file = file.substring(1);

   if (file[0] == '.')
      response.forbidden();
   else
   {
      response.setCache(86400, true); // It's important to use cache for better performance.
      response.sendFile(file);
   }
}

void onAjaxNetworkList(HttpRequest &request, HttpResponse &response)
{
   JsonObjectStream* stream = new JsonObjectStream();
   JsonObject& json = stream->getRoot();

   json["status"] = (bool)true;

   bool connected = WifiStation.isConnected();
   json["connected"] = connected;
   if (connected)
   {
      // Copy full string to JSON buffer memory
      json.addCopy("network", WifiStation.getSSID());
   }

   JsonArray& netlist = json.createNestedArray("available");
   for (int i = 0; i < networks.count(); i++)
   {
      if (networks[i].hidden) continue;
      JsonObject &item = netlist.createNestedObject();
      item.add("id", (int)networks[i].getHashId());
      // Copy full string to JSON buffer memory
      item.addCopy("title", networks[i].ssid);
      item.add("signal", networks[i].rssi);
      item.add("encryption", networks[i].getAuthorizationMethodName());
   }

   response.setAllowCrossDomainOrigin("*");
   response.sendJsonObject(stream);
}

void makeConnection()
{
   WifiStation.enable(true);
   WifiStation.config(network, password);

   AppSettings.ssid = network;
   AppSettings.password = password;
   AppSettings.save();

   network = ""; // task completed
}

void onAjaxConnect(HttpRequest &request, HttpResponse &response)
{
   JsonObjectStream* stream = new JsonObjectStream();
   JsonObject& json = stream->getRoot();

   String curNet = request.getPostParameter("network");
   String curPass = request.getPostParameter("password");

   bool updating = curNet.length() > 0 && (WifiStation.getSSID() != curNet || WifiStation.getPassword() != curPass);
   bool connectingNow = WifiStation.getConnectionStatus() == eSCS_Connecting || network.length() > 0;

   if (updating && connectingNow)
   {
      debugf("wrong action: %s %s, (updating: %d, connectingNow: %d)", network.c_str(), password.c_str(), updating, connectingNow);
      json["status"] = (bool)false;
      json["connected"] = (bool)false;
   }
   else
   {
      json["status"] = (bool)true;
      if (updating)
      {
         network = curNet;
         password = curPass;
         debugf("CONNECT TO: %s %s", network.c_str(), password.c_str());
         json["connected"] = false;
         connectionTimer.initializeMs(1200, makeConnection).startOnce();
      }
      else
      {
         json["connected"] = WifiStation.isConnected();
         debugf("Network already selected. Current status: %s", WifiStation.getConnectionStatusName());
      }
   }

   if (!updating && !connectingNow && WifiStation.isConnectionFailed())
      json["error"] = WifiStation.getConnectionStatusName();

   response.setAllowCrossDomainOrigin("*");
   response.sendJsonObject(stream);
}

void startWebServer()
{
   server.listen(80);
   server.addPath("/", onIndex);
   server.addPath("/ipconfig", onIpConfig);
   server.addPath("/ajax/get-networks", onAjaxNetworkList);
   server.addPath("/ajax/connect", onAjaxConnect);
   server.setDefaultHandler(onFile);
}

void startFTP()
{
   if (!fileExist("index.html"))
      fileSetContent("index.html", "<h3>Please connect to FTP and upload files from folder 'web/build' (details in code)</h3>");

   // Start FTP server
   ftp.listen(21);
   ftp.addUser("me", "123"); // FTP account
}

// Will be called when system initialization was completed
void startServers()
{
   startFTP();
   startWebServer();
}

void networkScanCompleted(bool succeeded, BssList list)
{
   if (succeeded)
   {
      for (int i = 0; i < list.count(); i++)
         if (!list[i].hidden && list[i].ssid.length() > 0)
            networks.add(list[i]);
   }
   networks.sort([](const BssInfo& a, const BssInfo& b){ return b.rssi - a.rssi; } );
}


void init()
{
   Serial.begin(SERIAL_BAUD_RATE); // 115200 by default
   Serial.systemDebugOutput(true); // Allow debug output to serial
   AppSettings.load();   

   ds.begin(); // It's required for one-wire initialization!

   procTimer.initializeMs(3000, readData).start();

   //WifiStation.config(WIFI_SSID, WIFI_PWD);
   //WifiStation.enable(true);
   //WifiAccessPoint.enable(false);

   // Run our method when station was connected to AP (or not connected)
   WifiStation.waitConnection(connectOk, 20, connectFail); // We recommend 20+ seconds for connection timeout at start
   
   WifiStation.enable(true);
   if (AppSettings.exist())
   {
      WifiStation.config(AppSettings.ssid, AppSettings.password);
      if (!AppSettings.dhcp && !AppSettings.ip.isNull())
         WifiStation.setIP(AppSettings.ip, AppSettings.netmask, AppSettings.gateway);
   }
   WifiStation.startScan(networkScanCompleted);

   // Start AP for configuration
   WifiAccessPoint.enable(true);
   WifiAccessPoint.config("Sming Configuration", "", AUTH_OPEN);

   // Run WEB server on system ready
   System.onReady(startServers);
}


Thanks for your help
Tobias