· 6 years ago · Feb 11, 2019, 04:16 PM
1/*
2 This sketch sends data via HTTP GET requests to data.sparkfun.com service.
3
4 You need to get streamId and privateKey at data.sparkfun.com and paste them
5 below. Or just customize this script to talk to other HTTP servers.
6
7*/
8
9#include <ESP8266WiFi.h>
10
11const char* ssid = "your-ssid";
12const char* password = "your-password";
13
14const char* host = "us-central1-test-dbdd7.cloudfunctions.net/addMessage";
15const char* streamId = "....................";
16const char* privateKey = "....................";
17
18void setup() {
19 Serial.begin(115200);
20 delay(10);
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
46int value = 0;
47
48void loop() {
49 delay(5000);
50 ++value;
51
52 Serial.print("connecting to ");
53 Serial.println(host);
54
55 // Use WiFiClient class to create TCP connections
56 WiFiClient client;
57 const int httpPort = 80;
58 if (!client.connect(host, httpPort)) {
59 Serial.println("connection failed");
60 return;
61 }
62
63 // We now create a URI for the request
64 int hujan_menit = random();
65 int hujan_total = random();
66 String url = "/?auth" + secretKey + "&hujan_menit=" + hujan_menit + "&hujan_total=" + hujan_total;
67
68 Serial.print("Requesting URL: ");
69 Serial.println(url);
70
71 // This will send the request to the server
72 client.print(String("GET ") + url + " HTTP/1.1\r\n" +
73 "Host: " + host + "\r\n" +
74 "Connection: close\r\n\r\n");
75 unsigned long timeout = millis();
76 while (client.available() == 0) {
77 if (millis() - timeout > 5000) {
78 Serial.println(">>> Client Timeout !");
79 client.stop();
80 return;
81 }
82 }
83
84 // Read all the lines of the reply from server and print them to Serial
85 while (client.available()) {
86 String line = client.readStringUntil('\r');
87 Serial.print(line);
88 }
89 while(hujan) {
90 Firebase.push("Perangkat2/" + line + "hujan_menit", nilaiHujan);
91 }
92
93 Serial.println();
94 Serial.println("closing connection");
95}