· 4 years ago · May 15, 2021, 11:56 AM
1 printf("Longitude: %s\n", longitude.c_str());
2
3 //--------------------------------------------------------------------- New connection
4 // Set certificate for weather api
5 result = socket->set_root_ca_cert(weathercert);
6 if (result != 0) {
7 printf("Error: socket->set_root_ca_cert() returned %d\n", result);
8 return result;
9 }
10 socket->open(network);
11
12 // Get IP address of (WEATHER)
13 result = network->gethostbyname("api.openweathermap.org", &address);
14
15 // Check result
16 if (result != 0) {
17 printf("Failed to get IP address of host: %d\n", result);
18 while (1);
19 }
20
21 printf("Got address of host\n");
22
23 // Set server port number, 443 for HTTPS/SSL
24 address.set_port(443);
25
26 // Connect to server at the given address
27 result = socket->connect(address);
28
29 if (result != 0) {
30 printf("Failed to connect to server: %d\n", result);
31 while (1);
32 }
33
34 // API key for weatherapi : 2179f8cb6e1174d4b0952b3d9af4f7b4
35 // Create HTTP request
36 char temp_get[300];
37
38 sprintf(temp_get, "GET /data/2.5/weather?lat=%s&lon=%s&appid=2179f8cb6e1174d4b0952b3d9af4f7b4 HTTP/1.1\r\n"
39 "Host: api.openweathermap.org\r\n"
40 "Connection: close\r\n"
41 "\r\n", latitude.c_str(), longitude.c_str());
42
43 result = send_request(socket, temp_get);
44
45 // Check result
46 if (result != 0) {
47 printf("Failed to send request: %d\n", result);
48 while (1);
49 }
50
51 // We need to read the response into memory. The destination is called a buffer.
52 // If you make this buffer static it will be placed in BSS and won't use stack memory.
53 result = read_response(socket, buffer, sizeof(buffer));
54
55 // Check result
56 if (result != 0) {
57 printf("Failed to read response: %d\n", result);
58
59 while (1);
60 }
61
62
63 socket->close();
64
65 // Check if we actually got JSON in the response
66 if (json_begin == nullptr || json_end == nullptr) {
67 printf("Failed to find JSON in response\n");
68 while (1);
69 }
70
71 // End the string after the end of the JSON data in case the response contains trailing data
72 json_end[1] = 0;
73
74 printf("JSON response:\n");
75 printf("%s\n", json_begin);
76
77 // Parse response as JSON, starting from the first {
78 json document2 = json::parse(json_begin);
79
80 while (true) {
81 ThisThread::sleep_for(1s);
82 }