blocksim 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
blocksim/avionics.py ADDED
@@ -0,0 +1,992 @@
1
+ """
2
+ Avionics data buses: ARINC 429 and MIL-STD-1553B.
3
+
4
+ Both protocols are deterministic and time-triggered, which is exactly the
5
+ shape blocksim's `DynamicClock` was built for: a clock whose handler picks
6
+ its own next tick, with the Scheduler re-reading the region boundary after
7
+ the handler runs. A bus schedule is then just a clock that walks itself.
8
+
9
+ WHAT IS MODELLED
10
+ The WORD/MESSAGE level with true timing: word and message durations
11
+ derived from the bit rate, response and inter-message gaps, transmit
12
+ schedules, transport latency, data staleness, bus utilisation and
13
+ frame overrun. Encoding is bit-accurate -- an ARINC 429 word is a real
14
+ 32-bit word with label, SDI, data, SSM and odd parity.
15
+
16
+ WHAT IS NOT
17
+ The physical layer. There are no Manchester or bipolar-RZ waveforms:
18
+ resolving 1 Mbit/s edges as continuous signals would pin the
19
+ integrator to sub-microsecond steps for no modelling gain. If you want
20
+ line coding and noise, that is signal-level work -- see `blocksim.comm`.
21
+
22
+ WHY THE TWO BUSES ARE WIRED DIFFERENTLY
23
+ ARINC 429 is physically point-to-point: ONE transmitter drives a
24
+ twisted pair that up to 20 receivers listen to. So the word travels
25
+ down a real blocksim connection, visible in `System.info()` and in the
26
+ generated diagram.
27
+
28
+ MIL-STD-1553 is a shared multi-drop bus with a bus controller and up
29
+ to 31 remote terminals, and any terminal may source data for any
30
+ other. Wiring that as point-to-point connections would need a
31
+ connection per (source, sink) pair and would misrepresent the medium.
32
+ Instead the terminals share a `MilStd1553Bus` object -- the medium
33
+ itself -- and blocksim connections carry only each terminal's own
34
+ engineering signals. The TIMING is simulated either way; what differs
35
+ is where the values travel.
36
+
37
+ TYPICAL USE
38
+ Put a real plant on one side and a controller on the other, and the
39
+ bus in between measures what it costs you: transport delay, sample
40
+ staleness, and what happens to the loop when the schedule is too full.
41
+ """
42
+
43
+ from dataclasses import dataclass, field
44
+ from typing import Optional
45
+
46
+ import numpy as np
47
+
48
+ from .core import Block, DynamicClock
49
+ from ._logging import get_logger
50
+
51
+ __all__ = [
52
+ "ARINC429_HIGH_SPEED",
53
+ "ARINC429_LOW_SPEED",
54
+ "Arinc429Label",
55
+ "Arinc429Receiver",
56
+ "Arinc429Transmitter",
57
+ "Arinc429Word",
58
+ "MilStd1553Bus",
59
+ "MilStd1553BusController",
60
+ "MilStd1553Message",
61
+ "MilStd1553RemoteTerminal",
62
+ "decode_arinc429",
63
+ "encode_arinc429_bcd",
64
+ "encode_arinc429_bnr",
65
+ "wire_arinc429",
66
+ "wire_1553",
67
+ ]
68
+
69
+ log = get_logger("avionics")
70
+
71
+ #: ARINC 429 high-speed bit rate in bit/s.
72
+ ARINC429_HIGH_SPEED = 100_000.0 # bit/s
73
+ #: ARINC 429 low-speed bit rate in bit/s.
74
+ ARINC429_LOW_SPEED = 12_500.0 # bit/s
75
+
76
+ ARINC429_WORD_BITS = 32
77
+ ARINC429_MIN_GAP_BITS = 4
78
+
79
+ _BNR_MAGNITUDE_BITS = 18
80
+
81
+
82
+ # ==========================================================================
83
+ # ARINC 429 word coding
84
+ #
85
+ # Bit numbering follows the standard, 1..32, so bit N is Python bit N-1:
86
+ #
87
+ # 1-8 label (octal), transmitted MSB-first while the rest of the word
88
+ # is LSB-first -- which is why the label byte appears REVERSED in
89
+ # a captured word. `label_reversed` controls that quirk.
90
+ # 9-10 SDI, source/destination identifier
91
+ # 11-28 BNR magnitude (18 bits) | BCD: five digits over bits 11-29
92
+ # 29 BNR sign (0 = +, 1 = -) |
93
+ # 30-31 SSM, sign/status matrix (3 = normal operation for BNR)
94
+ # 32 parity, ODD over the whole word
95
+ # ==========================================================================
96
+ def _reverse8(value: int) -> int:
97
+ return int(f"{value & 0xFF:08b}"[::-1], 2)
98
+
99
+
100
+ def _label_field(label: int, label_reversed: bool) -> int:
101
+ return _reverse8(label) if label_reversed else (label & 0xFF)
102
+
103
+
104
+ def _apply_odd_parity(word: int) -> int:
105
+ """Set bit 32 so the whole 32-bit word carries an odd number of ones."""
106
+ word &= 0x7FFF_FFFF
107
+ if bin(word).count("1") % 2 == 0:
108
+ word |= 1 << 31
109
+ return word
110
+
111
+
112
+ def encode_arinc429_bnr(
113
+ label: int,
114
+ value: float,
115
+ max_value: float,
116
+ sdi: int = 0,
117
+ ssm: int = 3,
118
+ label_reversed: bool = True,
119
+ ) -> int:
120
+ """Encode `value` as a BNR (binary) ARINC 429 word.
121
+
122
+ The 18-bit magnitude spans ``[0, max_value)``, so one LSB is
123
+ ``max_value / 2**18``. Values beyond full scale SATURATE, as the wire
124
+ format requires -- they cannot wrap.
125
+ """
126
+ if max_value <= 0:
127
+ raise ValueError("max_value must be positive")
128
+ full_scale = 1 << _BNR_MAGNITUDE_BITS
129
+ magnitude = int(round(abs(value) * full_scale / max_value))
130
+ magnitude = min(magnitude, full_scale - 1)
131
+
132
+ word = _label_field(label, label_reversed)
133
+ word |= (sdi & 0x3) << 8
134
+ word |= magnitude << 10
135
+ word |= (1 if value < 0 else 0) << 28
136
+ word |= (ssm & 0x3) << 29
137
+ return _apply_odd_parity(word)
138
+
139
+
140
+ def encode_arinc429_bcd(
141
+ label: int,
142
+ value: float,
143
+ sdi: int = 0,
144
+ label_reversed: bool = True,
145
+ ) -> int:
146
+ """Encode `value` as a BCD ARINC 429 word (five digits, bits 11-29).
147
+
148
+ The most significant digit is only 3 bits wide (0-7), as in the
149
+ standard. The sign goes into the SSM: 0 for plus, 3 for minus.
150
+ """
151
+ magnitude = min(int(round(abs(value))), 79999)
152
+ digits = [(magnitude // 10**i) % 10 for i in range(5)]
153
+
154
+ word = _label_field(label, label_reversed)
155
+ word |= (sdi & 0x3) << 8
156
+ for i, shift in enumerate((10, 14, 18, 22)): # four 4-bit digits
157
+ word |= digits[i] << shift
158
+ word |= (digits[4] & 0x7) << 26 # MSD, 3 bits
159
+ word |= (3 if value < 0 else 0) << 29
160
+ return _apply_odd_parity(word)
161
+
162
+
163
+ @dataclass
164
+ class Arinc429Word:
165
+ """A decoded ARINC 429 word. See :func:`decode_arinc429`."""
166
+
167
+ raw: int
168
+ label: int
169
+ sdi: int
170
+ ssm: int
171
+ parity_ok: bool
172
+
173
+ @property
174
+ def label_octal(self) -> str:
175
+ return f"{self.label:03o}"
176
+
177
+ def bnr_value(self, max_value: float) -> float:
178
+ """The BNR engineering value, given the label's full scale."""
179
+ magnitude = (self.raw >> 10) & 0x3_FFFF
180
+ sign = -1.0 if (self.raw >> 28) & 0x1 else 1.0
181
+ return sign * magnitude * max_value / (1 << _BNR_MAGNITUDE_BITS)
182
+
183
+ def bcd_value(self) -> float:
184
+ """The BCD engineering value; the SSM carries the sign."""
185
+ digits = [(self.raw >> shift) & 0xF for shift in (10, 14, 18, 22)]
186
+ digits.append((self.raw >> 26) & 0x7)
187
+ magnitude = sum(d * 10**i for i, d in enumerate(digits))
188
+ return -float(magnitude) if self.ssm == 3 else float(magnitude)
189
+
190
+ @property
191
+ def is_normal_operation(self) -> bool:
192
+ """BNR SSM = 3 means the source vouches for the data."""
193
+ return self.ssm == 3
194
+
195
+
196
+ def decode_arinc429(raw: int, label_reversed: bool = True) -> Arinc429Word:
197
+ """Split a raw 32-bit word into its fields and check the odd parity."""
198
+ raw = int(raw) & 0xFFFF_FFFF
199
+ label = raw & 0xFF
200
+ return Arinc429Word(
201
+ raw=raw,
202
+ label=_reverse8(label) if label_reversed else label,
203
+ sdi=(raw >> 8) & 0x3,
204
+ ssm=(raw >> 29) & 0x3,
205
+ parity_ok=bin(raw).count("1") % 2 == 1,
206
+ )
207
+
208
+
209
+ # ==========================================================================
210
+ # ARINC 429 blocks
211
+ # ==========================================================================
212
+ @dataclass
213
+ class Arinc429Label:
214
+ """One label a transmitter puts on the wire, and how often.
215
+
216
+ `rate_hz` is the nominal refresh rate. The transmitter serialises all
217
+ of its labels onto the single wire, so the achievable rate is bounded
218
+ by the bit rate; :meth:`Arinc429Transmitter.scheduled_utilisation` reports how
219
+ close to that bound the configured set actually is.
220
+ """
221
+
222
+ label: int
223
+ rate_hz: float
224
+ encoding: str = "bnr" # "bnr" or "bcd"
225
+ max_value: float = 1.0 # BNR full scale (ignored for BCD)
226
+ sdi: int = 0
227
+ ssm: int = 3
228
+ name: Optional[str] = None
229
+
230
+ def __post_init__(self):
231
+ if self.encoding not in ("bnr", "bcd"):
232
+ raise ValueError(f"unknown encoding {self.encoding!r}; use bnr or bcd")
233
+ if self.rate_hz <= 0:
234
+ raise ValueError(f"label {self.label:03o}: rate_hz must be positive")
235
+ if self.name is None:
236
+ self.name = f"L{self.label:03o}"
237
+
238
+ def encode(self, value: float) -> int:
239
+ if self.encoding == "bnr":
240
+ return encode_arinc429_bnr(
241
+ self.label, value, self.max_value, self.sdi, self.ssm
242
+ )
243
+ return encode_arinc429_bcd(self.label, value, self.sdi)
244
+
245
+
246
+ class Arinc429Transmitter(Block):
247
+ """An ARINC 429 line driver with one input per label and one wire output.
248
+
249
+ Labels are interleaved in rate order. A word occupies 32 bit times followed
250
+ by at least four gap bit times. At 100 kbit/s, each word therefore consumes
251
+ at least 360 microseconds, allowing approximately 2777 words per second.
252
+
253
+ The start clock latches an input and begins transmission. The done clock
254
+ fires 32 bit times later, when a receiver can use the completed word.
255
+ Receivers bind to the done clock; see :func:`wire_arinc429`.
256
+
257
+ Inputs are engineering values in label order. Outputs are:
258
+
259
+ * Port 0: the 32-bit word, represented exactly as a float.
260
+ * Port 1: its label in decimal.
261
+ * Port 2: busy flag, one during transmission and zero in a gap.
262
+ """
263
+
264
+ WORD, LABEL, BUSY = 0, 1, 2
265
+
266
+ def __init__(
267
+ self,
268
+ labels,
269
+ speed: str = "high",
270
+ bitrate_bps: Optional[float] = None,
271
+ gap_bits: int = ARINC429_MIN_GAP_BITS,
272
+ name: Optional[str] = None,
273
+ ):
274
+ self.labels = list(labels)
275
+ if not self.labels:
276
+ raise ValueError("a transmitter needs at least one label")
277
+ if bitrate_bps is None:
278
+ if speed not in ("high", "low"):
279
+ raise ValueError(f"speed must be 'high' or 'low', got {speed!r}")
280
+ bitrate_bps = ARINC429_HIGH_SPEED if speed == "high" else ARINC429_LOW_SPEED
281
+ self.bitrate_bps = float(bitrate_bps)
282
+ if gap_bits < ARINC429_MIN_GAP_BITS:
283
+ raise ValueError(
284
+ f"the standard requires at least {ARINC429_MIN_GAP_BITS} bit "
285
+ f"times between words, got {gap_bits}"
286
+ )
287
+ self.word_time = ARINC429_WORD_BITS / self.bitrate_bps
288
+ self.gap_time = gap_bits / self.bitrate_bps
289
+ self.slot_time = self.word_time + self.gap_time
290
+
291
+ super().__init__(
292
+ num_inputs=len(self.labels),
293
+ num_outputs=3,
294
+ name=name,
295
+ inputs=[(lab.name, None) for lab in self.labels],
296
+ outputs=[("word", None), ("label", None), ("busy", None)],
297
+ )
298
+
299
+ # a word starts here, and finishes one word time later
300
+ self.start_clock = DynamicClock(
301
+ first_tick=0.0, handler=self._begin_word, name=f"{self.name}_tx"
302
+ )
303
+ self.done_clock = DynamicClock(name=f"{self.name}_rx")
304
+ self.start_clock.bind(self)
305
+ # so System.add() registers the transmit clock on its own; the
306
+ # completion clock is added by wire_arinc429()
307
+ self.clock = self.start_clock
308
+
309
+ self._reset()
310
+
311
+ # ---- runtime state -----------------------------------------------------
312
+ def _reset(self):
313
+ self.current_word = 0
314
+ self.current_label = 0
315
+ self.words_sent = 0
316
+ self.busy_time = 0.0
317
+ self.max_lateness = 0.0 # worst delay past a label's due time
318
+ self._next_due = np.zeros(len(self.labels))
319
+ self._pending = np.zeros(len(self.labels))
320
+ self._word_end = -np.inf
321
+
322
+ def initialize(self):
323
+ super().initialize()
324
+ self._reset()
325
+ self.start_clock.schedule(0.0)
326
+
327
+ # ---- transmit scheduling ----------------------------------------------
328
+ def update(self, t, u):
329
+ """Latch the value of whichever label is due; called at word start."""
330
+ self._pending = np.asarray(u, dtype=float).copy()
331
+
332
+ def _begin_word(self, t):
333
+ """Pick the most overdue label, put its word on the wire, and
334
+ schedule both the end of this word and the next word start."""
335
+ index = self._select_label(t)
336
+ if index is None: # nothing due yet: idle until the earliest one is
337
+ self.start_clock.schedule(float(np.min(self._next_due)))
338
+ return
339
+
340
+ spec = self.labels[index]
341
+ self.max_lateness = max(self.max_lateness, t - self._next_due[index])
342
+ self.current_word = spec.encode(float(self._pending[index]))
343
+ self.current_label = spec.label
344
+ self.words_sent += 1
345
+ self.busy_time += self.word_time
346
+ self._word_end = t + self.word_time
347
+
348
+ period = 1.0 / spec.rate_hz
349
+ # keep the nominal cadence rather than drifting off the last
350
+ # transmission; a label that could not be served on time is late,
351
+ # not re-phased
352
+ self._next_due[index] = max(self._next_due[index] + period, t + self.word_time)
353
+
354
+ self.done_clock.schedule(self._word_end)
355
+ self.start_clock.schedule(t + self.slot_time)
356
+ log.debug(
357
+ "%s: label %03o at t=%.6f (word 0x%08X)",
358
+ self.name,
359
+ spec.label,
360
+ t,
361
+ self.current_word,
362
+ )
363
+
364
+ def _select_label(self, t):
365
+ """The label furthest past its due time; None if none is due."""
366
+ index = int(np.argmin(self._next_due))
367
+ return index if self._next_due[index] - t <= 1e-12 else None
368
+
369
+ def output(self, t):
370
+ busy = 1.0 if t < self._word_end else 0.0
371
+ return np.array([float(self.current_word), float(self.current_label), busy])
372
+
373
+ # ---- reporting ---------------------------------------------------------
374
+ @property
375
+ def scheduled_utilisation(self) -> float:
376
+ """Fraction of the line the configured labels ask for.
377
+
378
+ Above 1.0 the set cannot fit and labels will be transmitted late,
379
+ whatever the requested rates -- worth checking before a run.
380
+ """
381
+ return sum(lab.rate_hz for lab in self.labels) * self.slot_time
382
+
383
+ def measured_utilisation(self, t_final: float) -> float:
384
+ """Fraction of ``[0, t_final]`` actually spent clocking out words."""
385
+ return self.busy_time / t_final if t_final > 0 else 0.0
386
+
387
+
388
+ class Arinc429Receiver(Block):
389
+ """An ARINC 429 line receiver: decodes the labels it subscribes to.
390
+
391
+ It samples the wire when the transmitter finishes a word (it is bound
392
+ to the transmitter's `done_clock`), decodes it, and holds the value
393
+ until that label is refreshed -- so the output is a genuine
394
+ zero-order hold at the label's refresh rate, with the word's
395
+ transmission time as transport delay.
396
+
397
+ Words whose parity fails, or whose SSM is not "normal operation" when
398
+ `require_normal_ssm` is set, are counted and DISCARDED: the held value
399
+ goes stale rather than being corrupted, which is what a real receiver
400
+ does.
401
+
402
+ Outputs
403
+ ``value_<label>`` per subscribed label (held), then
404
+ ``age_<label>`` seconds since that label was last refreshed.
405
+ """
406
+
407
+ def __init__(
408
+ self,
409
+ labels,
410
+ initial_values=None,
411
+ require_normal_ssm: bool = True,
412
+ label_reversed: bool = True,
413
+ name: Optional[str] = None,
414
+ ):
415
+ self.subscriptions = [
416
+ lab if isinstance(lab, Arinc429Label) else Arinc429Label(lab, rate_hz=1.0)
417
+ for lab in labels
418
+ ]
419
+ if not self.subscriptions:
420
+ raise ValueError("a receiver needs at least one label")
421
+ self.require_normal_ssm = bool(require_normal_ssm)
422
+ self.label_reversed = bool(label_reversed)
423
+ self._index_of = {spec.label: i for i, spec in enumerate(self.subscriptions)}
424
+
425
+ n = len(self.subscriptions)
426
+ super().__init__(
427
+ num_inputs=1,
428
+ num_outputs=2 * n,
429
+ name=name,
430
+ inputs=[("word", None)],
431
+ outputs=(
432
+ [(f"value_{s.name}", None) for s in self.subscriptions]
433
+ + [(f"age_{s.name}", "s") for s in self.subscriptions]
434
+ ),
435
+ )
436
+ self.initial_values = (
437
+ np.zeros(n)
438
+ if initial_values is None
439
+ else np.atleast_1d(np.asarray(initial_values, dtype=float))
440
+ )
441
+ if self.initial_values.size != n:
442
+ raise ValueError(
443
+ f"initial_values has {self.initial_values.size} entries, "
444
+ f"but {n} labels are subscribed"
445
+ )
446
+ self._reset()
447
+
448
+ def _reset(self):
449
+ self.values = self.initial_values.copy()
450
+ self.last_rx = np.zeros(len(self.subscriptions))
451
+ self.words_accepted = 0
452
+ self.parity_errors = 0
453
+ self.rejected_ssm = 0
454
+ self._last_raw = None
455
+
456
+ def initialize(self):
457
+ super().initialize()
458
+ self._reset()
459
+
460
+ def update(self, t, u):
461
+ """Called when the transmitter finishes clocking out a word."""
462
+ raw = int(round(float(u[0])))
463
+ if raw == 0:
464
+ return # idle line
465
+ word = decode_arinc429(raw, self.label_reversed)
466
+ index = self._index_of.get(word.label)
467
+ if index is None:
468
+ return # not a label this receiver listens to
469
+ if not word.parity_ok:
470
+ self.parity_errors += 1
471
+ return
472
+ if self.require_normal_ssm and not word.is_normal_operation:
473
+ self.rejected_ssm += 1
474
+ return
475
+
476
+ spec = self.subscriptions[index]
477
+ self.values[index] = (
478
+ word.bnr_value(spec.max_value)
479
+ if spec.encoding == "bnr"
480
+ else word.bcd_value()
481
+ )
482
+ self.last_rx[index] = t
483
+ self.words_accepted += 1
484
+
485
+ def output(self, t):
486
+ # age before the first reception is simply the elapsed time
487
+ return np.concatenate([self.values, t - self.last_rx])
488
+
489
+
490
+ def wire_arinc429(system, transmitter: Arinc429Transmitter, *receivers):
491
+ """Put `receivers` on `transmitter`'s wire, with the right timing.
492
+
493
+ Two things are needed and it is easy to do only one of them: the
494
+ connection carrying the word, and the binding that makes a receiver
495
+ sample when the word FINISHES rather than when it starts.
496
+ """
497
+ system.add_clock(transmitter.start_clock)
498
+ system.add_clock(transmitter.done_clock)
499
+ for rx in receivers:
500
+ system.connect(transmitter, Arinc429Transmitter.WORD, rx, 0)
501
+ transmitter.done_clock.bind(rx)
502
+ return transmitter
503
+
504
+
505
+ # ==========================================================================
506
+ # MIL-STD-1553B
507
+ # ==========================================================================
508
+ MILSTD1553_BITRATE = 1_000_000.0 # bit/s
509
+ MILSTD1553_WORD_BITS = 20 # 3 sync + 16 data + 1 parity
510
+
511
+
512
+ @dataclass
513
+ class MilStd1553Message:
514
+ """One transfer in the bus controller's schedule.
515
+
516
+ direction
517
+ ``"BC2RT"``, ``"RT2BC"`` or ``"RT2RT"``.
518
+ rt, subaddress, word_count
519
+ The addressed terminal, its subaddress, and how many 16-bit data
520
+ words move (1..32).
521
+ rate_hz
522
+ How often the message runs. The bus controller turns this into a
523
+ slot in the minor/major frame structure.
524
+ rt_dest, subaddress_dest
525
+ The receiving terminal for ``RT2RT``.
526
+ """
527
+
528
+ direction: str
529
+ rt: int
530
+ subaddress: int
531
+ word_count: int
532
+ rate_hz: float
533
+ rt_dest: Optional[int] = None
534
+ subaddress_dest: Optional[int] = None
535
+ name: Optional[str] = None
536
+ # filled in by the bus controller when it builds the frame
537
+ period_frames: int = field(default=1, init=False)
538
+ phase: int = field(default=0, init=False)
539
+
540
+ def __post_init__(self):
541
+ if self.direction not in ("BC2RT", "RT2BC", "RT2RT"):
542
+ raise ValueError(
543
+ f"direction must be BC2RT, RT2BC or RT2RT, got {self.direction!r}"
544
+ )
545
+ if not 1 <= self.word_count <= 32:
546
+ raise ValueError("word_count must be between 1 and 32")
547
+ if not 0 <= self.rt <= 31:
548
+ raise ValueError("rt must be a 5-bit terminal address (0..31)")
549
+ if self.direction == "RT2RT" and self.rt_dest is None:
550
+ raise ValueError("an RT2RT message needs rt_dest")
551
+ if self.subaddress_dest is None:
552
+ self.subaddress_dest = self.subaddress
553
+ if self.name is None:
554
+ self.name = f"{self.direction}_RT{self.rt}SA{self.subaddress}"
555
+
556
+ def duration(self, word_time: float, response_time: float) -> float:
557
+ """Return bus occupation time, excluding the gap.
558
+
559
+ * BC2RT: command and N data words, followed by the RT status.
560
+ * RT2BC: command, followed by RT status and N data words.
561
+ * RT2RT: receive and transmit commands, source RT status and N data
562
+ words, followed by the receiving RT status.
563
+ """
564
+ if self.direction == "BC2RT":
565
+ words = 1 + self.word_count + 1
566
+ responses = 1
567
+ elif self.direction == "RT2BC":
568
+ words = 1 + 1 + self.word_count
569
+ responses = 1
570
+ else: # RT2RT
571
+ words = 2 + 1 + self.word_count + 1
572
+ responses = 2
573
+ return words * word_time + responses * response_time
574
+
575
+
576
+ class MilStd1553Bus:
577
+ """The shared medium: timing constants and the data words in flight.
578
+
579
+ 1553 is multi-drop, so values are exchanged THROUGH this object rather
580
+ than over point-to-point blocksim connections -- see the module
581
+ docstring. Terminals read and write buffers keyed by
582
+ ``(rt, subaddress)``.
583
+ """
584
+
585
+ def __init__(
586
+ self,
587
+ bitrate_bps: float = MILSTD1553_BITRATE,
588
+ response_time: float = 8e-6,
589
+ gap: float = 4e-6,
590
+ ):
591
+ if not 4e-6 <= response_time <= 12e-6:
592
+ raise ValueError(
593
+ "the standard allows an RT response time of 4..12 us, "
594
+ f"got {response_time * 1e6:.1f} us"
595
+ )
596
+ if gap < 4e-6:
597
+ raise ValueError("the inter-message gap must be at least 4 us")
598
+ self.bitrate_bps = float(bitrate_bps)
599
+ self.word_time = MILSTD1553_WORD_BITS / self.bitrate_bps
600
+ self.response_time = float(response_time)
601
+ self.gap = float(gap)
602
+ self.buffers = {}
603
+
604
+ def put(self, rt, subaddress, values):
605
+ self.buffers[(rt, subaddress)] = np.asarray(values, dtype=float).copy()
606
+
607
+ def get(self, rt, subaddress, word_count):
608
+ buf = self.buffers.get((rt, subaddress))
609
+ if buf is None:
610
+ return np.zeros(word_count)
611
+ return buf[:word_count]
612
+
613
+ def clear(self):
614
+ self.buffers.clear()
615
+
616
+
617
+ class MilStd1553BusController(Block):
618
+ """The bus controller: it owns the schedule and drives the bus.
619
+
620
+ Messages are placed in a minor/major frame structure built from their
621
+ rates: a message at `rate_hz` runs every ``minor_frame_hz / rate_hz``
622
+ minor frames, and messages sharing a period are spread across
623
+ different frames so the load is balanced rather than piled into
624
+ frame 0.
625
+
626
+ Each minor frame the controller walks its message list, occupying the
627
+ bus for each message's real duration and leaving the inter-message
628
+ gap. If the list does not fit in the frame, the overshoot is counted
629
+ in ``overruns`` and reported -- which is the question a schedule
630
+ simulation is usually asked to answer.
631
+
632
+ Inputs
633
+ the data words the CONTROLLER sources, i.e. the concatenated
634
+ `word_count` of every BC2RT message, in schedule order.
635
+ Outputs
636
+ 0 ``busy`` 1 while a message is on the bus
637
+ 1 ``frame`` minor frame index
638
+ 2 ``utilisation`` busy fraction of the last completed frame
639
+ 3 ``overruns`` running count of frames that did not fit
640
+ then the data words the controller RECEIVES, i.e. the concatenated
641
+ `word_count` of every RT2BC message, in schedule order.
642
+ """
643
+
644
+ BUSY, FRAME, UTILISATION, OVERRUNS = 0, 1, 2, 3
645
+ _N_STATUS = 4
646
+
647
+ def __init__(
648
+ self,
649
+ bus: MilStd1553Bus,
650
+ messages,
651
+ minor_frame_hz: float = 50.0,
652
+ name: Optional[str] = None,
653
+ ):
654
+ self.bus = bus
655
+ self.messages = list(messages)
656
+ if not self.messages:
657
+ raise ValueError("a bus controller needs at least one message")
658
+ self.minor_frame_hz = float(minor_frame_hz)
659
+ self.frame_time = 1.0 / self.minor_frame_hz
660
+ self._build_frame_schedule()
661
+
662
+ self._tx = [m for m in self.messages if m.direction == "BC2RT"]
663
+ self._rx = [m for m in self.messages if m.direction == "RT2BC"]
664
+ self._tx_slice, n_in = _port_slices(self._tx)
665
+ self._rx_slice, n_out = _port_slices(self._rx)
666
+
667
+ super().__init__(
668
+ num_inputs=n_in,
669
+ num_outputs=self._N_STATUS + n_out,
670
+ name=name,
671
+ inputs=_port_names(self._tx),
672
+ outputs=(
673
+ [
674
+ ("busy", None),
675
+ ("frame", None),
676
+ ("utilisation", None),
677
+ ("overruns", None),
678
+ ]
679
+ + _port_names(self._rx)
680
+ ),
681
+ )
682
+
683
+ self.start_clock = DynamicClock(
684
+ first_tick=0.0, handler=self._begin_message, name=f"{self.name}_bc"
685
+ )
686
+ self.done_clock = DynamicClock(
687
+ handler=self._end_message, name=f"{self.name}_done"
688
+ )
689
+ self.start_clock.bind(self)
690
+ self.done_clock.bind(self)
691
+ self.clock = self.start_clock
692
+ self.terminals = {} # address -> MilStd1553RemoteTerminal
693
+ self._reset()
694
+
695
+ # ---- frame construction ------------------------------------------------
696
+ def _build_frame_schedule(self):
697
+ """Assign each message a period in minor frames and a phase."""
698
+ used_by_period = {}
699
+ for msg in self.messages:
700
+ if msg.rate_hz > self.minor_frame_hz + 1e-9:
701
+ raise ValueError(
702
+ f"{msg.name} asks for {msg.rate_hz} Hz but the minor frame "
703
+ f"runs at {self.minor_frame_hz} Hz -- raise minor_frame_hz"
704
+ )
705
+ period = max(1, int(round(self.minor_frame_hz / msg.rate_hz)))
706
+ msg.period_frames = period
707
+ # spread same-period messages over distinct frames
708
+ msg.phase = used_by_period.get(period, 0) % period
709
+ used_by_period[period] = used_by_period.get(period, 0) + 1
710
+ self.major_frame_frames = int(
711
+ np.lcm.reduce([m.period_frames for m in self.messages])
712
+ )
713
+
714
+ def messages_in_frame(self, frame_index: int):
715
+ return [
716
+ m
717
+ for m in self.messages
718
+ if frame_index % m.period_frames == m.phase % m.period_frames
719
+ ]
720
+
721
+ def frame_duration(self, frame_index: int) -> float:
722
+ """Bus time the given minor frame needs, gaps included."""
723
+ return sum(
724
+ m.duration(self.bus.word_time, self.bus.response_time) + self.bus.gap
725
+ for m in self.messages_in_frame(frame_index)
726
+ )
727
+
728
+ @property
729
+ def worst_frame_utilisation(self) -> float:
730
+ """Utilisation of the fullest minor frame in the major frame.
731
+
732
+ Above 1.0 the schedule cannot be met -- check this before running.
733
+ """
734
+ return max(
735
+ self.frame_duration(k) / self.frame_time
736
+ for k in range(self.major_frame_frames)
737
+ )
738
+
739
+ # ---- runtime -----------------------------------------------------------
740
+ #
741
+ # All bus transfers happen in the two clock HANDLERS, never in update().
742
+ # The simulator runs update() on every block bound to a clock BEFORE it
743
+ # calls that clock's handlers, so update() is where each terminal takes
744
+ # a snapshot of its live inputs, and the handlers -- which run once the
745
+ # snapshots are fresh -- are where data actually moves.
746
+ def _reset(self):
747
+ self.frame_index = 0
748
+ self.overruns = 0
749
+ self.dropped_messages = 0
750
+ self.messages_sent = 0
751
+ self.bus.clear()
752
+ self.active = None
753
+ self._busy_this_frame = 0.0
754
+ self.last_utilisation = 0.0
755
+ self._message_end = -np.inf
756
+ self._frame_start = 0.0
757
+ self._queue = list(self.messages_in_frame(0))
758
+ self.snapshot = np.zeros(self.num_inputs)
759
+ self.received = np.zeros(self.num_outputs - self._N_STATUS)
760
+
761
+ def initialize(self):
762
+ super().initialize()
763
+ self._reset()
764
+ self.start_clock.schedule(0.0)
765
+
766
+ def attach(self, terminal):
767
+ """Register a remote terminal and put it on the bus timing."""
768
+ if terminal.address in self.terminals:
769
+ raise ValueError(f"RT address {terminal.address} is already taken")
770
+ self.terminals[terminal.address] = terminal
771
+ self.start_clock.bind(terminal)
772
+ self.done_clock.bind(terminal)
773
+ terminal.controller = self
774
+ return terminal
775
+
776
+ def update(self, t, u):
777
+ """Snapshot the words this controller sources. No bus access here."""
778
+ self.snapshot = np.asarray(u, dtype=float).copy()
779
+
780
+ def _begin_message(self, t):
781
+ """Put the next message on the bus, or wait for the frame boundary."""
782
+ if t >= self._frame_start + self.frame_time - 1e-12:
783
+ if self._queue: # the frame ran out of time before its list did
784
+ self.overruns += 1
785
+ self.dropped_messages += len(self._queue)
786
+ log.debug(
787
+ "%s: frame %d overran, %d message(s) dropped",
788
+ self.name,
789
+ self.frame_index,
790
+ len(self._queue),
791
+ )
792
+ self._close_frame()
793
+ self._open_frame()
794
+
795
+ if not self._queue: # an empty frame: idle until the next one
796
+ self.start_clock.schedule(self._frame_start + self.frame_time)
797
+ return
798
+
799
+ msg = self._queue.pop(0)
800
+ self._source(msg)
801
+
802
+ duration = msg.duration(self.bus.word_time, self.bus.response_time)
803
+ self.active = msg
804
+ self.messages_sent += 1
805
+ self._busy_this_frame += duration
806
+ self._message_end = t + duration
807
+
808
+ self.done_clock.schedule(self._message_end)
809
+ self.start_clock.schedule(self._message_end + self.bus.gap)
810
+ log.debug("%s: %s at t=%.6f (%.1f us)", self.name, msg.name, t, duration * 1e6)
811
+
812
+ def _end_message(self, t):
813
+ """The message is off the bus: hand the words to whoever receives."""
814
+ msg = self.active
815
+ if msg is None:
816
+ return
817
+ if msg.direction == "RT2BC":
818
+ lo, hi = self._rx_slice[msg.name]
819
+ self.received[lo:hi] = self.bus.get(msg.rt, msg.subaddress, msg.word_count)
820
+ else:
821
+ sink = self.terminals.get(
822
+ msg.rt_dest if msg.direction == "RT2RT" else msg.rt
823
+ )
824
+ if sink is not None:
825
+ sink.receive(t, msg)
826
+
827
+ def _source(self, msg):
828
+ """Copy the message's data words from their source onto the bus."""
829
+ if msg.direction == "BC2RT":
830
+ lo, hi = self._tx_slice[msg.name]
831
+ self.bus.put(msg.rt, msg.subaddress, self.snapshot[lo:hi])
832
+ return
833
+ source = self.terminals.get(msg.rt)
834
+ if source is not None:
835
+ source.transmit(msg)
836
+
837
+ def _close_frame(self):
838
+ self.last_utilisation = self._busy_this_frame / self.frame_time
839
+ self.frame_index += 1
840
+
841
+ def _open_frame(self):
842
+ self._busy_this_frame = 0.0
843
+ self._frame_start = self.frame_index * self.frame_time
844
+ self._queue = list(self.messages_in_frame(self.frame_index))
845
+
846
+ def output(self, t):
847
+ busy = 1.0 if t < self._message_end else 0.0
848
+ status = np.array(
849
+ [
850
+ busy,
851
+ float(self.frame_index),
852
+ float(self.last_utilisation),
853
+ float(self.overruns),
854
+ ]
855
+ )
856
+ return np.concatenate([status, self.received])
857
+
858
+
859
+ class MilStd1553RemoteTerminal(Block):
860
+ """A remote terminal: sources some subaddresses, sinks others.
861
+
862
+ It is bound to the controller's clocks by
863
+ :meth:`MilStd1553BusController.attach`, so at a message START it puts
864
+ its live input values on the bus if it is the source, and at the
865
+ message END it latches from the bus if it is the sink.
866
+
867
+ Inputs
868
+ the data words this terminal TRANSMITS, i.e. the concatenated
869
+ counts of `tx_subaddresses`, in the order given.
870
+ Outputs
871
+ the data words this terminal RECEIVES (`rx_subaddresses`, held),
872
+ then ``age`` -- seconds since this terminal was last written to,
873
+ which is the staleness a consumer should be watching.
874
+ """
875
+
876
+ def __init__(
877
+ self,
878
+ bus: MilStd1553Bus,
879
+ address: int,
880
+ tx_subaddresses=None,
881
+ rx_subaddresses=None,
882
+ name: Optional[str] = None,
883
+ ):
884
+ if not 0 <= address <= 31:
885
+ raise ValueError("a terminal address is 5 bits (0..31)")
886
+ self.bus = bus
887
+ self.address = int(address)
888
+ self.tx_subaddresses = dict(tx_subaddresses or {})
889
+ self.rx_subaddresses = dict(rx_subaddresses or {})
890
+ if not self.tx_subaddresses and not self.rx_subaddresses:
891
+ raise ValueError(f"RT{address} neither sources nor sinks anything")
892
+ self.controller = None
893
+
894
+ self._tx_slice, n_in = _slices_from_dict(self.tx_subaddresses)
895
+ self._rx_slice, n_out = _slices_from_dict(self.rx_subaddresses)
896
+
897
+ super().__init__(
898
+ num_inputs=n_in,
899
+ num_outputs=n_out + 1,
900
+ name=name or f"RT{address}",
901
+ inputs=_names_from_dict(self.tx_subaddresses, "tx"),
902
+ outputs=_names_from_dict(self.rx_subaddresses, "rx") + [("age", "s")],
903
+ )
904
+ self._reset()
905
+
906
+ def _reset(self):
907
+ self.received = np.zeros(self.num_outputs - 1)
908
+ self.snapshot = np.zeros(self.num_inputs)
909
+ self.last_rx = 0.0
910
+ self.words_received = 0
911
+ self.words_transmitted = 0
912
+
913
+ def initialize(self):
914
+ super().initialize()
915
+ self._reset()
916
+
917
+ def update(self, t, u):
918
+ """Snapshot this terminal's live inputs; the controller's handlers
919
+ do the actual bus access once every snapshot is fresh."""
920
+ self.snapshot = np.asarray(u, dtype=float).copy()
921
+
922
+ def transmit(self, msg):
923
+ """Put this terminal's data on the bus. Called by the controller."""
924
+ lo, hi = self._tx_slice.get(msg.subaddress, (None, None))
925
+ if lo is None:
926
+ log.debug(
927
+ "%s: asked for SA%d, which it does not publish",
928
+ self.name,
929
+ msg.subaddress,
930
+ )
931
+ return
932
+ self.bus.put(msg.rt, msg.subaddress, self.snapshot[lo:hi])
933
+ self.words_transmitted += msg.word_count
934
+
935
+ def receive(self, t, msg):
936
+ """Latch data addressed to this terminal. Called by the controller."""
937
+ subaddress = msg.subaddress_dest if msg.direction == "RT2RT" else msg.subaddress
938
+ lo, hi = self._rx_slice.get(subaddress, (None, None))
939
+ if lo is None:
940
+ log.debug("%s: SA%d addressed but not subscribed", self.name, subaddress)
941
+ return
942
+ self.received[lo:hi] = self.bus.get(msg.rt, msg.subaddress, msg.word_count)
943
+ self.last_rx = t
944
+ self.words_received += msg.word_count
945
+
946
+ def output(self, t):
947
+ return np.concatenate([self.received, [t - self.last_rx]])
948
+
949
+
950
+ def wire_1553(system, controller: MilStd1553BusController, *terminals):
951
+ """Register the controller's clocks and put `terminals` on the bus.
952
+
953
+ 1553 data rides the shared `MilStd1553Bus`, not blocksim connections,
954
+ so this is the whole wiring step -- connect each terminal's own
955
+ engineering signals to the rest of the diagram as usual.
956
+ """
957
+ system.add_clock(controller.start_clock)
958
+ system.add_clock(controller.done_clock)
959
+ for terminal in terminals:
960
+ controller.attach(terminal)
961
+ return controller
962
+
963
+
964
+ # ---- small helpers for laying data words out on ports ---------------------
965
+ def _port_slices(messages):
966
+ slices, offset = {}, 0
967
+ for msg in messages:
968
+ slices[msg.name] = (offset, offset + msg.word_count)
969
+ offset += msg.word_count
970
+ return slices, offset
971
+
972
+
973
+ def _port_names(messages):
974
+ return [
975
+ (f"{msg.name}_w{i}", None) for msg in messages for i in range(msg.word_count)
976
+ ]
977
+
978
+
979
+ def _slices_from_dict(subaddresses):
980
+ slices, offset = {}, 0
981
+ for subaddress, count in subaddresses.items():
982
+ slices[subaddress] = (offset, offset + count)
983
+ offset += count
984
+ return slices, offset
985
+
986
+
987
+ def _names_from_dict(subaddresses, prefix):
988
+ return [
989
+ (f"{prefix}_sa{subaddress}_w{i}", None)
990
+ for subaddress, count in subaddresses.items()
991
+ for i in range(count)
992
+ ]