ocppsim 0.2.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
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
use super::super::types::{SecurityProfileFallback, SecurityReconnectPlan};
use super::super::{
  CertificateType, ConfigurationEntry, ConfigurationKey, ConnectorState,
  ConnectorStatus, OcppVersion, ResponseStatus, Result, Simulator, anyhow,
};
use crate::ocpp::is_valid_basic_auth_password;

const MAX_CERTIFICATE_CHAIN_SIZE: usize = 10_000;

impl Simulator {
  /// Updates a configuration value and applies key-specific side effects.
  pub(in crate::simulator) fn set_configuration_value(
    &mut self,
    key: ConfigurationKey,
    value: &str,
  ) -> ResponseStatus {
    let Some(entry) = self.configuration.get(&key) else {
      return ResponseStatus::NotSupported;
    };
    if entry.read_only {
      return ResponseStatus::Rejected;
    }

    if let Some(status) = self.set_heartbeat_configuration(key, value) {
      return status;
    }
    if let Some(status) = self.set_security_configuration(key, value) {
      return status;
    }

    self.update_configuration_value(key, value);
    ResponseStatus::Accepted
  }

  fn set_heartbeat_configuration(
    &mut self,
    key: ConfigurationKey,
    value: &str,
  ) -> Option<ResponseStatus> {
    if key != ConfigurationKey::HeartbeatInterval {
      return None;
    }
    let Some(seconds) = value.parse::<u64>().ok().filter(|item| *item > 0)
    else {
      return Some(ResponseStatus::Rejected);
    };
    self.update_configuration_value(key, value);
    if self.heartbeat.is_some() {
      self.start_heartbeat(seconds);
    }
    Some(ResponseStatus::Accepted)
  }

  fn set_security_configuration(
    &mut self,
    key: ConfigurationKey,
    value: &str,
  ) -> Option<ResponseStatus> {
    let status = match key {
      ConfigurationKey::AuthorizationKey
      | ConfigurationKey::BasicAuthPassword => {
        self.set_basic_auth_password(value)
      }
      ConfigurationKey::SecurityProfile => self.set_security_profile(value),
      ConfigurationKey::AdditionalRootCertificateCheck => {
        self.set_additional_root_certificate_check(value)
      }
      ConfigurationKey::CertificateSignedMaxChainSize
      | ConfigurationKey::MaxCertificateChainSize => {
        self.set_certificate_chain_size(value)
      }
      ConfigurationKey::CpoName | ConfigurationKey::OrganizationName => {
        self.set_security_organization_name(value)
      }
      ConfigurationKey::SupportedFileTransferProtocols => {
        self.set_supported_file_transfer_protocols(value)
      }
      ConfigurationKey::CertificateStoreMaxLength => ResponseStatus::Rejected,
      _ => return None,
    };
    Some(status)
  }

  fn set_basic_auth_password(&mut self, value: &str) -> ResponseStatus {
    if !is_valid_basic_auth_password(value) {
      return ResponseStatus::Rejected;
    }
    self.security.basic_auth_password = Some(value.to_string());
    for key in [
      ConfigurationKey::AuthorizationKey,
      ConfigurationKey::BasicAuthPassword,
    ] {
      if let Some(entry) = self.configuration.get_mut(&key) {
        entry.value.clear();
      }
    }
    self.record_security_event(
      "ReconfigurationOfSecurityParameters",
      Some("Basic authentication password changed".to_string()),
    );
    self.request_security_reconnect(SecurityProfileFallback::None);
    ResponseStatus::Accepted
  }

