openc3-cosmos-constellation 0.8.0 → 0.8.1

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 196a8ae9e0ac56a5072dfc09d4caa41953f4713e826910e6d9547806116f45af
4
- data.tar.gz: 9cc3cd1844d301c00c6eeeee74d4d0884fe2374dd3fd765cc26cd294609a2841
3
+ metadata.gz: 96e58e8bfe303ce4366826261aa110703a0b2be39652fc9be8b6360ec51e040a
4
+ data.tar.gz: ebc7922734b48fa8437059a999d985f3cfccfc62285de6bf96da21dcb0723194
5
5
  SHA512:
6
- metadata.gz: 071e686a3a3981905c165fcf74690b4be066e50a0c6e3c20a8c8b6225fa1d3f01f7d427359c4d28bf67197f212add6b79ac711ef16661edf9f74db25ab75b1ea
7
- data.tar.gz: e5df71a389f4d36e234b27a892cdaba3422403eb894ecfc8e133248830630d6338c890fdaff8e4954df7dea6015d1580985cb7176aa423c188296f7987965946
6
+ metadata.gz: 84cc92cd55c5e864280d81110bb997becbf61c001dc2d36e17570cdf442803814655f57ba442e32faeedd73839dc34a5faabf4419b578be917769ca747881257
7
+ data.tar.gz: 54a40947f6cf787e3511c87a5e78a4c3c5a4958af0eb5efb3dfd8e88d7d0c7370f3815148bfe150943bb482e5d1f948c9854ba87362cb009f02838748a1eafc3
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/Rakefile CHANGED
@@ -1,5 +1,5 @@
1
- # Builds openc3-cosmos-constellation-<VERSION>.gem: rake build VERSION=0.8.0
2
- # (or ./openc3.sh cli rake build VERSION=0.8.0 inside a COSMOS checkout).
1
+ # Builds openc3-cosmos-constellation-<VERSION>.gem: rake build VERSION=0.8.1
2
+ # (or ./openc3.sh cli rake build VERSION=0.8.1 inside a COSMOS checkout).
3
3
  PLUGIN_NAME = Dir['*.gemspec'][0].split('.')[0..-2].join('.')
4
4
 
5
5
  # The tool draws the shared Constellation Forecast view, copied in from this repo when it is here.
@@ -9,9 +9,11 @@ SHARED_VIEW = '../shared/forecast-view.js'
9
9
  # the same way as a one-module constellation_space package.
10
10
  RESULTS = 'microservices/BRIDGE/constellation_space/results.py'
11
11
  SHARED_RESULTS = '../../clients/python/src/constellation_space/results.py'
12
+ # The repository's license, shipped in the gem.
13
+ SHARED_LICENSE = '../../LICENSE'
12
14
 
13
15
  task :build do
14
- abort('VERSION is required: rake build VERSION=0.8.0') unless ENV['VERSION']
16
+ abort('VERSION is required: rake build VERSION=0.8.1') unless ENV['VERSION']
15
17
  FileUtils.cp(SHARED_VIEW, VIEW) if File.exist?(SHARED_VIEW)
16
18
  abort("#{VIEW} is missing: copy bridges/shared/forecast-view.js there") unless File.exist?(VIEW)
17
19
  if File.exist?(SHARED_RESULTS)
@@ -20,5 +22,7 @@ task :build do
20
22
  FileUtils.touch(File.join(File.dirname(RESULTS), '__init__.py'))
21
23
  end
22
24
  abort("#{RESULTS} is missing: copy clients/python/src/constellation_space/results.py there") unless File.exist?(RESULTS)
25
+ FileUtils.cp(SHARED_LICENSE, 'LICENSE') if File.exist?(SHARED_LICENSE)
26
+ abort('LICENSE is missing: copy the repository root LICENSE here') unless File.exist?('LICENSE')
23
27
  system("gem build #{PLUGIN_NAME}.gemspec") || abort('gem build failed')
24
28
  end
@@ -9,7 +9,11 @@ target's packets (targets/CONSTELLATION/cmd_tlm/tlm.txt):
9
9
  NEXT_PASS the next predicted pass and its expected GB (p10/p50/p90)
10
10
  NEXT_24H passes and expected GB over the next 24 hours
11
11
  SWAP the soonest rain-fade swap to decide, with minutes left (limits go yellow, then red)
12
- RUN which workflow run the values came from
12
+ CAPACITY one day's capacity across the antennas, and the tightest
13
+ MODCOD the next pass's MODCOD plan
14
+ RUN the latest workflow run received, of any kind
15
+
16
+ A packet is injected only once a run of its kind has arrived.
13
17
 
14
18
  So COSMOS's own Telemetry Viewer, Telemetry Grapher, Limits Monitor and Data Extractor show the
15
19
  forecast with no other install. It also writes each run, and an index of workflows, as JSON into
@@ -24,6 +28,7 @@ added or changed there is used without a reinstall, and never leaves this proces
24
28
 
25
29
  import json
26
30
  import os
31
+ import re
27
32
  import sys
28
33
  import time
29
34
  import urllib.error
@@ -33,7 +38,7 @@ from typing import Any
33
38
 
34
39
  from constellation_space import results
35
40
 
36
- VERSION = "0.8.0"
41
+ VERSION = "0.8.1"
37
42
  TARGET = "CONSTELLATION"
38
43
  POLL_S = int(os.environ.get("POLL_SECONDS", "15"))
39
44
  # COSMOS shows a packet stale 30 s after its last value: re-inject every poll so a quiet feed
@@ -41,6 +46,8 @@ POLL_S = int(os.environ.get("POLL_SECONDS", "15"))
41
46
  REFRESH_S = 10
42
47
  # How often, with no key or a refused one, it looks for a new key in Admin > Secrets.
43
48
  KEY_WAIT_S = 60
49
+ # The connection names the API takes (its CONNECTION_PATTERN); any other is a 422 on every call.
50
+ CONNECTION = re.compile(r"[a-z0-9][a-z0-9-]{0,62}")
44
51
  SCOPE = os.environ.get("OPENC3_SCOPE", "DEFAULT")
45
52
  # Where the Constellation Forecast tool (tools/constellationforecast) reads the documents.
46
53
  DOCS = f"{SCOPE}/constellation"
@@ -52,6 +59,37 @@ if "OPENC3_SERVICE_PASSWORD" in os.environ:
52
59
  os.environ.setdefault("OPENC3_API_PASSWORD", os.environ["OPENC3_SERVICE_PASSWORD"])
53
60
 
54
61
 
