Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Dependencies: mbed MbedJSONValue HTTPClient TFT_fonts SPI_TFT_ILI9341 mbed-rtos picojsontest NTPClient SDFileSystem EthernetInterface DHT Stepper_Motor_X27168
Diff: main.cpp
- Revision:
- 1:f9a4cbb4af0d
- Parent:
- 0:9ab281898a9b
- Child:
- 4:1eea5edaffc4
--- a/main.cpp Fri Mar 20 14:24:06 2015 +0000
+++ b/main.cpp Mon Apr 29 00:53:56 2019 +0000
@@ -4,193 +4,157 @@
#include "DHT.h"
#include "EthernetInterface.h"
#include "NTPClient.h"
-#include "HTTPClient.h"
+#include "HTTPClient.h"
#include "picojson.h"
#include "SDFileSystem.h"
+#include <MbedJSONValue.h>
+#include <string>
//IMPORTANT YOU NEED TO SET THE API KEY for thingspeak look for "your key here"
//TAKE CARE URL doesn't excced buffer size
//sd card
- SDFileSystem sd(PTE3, PTE1, PTE2, PTE4, "sd"); // MOSI, MISO, SCLK, SSEL
+// SDFileSystem sd(PTE3, PTE1, PTE2, PTE4, "sd"); // MOSI, MISO, SCLK, SSEL
//Ethernet Interface
EthernetInterface eth;
//NTP service for date and Time used to set boards RTC
NTPClient ntp;
//HTTP Client for interfacing to web services
HTTPClient http;
-char resp[1024]; //buffer for the responce
+//char resp[1024]; //buffer for the responce
//On board LED
-DigitalOut myled(LED_GREEN);
+//DigitalOut myled(LED_GREEN);
//serial over USB for debug and Info
Serial pc(USBTX, USBRX);
+std::string resp;
//temperature sensor
-DHT sensor(PTB18,DHT22); // there are several libraries available, this reports CRC error sometimes
+//DHT sensor(PTB18,DHT22); // there are several libraries available, this reports CRC error sometimes
//320x240 Display ILI9341 controller (look on ebay)
-SPI_TFT_ILI9341 TFT(PTD2, PTD3, PTD1,PTC3 ,PTC4 ,PTD0 ,"TFT"); // mosi, miso, sclk, cs, reset, dc
+//SPI_TFT_ILI9341 TFT(PTD2, PTD3, PTD1,PTC3 ,PTC4 ,PTD0 ,"TFT"); // mosi, miso, sclk, cs, reset, dc
+
+MbedJSONValue v;
int main()
{
- int cnt = 0;
- int err;
+
int ret=0;
- char val[4][16];
- //used to parse the json data
- picojson::value v;
- char * json;
- HTTPMap map;
- HTTPText inText(resp, 1024);
- char sdfile[32];
- FILE *fp;
- pc.printf("Weather Reporter\n");
-
- //eithernet init
- eth.init(); //Use DHCP
- ret= eth.connect();
- if (!ret) {
- pc.printf("Connected, IP: %s, MASK: %s, GW: %s\n",
- eth.getIPAddress(), eth.getNetworkMask(), eth.getGateway());
- } else {
- pc.printf("Error eth.connect() - ret = %d\n", ret);
- }
+ //used to parse the json data
+// picojson::value v;
+// char * json;
+ std::string json;
+ HTTPMap map;
-
- //setup the TFT DISPLAY
- TFT.claim(stdout); // send stdout to the TFT display
- //ensure the output is write and not buffered
- setvbuf ( stdout , NULL , _IONBF , NULL );
- //TFT.claim(stderr); // send stderr to the TFT display
- TFT.set_orientation(1);
- TFT.background(Black); // set background to black
- //centerx = TFT.width() >> 1;
- //centery = TFT.height() >> 1;
+ pc.printf("\r\nWeather Reporter\n");
+
- TFT.cls();
- TFT.locate(0,0);
- TFT.set_font((unsigned char*) sansserif);
- //printf will now for to TFT because of the TFT.claim(stdout)
- printf("Weather Test\n");
- //setup the RTC with date and time
- printf("Trying to update time...\r\n");
- time_t ctTime;
- NTPResult result;
- result = ntp.setTime("pool.ntp.org");
- if (result == NTP_OK) {
- time(&ctTime);
- printf("Time is set to (UTC):\n%s\n", ctime(&ctTime));
- strcpy(sdfile,"/sd/results/default_results"); //could use time in name
- }else{
- printf("Error setting Time\n");
- strcpy(sdfile,"/sd/results/default_results");
- }
+
- //write to sdcard, we could use the time and date in the filename defained above to give a new file for every session
- mkdir("/sd/results", 0777);
- fp = fopen(sdfile, "w");
- if (fp == NULL) {
- pc.printf("Unable to write the file \n");
- } else {
- pc.printf("Writing data to SDCARD \n");
- //time,temp,humidity,forcast,pressure
- fprintf(fp, "time,temperature,humidity,forcastTemp,forcastPressure\n");
- fclose(fp);
- }
+ eth.init(); //Use DHCP
+ eth.connect();
+ pc.printf("IP Address is %s\r\n", eth.getIPAddress());
+ std::string mac;
+ mac = eth.getMACAddress();
+ pc.printf("MAC: %s\r\n", mac);
+ TCPSocketConnection sock;
+ sock.connect("api.openweathermap.org", 80);
+ char http_cmd[] = "GET /data/2.5/weather?q=Atlanta,US&APPID=a1c3afc7f18b7ef578cef48d5163cda6 HTTP/1.0\r\n\r\n";
+ if (!sock.is_connected()){
+ return -1;
+ }
+ sock.send_all(http_cmd, sizeof(http_cmd)-1);
+ char buffer[1000];
+ //int ret;
+ while (true) {
+ ret = sock.receive(buffer, sizeof(buffer)-1);
+ if (ret <= 0)
+ break;
+ buffer[ret] = '\0';
+ pc.printf("Received %d chars from server:\n%s\n", ret, buffer);
+ }
+
+ sock.close();
+
+ eth.disconnect();
- float humidity=0;
- float temperature=-100;
+ float forecastHumidity=0;
+// float temperature=-100;
float forcastTemp=0;
- float forcastPressure;
+ float forcastDescription = 0;
+// float forcastPressure;
wait(10);
pc.printf("\r\nDHT Test program");
pc.printf("\r\n******************\r\n");
wait(1); // wait 1 second for device stable status
+ char cstr[resp.size() + 1];
while(1){
//GET forcast data
pc.printf("\nTrying to fetch page...\n");
//try getting the weather, 5 second timeout
- ret = http.get("http://api.openweathermap.org/data/2.5/weather?q=Strathaven,uk", resp, 5000);
+// HTTPResult r = http.get("http://api.openweathermap.org/data/2.5/weather?q=Atlanta,US&APPID=a1c3afc7f18b7ef578cef48d5163cda6", resp, 5000);
+// HTTPResult r = http.get("www.google.com", resp, 4096, 20000);
+// ret = http.get("http://api.openweathermap.org/data/2.5/find?q=London",resp, 15000);
if(!ret){
+ std::string b2s(buffer, 1000);
+ int i = b2s.find("\r\n\r\n",0);
+ resp.assign(buffer+i+4);
pc.printf("responce=%s",resp);
- json=&resp[0];
- pc.printf("parsing");
- string err = picojson::parse(v, json, json + strlen(json));
- if(err.empty()){
- forcastTemp=v.get("main").get("temp").get<double>();
- forcastTemp=forcastTemp-273.15;
- forcastPressure=v.get("main").get("pressure").get<double>();
- // printf("Forcast temp: %f\n", forcastTemp);
- }
- else{
- pc.printf("error parsing");
- }
- }
- else{
- pc.printf("ERROR=%d", ret);
- }
-
- err = sensor.readData();
- if (err == 0) {
- TFT.cls();
- TFT.locate(0,0);
- time(&ctTime);
- printf("%s\n", ctime(&ctTime));
- temperature=sensor.ReadTemperature(CELCIUS);
- humidity=sensor.ReadHumidity();
- printf("Temperature: %4.2f C \r\n",temperature);
- printf("Forcast Temp: %4.2f C \r\n",forcastTemp);
- printf("Temperature is %4.2f F \r\n",sensor.ReadTemperature(FARENHEIT));
- printf("Humidity is %4.2f \r\n",humidity);
- printf("Dew point is %4.2f \r\n",sensor.CalcdewPoint(sensor.ReadTemperature(CELCIUS), sensor.ReadHumidity()));
- printf("Forcast Pressure: %4.2f C \r\n",forcastPressure);
- myled = 1;
- } else{
- pc.printf("\r\nErr %i \n",err);
- myled = 0;
- }
-
+ strcpy(cstr, resp.c_str());
+ int len = strlen(cstr);
+ cstr[5] = '\n';
+// json = NULL;
+ //char * result = NULL;
+// asprintf(&result, "%s%s", json, "NULL");
+// std::string sJson(json);
+// pc.printf("parsing");
+// const char * json = "{\"my_array\": [\"demo_string\", 10], \"my_boolean\": true}";
+
+ //parse the previous string and fill the object demo
+ std::string newline= "\n";
+ resp.append(newline);
+
+
+
+// std::string error = parse(v, cstr);
+ json = cstr;
+ struct weatherData{
+ std::string temp;
+ std::string desc;
+ std::string hum;
+ };
+
+ int beg, end;
+ weatherData weather;
+ //first find description
+ beg = json.find("description") + 14;
+ end = json.find("," , beg) - 1;
+ weather.desc = json.substr(beg,end-beg);
+ //next find temperature
+ beg = json.find("temp", end) + 6;
+ end = json.find("," , beg);
+ weather.temp = json.substr(beg,end-beg);;
+ //last find humidity
+ beg = json.find("humidity", end) + 10;
+ end = json.find(",", beg);
+ weather.hum = json.substr(beg,end-beg);
+//
+// pc.printf("humidity: %s", weather.hum);
+// pc.printf("temp: %s", weather.temp);
+// pc.printf("desc: %s", weather.desc);
+
+ // get time
+ std::time_t t = std::time(0);
+ std::time_t result = time(NULL);
+// std::cout << std::asctime(std::localtime(&result))
+
+ printf("\n\nCurrent Time: %s \r\n",ctime(&result));
+ printf("Current Temperature: %s Kelvin \r\n",weather.temp);
+ printf("Humidity is %s \r\n",weather.hum);
+ printf("Weather Condition: %s \r\n", weather.desc);
- //sent to thingsspeak
- if(cnt==10){ //don't update as often
- cnt=0;
- memset(resp, '\0', sizeof(resp));
- //POST data
- if(temperature!=-100){ //just check we have a valid temp
- map.put("api_key","YOUR KEY HERE");
- sprintf(val[0],"%4.1f",temperature);
- map.put("field1", val[0]);
- sprintf(val[1],"%4.1f",humidity);
- map.put("field2", val[1]);
- sprintf(val[2],"%4.1f",forcastTemp);
- map.put("field3", val[2]);
- sprintf(val[3],"%4.1f",forcastPressure);
- map.put("field4", val[3]);
- pc.printf("\nTrying to post data...\n");
- ret = http.post("https://api.thingspeak.com/update", map, &inText);
- if (!ret)
- {
- pc.printf("Executed POST successfully - read %d characters\n", strlen(resp));
- pc.printf("Result: %s\n", resp);
- }
- else
- {
- pc.printf("Error - ret = %d - HTTP return code = %d\n", ret, http.getHTTPResponseCode());
- }
- //Write Data to SDCARD
- fp = fopen(sdfile, "a");
- if (fp == NULL) {
- pc.printf("Unable to write the file \n");
- } else {
- pc.printf("Writing data to SDCARD \n");
- //time,temp,humidity,forcast,pressure
- fprintf(fp, "%s,%4.1f,%4.1f,%4.1f,%4.1f\n", ctime(&ctTime),temperature,humidity,forcastTemp,forcastPressure);
- fclose(fp);
- }
- }
-
- }
+
- cnt++;
- wait_ms(6000);
+ wait(60);
}
}
+}