ocppsim 0.1.0

A terminal OCPP-J charge point simulator.
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
432
433
434
435
436
mod app;
mod args;
mod commands;
mod config;
mod embedded_schemas;
mod ocpp;
mod simulator;
mod version;

use std::backtrace::Backtrace;
use std::panic;
use std::process;
use std::thread;

use anyhow::Result;
use app::{InputAction, TerminalApp, TerminalSession, restore_console};
use args::{CliArgs, ResolvedCliArgs};
use clap::Parser;
use commands::{UserCommand, help_text, parse_command, standards_text};
use simulator::{SimulatorCommand, SimulatorConfig, run_simulator};
use tokio::sync::mpsc;
use version::version_string;

/// Runs the interactive OCPP simulator command-line application.
pub async fn run() -> Result<()> {
  install_panic_hook();
  install_rustls_provider();

  let cli = CliArgs::parse();
  let resolved = cli.resolve()?;
  let protocol = resolved.protocol;

  let (cmd_tx, cmd_rx) = mpsc::unbounded_channel::<SimulatorCommand>();
  let (ui_tx, mut ui_rx) = mpsc::unbounded_channel();

  let config = SimulatorConfig::from_resolved(&resolved);
  let simulator_task =
    tokio::spawn(run_simulator(config, cmd_rx, ui_tx, cmd_tx.clone()));

  let mut terminal = TerminalSession::new()?;
  let mut app = TerminalApp::new(protocol);
  if let Some(path) = resolved.log_path.as_ref() {
    app.enable_log_path(path)?;
    app.push_info(format!("Appending logs to {}", path.display()));
  }

  log_profile_source(&mut app, &resolved);
  app.push_info(format!(
    "Simulator ready: cp-id={} protocol={} connectors={}",
    resolved.cp_id,
    protocol.label(),
    resolved.connectors
  ));
  app.push_info(
    "Type `help` for commands. Type `connect` to open a CSMS connection.",
  );

  let mut should_exit = false;
  while !should_exit {
    while let Ok(event) = ui_rx.try_recv() {
      app.apply(event);
    }

    terminal.draw(&mut app)?;
    match terminal.poll_input(&mut app)? {
      InputAction::None => {}
      InputAction::ExitRequested => {
        should_exit = true;
      }
      InputAction::Submitted(line) => {
        if line.is_empty() {
          continue;
        }
        app.push_user_input(&line);

        match parse_command(&line) {
          Ok(command) => {
            should_exit =
              handle_user_command(command, protocol, &cmd_tx, &mut app);
          }
          Err(message) => {
            app.push_error(message);
          }
        }
      }
    }
  }

  let _ = cmd_tx.send(SimulatorCommand::Shutdown);
  let _ = simulator_task.await;
  Ok(())
}

/// Installs the `ring` rustls crypto provider for TLS WebSocket connections.
fn install_rustls_provider() {
  let _ = rustls::crypto::ring::default_provider().install_default();
}

/// Installs a process-wide panic hook that restores the terminal and prints
/// a structured panic report with a captured backtrace.
fn install_panic_hook() {
  panic::set_hook(Box::new(|info| {
    restore_console();

    let current_thread = thread::current();
    let thread_name = current_thread.name().unwrap_or("<unnamed>").to_string();
    let location = info
      .location()
      .map(|loc| format!("{}:{}:{}", loc.file(), loc.line(), loc.column()))
      .unwrap_or_else(|| "<unknown>".to_string());
    let message = panic_message(info);
    let backtrace = Backtrace::force_capture();

    eprintln!();
    eprintln!("==================================================");
    eprintln!("ocppsim panic");
    eprintln!("thread:   {}", thread_name);
    eprintln!("location: {}", location);
    eprintln!("message:  {}", message);
    eprintln!();
    eprintln!("backtrace:");
    eprintln!("{}", backtrace);
    eprintln!("==================================================");
    eprintln!();

    process::exit(101);
  }));
}

/// Extracts a human-readable panic message from panic payload metadata.
fn panic_message(info: &panic::PanicHookInfo<'_>) -> String {
  if let Some(value) = info.payload().downcast_ref::<&str>() {
    return (*value).to_string();
  }
  if let Some(value) = info.payload().downcast_ref::<String>() {
    return value.clone();
  }
  "<non-string panic payload>".to_string()
}

/// Logs which profile and config file were used, when profile mode is active.
fn log_profile_source(app: &mut TerminalApp, resolved: &ResolvedCliArgs) {
  let Some(profile) = &resolved.profile else {
    return;
  };
  let path = resolved
    .config_path
    .as_ref()
    .map(|item| item.display().to_string())
    .unwrap_or_else(|| "<unknown>".to_string());
  app.push_info(format!("Loaded profile `{}` from {}", profile, path));
}