62
+ # The bytes of each STRING item in tlm.txt, by item name (a test holds them to it). COSMOS drops
63
+ # a whole injected packet holding a longer value, and says so only in its decom log, and the API
64
+ # takes ids longer than these, so a value is cut to fit. Its OVERFLOW TRUNCATE does not do it for
65
+ # a string in the Python decom of 7.0 to 7.5.
66
+ STRING_BYTES = {
67
+ "SATELLITE": 64,
68
+ "ANTENNA": 64,
69
+ "AOS": 32,
70
+ "LOS": 32,
71
+ "BACKUP_ANTENNA": 64,
72
+ "BACKUP_AOS": 32,
73
+ "DEADLINE": 32,
74
+ "STATUS": 16,
75
+ "DAY": 16,
76
+ "TIGHTEST_ANTENNA": 64,
77
+ "FIRST": 32,
78
+ "LAST": 32,
79
+ "WORKFLOW": 64,
80
+ "TEMPLATE": 32,
81
+ "RUN_ID": 64,
82
+ }
83
+
84
+
85
+ def fit(values: dict[str, Any]) -> dict[str, Any]:
86
+ """The values with each string cut to its item's bytes, never mid-character."""
87
+ return {
88
+ k: v.encode()[: STRING_BYTES[k]].decode(errors="ignore") if k in STRING_BYTES else v
89
+ for k, v in values.items()
90
+ }
91
+
92
+
55
93
  def inject(packet: str, values: dict[str, Any]) -> None:
56
94
  """COSMOS's inject_tlm, from whichever module this COSMOS exposes it in."""
57
95
  try:
@@ -78,8 +116,18 @@ def call(method: str, path: str, body: Any = None) -> Any:
78
116
  return results.http(method, f"{api}{path}", body, {"X-API-Key": api_key()})
79
117
 
80
118
 
81
- def log(message: str) -> None:
82
- print(f"constellation-bridge: {message}", flush=True)
119
+ def log(message: str, warn: bool = False) -> None:
120
+ """A line in COSMOS's log messages (CmdTlmServer > Log Messages), where an operator looks.
121
+ Outside COSMOS, stdout, or stderr for a warning. A plain print is not enough in COSMOS: its
122
+ operator holds a microservice's stdout back until a few KB of it pile up."""
123
+ line = f"constellation-bridge: {message}"
124
+ try:
125
+ from openc3.utilities.logger import Logger # type: ignore[import-not-found]
126
+ except ImportError:
127
+ print(line, file=sys.stderr if warn else sys.stdout, flush=True)
128
+ return
129
+ Logger.microservice_name = os.environ.get("OPENC3_MICROSERVICE_NAME")
130
+ (Logger.warn if warn else Logger.info)(line, scope=SCOPE)
83
131
 
84
132
 
85
133
  def output_of(resource: dict[str, Any]) -> dict[str, Any]:
