-
Notifications
You must be signed in to change notification settings - Fork 0
/
WxDataUploader.cs
194 lines (158 loc) · 8.27 KB
/
WxDataUploader.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json.Linq;
namespace PWSWeatherUploader
{
public class WxDataUploader
{
private readonly string PWSWeatherUploadUrl = @"https://pwsupdate.pwsweather.com/api/v1/submitwx";
private static readonly HttpClient _client = new HttpClient();
private string _id = "";
private string _password = "";
public WxDataUploader(string stationId, string uploadPassword)
{
// setup id and password variables
_id = stationId;
_password = uploadPassword;
}
public async Task UploadToPWSWeatherAsync(StationObservationModel.StationInfo station)
{
// Check for observation data in the download
if (station.Obs.Count == 0)
{
// There is no observations to work with, so throw an exception
throw new Exception("No observation data found.");
}
// There is an observation, so prepare to upload the data
StationObservationModel.Ob observation = station.Obs[0];
var readings = new Dictionary<string, string>
{
{ "ID", _id },
{ "PASSWORD", _password },
{ "dateutc", observation.Timestamp.EpochToDateTimeUtc().ToString("yyyy-MM-dd HH:mm:ss") },
{ "winddir", observation.WindDirection.ToString() },
{ "windspeedmph", observation.WindAvg.MsToMph().ToString("0.0") },
{ "windgustmph", observation.WindGust.MsToMph().ToString("0.0") },
{ "tempf", observation.AirTemperature.TempCtoF().ToString("0.0") },
{ "rainin", observation.Precip.MmToIn().ToString("0.00") },
{ "dailyrainin", observation.PrecipAccumLocalDay.MmToIn().ToString("0.00") },
{ "baromin", observation.BarometricPressure.MbToIn().ToString("0.00") },
{ "dewptf", observation.DewPoint.TempCtoF().ToString("0.0") },
{ "humidity", observation.RelativeHumidity.ToString() },
{ "solarradiation", observation.SolarRadiation.ToString() },
{ "UV", observation.Uv.ToString("0.0") },
{ "softwaretype", "PWSWeatherUploaderForWeatherFlow1.0" },
{ "action", "updateraw" },
};
// Use for debug output of dictionary
//var asString = string.Join(Environment.NewLine, readings);
//Console.WriteLine(asString);
// Turn dictionary into url encoded content
var content = new FormUrlEncodedContent(readings);
using (var client = new HttpClient())
{
// Set client timeout to 30 sec.
client.Timeout = TimeSpan.FromSeconds(5);
// Send post request async to API with payload
var response = await client.PostAsync(PWSWeatherUploadUrl, content);
// Receive response async
var responseString = await response.Content.ReadAsStringAsync();
// DEBUG: Console.WriteLine(responseString);
// Check json response for errors
dynamic jsonResponse = JObject.Parse(responseString);
// For debugging: dynamic jsonResponse = JObject.Parse("{ \"error\":null,\"success\":true}");
bool jsonResponseSuccess = jsonResponse.success;
string jsonResponseErrorMessage = jsonResponse.error;
//if (jsonResponseSuccess == true)
//{
// Console.WriteLine($"Observation successfully uploaded for {observation.Timestamp.EpochToDateTimeUtc().ToLocalTime().ToString()}.");
//}
//else
//{
// Console.WriteLine("Error:");
// Console.WriteLine(jsonResponseErrorMessage);
//}
if (jsonResponseSuccess != true)
{
throw new Exception($"An error was received in the JSON response: {jsonResponseErrorMessage}");
}
}
}
public void UploadToPWSWeather(StationObservationModel.StationInfo station)
{
// Check for observation data in the download
if (station.Obs.Count == 0)
{
// There is no observations to work with, so throw an exception
throw new Exception("No observation data found.");
}
// There is an observation, so prepare to upload the data
StationObservationModel.Ob observation = station.Obs[0];
var readings = new Dictionary<string, string>
{
{ "ID", _id },
{ "PASSWORD", _password },
{ "dateutc", observation.Timestamp.EpochToDateTimeUtc().ToString("yyyy-MM-dd HH:mm:ss") },
{ "winddir", observation.WindDirection.ToString() },
{ "windspeedmph", observation.WindAvg.MsToMph().ToString("0.0") },
{ "windgustmph", observation.WindGust.MsToMph().ToString("0.0") },
{ "tempf", observation.AirTemperature.TempCtoF().ToString("0.0") },
{ "rainin", observation.Precip.MmToIn().ToString("0.00") },
{ "dailyrainin", observation.PrecipAccumLocalDay.MmToIn().ToString("0.00") },
{ "baromin", observation.BarometricPressure.MbToIn().ToString("0.00") },
{ "dewptf", observation.DewPoint.TempCtoF().ToString("0.0") },
{ "humidity", observation.RelativeHumidity.ToString() },
{ "solarradiation", observation.SolarRadiation.ToString() },
{ "UV", observation.Uv.ToString("0.0") },
{ "softwaretype", "PWSWeatherUploaderForWeatherFlow1.0" },
{ "action", "updateraw" },
};
// DEBUG: Use for debug output of dictionary
//var asString = string.Join(Environment.NewLine, readings);
//Console.WriteLine(asString);
// Turn dictionary into url encoded content
var content = new FormUrlEncodedContent(readings);
using (var client = new HttpClient())
{
// Set client timeout to 30 sec.
client.Timeout = TimeSpan.FromSeconds(30);
// Send post request async to API with payload synchronously
var response = client.PostAsync(PWSWeatherUploadUrl, content).Result;
if(response.IsSuccessStatusCode)
{
var responseContent = response.Content;
// Receive response async
var responseString = responseContent.ReadAsStringAsync().Result;
// DEBUG: Console.WriteLine(responseString);
// Check json response for errors
dynamic jsonResponse = JObject.Parse(responseString);
// For debugging: dynamic jsonResponse = JObject.Parse("{ \"error\":null,\"success\":true}");
bool jsonResponseSuccess = jsonResponse.success;
string jsonResponseErrorMessage = jsonResponse.error;
//if (jsonResponseSuccess == true)
//{
// Console.WriteLine($"Observation successfully uploaded for {observation.Timestamp.EpochToDateTimeUtc().ToLocalTime().ToString()}.");
//}
//else
//{
// Console.WriteLine("Error:");
// Console.WriteLine(jsonResponseErrorMessage);
//}
if (jsonResponseSuccess != true)
{
throw new Exception($"An error was received in the JSON response: {jsonResponseErrorMessage}");
}
}
else
{
// Console.WriteLine($"Observation upload failed with a non-success response code. ({response.StatusCode.ToString()})");
throw new Exception($"Non-success response code received on upload. ({response.StatusCode.ToString()})");
}
}
}
}
}