1 |
/*
|
2 |
This sketch establishes a TCP connection to a "quote of the day" service.
|
3 |
It sends a "hello" message, and then prints received data.
|
4 |
*/
|
5 |
|
6 |
#include <ESP8266WiFi.h>
|
7 |
|
8 |
#ifndef STASSID
|
9 |
#define STASSID "shellyem3-3494547B8D61"
|
10 |
#define STAPSK ""
|
11 |
#endif
|
12 |
|
13 |
const char* ssid = STASSID;
|
14 |
const char* password = STAPSK;
|
15 |
|
16 |
const char* host = "192.168.33.1";
|
17 |
const uint16_t port = 80;
|
18 |
|
19 |
void setup() {
|
20 |
Serial.begin(115200);
|
21 |
|
22 |
// We start by connecting to a WiFi network
|
23 |
|
24 |
Serial.println();
|
25 |
Serial.println();
|
26 |
Serial.print("Connecting to ");
|
27 |
Serial.println(ssid);
|
28 |
|
29 |
/* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default,
|
30 |
would try to act as both a client and an access-point and could cause
|
31 |
network-issues with your other WiFi-devices on your WiFi-network. */
|
32 |
WiFi.mode(WIFI_STA);
|
33 |
WiFi.begin(ssid, password);
|
34 |
|
35 |
while (WiFi.status() != WL_CONNECTED) {
|
36 |
delay(500);
|
37 |
Serial.print(".");
|
38 |
}
|
39 |
|
40 |
Serial.println("");
|
41 |
Serial.println("WiFi connected");
|
42 |
Serial.println("IP address: ");
|
43 |
Serial.println(WiFi.localIP());
|
44 |
}
|
45 |
|
46 |
void loop() {
|
47 |
static bool wait = false;
|
48 |
|
49 |
Serial.print("connecting to ");
|
50 |
Serial.print(host);
|
51 |
Serial.print(':');
|
52 |
Serial.println(port);
|
53 |
|
54 |
// Use WiFiClient class to create TCP connections
|
55 |
WiFiClient client;
|
56 |
if (!client.connect(host, port)) {
|
57 |
Serial.println("connection failed");
|
58 |
delay(5000);
|
59 |
return;
|
60 |
}
|
61 |
|
62 |
// This will send a string to the server
|
63 |
Serial.println("sending data to server");
|
64 |
|
65 |
|
66 |
if (client.connected()) { client.println("shellyem3-3494547B8D61/emeter/0?"); }
|
67 |
|
68 |
|
69 |
|
70 |
// wait for data to be available
|
71 |
unsigned long timeout = millis();
|
72 |
while (client.available() == 0) {
|
73 |
if (millis() - timeout > 5000) {
|
74 |
Serial.println(">>> Client Timeout !");
|
75 |
client.stop();
|
76 |
delay(60000);
|
77 |
return;
|
78 |
}
|
79 |
}
|
80 |
|
81 |
// Read all the lines of the reply from server and print them to Serial
|
82 |
Serial.println("receiving from remote server");
|
83 |
// not testing 'client.connected()' since we do not need to send data here
|
84 |
while (client.available()) {
|
85 |
char ch = static_cast<char>(client.read());
|
86 |
Serial.print(ch);
|
87 |
}
|
88 |
|
89 |
// Close the connection
|
90 |
Serial.println();
|
91 |
Serial.println("closing connection");
|
92 |
client.stop();
|
93 |
|
94 |
if (wait) {
|
95 |
delay(300000); // execute once every 5 minutes, don't flood remote service
|
96 |
}
|
97 |
wait = true;
|
98 |
}
|