/// Converts a parsed user command into simulator actions.
///
/// Returns `true` when the UI loop should exit, otherwise `false`.
fn handle_user_command(
  command: UserCommand,
  protocol: ocpp::OcppVersion,
  cmd_tx: &mpsc::UnboundedSender<SimulatorCommand>,
  app: &mut TerminalApp,
) -> bool {
  match command {
    UserCommand::Status => send_command(cmd_tx, SimulatorCommand::Status, app),
    UserCommand::Connect => {
      send_command(cmd_tx, SimulatorCommand::Connect, app)
    }
    UserCommand::Disconnect => {
      send_command(cmd_tx, SimulatorCommand::Disconnect, app)
    }
    UserCommand::Boot => send_command(cmd_tx, SimulatorCommand::Boot, app),
    UserCommand::Authorize { id_token } => {
      send_command(cmd_tx, SimulatorCommand::Authorize { id_token }, app)
    }
    UserCommand::DataTransfer {
      vendor_id,
      message_id,
      data,
    } => send_command(
      cmd_tx,
      SimulatorCommand::DataTransfer {
        vendor_id,
        message_id,
        data,
      },
      app,
    ),
    UserCommand::Start {
      connector,
      id_token,
    } => send_command(
      cmd_tx,
      SimulatorCommand::StartTransaction {
        connector,
        id_token,
      },
      app,
    ),
    UserCommand::Stop { connector, reason } => send_command(
      cmd_tx,
      SimulatorCommand::StopTransaction { connector, reason },
      app,
    ),
    UserCommand::SetConnectorStatus { connector, status } => send_command(
      cmd_tx,
      SimulatorCommand::SetConnectorStatus { connector, status },
      app,
    ),
    UserCommand::Meter {
      connector,
      value_wh,
    } => send_command(
      cmd_tx,
      SimulatorCommand::SetMeter {
        connector,
        value_wh,
      },
      app,
    ),
    UserCommand::SendMeter { connector } => {
      send_command(cmd_tx, SimulatorCommand::SendMeter { connector }, app)
    }
    UserCommand::Heartbeat => {
      send_command(cmd_tx, SimulatorCommand::Heartbeat, app)
    }
    UserCommand::HeartbeatStart { seconds } => {
      send_command(cmd_tx, SimulatorCommand::StartHeartbeat { seconds }, app)
    }
    UserCommand::HeartbeatStop => {
      send_command(cmd_tx, SimulatorCommand::StopHeartbeat, app)
    }
    UserCommand::Clear => {
      app.clear_logs();
      false
    }
    UserCommand::Standards => {
      app.push_info(standards_text(protocol));
      false
    }
    UserCommand::Help => {
      app.push_info(help_text());
      false
    }
    UserCommand::Exit => true,
  }
}

/// Sends a simulator command over the command channel.
///
/// Returns `true` when the simulator task is unavailable and the caller should
/// terminate the UI loop, otherwise `false`.
fn send_command(
  cmd_tx: &mpsc::UnboundedSender<SimulatorCommand>,
  command: SimulatorCommand,
  app: &mut TerminalApp,
) -> bool {
  if cmd_tx.send(command).is_err() {
    app.push_error("Simulator task is no longer running.");
    return true;
  }
  false
}

#[cfg(test)]
mod tests {
  use tokio::sync::mpsc;

  use super::*;