@@ -174,6 +222,48 @@ def swap_items(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
174
222
  return shown
175
223
 
176
224
 
225
+ def held_until(item: dict[str, Any]) -> str:
226
+ """When a held action can no longer be approved, as the API's expires_at() has it: its cancel
227
+ deadline, else when its pass starts, or a link's span ends. The API sends a held item without
228
+ its action, so mostly the latter."""
229
+ end = item["until"] if (item.get("entity") or {}).get("type") == "link" else item["target_at"]
230
+ return (item.get("action") or {}).get("deadline") or end
231
+
232
+
233
+ # With no pass ahead, NEXT_PASS says so rather than keep the last run's pass.
234
+ NO_PASS: dict[str, Any] = {
235
+ "SATELLITE": "NONE",
236
+ "ANTENNA": "NONE",
237
+ "AOS": "",
238
+ "LOS": "",
239
+ "EXPECTED_GB_P10": 0.0,
240
+ "EXPECTED_GB_P50": 0.0,
241
+ "EXPECTED_GB_P90": 0.0,
242
+ "MAX_ELEVATION": 0.0,
243
+ }
244
+
245
+ # The same for CAPACITY and MODCOD, with no antenna-day or no plan ahead.
246
+ NO_CAPACITY: dict[str, Any] = {
247
+ "DAY": "NONE",
248
+ "ANTENNAS": 0,
249
+ "PASSES": 0,
250
+ "SELLABLE_MIN": 0.0,
251
+ "GB_P10": 0.0,
252
+ "GB_P50": 0.0,
253
+ "TIGHTEST_ANTENNA": "NONE",
254
+ "TIGHTEST_GB_P50": 0.0,
255
+ }
256
+ NO_MODCOD: dict[str, Any] = {
257
+ "SATELLITE": "NONE",
258
+ "ANTENNA": "NONE",
259
+ "AOS": "",
260
+ "CHANGES": 0,
261
+ "FIRST": "NONE",
262
+ "LAST": "NONE",
263
+ "MIN_SINR_DB": 0.0,
264
+ "PLANNED_PASSES": 0,
265
+ }
266
+
177
267
  # Every SWAP item is written each time, so a cleared swap never leaves the last one's values
178
268
  # behind. With nothing to decide, the minutes left sit far above the limits: green, not red.
179
269
  NO_SWAP: dict[str, Any] = {
@@ -230,8 +320,8 @@ def modcod_plans(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
230
320
 
231
321
 
232
322
  def modcod_packet(items: list[dict[str, Any]], now: datetime) -> dict[str, Any] | None:
233
- """MODCOD: the next pass's MODCOD plan, its changes and its lowest SINR. None without a plan
234
- still to fly."""
323
+ """MODCOD: the next pass's MODCOD plan, its changes and its lowest SINR at a change (the series
324
+ holds only the changes). None without a plan still to fly."""
235
325
  plans = sorted(
236
326
  (p for p in modcod_plans(items) if datetime.fromisoformat(p["until"]) > now),
237
327
  key=lambda p: p["target_at"],
@@ -277,10 +367,12 @@ def packets(
277
367
  "EXPECTED_GB_P10": round(sum(results.expected_gb(p)["p10"] for p in day), 3),
278
368
  "EXPECTED_GB_P50": round(sum(results.expected_gb(p)["p50"] for p in day), 3),
279
369
  },
370
+ "NEXT_PASS": NO_PASS,
280
371
  "SWAP": {**NO_SWAP, "PENDING": pending},
281
372
  }
282
- if upcoming:
283
- nxt = upcoming[0]
373
+ # The next AOS, as the Forecast tool shows it: a pass already under way counts in the day only.
374
+ nxt = next((p for p in upcoming if datetime.fromisoformat(p["target_at"]) > now), None)
375
+ if nxt:
284
376
  gb = results.expected_gb(nxt)
285
377
  elevation = results.max_elevation(nxt)
286
378
  out["NEXT_PASS"] = {
@@ -318,15 +410,18 @@ def packets(
318
410
  class Forecast:
319
411
  """The newest answer of each kind of workflow: a run replaces what the last run of its kind
320
412
  said, empty or not (a swap run advising nothing takes the swap down), and never another
321
- kind's. Which kind is the run's own constellation.template, else read off its items."""
413
+ kind's. Which kind is the run's own constellation.template, else read off its items. A kind
414
+ no run has brought is None, and its packets are not injected: COSMOS shows no value rather
415
+ than NONE and 0, which would read as a forecast of nothing."""
322
416
 
323
417
  def __init__(self) -> None:
324
- self.passes: list[dict[str, Any]] = []
325
- self.swaps: list[dict[str, Any]] = []
326
- # Swaps the newest swap run holds for approval in Constellation: counted, not shown.
327
- self.pending = 0
328
- self.capacity: list[dict[str, Any]] = []
329
- self.plans: list[dict[str, Any]] = []
418
+ self.passes: list[dict[str, Any]] | None = None
419
+ self.swaps: list[dict[str, Any]] | None = None
420
+ # When each swap the newest swap run holds for approval in Constellation can no longer
421
+ # be approved (held_until): counted until then, not shown. None only in a 0.8.0 state.
422
+ self.held: list[str | None] = []
423
+ self.capacity: list[dict[str, Any]] | None = None
424
+ self.plans: list[dict[str, Any]] | None = None
330
425
  self.run: dict[str, Any] = {}
331
426
  # Approvals already reported carried out, by decision: each run shows them again.
332
427
  self.acted: dict[str, str] = {}
@@ -335,7 +430,7 @@ class Forecast:
335
430
  answers = resource.get("constellation.template") or results.kind(items)
336
431
  if answers == "rain-fade-swap":
337
432
  self.swaps = swap_items(items)
338
- self.pending = sum(results.action_state(i) == "pending" for i in items)
433
+ self.held = [held_until(i) for i in items if results.action_state(i) == "pending"]
339
434
  elif answers == "antenna-capacity":
340
435
  self.capacity = items
341
436
  elif answers == "modcod-plan":
@@ -355,20 +450,28 @@ class Forecast:
355
450
  return dict(vars(self))
356
451
 
357
452
  def restore(self, saved: dict[str, Any]) -> None:
453
+ saved = dict(saved)
454
+ # A state kept before deadlines were (0.8.0) has only the count.
455
+ count = saved.pop("pending", 0)
358
456
  vars(self).update(saved)
457
+ if "held" not in saved:
458
+ self.held = [None] * int(count or 0)
359
459
 
360
460
  def publish(self, now: datetime) -> int:
361
- out = packets(self.passes, self.swaps, now, self.pending)
362
- for packet, values in (
363
- ("CAPACITY", capacity_packet(self.capacity, now)),
364
- ("MODCOD", modcod_packet(self.plans, now)),
365
- ):
366
- if values is not None:
367
- out[packet] = values
461
+ pending = sum(d is None or datetime.fromisoformat(d) > now for d in self.held)
462
+ out = packets(self.passes or [], self.swaps or [], now, pending)
463
+ if self.passes is None:
464
+ del out["NEXT_PASS"], out["NEXT_24H"]
465
+ if self.swaps is None:
466
+ del out["SWAP"]
467
+ if self.capacity is not None:
468
+ out["CAPACITY"] = capacity_packet(self.capacity, now) or NO_CAPACITY
469
+ if self.plans is not None:
470
+ out["MODCOD"] = modcod_packet(self.plans, now) or NO_MODCOD
368
471
  if self.run:
369
472
  out["RUN"] = self.run
370
473
  for packet, values in out.items():
371
- inject(packet, values)
474
+ inject(packet, fit(values))
372
475
  return len(out)
373
476
 
374
477
 
@@ -394,7 +497,11 @@ def check_in(consumer: str) -> bool:
394
497
  except Exception as exc:
395
498
  if isinstance(exc, urllib.error.HTTPError) and exc.code in (401, 403):
396
499
  raise
397
- print(f"constellation-bridge: could not check in ({exc})", file=sys.stderr, flush=True)
500
+ # An outage is said by the poll that follows.
501
+ if not isinstance(exc, OSError) or (
502
+ isinstance(exc, urllib.error.HTTPError) and exc.code < 500
503
+ ):
504
+ log(f"could not check in ({exc})", warn=True)
398
505
  return False
399
506
  return True
400
507
 
@@ -403,7 +510,11 @@ def report(consumer: str, cursor: str, applied: dict[str, int]) -> None:
403
510
  try:
404
511
  results.report(call, consumer, cursor, applied, f"OpenC3 COSMOS target {TARGET}")
405
512
  except Exception as exc:
406
- print(f"constellation-bridge: could not report ({exc})", file=sys.stderr, flush=True)
513
+ log(f"could not report ({exc})", warn=True)
514
+
515
+
516
+ def api_origin() -> str:
517
+ return results.origin(os.environ["CONSTELLATION_API_URL"])
407
518
 
408
519
 
409
520
  def state_key(consumer: str) -> str:
@@ -415,19 +526,24 @@ def resume(consumer: str, forecast: Forecast) -> str:
415
526
  start's."""
416
527
  client, name = bucket()
417
528
  found = client.get_object(bucket=name, key=state_key(consumer))
418
- if not found:
529
+ saved = json.loads(found["Body"].read()) if found else {}
530
+ # A cursor is the feed's own: one kept for another API means nothing here.
531
+ if saved.get("api", api_origin()) != api_origin():
532
+ log(f"the state kept for {saved['api']} is not for this API: starting afresh")
533
+ saved = {}
534
+ if not saved:
419
535
  cursor = results.start_cursor(call, consumer)
420
- print(f"constellation-bridge: first start, reading after {cursor!r}", flush=True)
536
+ log(f"first start, reading after {cursor!r}")
421
537
  return cursor
422
- saved = json.loads(found["Body"].read())
423
538
  forecast.restore(saved["forecast"])
424
- print(f"constellation-bridge: resuming after {saved['cursor']!r}", flush=True)
539
+ log(f"resuming after {saved['cursor']!r}")
425
540
  return saved["cursor"]
426
541
 
427
542
 
428
543
  def keep(consumer: str, cursor: str, forecast: Forecast) -> None:
429
544
  client, name = bucket()
430
- body = json.dumps({"cursor": cursor, "forecast": forecast.saved()}).encode()
545
+ kept = {"cursor": cursor, "forecast": forecast.saved(), "api": api_origin()}
546
+ body = json.dumps(kept).encode()
431
547
  client.put_object(
432
548
  bucket=name, key=state_key(consumer), body=body, content_type="application/json"
433
549
  )
@@ -436,25 +552,55 @@ def keep(consumer: str, cursor: str, forecast: Forecast) -> None:
436
552
  def main() -> None:
437
553
  consumer = os.environ.get("CONSUMER", "cosmos-bridge")
438
554
  forecast, refreshed, checked_in, refused, held = Forecast(), 0.0, "", "", ""
555
+ # Why Constellation could not be read, said once until it can be again.
556
+ failing = ""
557
+ hinted = False
439
558
  checked_at = 0.0
440
559
  cursor: str | None = None
441
- if why := results.key_refusal(os.environ["CONSTELLATION_API_URL"]):
442
- print(f"constellation-bridge: {why}", file=sys.stderr, flush=True)
443
- sys.exit(2)
444
- print(f"constellation-bridge: feed -> COSMOS {TARGET} as {consumer}", flush=True)
560
+
561
+ def pause(seconds: float) -> None:
562
+ """Waits `seconds`, refreshing the packets at least every POLL_S meanwhile, whatever the
563
+ wait is for (a poll, a missing or refused key, a hold-off): the forecast held is the
564
+ newest there is, and the next pass and the minutes left to a swap move with the clock,
565
+ not only with runs."""
566
+ nonlocal refreshed
567
+ while seconds > 0:
568
+ if time.time() - refreshed > REFRESH_S and forecast.run:
569
+ try:
570
+ forecast.publish(datetime.now(UTC))
571
+ refreshed = time.time()
572
+ except Exception as exc:
573
+ log(f"could not refresh the packets ({type(exc).__name__}: {exc})", warn=True)
574
+ time.sleep(min(seconds, POLL_S))
575
+ seconds -= POLL_S
576
+
577
+ why = results.key_refusal(os.environ["CONSTELLATION_API_URL"])
578
+ if not CONNECTION.fullmatch(consumer):
579
+ why = (
580
+ f"consumer {consumer!r} is not a connection name Constellation takes: 1 to 63"
581
+ " lowercase letters, digits and hyphens, not starting with a hyphen. Change it in"
582
+ " the plugin's variables"
583
+ )
584
+ if why:
585
+ # Said once and waited on, not exited: COSMOS respawns a microservice that exits.
586
+ log(why, warn=True)
587
+ while True:
588
+ time.sleep(KEY_WAIT_S)
589
+ log(f"feed -> COSMOS {TARGET} as {consumer}")
445
590
  while True:
446
591
  key = api_key()
447
592
  if not key:
448
- print(
449
- "constellation-bridge: No CONSTELLATION_API_KEY in Admin > Secrets yet",
450
- file=sys.stderr,
451
- flush=True,
593
+ log(
594
+ "No CONSTELLATION_API_KEY in Admin > Secrets yet: add a Constellation key with"
595
+ f" predictions:read there ({results.site()}/keys)",
596
+ warn=True,
452
597
  )
453
- time.sleep(KEY_WAIT_S)
598
+ pause(KEY_WAIT_S)
454
599
  continue
455
600
  if key == refused:
456
- time.sleep(KEY_WAIT_S)
601
+ pause(KEY_WAIT_S)
457
602
  continue
603
+ failed = ""
458
604
  try:
459
605
  stale = time.time() - checked_at > results.CHECKIN_S
460
606
  if (key != checked_in or stale) and check_in(consumer):
@@ -463,8 +609,17 @@ def main() -> None:
463
609
  cursor = resume(consumer, forecast)
464
610
  page = results.results_page(call, consumer, cursor)
465
611
  held = ""
612
+ if failing:
613
+ log("reached Constellation again")
614
+ failing = ""
615
+ if not (forecast.run or page["entries"] or hinted):
616
+ log(
617
+ f"no run for {consumer} yet. In Constellation, send a workflow to the OpenC3"
618
+ f" COSMOS output with connection {consumer}"
619
+ )
620
+ hinted = True
466
621
  if lost := results.expired(page, cursor):
467
- print(f"constellation-bridge: {lost}", file=sys.stderr, flush=True)
622
+ log(lost, warn=True)
468
623
  for entry in page["entries"]:
469
624
  entry = results.whole(entry, lambda c, n: results.rest_of_run(call, consumer, c, n))
470
625
  parts = results.unpack(entry["otlp"], consumer, log)
@@ -502,44 +657,41 @@ def main() -> None:
502
657
  cursor = entry["cursor"]
503
658
  report(consumer, cursor, applied)
504
659
  keep(consumer, cursor, forecast)
505
- print(
506
- f"constellation-bridge: injected {applied['parameters']} packets, {cursor}",
507
- flush=True,
508
- )
509
- # The next pass and the minutes left to a swap move with the clock, not only with runs.
510
- if time.time() - refreshed > REFRESH_S and forecast.run:
511
- forecast.publish(datetime.now(UTC))
512
- refreshed = time.time()
660
+ log(f"injected {applied['parameters']} packets, {cursor}")
513
661
  if page["entries"]:
514
662
  continue # catching up on the runs since the cursor: the next one now
515
663
  except urllib.error.HTTPError as exc:
516
664
  body = exc.read()
517
665
  if why := results.refusal(exc.code, body):
518
- print(
519
- f"constellation-bridge: {why}. Stopped polling until the key in Admin >"
520
- " Secrets changes or the plugin restarts",
521
- file=sys.stderr,
522
- flush=True,
666
+ log(
667
+ f"{why}. Stopped polling until the key in Admin > Secrets changes or the"
668
+ " plugin restarts",
669
+ warn=True,
523
670
  )
524
671
  refused = key
525
- time.sleep(KEY_WAIT_S)
672
+ pause(KEY_WAIT_S)
526
673
  continue
527
674
  # Locked out, rate limited or out of plan: said once and waited out, never hammered.
528
675
  if hold := results.held_off(exc.code, body):
529
676
  why, wait = hold
530
677
  if why != held:
531
- print(
532
- f"constellation-bridge: {why}. Asking again in {wait:.0f} s",
533
- file=sys.stderr,
534
- flush=True,
535
- )
678
+ log(f"{why}. Asking again in {wait:.0f} s", warn=True)
536
679
  held = why
537
- time.sleep(wait)
680
+ pause(wait)
538
681
  continue
539
- print(f"constellation-bridge: {exc}", file=sys.stderr, flush=True)
682
+ failed = f"Constellation answered HTTP {exc.code}"
683
+ except OSError as exc: # unreachable, refused, timed out (URLError is one)
684
+ failed = f"could not reach Constellation ({getattr(exc, 'reason', exc)})"
540
685
  except Exception as exc: # a bad poll is logged and retried, never fatal
541
- print(f"constellation-bridge: {type(exc).__name__}: {exc}", file=sys.stderr, flush=True)
542
- time.sleep(POLL_S)
686
+ log(f"{type(exc).__name__}: {exc}", warn=True)
687
+ if failed:
688
+ if failed != failing:
689
+ log(
690
+ f"{failed}. Showing the forecast held and asking again every {POLL_S} s",
691
+ warn=True,
692
+ )
693
+ failing = failed
694
+ pause(POLL_S)
543
695
 
544
696
 
545
697
  if __name__ == "__main__":
@@ -72,6 +72,13 @@ def key_refusal(url: str) -> str:
72
72
  return f"not sending the API key to {url}: it is not https (plain http only to localhost)"
73
73
 
74
74
 
75
+ class _Unredirected(urllib.request.HTTPRedirectHandler):
76
+ """Answers a redirect as the HTTPError it is, never following it."""
77
+
78
+ def redirect_request(self, *args: Any, **kwargs: Any) -> None:
79
+ return None
80
+
81
+
75
82
  def http(
76
83
  method: str,
77
84
  url: str,
@@ -81,12 +88,16 @@ def http(
81
88
  timeout: float = 60,
82
89
  ) -> Any:
83
90
  """One HTTP call: `body` sent as JSON (or `raw` as is), the answer's JSON back, or None for an
84
- answer that is not JSON. An HTTP error is raised as urllib's HTTPError."""
91
+ answer that is not JSON. An HTTP error is raised as urllib's HTTPError, and so is a redirect of
92
+ a call carrying an X-API-Key: following it could send the key to another host, or over plain
93
+ http (key_safe holds only for the URL asked)."""
85
94
  data = raw if raw is not None else None if body is None else json.dumps(body).encode()
86
95
  req = urllib.request.Request(url, data=data, method=method, headers=headers or {})
87
96
  if body is not None and raw is None:
88
97
  req.add_header("Content-Type", "application/json")
89
- with urllib.request.urlopen(req, timeout=timeout) as resp:
98
+ keyed = any(name.lower() == "x-api-key" for name in headers or {})
99
+ open_ = urllib.request.build_opener(_Unredirected).open if keyed else urllib.request.urlopen
100
+ with open_(req, timeout=timeout) as resp:
90
101
  payload = resp.read()
91
102
  return json.loads(payload) if payload and payload[:1] in b"{[" else None
92
103
 
data/plugin.txt CHANGED
@@ -3,9 +3,9 @@
3
3
  # microservice fills from the Constellation feed. Everything here is a forecast, not telemetry
4
4
  # measured from a spacecraft or a ground station.
5
5
  VARIABLE constellation_api_url https://api.constellation.space
6
- VARIABLE_DESCRIPTION "Constellation API base URL"
6
+ VARIABLE_DESCRIPTION "Constellation API URL. The API key goes in Admin > Secrets as CONSTELLATION_API_KEY"
7
7
  VARIABLE consumer cosmos-bridge
8
- VARIABLE_DESCRIPTION "This connection's name: workflows pick it as an output"
8
+ VARIABLE_DESCRIPTION "Connection name Constellation workflows send to: lowercase letters, digits and hyphens. Change it only if another COSMOS uses cosmos-bridge"
9
9
 
10
10
  TARGET CONSTELLATION CONSTELLATION
11
11
 
Binary file
@@ -6,20 +6,26 @@ TELEMETRY CONSTELLATION NEXT_PASS BIG_ENDIAN "Forecast: the next predicted pass,
6
6
  APPEND_ITEM LOS 256 STRING "Predicted loss of signal, UTC"
7
7
  APPEND_ITEM EXPECTED_GB_P10 32 FLOAT "Expected GB, wet tail (p10)"
8
8
  UNITS Gigabytes GB
9
+ FORMAT_STRING "%.3f"
9
10
  APPEND_ITEM EXPECTED_GB_P50 32 FLOAT "Expected GB, median (p50)"
10
11
  UNITS Gigabytes GB
12
+ FORMAT_STRING "%.3f"
11
13
  APPEND_ITEM EXPECTED_GB_P90 32 FLOAT "Expected GB, best case (p90)"
12
14
  UNITS Gigabytes GB
15
+ FORMAT_STRING "%.3f"
13
16
  APPEND_ITEM MAX_ELEVATION 32 FLOAT "Peak elevation"
14
17
  UNITS Degrees deg
18
+ FORMAT_STRING "%.2f"
15
19
 
16
20
  TELEMETRY CONSTELLATION NEXT_24H BIG_ENDIAN "Forecast: every predicted pass in the next 24 hours, summed"
17
21
  ALLOW_SHORT
18
22
  APPEND_ITEM PASSES 32 UINT "Predicted passes"
19
- APPEND_ITEM EXPECTED_GB_P10 32 FLOAT "Expected GB, wet tail (p10)"
23
+ APPEND_ITEM EXPECTED_GB_P10 64 FLOAT "Expected GB, wet tail (p10)"
20
24
  UNITS Gigabytes GB
21
- APPEND_ITEM EXPECTED_GB_P50 32 FLOAT "Expected GB, median (p50)"
25
+ FORMAT_STRING "%.3f"
26
+ APPEND_ITEM EXPECTED_GB_P50 64 FLOAT "Expected GB, median (p50)"
22
27
  UNITS Gigabytes GB
28
+ FORMAT_STRING "%.3f"
23
29
 
24
30
  TELEMETRY CONSTELLATION SWAP BIG_ENDIAN "Forecast: the soonest open rain-fade swap, advised or approved"
25
31
  ALLOW_SHORT
@@ -30,17 +36,20 @@ TELEMETRY CONSTELLATION SWAP BIG_ENDIAN "Forecast: the soonest open rain-fade sw
30
36
  APPEND_ITEM AOS 256 STRING "Predicted AOS of the pass at risk, UTC"
31
37
  APPEND_ITEM KEEPS_GB_P10 32 FLOAT "GB the pass keeps if it rains (p10)"
32
38
  UNITS Gigabytes GB
39
+ FORMAT_STRING "%.3f"
33
40
  APPEND_ITEM EXPECTED_GB_P50 32 FLOAT "GB the pass delivers dry (p50)"
34
41
  UNITS Gigabytes GB
42
+ FORMAT_STRING "%.3f"
35
43
  APPEND_ITEM BACKUP_ANTENNA 512 STRING "Antenna to book instead, or NONE"
36
44
  APPEND_ITEM BACKUP_AOS 256 STRING "Backup pass AOS, UTC"
37
45
  APPEND_ITEM DEADLINE 256 STRING "Cancel the original by, UTC"
38
46
  APPEND_ITEM MINUTES_TO_DEADLINE 32 FLOAT "Minutes left to decide (99999 when no swap is open)"
39
47
  UNITS Minutes min
48
+ FORMAT_STRING "%.1f"
40
49
  LIMITS DEFAULT 1 ENABLED 15 30 100000 100000
41
50
  APPEND_ITEM STATUS 128 STRING "The swap shown: ADVISED, APPROVED (approved in Constellation: carry it out) or NONE"
42
51
  APPEND_ITEM APPROVED 32 UINT "Open swaps approved in Constellation"
43
- APPEND_ITEM PENDING 32 UINT "Swaps held for approval in Constellation"
52
+ APPEND_ITEM PENDING 32 UINT "Swaps held for approval in Constellation, deadline ahead"
44
53
 
45
54
  TELEMETRY CONSTELLATION CAPACITY BIG_ENDIAN "Forecast: one day's capacity across the antennas, and the tightest"
46
55
  ALLOW_SHORT
@@ -49,13 +58,17 @@ TELEMETRY CONSTELLATION CAPACITY BIG_ENDIAN "Forecast: one day's capacity across
49
58
  APPEND_ITEM PASSES 32 UINT "Predicted passes"
50
59
  APPEND_ITEM SELLABLE_MIN 32 FLOAT "Sellable contact minutes"
51
60
  UNITS Minutes min
52
- APPEND_ITEM GB_P10 32 FLOAT "Expected GB, wet tail (p10)"
61
+ FORMAT_STRING "%.1f"
62
+ APPEND_ITEM GB_P10 64 FLOAT "Expected GB, wet tail (p10)"
53
63
  UNITS Gigabytes GB
54
- APPEND_ITEM GB_P50 32 FLOAT "Expected GB, median (p50)"
64
+ FORMAT_STRING "%.3f"
65
+ APPEND_ITEM GB_P50 64 FLOAT "Expected GB, median (p50)"
55
66
  UNITS Gigabytes GB
67
+ FORMAT_STRING "%.3f"
56
68
  APPEND_ITEM TIGHTEST_ANTENNA 512 STRING "Antenna with the least expected GB that day"
57
69
  APPEND_ITEM TIGHTEST_GB_P50 32 FLOAT "Its expected GB (p50)"
58
70
  UNITS Gigabytes GB
71
+ FORMAT_STRING "%.3f"
59
72
 
60
73
  TELEMETRY CONSTELLATION MODCOD BIG_ENDIAN "Forecast: the next pass's MODCOD plan"
61
74
  ALLOW_SHORT
@@ -65,11 +78,12 @@ TELEMETRY CONSTELLATION MODCOD BIG_ENDIAN "Forecast: the next pass's MODCOD plan
65
78
  APPEND_ITEM CHANGES 32 UINT "MODCOD changes over the pass"
66
79
  APPEND_ITEM FIRST 256 STRING "MODCOD at AOS"
67
80
  APPEND_ITEM LAST 256 STRING "MODCOD at LOS"
68
- APPEND_ITEM MIN_SINR_DB 32 FLOAT "Lowest planned SINR over the pass"
81
+ APPEND_ITEM MIN_SINR_DB 32 FLOAT "Lowest planned SINR (p50) at a MODCOD change"
69
82
  UNITS Decibels dB
83
+ FORMAT_STRING "%.2f"
70
84
  APPEND_ITEM PLANNED_PASSES 32 UINT "Passes with a plan still to fly"
71
85
 
72
- TELEMETRY CONSTELLATION RUN BIG_ENDIAN "The workflow run these forecasts came from"
86
+ TELEMETRY CONSTELLATION RUN BIG_ENDIAN "The latest workflow run received, of any kind: each other packet holds the newest run of its own kind"
73
87
  ALLOW_SHORT
74
88
  APPEND_ITEM WORKFLOW 512 STRING "Workflow"
75
89
  APPEND_ITEM TEMPLATE 256 STRING "Template"
@@ -0,0 +1,65 @@
1
+ SCREEN AUTO AUTO 1.0
2
+
3
+ TITLE "Constellation forecast: predicted values, not measured telemetry"
4
+
5
+ HORIZONTALBOX "Latest run received"
6
+ LABELVALUEDESC CONSTELLATION RUN WORKFLOW "Workflow" CONVERTED 16
7
+ LABELVALUEDESC CONSTELLATION RUN WORKFLOW_VERSION "Version" CONVERTED 4
8
+ LABELVALUEDESC CONSTELLATION RUN RUN_ID "Run" CONVERTED 28
9
+ LABELVALUEDESC CONSTELLATION RUN RESULTS "Results" CONVERTED 6
10
+ END
11
+
12
+ HORIZONTAL
13
+ VERTICAL
14
+ VERTICALBOX "Next pass"
15
+ LABELVALUEDESC CONSTELLATION NEXT_PASS SATELLITE "Satellite" CONVERTED 16
16
+ LABELVALUEDESC CONSTELLATION NEXT_PASS ANTENNA "Antenna" CONVERTED 16
17
+ LABELVALUEDESC CONSTELLATION NEXT_PASS AOS "AOS" CONVERTED 16
18
+ LABELVALUEDESC CONSTELLATION NEXT_PASS LOS "LOS" CONVERTED 16
19
+ LABELVALUEDESC CONSTELLATION NEXT_PASS EXPECTED_GB_P50 "GB p50" WITH_UNITS 16
20
+ LABELVALUEDESC CONSTELLATION NEXT_PASS EXPECTED_GB_P10 "GB p10" WITH_UNITS 16
21
+ LABELVALUEDESC CONSTELLATION NEXT_PASS EXPECTED_GB_P90 "GB p90" WITH_UNITS 16
22
+ LABELVALUEDESC CONSTELLATION NEXT_PASS MAX_ELEVATION "Elevation" WITH_UNITS 16
23
+ END
24
+ VERTICALBOX "Next 24 hours"
25
+ LABELVALUEDESC CONSTELLATION NEXT_24H PASSES "Passes" CONVERTED 16
26
+ LABELVALUEDESC CONSTELLATION NEXT_24H EXPECTED_GB_P50 "GB p50" WITH_UNITS 16
27
+ LABELVALUEDESC CONSTELLATION NEXT_24H EXPECTED_GB_P10 "GB p10" WITH_UNITS 16
28
+ END
29
+ END
30
+ VERTICALBOX "Rain-fade swap"
31
+ LABELVALUEDESC CONSTELLATION SWAP MINUTES_TO_DEADLINE "Minutes left" WITH_UNITS 16
32
+ LABELVALUEDESC CONSTELLATION SWAP OPEN "Open" CONVERTED 16
33
+ LABELVALUEDESC CONSTELLATION SWAP STATUS "Status" CONVERTED 16
34
+ LABELVALUEDESC CONSTELLATION SWAP SATELLITE "Satellite" CONVERTED 16
35
+ LABELVALUEDESC CONSTELLATION SWAP ANTENNA "Antenna" CONVERTED 16
36
+ LABELVALUEDESC CONSTELLATION SWAP AOS "AOS" CONVERTED 16
37
+ LABELVALUEDESC CONSTELLATION SWAP DEADLINE "Cancel by" CONVERTED 16
38
+ LABELVALUEDESC CONSTELLATION SWAP BACKUP_ANTENNA "Backup" CONVERTED 16
39
+ LABELVALUEDESC CONSTELLATION SWAP BACKUP_AOS "Backup AOS" CONVERTED 16
40
+ LABELVALUEDESC CONSTELLATION SWAP KEEPS_GB_P10 "If rain" WITH_UNITS 16
41
+ LABELVALUEDESC CONSTELLATION SWAP EXPECTED_GB_P50 "GB if dry" WITH_UNITS 16
42
+ LABELVALUEDESC CONSTELLATION SWAP APPROVED "Approved" CONVERTED 16
43
+ LABELVALUEDESC CONSTELLATION SWAP PENDING "Pending" CONVERTED 16
44
+ END
45
+ VERTICALBOX "Capacity"
46
+ LABELVALUEDESC CONSTELLATION CAPACITY DAY "Day" CONVERTED 16
47
+ LABELVALUEDESC CONSTELLATION CAPACITY ANTENNAS "Antennas" CONVERTED 16
48
+ LABELVALUEDESC CONSTELLATION CAPACITY PASSES "Passes" CONVERTED 16
49
+ LABELVALUEDESC CONSTELLATION CAPACITY SELLABLE_MIN "Sellable" WITH_UNITS 16
50
+ LABELVALUEDESC CONSTELLATION CAPACITY GB_P50 "GB p50" WITH_UNITS 16
51
+ LABELVALUEDESC CONSTELLATION CAPACITY GB_P10 "GB p10" WITH_UNITS 16
52
+ LABELVALUEDESC CONSTELLATION CAPACITY TIGHTEST_ANTENNA "Tightest" CONVERTED 16
53
+ LABELVALUEDESC CONSTELLATION CAPACITY TIGHTEST_GB_P50 "Its p50" WITH_UNITS 16
54
+ END
55
+ VERTICALBOX "MODCOD plan"
56
+ LABELVALUEDESC CONSTELLATION MODCOD SATELLITE "Satellite" CONVERTED 16
57
+ LABELVALUEDESC CONSTELLATION MODCOD ANTENNA "Antenna" CONVERTED 16
58
+ LABELVALUEDESC CONSTELLATION MODCOD AOS "AOS" CONVERTED 16
59
+ LABELVALUEDESC CONSTELLATION MODCOD CHANGES "Changes" CONVERTED 16
60
+ LABELVALUEDESC CONSTELLATION MODCOD FIRST "At AOS" CONVERTED 16
61
+ LABELVALUEDESC CONSTELLATION MODCOD LAST "At LOS" CONVERTED 16
62
+ LABELVALUEDESC CONSTELLATION MODCOD MIN_SINR_DB "Min SINR" WITH_UNITS 16
63
+ LABELVALUEDESC CONSTELLATION MODCOD PLANNED_PASSES "Planned" CONVERTED 16
64
+ END
65
+ END
@@ -86,8 +86,9 @@ function axisTicks(max, n = 4) {
86
86
  const raw = max / n;
87
87
  const mag = 10 ** Math.floor(Math.log10(raw));
88
88
  const step = [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw) || raw;
89
- const out = [];
90
- for (let v = 0; v <= max + step * 0.01; v += step) out.push(v);
89
+ // The top tick is at or above max, so the data never runs past the axis.
90
+ const out = [0];
91
+ while (out[out.length - 1] < max - step * 0.01) out.push(out[out.length - 1] + step);
91
92
  return out;
92
93
  }
93
94
 
@@ -302,8 +303,8 @@ const RFI = {
302
303
  return `<div class="cf-card"><div class="cf-card-head"><span class="cf-status-warn" aria-hidden="true">▲</span><b>${approved ? 'Approved: carry out' : 'Reroute advised'}</b></div><div>${esc(linkLabel(i))} from ${minute(i.target_at)}: up to ${num(i.value?.p90)} dB of RFI at p90, lock-loss risk ${pct(risk(i))}.</div><div class="cf-card-action">Reroute off ${esc(shortAntenna(i.entity.antenna_id))}</div>${approved ? '<div class="cf-note">Approved in Constellation.</div>' : ''}</div>`;
303
304
  });
304
305
  const waiting = held ? ` ${held} awaiting approval in Constellation.` : '';
305
- const body = cards.length ? `<div class="cf-cards">${cards.join('')}</div>` : `<p class="cf-empty">No reroutes advised.${waiting}</p>`;
306
- return section('Reroutes', body, `Approved first, then the highest lock-loss risk.${waiting}`);
306
+ if (!cards.length) return section('Reroutes', `<p class="cf-empty">No reroutes advised.${waiting}</p>`);
307
+ return section('Reroutes', `<div class="cf-cards">${cards.join('')}</div>`, `Approved first, then the highest lock-loss risk.${waiting}`);
307
308
  },
308
309
  list(run, items, selected) {
309
310
  const rows = items
@@ -368,7 +369,12 @@ export const VIEWS = {
368
369
  }
369
370
  if (run.kind === 'rain-fade-swap') {
370
371
  const risky = items.filter(actionable).slice(0, 20);
371
- if (!risky.length) return section('Passes at weather risk', '<p class="cf-empty">No pass is at risk in this run.</p>');
372
+ if (!risky.length) {
373
+ // A held swap is not shown until it is approved, but its pass is still at risk.
374
+ const held = items.filter((i) => actionState(i) === 'pending').length;
375
+ const none = held ? `${held} ${held === 1 ? 'pass' : 'passes'} at risk awaiting approval in Constellation; each shows here once approved.` : 'No pass is at risk in this run.';
376
+ return section('Passes at weather risk', `<p class="cf-empty">${none}</p>`);
377
+ }
372
378
  return section(
373
379
  'What each at-risk pass keeps if it rains',
374
380
  dumbbell(
@@ -441,7 +447,8 @@ export const VIEWS = {
441
447
  const waiting = held ? ` ${held} awaiting approval in Constellation.` : '';
442
448
  const more = (all.length > 6 ? `The ${6} soonest of ${all.length}. Every swap is in Results below.` : 'Approved first, then the soonest decision.') + waiting;
443
449
  const title = all.some((i) => actionState(i) === 'approved') ? 'Swaps to carry out and to decide' : 'Swaps to decide';
444
- return section(title, cards.length ? `<div class="cf-cards">${cards.join('')}</div>` : `<p class="cf-empty">No swaps to decide.${waiting}</p>`, more);
450
+ if (!cards.length) return section(title, `<p class="cf-empty">No swaps to decide.${waiting}</p>`);
451
+ return section(title, `<div class="cf-cards">${cards.join('')}</div>`, more);
445
452
  },
446
453
 
447
454
  list(run, items, selected) {
@@ -631,7 +638,7 @@ export function mountForecast(element, { load, refreshMs = REFRESH_MS, theme = '
631
638
  body = `<p class="cf-meta">${esc(TITLES[run.kind] ?? run.kind)} · workflow ${esc(run.workflow)} v${esc(run.workflow_version)} · run ${esc(run.run_id)} · delivered ${ago(run.delivered_at)}</p>${flows}<div class="cf-grid2"><div>${main}</div><div>${side}</div></div>`;
632
639
  }
633
640
  root.innerHTML = `<div class="cf-head"><h2>Constellation Forecast</h2><span class="cf-forecast">Forecast · not scheduled contacts</span></div>
634
- <p class="cf-meta">Predictions from Constellation workflows. Measured telemetry lives in its usual place.</p>
641
+ <p class="cf-meta">Predicted by Constellation workflows. Nothing here is measured telemetry.</p>
635
642
  ${error === 'restarting' ? '<p class="cf-note">Waiting for the host to come back; this refreshes on its own.</p>' : error ? `<div class="cf-error">Could not read the forecasts: ${esc(error)}</div>` : ''}
636
643
  ${workflows.length ? `<div class="cf-cats" role="tablist">${cats}</div>` : ''}${body}`;
637
644
  }
@@ -34,7 +34,10 @@ System.register([], function (_export) {
34
34
  location.assign(`/login?redirect=${encodeURIComponent(location.pathname)}`);
35
35
  throw new Error('Your COSMOS sign-in expired: signing in again');
36
36
  }
37
- if (!response.ok) throw new Error(response.status === 404 ? 'none yet' : `COSMOS answered ${response.status}`);
37
+ // Not written yet (before the first run): a 404, or before COSMOS 7.5 a 500 whose message
38
+ // says the file is not there.
39
+ const missing = response.status === 404 || (response.status === 500 && /No such file/i.test((await response.json().catch(() => ({}))).message || ''));
40
+ if (!response.ok) throw new Error(missing ? 'none yet' : `COSMOS answered ${response.status}`);
38
41
  const bytes = Uint8Array.from(atob((await response.json()).contents), (c) => c.charCodeAt(0));
39
42
  return JSON.parse(new TextDecoder().decode(bytes));
40
43
  }
@@ -79,11 +82,19 @@ System.register([], function (_export) {
79
82
  mount: async () => {
80
83
  ({ mountForecast } = await import(`${BASE}/forecast-view.js`));
81
84
  const root = document.getElementById('openc3-tool');
85
+ // The tool's name where COSMOS's own tools put theirs: the tab and the top bar.
86
+ document.title = 'Constellation Forecast';
87
+ const menu = document.getElementById('openc3-menu');
88
+ if (menu) menu.innerHTML = '<span style="font-size:32px; line-height:1.2">Constellation Forecast</span>';
89
+ // COSMOS's theme tokens, so the view follows whichever COSMOS theme is chosen.
82
90
  root.innerHTML = `<style>
83
- .cfc { min-height:100%; background:#1a1a19; }
84
- .cfc-nav { display:flex; gap:4px; flex-wrap:wrap; padding:12px 24px 0; font:13px Roboto, system-ui, sans-serif; }
85
- .cfc-nav a { color:#a3a29c; text-decoration:none; padding:4px 10px; border:1px solid rgba(255,255,255,.12); border-radius:6px; }
86
- .cfc-nav a[aria-current] { color:#e8e8e6; border-color:#e8e8e6; }
91
+ .cfc { min-height:100%; background:var(--color-background-surface-default, #1b2d3e); }
92
+ .cfc .cf[data-theme] { --cf-ink:var(--color-text-primary, #fff); --cf-muted:var(--color-text-secondary, #d4d8dd);
93
+ --cf-line:var(--color-border-interactive-muted, #2b659b); --cf-surface:var(--color-background-surface-default, #1b2d3e);
94
+ --cf-raise:var(--color-background-surface-header, #172635); font-family:inherit; }
95
+ .cfc-nav { display:flex; gap:4px; flex-wrap:wrap; padding:12px 24px 0; font-size:13px; }
96
+ .cfc-nav a { color:var(--color-text-secondary, #d4d8dd); text-decoration:none; padding:4px 10px; border:1px solid var(--color-border-interactive-muted, #2b659b); border-radius:6px; }
97
+ .cfc-nav a[aria-current] { color:var(--color-text-primary, #fff); border-color:var(--color-border-interactive-default, #4dacff); }
87
98
  </style><div class="cfc"><nav class="cfc-nav" aria-label="Constellation Forecast"></nav><div></div></div>`;
88
99
  [nav, body] = [root.querySelector('nav'), root.querySelector('nav + div')];
89
100
  nav.addEventListener('click', follow);
@@ -95,6 +106,8 @@ System.register([], function (_export) {
95
106
  view?.destroy();
96
107
  view = null;
97
108
  document.getElementById('openc3-tool').innerHTML = '';
109
+ const menu = document.getElementById('openc3-menu');
110
+ if (menu) menu.innerHTML = '';
98
111
  },
99
112
  });
100
113
  },
metadata CHANGED
@@ -1,40 +1,50 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: openc3-cosmos-constellation
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.8.0
4
+ version: 0.8.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Constellation Space Corp
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-18 00:00:00.000000000 Z
11
+ date: 2026-11-20 00:00:00.000000000 Z
12
12
  dependencies: []
13
- description: |2
14
- A CONSTELLATION target whose packets a bridge microservice fills from the Constellation
15
- feed: the next predicted pass, the next 24 hours, the soonest rain-fade swap to decide, a
16
- day's capacity across the antennas (CAPACITY), the next pass's MODCOD plan (MODCOD), and the
17
- run they came from. Every value is a forecast.
13
+ description: 'A CONSTELLATION target whose packets a bridge microservice fills from
14
+ the Constellation feed: the next predicted pass, the next 24 hours, the soonest
15
+ rain-fade swap to decide, a day''s capacity across the antennas (CAPACITY), the
16
+ next pass''s MODCOD plan (MODCOD), and the run they came from. A Telemetry Viewer
17
+ screen shows them all, and a Constellation Forecast tool charts each workflow. Every
18
+ value is a forecast.'
18
19
  email:
19
20
  - support@constellation.space
20
21
  executables: []
21
22
  extensions: []
22
23
  extra_rdoc_files: []
23
24
  files:
25
+ - LICENSE
24
26
  - Rakefile
25
27
  - microservices/BRIDGE/bridge.py
26
28
  - microservices/BRIDGE/constellation_space/__init__.py
27
29
  - microservices/BRIDGE/constellation_space/results.py
28
30
  - plugin.txt
31
+ - public/store_img.png
29
32
  - targets/CONSTELLATION/cmd_tlm/tlm.txt
33
+ - targets/CONSTELLATION/screens/forecast.txt
30
34
  - targets/CONSTELLATION/target.txt
31
35
  - tools/constellationforecast/forecast-view.js
32
36
  - tools/constellationforecast/main.js
33
- homepage: https://constellation.space
37
+ homepage: https://platform.constellation.space/docs/connectors/cosmos
34
38
  licenses:
35
39
  - Apache-2.0
36
40
  metadata:
37
41
  source_code_uri: https://github.com/constellationhq/connectors
42
+ openc3_store_title: Constellation Forecasts
43
+ openc3_store_keywords: forecast, ground station, pass prediction, rain fade, modcod,
44
+ antenna capacity, scheduling
45
+ openc3_store_image: public/store_img.png
46
+ openc3_store_access_type: public
47
+ openc3_cosmos_minimum_version: 7.0.0
38
48
  post_install_message:
39
49
  rdoc_options: []
40
50
  require_paths: