-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathGetWheather_8266
263 lines (241 loc) · 8.36 KB
/
GetWheather_8266
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
/**
* 日期:2017/12/01
* 功能:8266获取心知天气
* 作者:ANTBOT
* 16X16点阵显示 取模方式 阴码+逐行式+顺向
**/
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
//#define DEBUG 是否启用debug功能
#ifdef DEBUG
#define DebugPrintln(message) Serial.println(message)
#define DebugPrint(message) Serial.print(message)
#else
#define DebugPrintln(message)
#define DebugPrint(message)
#endif
#define LED 2
const unsigned long BAUD_RATE = 115200; // serial connection speed
const unsigned long HTTP_TIMEOUT = 5000; // max respone time from server
const size_t MAX_CONTENT_SIZE = 2048; // max size of the HTTP response
const char ssid[] = "XXXXXX"; //修改为自己的路由器用户名
const char password[] = "XXXXXXXX"; //修改为自己的路由器密码
const char* host = "api.seniverse.com";
const char* APIKEY = "xxxxxxxxxxxxxxx"; //心知天气网站提供的API KEY
const char* city = "beijing";
const char* language = "en";//zh-Hans 简体中文 会显示乱码
unsigned int cntFlag=0;
WiFiClient client;
char response[MAX_CONTENT_SIZE];
char responseLife[MAX_CONTENT_SIZE];
char endOfHeaders[] = "\r\n\r\n";
unsigned int flag = HIGH;//默认当前灭灯
long lastTime = 0;
// 请求服务间隔
long Delay = 20000;
// 我们要从此网页中提取的数据的类型
struct UserData {
char city[16];//城市名称
char weather[32];//天气介绍(多云...)
char temp[16];//温度
char udate[32];//更新时间
};
//生活指数
struct UserDataLife {
char dressing[16];//穿衣指数
char uv[16];//紫外线强度
char sport[16];//运动指数
char car_washing[16];//洗车指数
char travel[16];//旅游指数
char flu[16];//感冒指数
};
void connectWifi()
{ Serial.print("Connecting to " + *ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print("."); }
Serial.println("");
Serial.println("Connected");
Serial.println("");
digitalWrite(0, HIGH);
delay(1000);
digitalWrite(0, LOW);
delay(1000);
digitalWrite(0, HIGH);
}
/**
* @Desc 初始化操作
*/
void setup() {
Serial.begin(BAUD_RATE);
pinMode(LED,OUTPUT);
digitalWrite(LED, HIGH);
connectWifi();
DebugPrintln("IP address: ");
DebugPrintln(WiFi.localIP());//WiFi.localIP()返回8266获得的ip地址
lastTime = millis();
}
void loop() {
while (!client.connected()){
if (!client.connect(host, 80)){
flag = !flag;
digitalWrite(LED, flag);
delay(500);
}
}
if(millis()-lastTime>=Delay){
//每间隔20s左右调用一次
cntFlag = !cntFlag;
Serial.println( cntFlag);
lastTime = millis();
if(cntFlag==1)//读取天气
{
if (sendRequest(host, city, APIKEY) && skipResponseHeaders()) {
clrEsp8266ResponseBuffer();
readReponseContent(response, sizeof(response));
UserData userData;
if (parseUserData(response, &userData)) {
sendtoArduino(&userData);
}
}
}else if(cntFlag==0){//读取生活指数
if (sendRequestLife(host, city, APIKEY) && skipResponseHeaders()) {
clrEsp8266ResponseBuffer();
readReponseContent(responseLife, sizeof(responseLife));
UserDataLife userData;
if (parseUserDataLife(responseLife, &userData)) {
sendtoArduinoLife(&userData);
}
}
}
}
}
/**
* @发送请求指令
*/
bool sendRequest(const char* host, const char* cityid, const char* apiKey) {
// We now create a URI for the request
//心知天气
String GetUrl = "/v3/weather/now.json?key=";
GetUrl += apiKey;
GetUrl += "&location=";
GetUrl += city;
GetUrl += "&language=";
GetUrl += language;
// This will send the request to the server
client.print(String("GET ") + GetUrl + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
DebugPrintln("create a request:");
DebugPrintln(String("GET ") + GetUrl + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n");
delay(1000);
return true;
}
bool sendRequestLife(const char* host, const char* cityid, const char* apiKey) {
// We now create a URI for the request
//心知天气
String GetUrl = "/v3/life/suggestion.json?key=";
GetUrl += apiKey;
GetUrl += "&location=";
GetUrl += city;
GetUrl += "&language=";
GetUrl += language;
// This will send the request to the server
client.print(String("GET ") + GetUrl + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
DebugPrintln("create a request:");
DebugPrintln(String("GET ") + GetUrl + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n");
delay(1000);
return true;
}
/**
* @Desc 跳过 HTTP 头,使我们在响应正文的开头
*/
bool skipResponseHeaders() {
// HTTP headers end with an empty line
bool ok = client.find(endOfHeaders);
if (!ok) {
DebugPrintln("No response or invalid response!");
}
return ok;
}
/**
* @Desc 从HTTP服务器响应中读取正文
*/
void readReponseContent(char* content, size_t maxSize) {
size_t length = client.peekBytes(content, maxSize);
delay(200);
//Serial.println(length);
DebugPrintln("Get the data from Internet!");
content[length] = 0;
DebugPrintln(content);
DebugPrintln("Read data Over!");
client.flush();//这句代码需要加上 不然会发现每隔一次client.find会失败
}
// 关闭与HTTP服务器连接
void stopConnect() {
client.stop();
}
void clrEsp8266ResponseBuffer(void){
memset(response, 0, MAX_CONTENT_SIZE); //清空
memset(responseLife, 0, MAX_CONTENT_SIZE); //清空
}
bool parseUserDataLife(char* content, struct UserDataLife* userData) {
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(content);
if (!root.success()) {
Serial.println("JSON parsing failed!");
return false;
}
//复制我们感兴趣的字符串
strcpy(userData->dressing, root["results"][0]["suggestion"]["dressing"]["brief"]);
strcpy(userData->uv, root["results"][0]["suggestion"]["uv"]["brief"]);
strcpy(userData->sport, root["results"][0]["suggestion"]["sport"]["brief"]);
strcpy(userData->car_washing, root["results"][0]["suggestion"]["car_washing"]["brief"]);
strcpy(userData->travel, root["results"][0]["suggestion"]["travel"]["brief"]);
strcpy(userData->flu, root["results"][0]["suggestion"]["flu"]["brief"]);
// -- 这不是强制复制,你可以使用指针,因为他们是指向“内容”缓冲区内,所以你需要确保
// 当你读取字符串时它仍在内存中
return true;
}
bool parseUserData(char* content, struct UserData* userData) {
// -- 根据我们需要解析的数据来计算JSON缓冲区最佳大小
// 如果你使用StaticJsonBuffer时才需要
// const size_t BUFFER_SIZE = 1024;
// 在堆栈上分配一个临时内存池
// StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;
// -- 如果堆栈的内存池太大,使用 DynamicJsonBuffer jsonBuffer 代替
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(content);
if (!root.success()) {
Serial.println("JSON parsing failed!");
return false;
}
//复制我们感兴趣的字符串
strcpy(userData->city, root["results"][0]["location"]["name"]);
strcpy(userData->weather, root["results"][0]["now"]["text"]);
strcpy(userData->temp, root["results"][0]["now"]["temperature"]);
strcpy(userData->udate, root["results"][0]["last_update"]);
// -- 这不是强制复制,你可以使用指针,因为他们是指向“内容”缓冲区内,所以你需要确保
// 当你读取字符串时它仍在内存中
return true;
}
// 打印从JSON中提取的数据
void sendtoArduino(const struct UserData* userData) {
char s2Uno[128];
Serial.println("Wheather:[city] [wheather] [tempreture]");
sprintf(s2Uno,"[%s][%s][%s]",userData->city,userData->weather,userData->temp);
Serial.println(s2Uno);
}
void sendtoArduinoLife(const struct UserDataLife* userData) {
char s2Uno[256];
Serial.println("Life:(dressing)(UV)(sport)(car-wash)(travel)(flu)");
sprintf(s2Uno,"(%s)(%s)(%s)(%s)(%s)(%s)",userData->dressing,userData->uv,userData->sport,userData->car_washing,userData->travel,userData->flu);
Serial.println(s2Uno);
}