-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.rs
482 lines (422 loc) · 15.4 KB
/
main.rs
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
mod ct;
mod ota;
pub(crate) mod utils;
use std::sync::{Arc, Mutex};
use std::thread::sleep;
use std::time::{Duration, Instant};
use embedded_svc::http::server::registry::Registry;
use embedded_svc::http::server::{Request, Response};
use embedded_svc::http::{Headers, SendStatus};
use embedded_svc::io::Read as SvcRead;
use embedded_svc::ipv4::{Ipv4Addr, Mask, RouterConfiguration, Subnet};
use embedded_svc::wifi::Wifi;
use embedded_svc::wifi::{AccessPointConfiguration, ApIpStatus, ApStatus, AuthMethod, Status};
use esp_idf_svc::http::server::EspHttpServer;
use esp_idf_svc::netif::EspNetifStack;
use esp_idf_svc::nvs::EspDefaultNvs;
use esp_idf_svc::nvs_storage::EspNvsStorage;
use esp_idf_svc::sysloop::EspSysLoopStack;
use esp_idf_svc::wifi::EspWifi;
use esp_idf_sys::{esp, gettimeofday, settimeofday, timeval};
use esp_idf_hal::adc;
use esp_idf_hal::prelude::Peripherals;
use anyhow::bail;
use cstr::cstr;
#[allow(unused_imports)]
use log::{debug, error, info, warn};
use crate::ct::{CTStorage, CT};
use crate::ota::{first_run_validate, ota_update_from_reader};
// const SINGLE_PHASE_CURRENT_PIN: u8 = 35;
// const SINGLE_PHASE_VOLTAGE_PIN: u8 = 34;
// const THREE_PHASE_CURRENT_PINS: [u8; 3] = [32, 35, 34];
// const THREE_PHASE_VOLTAGE_PINS: [u8; 3] = [39, 36, 33];
// const LED_PIN: u8 = 14;
// const DC_VOLTAGE: [u16; 3] = [1892; 3];
// const DC_CURRENT: [u16; 3] = [1635; 3];
// const CURRENT_SCALE: [f32; 3] = [102.0; 3]; //111.1;
// const VOLTAGE_SCALE: [f32; 3] = [232.5; 3];
/// Specify the number of CT modules that will be connected
/// to this system.
#[cfg(feature = "single-phase")]
const AC_PHASE: usize = 1;
#[cfg(feature = "three-phase")]
const AC_PHASE: usize = 3;
// version used for OTA
const VERSION: u32 = 102;
// ADC constants
// const ADC_BITS: u32 = 12;
// const MAX_READING: u32 = 1 << ADC_BITS;
const MAX_MV_ATTEN_11: u16 = 2450;
const SUPPLY_VOLTAGE: f32 = 3.3;
const NOISE_THRESHOLD: f32 = MAX_MV_ATTEN_11 as f32 / 8.0;
// Periodic actions constants
const SAVE_PERIOD_TIMEOUT: u64 = 3600; // 3600 for one hour
// Storage constants
const MAX_SHARD_SIZE: u64 = 4096; // in bytes
const MAX_TIME_STORAGE_SIZE: u64 = 4096; // in bytes
const CT_READING_SIZE: usize = 30; // in bytes
// Network constants
const ACCESS_TOKEN_SIZE: usize = 56;
const AP_PASSWORD: &str = "12345678";
const GATEWAY_IP: Ipv4Addr = Ipv4Addr::new(10, 0, 0, 1);
fn main() -> anyhow::Result<()> {
esp_idf_sys::link_patches();
// Bind the log crate to the ESP Logging facilities
esp_idf_svc::log::EspLogger::initialize_default();
println!("SEM Device running version: {}", VERSION);
// Initialize LittleFS storage
let _fs_conf = init_littlefs_storage()?;
info!("Initialized and mounted littlefs storage.");
// Initialize CT readings shards
let storage_lock = Arc::new(Mutex::new(CTStorage::new()));
{
let mut ct_storage = match storage_lock.lock() {
Ok(gaurd) => gaurd,
Err(poisoned) => poisoned.into_inner(),
};
info!("Finding newest shard.");
ct_storage.find_newest_readings_shard_num()?;
ct_storage.update_system_time()?;
ct_storage.log_powerloss()?;
}
// Initialize NVS storage
let (default_nvs, _keystore) = init_nvs_storage()?;
info!("Initialized default NVS storage.");
// SSID and password for the Wifi access point.
let mut ap_ssid: String = String::new();
let ap_password: &str = AP_PASSWORD;
configure_access_point_ssid(&mut ap_ssid)?;
info!("Configured AP SSID as: {}.", ap_ssid);
let _wifi = init_access_point(&ap_ssid, ap_password, default_nvs)?;
info!("Initialized Wifi.");
let _web_server = init_web_server(storage_lock.clone())?;
info!("Initialized Web Server.");
// Initilize peripherals and pins
let peripherals = Peripherals::take().unwrap();
let pins = peripherals.pins;
// Initilize ADC
let mut powered_adc1 = adc::PoweredAdc::new(
peripherals.adc1,
adc::config::Config::new().calibration(false),
)?;
let mut cts = CT::init(pins)?;
info!("Initialized ADC 1.");
// If everything is working fine, cancel rollback on the next restart to the previous firmware
first_run_validate()?;
// Main Loop
let mut save_period_start = Instant::now();
loop {
for ct in &mut cts {
ct.calculate_energy(&mut powered_adc1, 100, std::time::Duration::new(3, 0))?;
ct.reading.set_time(now().as_millis() as u64);
info!("Energy Reading: {:?}", ct.reading);
}
// save the readings of CTs to storage.
if save_period_start.elapsed() > Duration::new(SAVE_PERIOD_TIMEOUT, 0) {
info!("Saving to storage.");
let mut ct_storage = match storage_lock.lock() {
Ok(gaurd) => gaurd,
Err(poisoned) => poisoned.into_inner(),
};
info!("Got storage lock.");
let res = ct_storage.save_to_storage(&cts);
println!("{:?}", res);
let res = ct_storage.store_time(now().as_millis() as u64);
println!("{:?}", res);
// Reset CT readings.
for ct in &mut cts {
ct.reset();
}
save_period_start = Instant::now();
}
sleep(Duration::from_millis(1000));
}
}
/// Initializes a littlefs file system.
///
/// A partition with name `LITTLEFS_PARTITION_NAME` has to be specified
/// in the partition table csv file.
fn init_littlefs_storage() -> anyhow::Result<esp_idf_sys::esp_vfs_littlefs_conf_t> {
let mut fs_conf = esp_idf_sys::esp_vfs_littlefs_conf_t {
base_path: cstr!("/littlefs").as_ptr(),
partition_label: cstr!("littlefs").as_ptr(),
..Default::default()
};
fs_conf.set_format_if_mount_failed(true as u8);
fs_conf.set_dont_mount(false as u8);
unsafe { esp!(esp_idf_sys::esp_vfs_littlefs_register(&fs_conf))? };
let (mut fs_total_bytes, mut fs_used_bytes) = (0, 0);
unsafe {
esp!(esp_idf_sys::esp_littlefs_info(
fs_conf.partition_label,
&mut fs_total_bytes,
&mut fs_used_bytes
))?
};
info!(
"LittleFs Info: total bytes = {}, used bytes = {}.",
fs_total_bytes, fs_used_bytes
);
Ok(fs_conf)
}
/// Initializes a nvs file system.
///
/// A partition with name `NVS_PARTITION_NAME` has to be specified
/// in the partition table csv file.
fn init_nvs_storage() -> anyhow::Result<(Arc<EspDefaultNvs>, Arc<EspNvsStorage>)> {
let default_nvs = Arc::new(EspDefaultNvs::new()?);
let keystore = Arc::new(EspNvsStorage::new_default(default_nvs.clone(), "f", true)?);
Ok((default_nvs, keystore))
}
/// Sets the value of `ap_ssid` as a combination of this
/// device MAC address and a custom string.
fn configure_access_point_ssid(ap_ssid: &mut String) -> anyhow::Result<()> {
let mut mac = [0u8; 6];
esp!(unsafe {
esp_idf_sys::esp_read_mac(
mac.as_mut_ptr() as *mut _,
esp_idf_sys::esp_mac_type_t_ESP_MAC_WIFI_SOFTAP,
)
})?;
ap_ssid.push_str("SEM-");
ap_ssid.push_str(
format!(
"{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]
)
.as_str(),
);
Ok(())
}
/// Initializes access point with the given ssid and pasword.
///
/// Authentication method is WPA2Personal.
fn init_access_point(
ssid: &str,
password: &str,
default_nvs: Arc<EspDefaultNvs>,
) -> anyhow::Result<Box<EspWifi>> {
let netif_stack = Arc::new(EspNetifStack::new()?);
let sys_loop_stack = Arc::new(EspSysLoopStack::new()?);
let mut wifi = Box::new(EspWifi::new(netif_stack, sys_loop_stack, default_nvs)?);
wifi.set_configuration(&embedded_svc::wifi::Configuration::AccessPoint(
AccessPointConfiguration {
ssid: ssid.into(),
password: password.into(),
auth_method: AuthMethod::WPA2Personal,
ip_conf: Some(RouterConfiguration {
subnet: Subnet {
gateway: GATEWAY_IP,
mask: Mask(24),
},
dhcp_enabled: true,
dns: None,
secondary_dns: None,
}),
..Default::default()
},
))?;
let status = wifi.get_status();
wifi.wait_status_with_timeout(Duration::from_secs(20), |status| !status.is_transitional())
.map_err(|e| anyhow::anyhow!("Unexpected Wifi status: {:?}", e))?;
if let Status(_, ApStatus::Started(ApIpStatus::Done)) = status {
info!("Wifi Status: {:?}", status);
} else {
bail!("Unexpected Wifi status: {:?}", status);
}
Ok(wifi)
}
/// Initilizes the web server and registers some handlers.
fn init_web_server(storage_lock: Arc<Mutex<CTStorage>>) -> anyhow::Result<EspHttpServer> {
let mut server = EspHttpServer::new(&Default::default())?;
server.handle_get("/", |_req, res| {
res.send_str(&templated_webpage("You should not be here."))?;
log::info!("Request handler done");
Ok(())
})?;
let handler_storage_lock = storage_lock.clone();
server.handle_get("/telemetry", move |_req, res| {
log::info!("Handling telemetry reqeuest.");
let mut writer = res.into_writer()?;
{
let mut ct_storage = match handler_storage_lock.lock() {
Ok(gaurd) => gaurd,
Err(poisoned) => poisoned.into_inner(),
};
ct_storage.send_readings_shards(&mut writer)?;
}
log::info!("Request handler done");
Ok(())
})?;
let handler_storage_lock = storage_lock.clone();
server.handle_get("/powerloss_log", move |_req, res| {
log::info!("Handling powerloss log reqeuest.");
let mut writer = res.into_writer()?;
{
let mut ct_storage = match handler_storage_lock.lock() {
Ok(gaurd) => gaurd,
Err(poisoned) => poisoned.into_inner(),
};
ct_storage.send_powerloss_log(&mut writer)?;
}
log::info!("Request handler done");
Ok(())
})?;
let handler_storage_lock = storage_lock.clone();
server.handle_post("/time", move |mut req, _res| {
log::info!("Handling time post request.");
let mut buf = [0_u8; std::mem::size_of::<u64>()];
let mut size = 0;
let mut reader = req.reader();
loop {
let n = reader.read(&mut buf[size..])?;
if n == 0 {
break;
}
size += n;
}
println!("Read {} bytes of data", size);
// Convert raw bytes to time. Store it and update system time.
let time = u64::from_le_bytes(buf);
{
let mut ct_storage = match handler_storage_lock.lock() {
Ok(gaurd) => gaurd,
Err(poisoned) => poisoned.into_inner(),
};
ct_storage.store_time(time)?;
println!("Response: {}", time);
}
set_system_time(time)?;
log::info!("Request handler done");
Ok(())
})?;
let handler_storage_lock = storage_lock.clone();
server.handle_post("/token", move |mut req, _res| {
log::info!("Handling token post request.");
let mut buf = [0_u8; ACCESS_TOKEN_SIZE];
let mut size = 0;
let mut reader = req.reader();
loop {
let n = reader.read(&mut buf[size..])?;
if n == 0 {
break;
}
size += n;
}
println!("Read {} bytes of data", size);
let token = buf;
// Store the given token in storage.
{
let mut ct_storage = match handler_storage_lock.lock() {
Ok(gaurd) => gaurd,
Err(poisoned) => poisoned.into_inner(),
};
ct_storage.store_token(&token)?;
println!("Response: {}", std::str::from_utf8(&token)?);
}
log::info!("Request handler done");
Ok(())
})?;
let handler_storage_lock = storage_lock.clone();
server.handle_get("/token", move |_req, res| {
log::info!("Handling token get request.");
{
let mut ct_storage = match handler_storage_lock.lock() {
Ok(gaurd) => gaurd,
Err(poisoned) => poisoned.into_inner(),
};
let token_buf = ct_storage.retrieve_token()?;
res.send_bytes(&token_buf)?;
log::info!("Sent token: {}", std::str::from_utf8(&token_buf)?);
}
log::info!("Request handler done");
Ok(())
})?;
let handler_storage_lock = storage_lock.clone();
server.handle_get("/reset", move |_req, _res| {
log::info!("Handling reset request.");
{
let mut ct_storage = match handler_storage_lock.lock() {
Ok(gaurd) => gaurd,
Err(poisoned) => poisoned.into_inner(),
};
ct_storage.reset_storage()?;
}
log::info!("Request handler done");
Ok(())
})?;
let handler_storage_lock = storage_lock.clone();
server.handle_post("/ota", move |mut req, mut res| {
log::info!("Handling ota post request.");
let version_str_wrapper = req.header("X-FIRMWARE-VERSION");
if let Some(version_str) = version_str_wrapper {
println!("found header {}", version_str);
if let Ok(version) = version_str.parse::<u32>() {
println!("found version {}", version);
if version > VERSION {
log::info!(
"version: {} is higher than internal VERSION: {}",
version,
VERSION
);
let reader = req.reader();
ota_update_from_reader(reader)?;
res.set_ok();
log::info!("Request handler done");
return Ok(());
}
}
}
res.set_status(400);
res.set_status_message("Bad Request");
log::info!("Request handler done");
Ok(())
})?;
let handler_storage_lock = storage_lock.clone();
server.handle_get("/version", move |_req, res| {
log::info!("Handling version get request.");
res.send_str(&VERSION.to_string())?;
log::info!("Sent version: {}", VERSION);
log::info!("Request handler done");
Ok(())
})?;
Ok(server)
}
fn templated_webpage(content: impl AsRef<str>) -> String {
format!(
r#"
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>esp-rs web server</title>
</head>
<body>
{}
</body>
</html>
"#,
content.as_ref()
)
}
/// Calculates the RMS value for a given slice of samples.
#[allow(dead_code)]
fn calc_rms(samples: &[f32], size: usize) -> f32 {
(samples[..size].iter().fold(0.0, |sum, &x| sum + (x * x)) / size as f32).sqrt()
}
fn now() -> Duration {
let mut tv_now: timeval = Default::default();
unsafe {
gettimeofday(&mut tv_now as *mut _, core::ptr::null_mut());
}
Duration::from_micros(tv_now.tv_sec as u64 * 1000000_u64 + tv_now.tv_usec as u64)
}
fn set_system_time(time_milis: u64) -> anyhow::Result<()> {
let mut tv_now: timeval = timeval {
tv_sec: (time_milis / 1000) as i32,
tv_usec: 0,
};
println!("settimeofday milis: {} sec: {}", time_milis, tv_now.tv_sec);
esp!(unsafe { settimeofday(&mut tv_now as *mut _, core::ptr::null_mut()) })?;
Ok(())
}