pvoutput-client 0.0.3

Client for the PVOutput.org API
Documentation
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
mod patterns;

use std::fmt::{Debug, Display};

use jiff::civil::Time;

use crate::{
	Client,
	parser::patterns::INVALID_TIME,
	types::{
		error::{
			AddOutputError, AddStatusError, ClientError, DateTimeError, ExtendedDataField, NoEndpointSpecificError,
			PostSystemError, Result,
		},
		params::{GetOutputParams, GetStatisticsParams, GetSystemParams},
		response::{
			AggregatedOutput, ConsumptionStatistics, DailyStatus, FavouriteSystem, FullSystem, Output, OutputExport,
			Statistics, System, Tariffs,
		},
	},
};

pub fn daily_status(response: &str) -> Result<DailyStatus, NoEndpointSpecificError> {
	let semicolons = response.chars().filter(|c| *c == ';').count();
	let response = response.replace(';', "\n") + "\n";
	let mut reader = Client::reader(&response);

	// zeroth object: status
	let mut status: DailyStatus = reader.deserialize().next().ok_or(ClientError::MissingField)??;

	if semicolons > 0 {
		// /!\ JANK ALERT /!\
		if response.lines().nth(1).is_some_and(|l| l.chars().filter(|c| *c == ',').count() == 3) {
			// four entries - this is probably consumption data
			status.consumption = Some(reader.deserialize().next().ok_or(ClientError::MissingField)??);
		} else {
			// temperature data, one would assume
			status.temperatures = Some(reader.deserialize().next().ok_or(ClientError::MissingField)??);
		}

		if semicolons > 1 {
			// if there are two fields, the second one will surely be temperature. surely.
			status.temperatures = Some(reader.deserialize().next().ok_or(ClientError::MissingField)??);
		}
	}

	Ok(status)
}

// perfectly normal function
pub fn statistics(response: &str, params: &GetStatisticsParams) -> Result<Statistics, NoEndpointSpecificError> {
	type Params = GetStatisticsParams;
	let mut reader = Client::reader(response);

	Ok(match params {
		Params { system_id: Some(_), .. }
		| Params {
			consumption: false,
			credit_and_debit: false,
			..
		} => {
			// we built jank city!
			reader.deserialize().next().ok_or(ClientError::MissingField)??
		}
		Params {
			consumption: true,
			credit_and_debit: true,
			..
		} => {
			// we built jank city on parse and load!
			let (mut stats, consumption, credit, debit): (Statistics, ConsumptionStatistics, f32, f32) =
				reader.deserialize().next().ok_or(ClientError::MissingField)??;
			stats.consumption = Some(consumption);
			stats.credit = Some(credit);
			stats.debit = Some(debit);

			stats
		}
		Params { consumption: true, .. } => {
			// we built jank city!
			let (mut stats, consumption): (Statistics, ConsumptionStatistics) =
				reader.deserialize().next().ok_or(ClientError::MissingField)??;
			stats.consumption = Some(consumption);

			stats
		}
		Params {
			credit_and_debit: true, ..
		} => {
			// we built jank city on parse and looooad...
			let (mut stats, credit, debit): (Statistics, f32, f32) =
				reader.deserialize().next().ok_or(ClientError::MissingField)??;
			stats.credit = Some(credit);
			stats.debit = Some(debit);

			stats
		}
	})
}

pub fn system(response: &str, params: &GetSystemParams) -> Result<FullSystem, NoEndpointSpecificError> {
	let response = response.replace(';', "\n") + "\n";
	let mut reader = Client::reader(&response);

	// zeroth object: system
	let (subsystem, mut system) =
		reader.deserialize::<(System, FullSystem)>().next().ok_or(ClientError::MissingField)??;
	system.system = subsystem;

	// first object: tariffs
	// this object is always present.
	// the API returns an empty value if the parameter isn't set, which would be OK, but the `csv` parser skips empty
	// lines!
	// if `params.tariff` is false, and we try to deserialise the next object anyway, we'll end up parsing the
	// donation count as a tariff, which (obviously) fails.
	if params.tariffs
		&& let Some(tariffs) = reader.deserialize::<Tariffs>().next()
	{
		system.tariffs = tariffs?;
	}

	if params.teams {
		// only present if requested
		if let Some(teams) = reader.deserialize().next() {
			system.teams = teams?;
		}
	}

	// second object: donations
	system.donations = reader.deserialize().next().ok_or(ClientError::MissingField)??;

	// the remaining objects are optional
	if params.extended_data
		&& let Some(extended) = reader.deserialize().next()
	{
		system.extended_data = extended?;
	}

	if params.monthly_estimates
		&& let Some(monthly_estimates) = reader.deserialize().next()
	{
		system.monthly_estimates = monthly_estimates?;
	}

	Ok(system)
}