  fn set_security_profile(&mut self, value: &str) -> ResponseStatus {
    let Some(profile) = value.parse::<u8>().ok().filter(|item| *item <= 3)
    else {
      return ResponseStatus::Rejected;
    };
    let current = self.security.security_profile.unwrap_or(0);
    let allow_downgrade = self
      .configuration
      .get(&ConfigurationKey::AllowSecurityProfileDowngrade)
      .is_some_and(|entry| entry.value.eq_ignore_ascii_case("true"));
    if profile == current {
      return ResponseStatus::Rejected;
    }
    if profile < current
      && (self.config.protocol == OcppVersion::V1_6
        || !(allow_downgrade && current == 3 && profile == 2))
    {
      return ResponseStatus::Rejected;
    }
    if profile > current && !self.security_profile_prerequisites_met(profile) {
      return ResponseStatus::Rejected;
    }
    let previous_profile = self.security.security_profile;
    self.security.security_profile = (profile != 0).then_some(profile);
    self.config.security_profile = self.security.security_profile;
    self.update_configuration_value(ConfigurationKey::SecurityProfile, value);
    self.record_security_event(
      "ReconfigurationOfSecurityParameters",
      Some(format!("SecurityProfile changed to {profile}")),
    );
    self.request_security_reconnect(SecurityProfileFallback::Restore(
      previous_profile,
    ));
    ResponseStatus::Accepted
  }

  fn security_profile_prerequisites_met(&self, profile: u8) -> bool {
    if matches!(profile, 1 | 2)
      && !self
        .security
        .basic_auth_password
        .as_deref()
        .is_some_and(is_valid_basic_auth_password)
    {
      return false;
    }
    if matches!(profile, 2 | 3) && !self.has_central_system_root_certificate() {
      return false;
    }
    if profile == 3 && !self.has_charge_point_certificate() {
      return false;
    }
    true
  }

  fn has_central_system_root_certificate(&self) -> bool {
    self.config.ca_cert_path.is_some()
      || self.security.certificates.iter().any(|item| {
        CertificateType::parse(&item.certificate_type)
          .is_some_and(CertificateType::is_central_system_root)
      })
  }

  fn has_charge_point_certificate(&self) -> bool {
    self.config.client_cert_path.is_some()
      && self.config.client_key_path.is_some()
  }

  fn set_additional_root_certificate_check(
    &mut self,
    value: &str,
  ) -> ResponseStatus {
    let Some(enabled) = parse_bool(value) else {
      return ResponseStatus::Rejected;
    };
    self.security.additional_root_certificate_check = enabled;
    self.update_configuration_value(
      ConfigurationKey::AdditionalRootCertificateCheck,
      value,
    );
    ResponseStatus::Accepted
  }

  fn set_certificate_chain_size(&mut self, value: &str) -> ResponseStatus {
    let Some(size) = value
      .parse::<usize>()
      .ok()
      .filter(|item| (1..=MAX_CERTIFICATE_CHAIN_SIZE).contains(item))
    else {
      return ResponseStatus::Rejected;
    };
    self.security.certificate_signed_max_chain_size = size;
    self.update_configuration_value(
      ConfigurationKey::CertificateSignedMaxChainSize,
      value,
    );
    self.update_configuration_value(
      ConfigurationKey::MaxCertificateChainSize,
      value,
    );
    ResponseStatus::Accepted
  }

  fn request_security_reconnect(
    &mut self,
    fallback_security_profile: SecurityProfileFallback,
  ) {
    if self.connected {
      self.security.pending_reconnect = Some(SecurityReconnectPlan {
        fallback_security_profile,
      });
    }
  }

  fn set_security_organization_name(&mut self, value: &str) -> ResponseStatus {
    if value.is_empty() {
      return ResponseStatus::Rejected;
    }
    self.security.cpo_name = value.to_string();
    self.update_configuration_value(ConfigurationKey::CpoName, value);
    self.update_configuration_value(ConfigurationKey::OrganizationName, value);
    ResponseStatus::Accepted
  }

  fn set_supported_file_transfer_protocols(
    &mut self,
    value: &str,
  ) -> ResponseStatus {
    let protocols = value
      .split(',')
      .map(str::trim)
      .filter(|item| !item.is_empty())
      .map(str::to_ascii_uppercase)
      .collect::<Vec<_>>();
    if protocols.is_empty() {
      return ResponseStatus::Rejected;
    }
    self.security.supported_file_transfer_protocols = protocols;
    self.update_configuration_value(
      ConfigurationKey::SupportedFileTransferProtocols,
      value,
    );
    ResponseStatus::Accepted
  }

  fn update_configuration_value(&mut self, key: ConfigurationKey, value: &str) {
    if let Some(entry) = self.configuration.get_mut(&key) {
      entry.value = value.to_string();
    }
  }

  /// Finds a configuration entry by case-insensitive variable name.
  pub(in crate::simulator) fn configuration_entry(
    &self,
    variable: &str,
  ) -> Option<(ConfigurationKey, &ConfigurationEntry)> {
    let key = ConfigurationKey::parse(variable)?;
    if matches!(
      key,
      ConfigurationKey::AuthorizationKey | ConfigurationKey::BasicAuthPassword
    ) {
      return self
        .configuration
        .get_key_value(&key)
        .map(|(key, value)| (*key, value));
    }
    self
      .configuration
      .get_key_value(&key)
      .map(|(key, value)| (*key, value))
  }

  /// Finds the canonical configuration key for a variable name.
  pub(in crate::simulator) fn configuration_key(
    &self,
    variable: &str,
  ) -> Option<ConfigurationKey> {
    let key = ConfigurationKey::parse(variable)?;
    self.configuration.contains_key(&key).then_some(key)
  }

  /// Returns true when any active reservation targets this connector.
  pub(in crate::simulator) fn connector_has_reservation(
    &self,
    connector: u16,
  ) -> bool {
    self.reservations.values().any(|item| *item == connector)
  }

  /// Returns whether OCPP 1.6 remote starts must authorize before starting.
  pub(in crate::simulator) fn authorize_remote_tx_requests(&self) -> bool {
    self
      .configuration
      .get(&ConfigurationKey::AuthorizeRemoteTxRequests)
      .is_none_or(|entry| entry.value.eq_ignore_ascii_case("true"))
  }

  /// Finds the first connector currently eligible for a new transaction.
  pub(in crate::simulator) fn first_startable_connector(&self) -> Option<u16> {
    self.connectors.iter().find_map(|(connector, _)| {
      if self.validate_start_connector(*connector).is_ok() {
        Some(*connector)
      } else {
        None
      }
    })
  }

  /// Validates connector state before starting a transaction.
  pub(in crate::simulator) fn validate_start_connector(
    &self,
    connector: u16,
  ) -> Result<()> {
    let state = self
      .connectors
      .get(&connector)
      .ok_or_else(|| anyhow!("Connector {connector} does not exist."))?;
    if state.transaction.is_some() {
      return Err(anyhow!(
        "Connector {connector} already has an active transaction."
      ));
    }
    if self.connector_has_reservation(connector) {
      return Err(anyhow!("Connector {connector} is reserved."));
    }
    match state.status {
      ConnectorStatus::Available | ConnectorStatus::Preparing => Ok(()),
      other => Err(anyhow!(
        "Connector {} is not startable while {}.",
        connector,
        other.display()
      )),
    }
  }

  /// Applies an immediate availability state to one connector.
  pub(in crate::simulator) fn apply_availability_status(
    &mut self,
    connector: u16,
    target_status: ConnectorStatus,
  ) -> Result<()> {
    let has_reservation = self.connector_has_reservation(connector);
    let connector_state = self.connector_mut(connector)?;
    connector_state.scheduled_availability = None;
    connector_state.status =
      if target_status == ConnectorStatus::Available && has_reservation {
        ConnectorStatus::Reserved
      } else {
        target_status
      };
    Ok(())
  }

  /// Stores an availability state to apply after the current transaction.
  pub(in crate::simulator) fn schedule_availability_status(
    &mut self,
    connector: u16,
    target_status: ConnectorStatus,
  ) -> Result<()> {
    self.connector_mut(connector)?.scheduled_availability = Some(target_status);
    Ok(())
  }