  #[test]
  /// Verifies parsed interactive commands dispatch to simulator commands.
  fn parsed_commands_dispatch_to_simulator_commands() {
    let protocol = ocpp::OcppVersion::V2_1;
    let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
    let mut app = TerminalApp::new(protocol);

    assert!(!dispatch("connect", protocol, &cmd_tx, &mut app));
    assert!(matches!(
      next_command(&mut cmd_rx),
      SimulatorCommand::Connect
    ));

    assert!(!dispatch("status", protocol, &cmd_tx, &mut app));
    assert!(matches!(
      next_command(&mut cmd_rx),
      SimulatorCommand::Status
    ));

    assert!(!dispatch("boot", protocol, &cmd_tx, &mut app));
    assert!(matches!(next_command(&mut cmd_rx), SimulatorCommand::Boot));

    assert!(!dispatch("authorize TOKEN", protocol, &cmd_tx, &mut app));
    match next_command(&mut cmd_rx) {
      SimulatorCommand::Authorize { id_token } => assert_eq!(id_token, "TOKEN"),
      other => panic!("unexpected command: {other:?}"),
    }

    assert!(!dispatch(
      "data-transfer vendor message hello world",
      protocol,
      &cmd_tx,
      &mut app,
    ));
    match next_command(&mut cmd_rx) {
      SimulatorCommand::DataTransfer {
        vendor_id,
        message_id,
        data,
      } => {
        assert_eq!(vendor_id, "vendor");
        assert_eq!(message_id.as_deref(), Some("message"));
        assert_eq!(data.as_deref(), Some("hello world"));
      }
      other => panic!("unexpected command: {other:?}"),
    }

    assert!(!dispatch("start 2 ID", protocol, &cmd_tx, &mut app));
    match next_command(&mut cmd_rx) {
      SimulatorCommand::StartTransaction {
        connector,
        id_token,
      } => {
        assert_eq!(connector, 2);
        assert_eq!(id_token, "ID");
      }
      other => panic!("unexpected command: {other:?}"),
    }

    assert!(!dispatch(
      "stop 2 EVDisconnected",
      protocol,
      &cmd_tx,
      &mut app,
    ));
    match next_command(&mut cmd_rx) {
      SimulatorCommand::StopTransaction { connector, reason } => {
        assert_eq!(connector, 2);
        assert_eq!(reason.as_deref(), Some("EVDisconnected"));
      }
      other => panic!("unexpected command: {other:?}"),
    }

    assert!(!dispatch("meter 2 1234", protocol, &cmd_tx, &mut app));
    match next_command(&mut cmd_rx) {
      SimulatorCommand::SetMeter {
        connector,
        value_wh,
      } => {
        assert_eq!(connector, 2);
        assert_eq!(value_wh, 1234);
      }
      other => panic!("unexpected command: {other:?}"),
    }

    assert!(!dispatch("send-meter 2", protocol, &cmd_tx, &mut app));
    match next_command(&mut cmd_rx) {
      SimulatorCommand::SendMeter { connector } => assert_eq!(connector, 2),
      other => panic!("unexpected command: {other:?}"),
    }

    assert!(!dispatch("heartbeat start 12", protocol, &cmd_tx, &mut app));
    match next_command(&mut cmd_rx) {
      SimulatorCommand::StartHeartbeat { seconds } => assert_eq!(seconds, 12),
      other => panic!("unexpected command: {other:?}"),
    }

    assert!(!dispatch("heartbeat", protocol, &cmd_tx, &mut app));
    assert!(matches!(
      next_command(&mut cmd_rx),
      SimulatorCommand::Heartbeat
    ));

    assert!(!dispatch("heartbeat stop", protocol, &cmd_tx, &mut app));
    assert!(matches!(
      next_command(&mut cmd_rx),
      SimulatorCommand::StopHeartbeat
    ));

    assert!(!dispatch(
      "connector-status 2 Faulted",
      protocol,
      &cmd_tx,
      &mut app,
    ));
    match next_command(&mut cmd_rx) {
      SimulatorCommand::SetConnectorStatus { connector, status } => {
        assert_eq!(connector, 2);
        assert_eq!(status, "Faulted");
      }
      other => panic!("unexpected command: {other:?}"),
    }

    assert!(!dispatch("disconnect", protocol, &cmd_tx, &mut app));
    assert!(matches!(
      next_command(&mut cmd_rx),
      SimulatorCommand::Disconnect
    ));
  }

  #[test]
  /// Verifies local UI commands do not enqueue simulator work.
  fn local_commands_do_not_dispatch_to_simulator() {
    let protocol = ocpp::OcppVersion::V2_1;
    let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel();
    let mut app = TerminalApp::new(protocol);

    assert!(!dispatch("help", protocol, &cmd_tx, &mut app));
    assert!(cmd_rx.try_recv().is_err());

    assert!(!dispatch("standards", protocol, &cmd_tx, &mut app));
    assert!(cmd_rx.try_recv().is_err());

    app.push_info("temporary log");
    assert!(!dispatch("clear", protocol, &cmd_tx, &mut app));
    assert!(cmd_rx.try_recv().is_err());

    assert!(dispatch("exit", protocol, &cmd_tx, &mut app));
    assert!(cmd_rx.try_recv().is_err());
  }

  fn dispatch(
    input: &str,
    protocol: ocpp::OcppVersion,
    cmd_tx: &mpsc::UnboundedSender<SimulatorCommand>,
    app: &mut TerminalApp,
  ) -> bool {
    let command = parse_command(input).expect("valid command");
    handle_user_command(command, protocol, cmd_tx, app)
  }

  fn next_command(
    cmd_rx: &mut mpsc::UnboundedReceiver<SimulatorCommand>,
  ) -> SimulatorCommand {
    cmd_rx.try_recv().expect("simulator command")
  }
}