pub fn outputs(response: &str, params: &GetOutputParams) -> Result<Vec<Output>, NoEndpointSpecificError> {
	#[derive(serde::Deserialize)]
	struct NanU32(#[serde(deserialize_with = "crate::types::response::opt_nan_u32")] Option<u32>);

	let response = response.replace(';', "\n") + "\n";
	let mut reader = Client::reader(&response);

	let mut outputs = Vec::with_capacity(response.lines().count());

	loop {
		outputs.push(match (params.time_of_export, params.insolation) {
			(true, true) => match reader.deserialize::<(Output, OutputExport, NanU32)>().next() {
				Some(result) => {
					let (mut output, export, insolation) = result?;
					output.export = Some(export);
					output.insolation = insolation.0;
					output
				}
				None => break,
			},
			(false, true) => match reader.deserialize::<(Output, NanU32)>().next() {
				Some(result) => {
					let (mut output, insolation) = result?;
					output.insolation = insolation.0;
					output
				}
				None => break,
			},
			(true, false) => match reader.deserialize::<(Output, OutputExport)>().next() {
				Some(result) => {
					let (mut output, export) = result?;
					output.export = Some(export);
					output
				}
				None => break,
			},
			_ => match reader.deserialize::<Output>().next() {
				Some(output) => output?,
				None => break,
			},
		});
	}

	Ok(outputs)
}

pub fn aggregate_outputs(response: &str, export: bool) -> Result<Vec<AggregatedOutput>, NoEndpointSpecificError> {
	let response = response.replace(';', "\n") + "\n";
	let mut reader = Client::reader(&response);

	let mut outputs = Vec::with_capacity(response.lines().count());

	loop {
		outputs.push(if export {
			match reader.deserialize::<(AggregatedOutput, OutputExport)>().next() {
				Some(result) => {
					let (mut output, export) = result?;
					output.export = Some(export);
					output
				}
				None => break,
			}
		} else {
			match reader.deserialize::<AggregatedOutput>().next() {
				Some(output) => output?,
				None => break,
			}
		});
	}

	Ok(outputs)
}

pub fn favourites(response: &str) -> Result<Vec<FavouriteSystem>, NoEndpointSpecificError> {
	let mut reader = Client::reader(response);

	Ok(
		reader
			.deserialize::<(u32, System, u32)>()
			.map(|r| r.map(|(id, system, interval)| FavouriteSystem::new(system, id, interval)))
			.collect::<core::result::Result<_, _>>()?,
	)
}

pub async fn error<F, Endpoint>(response: reqwest::Response, endpoint_parser: F) -> ClientError<Endpoint>
where
	F: FnOnce(&str) -> Option<Endpoint>,
	Endpoint: Debug + Display,
{
	let status = response.status();
	let response = response.text().await;
	response.map_or_else(
		|_| ClientError::UnrecognisedStatusCode(status, None),
		|response| {
			// sometimes 400 errors start with `Bad request 400: `, and sometimes they start with `Bad Request 400: `.
			// notice the capital R in `Request`.
			match response.trim().trim_start_matches("Bad request 400: ").trim_start_matches("Bad Request 400: ") {
				// general errors
				"Unauthorized 401: Invalid System ID" => ClientError::InvalidSystemId,
				"Unauthorized 401: Invalid API Key" => ClientError::InvalidApiKey,
				"Unauthorized 401: Disabled API Key" => ClientError::DisabledApiKey,
				"Forbidden 403: Read only key" => ClientError::ReadOnlyKey,
				"Unauthorized 401: Missing, invalid or inactive api key information (X-Pvoutput-Apikey)" => {
					ClientError::BadApiKey
				}
				"Forbidden 403: Exceeded number requests per hour" => ClientError::RateLimitExceeded,
				"Forbidden 403: Donation mode" => ClientError::DonationModeRequired,

				// `getstatus.jsp`, possibly others?
				"Unauthorized 401: Inaccessible System ID" => ClientError::InaccessibleSystemId,

				// `deletestatus.jsp`
				"Status not found" => ClientError::NotFound,

				// various
				e if e.starts_with("No") && e.ends_with("found") => ClientError::NotFound,

				// other
				e => endpoint_parser(e).map_or_else(
					|| ClientError::UnrecognisedStatusCode(status, Some(response)),
					|e| ClientError::EndpointSpecific(e),
				),
			}
		},
	)
}

pub const fn parse_none(_error: &str) -> Option<NoEndpointSpecificError> { None }

pub fn parse_datetime_error(error: &str) -> Option<DateTimeError> {
	Some(if error == "Date missing" || error == "Date is required" {
		DateTimeError::MissingDateOrTime
	} else if let Some(Ok(date)) = patterns::DATE_TOO_OLD.captures(error).map(|c| c[1].parse()) {
		DateTimeError::DateTooOld(date)
	} else if let Some(Ok(date)) = patterns::DATE_TOO_NEW.captures(error).map(|c| c[1].parse()) {
		DateTimeError::DateTooNew(date)
	} else if let Some(date) = patterns::INVALID_DATE
		.captures(error)
		.map(|c| c.get(1).map_or_else(|| c[2].to_string(), |g| g.as_str().to_string()))
	{
		DateTimeError::InvalidDate(date)
	} else if let Some(time) = INVALID_TIME
		.captures(error)
		.map(|c| c.get(1).map_or_else(|| c[2].to_string(), |g| g.as_str().to_string()))
	{
		DateTimeError::InvalidTime(time)
	} else {
		return None;
	})
}

pub fn parse_add_output_error(error: &str) -> Option<AddOutputError> {
	// The Automechanical Megalomaniacal Regex-O-Matic (pat. pend.)!
	Some(
		if error == "No outputs added"
			|| error == "Missing parameter [data]"
			|| error == "No statuses added or updated"
			|| error == "Invalid data format []"
		{
			AddOutputError::NoData
		} else if let Some(datetime_error) = parse_datetime_error(error) {
			AddOutputError::InvalidDateTime(datetime_error)
		} else if let Some((which, Ok(value), Ok(system_size), Ok(date))) = patterns::GENERATION_OR_EXPORT_TOO_HIGH
			.captures(error)
			.map(|c| (c[1].to_string(), c[2].parse(), c[3].parse(), c[4].parse()))
		{
			if which == "Generation" {
				AddOutputError::GenerationTooHigh {
					generation: value,
					system_size,
					date,
				}
			} else {
				debug_assert_eq!(which, "Export");
				AddOutputError::ExportTooHigh {
					export: value,
					system_size,
					date,
				}
			}
		} else if let Some((Ok(export), Ok(generation))) =
			patterns::EXPORT_EXCEEDS_GENERATION.captures(error).map(|c| (c[1].parse(), c[2].parse()))
		{
			AddOutputError::ExportExceedsGeneration { export, generation }
		} else if let Some((Ok(consumption), Ok(date))) =
			patterns::CONSUMPTION_TOO_HIGH.captures(error).map(|c| (c[1].parse(), c[2].parse()))
		{
			AddOutputError::ConsumptionTooHigh(consumption, date)
		} else if let Some((Ok(peak_power), Ok(system_size), Ok(date))) =
			patterns::PEAK_POWER_TOO_HIGH.captures(error).map(|c| (c[1].parse(), c[2].parse(), c[3].parse()))
		{
			AddOutputError::PeakPowerTooHigh {
				peak_power,
				system_size,
				date,
			}
		} else if let Some((which, Ok(date))) =
			patterns::TEMPERATURE_MISSING.captures(error).map(|c| (c[1].to_string(), c[2].parse()))
		{
			if which == "Max" {
				AddOutputError::MinTemperatureWithoutMax(date)
			} else {
				debug_assert_eq!(which, "Min");
				AddOutputError::MaxTemperatureWithoutMin(date)
			}
		} else {
			return None;
		},
	)
}

pub fn parse_add_status_error(error: &str) -> Option<AddStatusError> {
	Some(match error {
		"No outputs added" | "Missing parameter [data]" | "No statuses added or updated" | "Invalid data format []" => {
			AddStatusError::NoData
		}
		"Missing energy and power values" => AddStatusError::MissingFields,
		e if e.starts_with("Missing required data") || e.starts_with("Missing parameter") => AddStatusError::MissingFields,
		"Moon Powered" => AddStatusError::MoonPowered,
		"Invalid net and cumulative" => AddStatusError::BothCumulativeAndNet,
		"Missing net power value" => AddStatusError::NoEnergyData,
		e => {
			if let Some(datetime_error) = parse_datetime_error(e) {
				AddStatusError::InvalidDateTime(datetime_error)
			} else if let Some((which, Ok(value), Ok(system_size))) =
				patterns::PRODUCTION_TOO_HIGH.captures(e).map(|c| (c[1].to_string(), c[2].parse(), c[3].parse()))
			{
				if which == "Power" {
					AddStatusError::ExcessivePowerGeneration {
						power: value,
						system_size,
					}
				} else {
					debug_assert_eq!(which, "Energy");
					AddStatusError::ExcessiveEnergyGeneration {
						energy: value,
						system_size,
					}
				}
			} else if let Some((Ok(value), Ok(hour), Ok(minute))) =
				patterns::ENERGY_TOO_HIGH_FOR_TIME.captures(e).map(|c| (c[1].parse(), c[2].parse(), c[3].parse()))
			{
				AddStatusError::EnergyTooHighForTime(value, Time::new(hour, minute, 0, 0).expect("time should be valid"))
			} else if let Some(data) = patterns::INVALID_DATA_FORMAT.captures(e).map(|c| c[1].to_string()) {
				AddStatusError::InvalidDataFormat(data)
			} else {
				return None;
			}
		}
	})
}

#[allow(clippy::too_many_lines, clippy::cognitive_complexity)]
pub fn parse_post_system_error(error: &str) -> Option<PostSystemError> {
	Some(if error == "System name is too long" {
		PostSystemError::SystemNameTooLong
	} else if let Some((Ok(v), which)) =
		patterns::MISSING_EXTENDED_DATA_FIELD.captures(error).map(|c| (c[1].parse(), c[2].to_string()))
	{
		if which == "unit" {
			PostSystemError::MissingExtendedDataUnit(v)
		} else {
			debug_assert_eq!(which, "label");
			PostSystemError::MissingExtendedDataLabel(v)
		}
	} else if let Some((Ok(v), which)) =
		patterns::EXTENDED_DATA_FIELD_TOO_LONG.captures(error).map(|c| (c[1].parse(), c[2].to_string()))
	{
		if which == "unit" {
			PostSystemError::ExtendedDataUnitTooLong(v)
		} else {
			debug_assert_eq!(which, "label");
			PostSystemError::ExtendedDataLabelTooLong(v)
		}
	} else if let Some(Ok(v)) = patterns::INVALID_EXTENDED_DATA_GRAPH.captures(error).map(|c| c[1].parse()) {
		PostSystemError::InvalidExtendedDataField(v, ExtendedDataField::Graph)
	} else if let Some(Ok(v)) = patterns::INVALID_EXTENDED_DATA_AXIS.captures(error).map(|c| c[1].parse()) {
		PostSystemError::InvalidExtendedDataField(v, ExtendedDataField::Axis)
	} else if let Some(Ok(v)) = patterns::INVALID_EXTENDED_DATA_COLOUR.captures(error).map(|c| c[1].parse()) {
		PostSystemError::InvalidExtendedDataField(v, ExtendedDataField::Colour)
	} else {
		return None;
	})
}