  /// Returns connector status after a transaction is no longer active.
  pub(in crate::simulator) fn inactive_connector_status(
    &mut self,
    connector: u16,
    default_status: ConnectorStatus,
  ) -> Result<ConnectorStatus> {
    let has_reservation = self.connector_has_reservation(connector);
    let connector_state = self.connector_mut(connector)?;
    if let Some(status) = connector_state.scheduled_availability.take() {
      return Ok(status);
    }
    if has_reservation {
      return Ok(ConnectorStatus::Reserved);
    }
    Ok(default_status)
  }

  /// Increments the transaction sequence number for one active transaction.
  pub(in crate::simulator) fn bump_seq_no(
    &mut self,
    connector: u16,
    local_tx_id: u64,
  ) -> Result<()> {
    let connector_state = self.connector_mut(connector)?;
    let tx = connector_state.transaction.as_mut().ok_or_else(|| {
      anyhow!("No active transaction on connector {connector}.")
    })?;
    if tx.local_id != local_tx_id {
      return Err(anyhow!(
        "Transaction mismatch on connector {} (expected {}, got {}).",
        connector,
        local_tx_id,
        tx.local_id,
      ));
    }
    tx.seq_no = tx.seq_no.saturating_add(1);
    Ok(())
  }

  /// Stores the transaction id returned by OCPP 1.6 `StartTransaction`.
  pub(in crate::simulator) fn set_v1_6_transaction_id(
    &mut self,
    connector: u16,
    local_tx_id: u64,
    transaction_id: i64,
  ) -> Result<()> {
    let connector_state = self.connector_mut(connector)?;
    let tx = connector_state.transaction.as_mut().ok_or_else(|| {
      anyhow!("No active transaction on connector {connector}.")
    })?;
    if tx.local_id != local_tx_id {
      return Err(anyhow!(
        "Transaction mismatch on connector {} (expected {}, got {}).",
        connector,
        local_tx_id,
        tx.local_id,
      ));
    }
    tx.v1_6_transaction_id = Some(transaction_id);
    Ok(())
  }

  /// Rolls back local start state when start is rejected or fails.
  pub(in crate::simulator) fn cancel_transaction_start(
    &mut self,
    connector: u16,
    local_tx_id: u64,
  ) -> Result<()> {
    let should_cancel = self
      .connectors
      .get(&connector)
      .ok_or_else(|| anyhow!("Connector {connector} does not exist."))?
      .transaction
      .as_ref()
      .is_some_and(|tx| tx.local_id == local_tx_id);
    if should_cancel {
      let target_status = self
        .inactive_connector_status(connector, ConnectorStatus::Available)?;
      let connector_state = self.connector_mut(connector)?;
      connector_state.transaction = None;
      connector_state.status = target_status;
    }
    Ok(())
  }

  /// Completes a stop/end flow once the CSMS acknowledges the terminal event.
  pub(in crate::simulator) fn complete_transaction_stop(
    &mut self,
    connector: u16,
    local_tx_id: u64,
  ) -> Result<()> {
    let should_complete = self
      .connectors
      .get(&connector)
      .ok_or_else(|| anyhow!("Connector {connector} does not exist."))?
      .transaction
      .as_ref()
      .is_some_and(|tx| tx.local_id == local_tx_id);
    if !should_complete {
      return Ok(());
    }
    let target_status =
      self.inactive_connector_status(connector, ConnectorStatus::Finishing)?;
    let connector_state = self.connector_mut(connector)?;
    connector_state.transaction = None;
    connector_state.status = target_status;
    Ok(())
  }

  /// Restores the active status after a stop/end request fails or times out.
  pub(in crate::simulator) fn restore_active_transaction_status(
    &mut self,
    connector: u16,
    local_tx_id: u64,
  ) -> Result<()> {
    let protocol = self.config.protocol;
    let connector_state = self.connector_mut(connector)?;
    let Some(transaction) = connector_state.transaction.as_ref() else {
      return Ok(());
    };
    if transaction.local_id != local_tx_id {
      return Ok(());
    }
    connector_state.status = if protocol == OcppVersion::V1_6 {
      ConnectorStatus::Charging
    } else {
      ConnectorStatus::Occupied
    };
    Ok(())
  }

  /// Finds a connector by OCPP 1.6 transaction id or local fallback id.
  pub(in crate::simulator) fn find_v1_6_transaction(
    &self,
    transaction_id: i64,
  ) -> Option<u16> {
    self.connectors.iter().find_map(|(connector, state)| {
      state.transaction.as_ref().and_then(|tx| {
        if tx.v1_6_transaction_id == Some(transaction_id)
          || tx.local_id.cast_signed() == transaction_id
        {
          Some(*connector)
        } else {
          None
        }
      })
    })
  }

  /// Returns the active OCPP 2.x transaction id for one connector.
  pub(in crate::simulator) fn active_transaction_uid(
    &self,
    connector: u16,
  ) -> Option<String> {
    self.connectors.get(&connector).and_then(|state| {
      state
        .transaction
        .as_ref()
        .map(|tx| tx.transaction_uid.clone())
    })
  }

  /// Finds a connector by OCPP 2.x transaction id.
  pub(in crate::simulator) fn find_transaction_by_uid(
    &self,
    transaction_uid: &str,
  ) -> Option<u16> {
    self.connectors.iter().find_map(|(connector, state)| {
      state.transaction.as_ref().and_then(|tx| {
        if tx.transaction_uid == transaction_uid {
          Some(*connector)
        } else {
          None
        }
      })
    })
  }

  /// Returns a shared connector state or an error if connector is unknown.
  pub(in crate::simulator) fn connector_ref(
    &self,
    connector: u16,
  ) -> Result<&ConnectorState> {
    self
      .connectors
      .get(&connector)
      .ok_or_else(|| anyhow!("Connector {connector} does not exist."))
  }

  /// Returns a mutable connector state or an error if connector is unknown.
  pub(in crate::simulator) fn connector_mut(
    &mut self,
    connector: u16,
  ) -> Result<&mut ConnectorState> {
    self
      .connectors
      .get_mut(&connector)
      .ok_or_else(|| anyhow!("Connector {connector} does not exist."))
  }

  /// Sets the offered power limit for a connector.
  pub(in crate::simulator) fn set_offered_limit(
    &mut self,
    connector: u16,
    limit: Option<f64>,
  ) -> Result<()> {
    let state = self.connector_mut(connector)?;
    state.offered_limit = limit;
    Ok(())
  }

  /// Applies connector status transitions implied by charging profile
  /// enable/disable.
  pub(in crate::simulator) fn apply_charging_profile_state(
    &mut self,
    connector: u16,
  ) -> Result<()> {
    let Some(current) = self.connectors.get(&connector).map(|item| item.status)
    else {
      return Ok(());
    };
    let offered_limit = self
      .connectors
      .get(&connector)
      .and_then(|item| item.offered_limit);
    let has_active_tx = self
      .connectors
      .get(&connector)
      .and_then(|item| item.transaction.as_ref())
      .is_some();
    let target = if has_active_tx {
      if offered_limit.is_some_and(|limit| limit <= 0.0) {
        ConnectorStatus::SuspendedEvse
      } else if self.config.protocol == OcppVersion::V1_6 {
        ConnectorStatus::Charging
      } else {
        ConnectorStatus::Occupied
      }
    } else {
      match current {
        ConnectorStatus::Reserved
        | ConnectorStatus::Unavailable
        | ConnectorStatus::Faulted => current,
        _ => ConnectorStatus::Available,
      }
    };

    if target == current {
      return Ok(());
    }

    let state = self.connector_mut(connector)?;
    state.status = target;
    self.enqueue_status_notification(connector)?;
    self.emit_snapshot();
    Ok(())
  }
}

fn parse_bool(value: &str) -> Option<bool> {
  if value.eq_ignore_ascii_case("true") {
    Some(true)
  } else if value.eq_ignore_ascii_case("false") {
    Some(false)
  } else {
    None
  }
}