Repository navigation
Expand file tree
/
Copy pathconsole.py
More file actions
executable file
·1211 lines (1067 loc) · 58.8 KB
/
Copy pathconsole.py
File metadata and controls
executable file
·1211 lines (1067 loc) · 58.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""A control console in the browser, for the person beside the telescope.
./console.py open the console (http://127.0.0.1:8081)
./console.py --demo try it with a simulated mount and a made-up run
Every button runs one of the project's own commands, as a person would type
it, so every limit and the MOTION_LOCKED file apply as they always do. A move
is first planned with --dry-run and shown; the mount moves only when the
person confirms that plan. Stop is always allowed.
It listens on this computer only and needs a key made each time it starts.
serve.py remains the read-only page for the rest of the house. The design is
in docs/gui.md.
"""
import os
import sys
if "--demo" in sys.argv[1:]:
os.environ["TY_DEMO"] = "1" # before anything is imported: the demo keeps its own files
import argparse
import json
import math
import secrets
import subprocess
import threading
import time
import uuid
import webbrowser
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import unquote, urlparse
import config
import host
import interface
ROOT = Path(__file__).parent
PAGE = ROOT / "console"
WEB = config.DATA / "web"
PYTHON = sys.executable
PLAN_LIFE = 120 # seconds a plan may be confirmed for
# Seconds a job asked to end is given before it is killed. On Windows the
# request is only noticed between calls, so it must outlast a frame arriving.
FINISH_WAIT = 30
KEEP_LINES = 400 # progress lines kept per job
# The page's own files, and the pictures it may show. Nothing else is served.
FILES = {"/": ("index.html", "text/html; charset=utf-8"),
"/console.css": ("console.css", "text/css; charset=utf-8"),
"/console.js": ("console.js", "text/javascript; charset=utf-8"),
"/icons.svg": ("icons.svg", "image/svg+xml")}
PICTURES = ("latest.jpg", "stack.jpg", "scope.jpg", "clouds.jpg", "landmark.jpg", "polaris.jpg")
HEADERS = {
"Content-Security-Policy": "default-src 'self'; img-src 'self' data:; style-src 'self'; "
"script-src 'self'; connect-src 'self'; frame-ancestors 'none'; "
"base-uri 'none'; form-action 'self'",
"X-Frame-Options": "DENY",
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "no-referrer",
"Cache-Control": "no-store",
}
class Refused(Exception):
"""A request the console will not act on. Becomes an error envelope."""
def __init__(self, message, status=409, code="INVALID_REQUEST"):
super().__init__(message)
self.message, self.status, self.code = message, status, code
# --- what the console can be asked to do -------------------------------------
#
# Each action builds its command from checked values and nothing else. `uses`
# says what it holds while it runs: "mount" (which Stop ends at once),
# "camera", or None for an order to a run already going. `moves` means it
# goes through a plan that a person confirms.
def target_name(params):
import mount
name = str(params.get("target", "")).strip()
if not name or len(name) > 60:
raise Refused("Choose a target.")
try:
return mount.find_target(name)["id"]
except interface.Refusal as refusal:
raise Refused(refusal.message, code=refusal.code_name)
def number(params, key, low, high, default=None, whole=False):
value = params.get(key, default)
try:
value = int(value) if whole else float(value)
except (TypeError, ValueError):
raise Refused(f"{key} must be a number.")
if not low <= value <= high:
raise Refused(f"{key} must be between {low:g} and {high:g}.")
return value
def choice(params, key, allowed, default):
value = params.get(key, default)
if value not in allowed:
raise Refused(f"{key} must be one of: {', '.join(map(str, allowed))}.")
return value
def goto(params):
return ["mount.py", "goto", target_name(params)] + (["--solve"] if params.get("solve") else [])
def run(params):
exposure = choice(params, "exposure", ("auto", "1", "2", "3", "4"), "2")
cmd = ["shoot.py", target_name(params), "--frames", str(number(params, "frames", 1, 5000, 60, True)),
"--exposure", exposure, "--gain", str(number(params, "gain", 100, 5000, 1500, True))]
if not params.get("recentre", True):
return cmd + ["--no-recentre"] # shoot.py then never touches the mount, assist included
return cmd + (["--assist"] if params.get("assist") else [])
def programmes():
"""The patrol programmes there are: the files in programmes/."""
return tuple(sorted(p.stem for p in (ROOT / "programmes").glob("*.toml")))
def patrolling(params):
cmd = ["patrol.py", choice(params, "programme", programmes(), "m31-novae")]
if params.get("minutes") not in (None, ""):
cmd += ["--minutes", f"{number(params, 'minutes', 1, 240):g}"]
return cmd
def focusing(params):
sound = choice(params, "sound", ("sound", "silent"), "sound")
return ["focus.py"] + {"sound": [], "silent": ["--quiet"]}[sound]
def survey(params):
cmd = ["horizon.py"]
if params.get("trace"):
cmd.append("--trace")
if params.get("daylight"):
cmd.append("--daylight")
if params.get("fresh"):
cmd.append("--fresh")
return cmd
def picture_file(params):
"""A picture on this computer, by its path. It is only ever read."""
path = params.get("file")
if not isinstance(path, str) or not path.strip() or len(path) > 400 or path.strip().startswith("-") \
or any(ord(c) < 32 for c in path):
raise Refused("Give the panorama's file: its full path on this computer.")
return path.strip().strip('"')
def which_picture(params):
return ["--picture", str(number(params, "picture", 1, 3, 1, True))]
def panorama_mark(params):
cmd = ["panorama.py", "mark", f"{number(params, 'x', 0, 1):g}", f"{number(params, 'y', 0, 1):g}"]
if params.get("telescope"):
cmd.append("--telescope")
elif params.get("landmark"):
cmd += ["--landmark", landmark_name({"name": params["landmark"]})]
else:
cmd += [f"{number(params, 'bearing', 0, 360):g}", f"{number(params, 'height', -10, 89):g}"]
return cmd + which_picture(params)
def panorama_move(params):
points = params.get("points")
if not isinstance(points, list) or not 1 <= len(points) <= 150:
raise Refused("No points of the skyline were sent.")
pairs = []
for point in points:
if not isinstance(point, list) or len(point) != 2:
raise Refused("A point of the skyline is how far across and how far down.")
pairs.append(",".join(f"{number({'v': v}, 'v', 0, 1):.4f}" for v in point))
return ["panorama.py", "move"] + pairs + which_picture(params)
def landmark_name(params):
import landmark
try:
return landmark.name_ok(str(params.get("name", "")))
except interface.Refusal as refusal:
raise Refused(refusal.message)
def pointing(params):
return ["mount.py", "point", f"{number(params, 'bearing', 0, 360):g}", f"{number(params, 'height', 2, 89):g}"]
def polar_measure(params):
"""A polar measurement, with the turns made on each pair of bolts since
the last one if the person says what they were, to be learned from."""
import polaralign
turned = []
for axis in ("azimuth", "altitude"):
# The person says which bolt of the pair went in and how far; the
# sign polaralign.py wants (the first of the pair is plus) is made here.
said = params.get(axis) or {}
if not isinstance(said, dict):
raise Refused(f"{axis} is which bolt was turned in, and how far.")
first, second = polaralign.PAIRS[axis]
bolt = choice(said, "bolt", ("neither", first, second), "neither")
turns = number(said, "turns", 0, 30, 0)
turned.append(0 if bolt == "neither" else turns if bolt == first else -turns)
return ["polaralign.py"] + (["--turned", f"{turned[0]:g}", f"{turned[1]:g}"] if any(turned) else [])
def calibration(params):
kind = choice(params, "kind", ("dark", "bias", "flat"), "dark")
return ["calibrate.py", kind, "--frames", str(number(params, "frames", 1, 200, 20, True)),
"--exposure", f"{number(params, 'exposure', 0.001, 60, 2.0):g}",
"--gain", str(number(params, "gain", 100, 5000, 1500, True))]
def restacking(params):
name = target_name(params)
return ["restack.py", name] + (["--all"] if params.get("all") else [])
ACTIONS = {
"goto": {"label": "Go to {target}", "command": goto, "uses": "mount", "moves": True},
"home": {"label": "Home", "command": lambda p: ["mount.py", "home"], "uses": "mount", "moves": True},
"zenith": {"label": "Zenith", "command": lambda p: ["mount.py", "zenith"], "uses": "mount", "moves": True},
"compensate": {"label": "Compensate for drift", "command": lambda p: ["mount.py", "compensate"],
"uses": "mount", "moves": True,
"says": "This slews the mount twice, plate-solving each time, and then changes "
"the Dec motor's creep."},
"drift": {"label": "Measure drift", "command": lambda p: ["mount.py", "drift"],
"uses": "mount", "moves": True,
"says": "The tube does not slew, but the Dec motor's creep will be changed."},
"sync": {"label": "Sync from plate solve", "command": lambda p: ["mount.py", "sync"],
"uses": "mount", "moves": False},
"position": {"label": "Read position", "command": lambda p: ["mount.py", "status"],
"uses": "mount", "moves": False, "demo": True},
"run": {"label": "Image {target}", "command": run, "uses": "mount", "moves": True},
"patrol": {"label": "Discovery patrol", "command": patrolling, "uses": "mount", "moves": True,
"says": "It points at each field in turn, images it, and looks for anything new "
"against the field's reference. A MOTION_LOCKED file stops it before anything moves."},
"focus": {"label": "Focusing", "command": focusing, "uses": "camera", "moves": False},
"horizon": {"label": "Horizon survey", "command": survey, "uses": "mount", "moves": True,
"says": "This moves the mount all over the sky, over the pole and back, for "
"about a minute per look. Keep clear of it while it runs."},
"compendium": {"label": "Download Gary Imm's Compendium", "uses": None, "moves": False,
"command": lambda p: ["compendium.py", "fetch"]},
"horizon-forget": {"label": "Forget the measured skyline", "uses": None, "moves": False,
"command": lambda p: ["horizon.py", "--forget"]},
# The skyline from a phone panorama (panorama.py). None of it moves the
# mount; a mark taken from the telescope reads where it points.
"panorama-use": {"label": "Find the skyline in a panorama", "uses": None, "moves": False,
"command": lambda p: ["panorama.py", "use", picture_file(p)]},
"panorama-also": {"label": "Add a panorama from another height", "uses": None, "moves": False,
"command": lambda p: ["panorama.py", "also", picture_file(p)]},
"panorama-mark": {"label": "Mark the panorama", "uses": None, "moves": False, "command": panorama_mark},
"panorama-unmark": {"label": "Remove a mark", "uses": None, "moves": False,
"command": lambda p: ["panorama.py", "unmark", str(number(p, "mark", 1, 20, whole=True))]
+ which_picture(p)},
"panorama-move": {"label": "Correct the skyline", "uses": None, "moves": False, "command": panorama_move},
"panorama-save": {"label": "Keep the panorama's skyline", "uses": None, "moves": False,
"command": lambda p: ["panorama.py", "save"]},
"panorama-clear": {"label": "Clear the panoramas", "uses": None, "moves": False,
"command": lambda p: ["panorama.py", "clear"]},
# Fetches nothing from the network and needs no camera to start: it is
# what says why there is no camera yet.
"camera-setup": {"label": "Set up the camera", "uses": "camera", "moves": False,
"command": lambda p: ["camera_setup.py", "--open"]},
"point": {"label": "Point at a bearing", "command": pointing, "uses": "mount", "moves": True},
"landmark-remember": {"label": "Remember landmark", "uses": "mount", "moves": False,
"command": lambda p: ["landmark.py", "remember", landmark_name(p)]},
"landmark-check": {"label": "Check landmark", "uses": "mount", "moves": True,
"command": lambda p: ["landmark.py", "check", landmark_name(p), "--watch", "40"],
"says": "The mount turns to where it was when the landmark was remembered, holds "
"there, and photographs it every few seconds for two minutes while you "
"turn the azimuth bolts. Press Finish when it is on the cross."},
"polar": {"label": "Polar alignment", "command": lambda p: polar_measure(p), "uses": "mount", "moves": True,
"says": "This photographs the sky where the telescope is, slews 25° away from the "
"meridian twice, photographing each time, and returns. Start from a target "
"well away from the pole."},
# Polar alignment before dark, from Polaris alone (polaris.py).
"polaris-check": {"label": "Is it worth trying by day", "uses": "camera", "moves": False,
"command": lambda p: ["polaris.py", "check"]},
"polaris-find": {"label": "Find Polaris by day", "uses": "mount", "moves": True,
"command": lambda p: ["polaris.py", "find", "--record"] + (["--anyway"] if p.get("anyway") else []),
"says": "From the home position the RA axis turns 88° to one side and across to the "
"other, and back again if the star is further out: the counterweight bar "
"swings level both ways. The tube tips a few degrees either side of the pole. "
"It stops at the first look that shows Polaris. It will not start on a focus "
"nobody has checked today."},
"polaris-align": {"label": "Measure from Polaris", "uses": "mount", "moves": True,
"command": lambda p: ["polaris.py", "align", "--watch", "60"],
"says": "With Polaris in view, the tube tips a tenth of a degree and the RA axis turns "
"to five readings up to 12° apart, then goes back. It then photographs Polaris "
"every few seconds for about four minutes and says how far there is to go "
"while you turn the bolts. Press Finish when it says close enough."},
# The rig measuring itself (ty characterise says which have been made).
"polar-repeat": {"label": "Polar alignment, five times over", "uses": "mount", "moves": True,
"command": lambda p: ["polaralign.py", "--repeat", "5", "--step", f"{number(p, 'step', 5, 25, 12):g}"],
"says": "Five polar measurements one after another, to see how well they agree: each "
"slews 12° away from the meridian twice and returns. Leave the bolts alone until "
"it has finished. About ten minutes."},
"find-home": {"label": "Find the true home position", "uses": "mount", "moves": True,
"command": lambda p: ["mount.py", "findhome"],
"says": "After polar alignment. The mount goes to eight places, four each side of the "
"meridian, and plate-solves at each, to work out where home really is. The tube "
"swings over the pole once. Nothing is changed by it."},
"true-home": {"label": "Go to the true home position", "uses": "mount", "moves": True,
"command": lambda p: ["mount.py", "truehome"],
"says": "The mount goes to the home position just measured and holds there. Mark both "
"joints, then switch the handset off and on with the mount on its marks."},
"pointing-survey": {"label": "Pointing survey", "uses": "mount", "moves": True,
"command": lambda p: ["mount.py", "pointing"],
"says": "The mount goes to eight places, four each side of the meridian, and plate-solves "
"at each. The tube swings over the pole once. Watch it the first time."},
"camera-timing": {"label": "Camera timing", "uses": "camera", "moves": False,
"command": lambda p: ["camera_test.py", "--timing"]},
"camera-trail": {"label": "Real exposure from star trails", "uses": "mount", "moves": True,
"command": lambda p: ["camera_test.py", "--trail"],
"says": "The mount stops following the sky for one ten-second frame, so the stars "
"trail, and starts following again. Point at a field with bright stars, away "
"from the pole, first."},
"camera-capabilities": {"label": "What the camera is", "uses": "camera", "moves": False,
"command": lambda p: ["camera_test.py", "--capabilities"]},
"camera-throughput": {"label": "Throughput test", "uses": "camera", "moves": False,
"command": lambda p: ["camera_test.py", "--throughput"]},
"camera-gain-sweep": {"label": "Gain sweep", "uses": "camera", "moves": False,
"command": lambda p: ["camera_test.py", "--gain-sweep"]},
"calibrate": {"label": "Calibration frames", "command": calibration, "uses": "camera", "moves": False},
"restack": {"label": "Restack {target}", "command": restacking, "uses": "camera", "moves": False},
# Orders to an imaging run that is already going: they hold nothing.
"run-finish": {"label": "Finish run", "command": lambda p: ["ty", "run", "stop"], "uses": None},
"run-recentre": {"label": "Re-centre", "command": lambda p: ["ty", "run", "recentre"], "uses": None},
"run-assist-on": {"label": "Drift assist on", "command": lambda p: ["ty", "run", "assist-on"], "uses": None},
"run-assist-off": {"label": "Drift assist off", "command": lambda p: ["ty", "run", "assist-off"], "uses": None},
}
# The demo has a pretend mount, camera and sky, so nearly everything runs in
# it. These do not: they test or set up real equipment.
NOT_IN_DEMO = ("camera-setup", "camera-capabilities", "camera-throughput", "camera-gain-sweep",
# The pretend sky does not turn and the pretend camera keeps perfect time.
"camera-timing", "camera-trail", "pointing-survey", "find-home", "true-home",
"calibrate", "sync", "drift", "compensate",
# Each demo command starts a fresh pretend mount at home, so there
# is no "where it was pointing" for a landmark to be remembered at.
"landmark-remember", "landmark-check",
# The pretend sky is a night sky: there is no daylight Polaris in it.
"polaris-check", "polaris-find", "polaris-align")
# Setting up and testing the equipment belongs to the application's own
# window. The companion page in a browser is for observing, and is refused these.
WORKSTATION = ("camera-setup", "camera-capabilities", "camera-throughput", "camera-gain-sweep",
"calibrate", "horizon", "horizon-forget", "panorama-use", "panorama-also", "panorama-mark",
"panorama-unmark", "panorama-move", "panorama-save", "panorama-clear",
"polar", "point", "landmark-remember", "landmark-check", "restack",
"polaris-check", "polaris-find", "polaris-align",
"drift", "compensate", "sync", "open-settings",
"polar-repeat", "pointing-survey", "camera-timing", "camera-trail",
"find-home", "true-home", "compendium")
# Orders that have a run move the mount or change its motors.
MOVING_ORDERS = ("run-recentre", "run-assist-on", "run-assist-off")
def moves(action, params):
"""Whether this needs a plan a person confirms. An imaging run started
without re-centring never touches the mount, so it does not."""
if action == "run":
return bool(params.get("recentre", True))
return bool(ACTIONS[action].get("moves"))
def uses(action, params):
"""What it holds while it runs: "mount" (which Stop ends at once),
"camera", or None."""
if action == "run" and not params.get("recentre", True):
return "camera"
if action == "panorama-mark" and params.get("telescope"):
return "mount" # it asks the mount where it points, so nothing else may have it
return ACTIONS[action]["uses"]
def command(action, params, demo=False, dry_run=False):
"""The full command line for an action, as a list. Never a string."""
if action not in ACTIONS:
raise Refused(f"No such action: {action}", status=404)
if demo and action in NOT_IN_DEMO:
raise Refused("That tests or sets up real equipment; there is no demo of it.", code="DEMO_UNSUPPORTED")
cmd = [PYTHON, str(ROOT / (script := ACTIONS[action]["command"](params))[0])] + script[1:]
if dry_run:
cmd.append("--dry-run")
return cmd + ["--json"]
def label(action, params):
return ACTIONS[action]["label"].format(target=str(params.get("target", "")).strip())
# --- jobs ----------------------------------------------------------------------
def start(cmd, **more):
return subprocess.Popen(cmd, cwd=ROOT, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, encoding="utf-8", errors="replace", **more)
def surroundings(demo):
"""The environment a command is started in. In the demo it says so, and
says where the demo keeps its files, so the command uses the pretend
mount and camera and never touches a real night's files."""
if not demo:
return None
return {**os.environ, "TY_DEMO": "1", "TY_DATA": str(config.DATA)}
def envelope_from(text):
"""The envelope a script printed, or None if it printed something else."""
try:
found = json.loads(text)
return found if isinstance(found, dict) and "ok" in found else None
except ValueError:
return None
class Jobs:
"""At most one job holds the mount or the camera. This is the rule, not a
first version of something cleverer."""
def __init__(self, demo=False, start=start, mode="app"):
self.demo, self.start, self.mode = demo, start, mode
self.lock = threading.Lock()
self.current = None # the job running now
self.history = [] # finished ones, newest last
self.plans = {} # id -> {"action", "params", "made", "plan", "used"}
self.stopping = False # Stop is under way: nothing may open the mount
# Counts presses of Stop. A request to start the mount that was already
# on its way when Stop was pressed carries the old count and is dead
# for good: it must not start once Stop has finished.
self.stops = 0
self.run_scope = None # what the run started here was allowed: {"mount": bool}
self.position = None # the last answer from "Read position", with its time
# -- reading
def describe(self, job):
if job is None:
return None
return {k: job[k] for k in ("id", "action", "label", "uses", "state", "outcome", "started",
"ended", "lines", "result", "error")}
def snapshot(self):
with self.lock:
return {"running": self.describe(self.current),
"recent": [self.describe(j) for j in self.history[-10:]],
"stopping": self.stopping, "position": self.position, "run_scope": self.run_scope}
# -- planning and starting
def dry_run(self, action, params):
"""The plan for a move, or a Refused carrying the script's refusal."""
done = subprocess.run(command(action, params, self.demo, dry_run=True), cwd=ROOT,
capture_output=True, text=True, encoding="utf-8", errors="replace",
timeout=120, env=surroundings(self.demo), **host.QUIET)
answer = envelope_from(done.stdout)
if answer is None:
raise Refused("The plan could not be made: " + (done.stderr.strip()[-300:] or "no answer"),
status=500, code="INTERNAL_ERROR")
if not answer["ok"]:
raise PlanRefused(answer["errors"][0])
plan = dict(answer["data"], warnings=answer["data"].get("warnings") or answer["warnings"])
if ACTIONS[action].get("says"):
plan["says"] = ACTIONS[action]["says"]
return plan
def plan(self, action, params):
if action not in ACTIONS:
raise Refused(f"No such action: {action}", status=404)
self.allowed_here(action)
if not moves(action, params):
raise Refused(f"{action} is not planned; it does not move the mount.")
found = self.dry_run(action, params)
with self.lock:
now = time.time()
self.plans = {k: v for k, v in self.plans.items() if now - v["made"] < PLAN_LIFE}
plan_id = uuid.uuid4().hex
self.plans[plan_id] = {"action": action, "params": params, "made": now, "plan": found,
"used": False}
return {"id": plan_id, "action": action, "label": label(action, params), "plan": found,
"expires_in_s": PLAN_LIFE}
def confirm(self, plan_id):
"""Start a planned move, if the plan still holds. The plan is made
again first: it described the world two minutes ago at most, and the
sky and the mount move on."""
with self.lock:
held = self.plans.get(plan_id)
if held is None or held["used"] or time.time() - held["made"] >= PLAN_LIFE:
raise Refused("That plan is no longer valid. Make it again.", status=410)
held["used"] = True
stops = self.stops
again = self.dry_run(held["action"], held["params"])
if changed(held["plan"], again):
fresh = self.plan(held["action"], held["params"])
return dict(fresh, changed=True, message="The situation has changed. Look at the new plan.")
return self.begin(held["action"], held["params"], stops)
def allowed_here(self, action):
if self.mode == "companion" and action in WORKSTATION:
raise Refused("That is done in the TelescopeYoke application, not in the companion page.", 403)
def act(self, action, params):
if action not in ACTIONS:
raise Refused(f"No such action: {action}", status=404)
self.allowed_here(action)
if moves(action, params):
raise Refused(f"{label(action, params)} moves the mount: it needs a confirmed plan.")
if action in MOVING_ORDERS:
# shoot.py ignores these in a run started without re-centring, and
# the console cannot know what a run started elsewhere was allowed.
with self.lock:
scope = self.run_scope
if scope is None:
raise Refused("No imaging run started from this console is going. Give the order "
"where the run was started.")
if not scope["mount"]:
raise Refused("This run was started without re-centring, so it may not move the "
"mount. Finish it and start one with re-centring.")
with self.lock:
stops = self.stops
return self.begin(action, params, stops)
def begin(self, action, params, stops=None):
"""Start an action. `stops` is the count of Stop presses when the
request was made; if Stop has been pressed since, it is refused."""
using = uses(action, params)
cmd = command(action, params, self.demo)
with self.lock:
touches_mount = using == "mount" or action in MOVING_ORDERS
if touches_mount and (self.stopping or (stops is not None and stops != self.stops)):
raise Refused("Stop was pressed. This request is cancelled; plan it again if it is "
"still wanted." if not self.stopping else
"Stop is under way. Nothing may use the mount until it has answered.")
if using and self.current:
raise Refused(f"Busy: {self.current['label']} is running.")
job = {"id": uuid.uuid4().hex, "action": action, "label": label(action, params),
"uses": using, "state": "running", "outcome": None, "started": time.time(),
"ended": None, "lines": [], "result": None, "error": None, "stopped": False}
job["child"] = self.start(cmd, env=surroundings(self.demo), **host.OWN_GROUP)
if using:
self.current = job
if action == "run":
self.run_scope = {"mount": using == "mount"}
threading.Thread(target=self._watch, args=(job,), daemon=True).start()
return {"job": self.describe(job)}
def _watch(self, job):
child = job["child"]
def progress():
for line in child.stderr:
if line.strip():
job["lines"].append({"time": time.time(), "text": line.rstrip()})
del job["lines"][:-KEEP_LINES]
reader = threading.Thread(target=progress, daemon=True)
reader.start()
printed = child.stdout.read()
child.wait()
reader.join(timeout=2)
answer = envelope_from(printed)
with self.lock:
job["ended"] = time.time()
if job["stopped"]:
job["outcome"], job["error"] = "stopped", {"message": "Ended by Stop."}
elif job.get("finishing") and (answer is None or answer["ok"]):
job["outcome"], job["result"] = "finished", (answer or {}).get("data")
elif answer and answer["ok"]:
job["outcome"], job["result"] = "finished", answer["data"]
else:
job["outcome"] = "failed"
job["error"] = (answer["errors"][0] if answer and answer["errors"] else
{"message": (job["lines"][-1]["text"] if job["lines"] else
f"It ended with code {child.returncode} and no answer.")})
job["state"] = "ended"
if job["action"] == "position" and job["result"]:
self.position = dict(job["result"], read=job["ended"])
if self.current is job:
self.current = None
if job["action"] == "run":
self.run_scope = None
self.history.append(job)
del self.history[:-20]
# -- ending
def finish(self):
"""Ask the running job to end as Ctrl+C would, so that it closes the
camera properly; kill it only if it does not go. This is not Stop."""
with self.lock:
job = self.current
if job is None:
raise Refused("Nothing is running.")
job["finishing"] = True
child = job["child"]
try:
host.ask_to_end(child)
except OSError:
pass # it has just gone by itself
def make_sure():
try:
child.wait(timeout=FINISH_WAIT)
except subprocess.TimeoutExpired:
child.kill()
threading.Thread(target=make_sure, daemon=True).start()
return {"finishing": job["label"]}
def stop(self):
"""Stop the mount, now. In this order: nothing may open the mount from
here on; whatever holds its serial port is killed, since on Windows a
port can be held by one process only; then the handset is told to
stop. Returns how long that took."""
pressed = time.monotonic()
with self.lock:
self.stopping = True
self.stops += 1 # every mount start already on its way is now dead
job = self.current if self.current and self.current["uses"] == "mount" else None
if job:
job["stopped"] = True
try:
if job:
job["child"].kill()
job["child"].wait(timeout=10) # until the system says it has gone
cmd = [PYTHON, str(ROOT / "mount.py"), "stop", "--json"]
done = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, encoding="utf-8",
errors="replace", timeout=30, env=surroundings(self.demo), **host.QUIET)
answer = envelope_from(done.stdout)
finally:
with self.lock:
self.stopping = False
took = round(time.monotonic() - pressed, 2)
ok = bool(answer and answer["ok"])
return {"stopped": ok, "seconds": took, "ended_job": job["label"] if job else None,
"error": None if ok else (answer["errors"][0] if answer and answer["errors"] else
{"message": done.stderr.strip()[-300:] or "no answer"})}
def close(self):
"""The console is closing: end whatever is running, and always tell
the mount to stop, whether or not anything here was using it."""
with self.lock:
job = self.current
if job and job["uses"] != "mount":
try:
host.ask_to_end(job["child"])
job["child"].wait(timeout=FINISH_WAIT)
except (OSError, subprocess.TimeoutExpired):
job["child"].kill()
return self.stop()
class PlanRefused(Exception):
"""The script refused the plan: the limits working, not a fault."""
def __init__(self, error):
super().__init__(error.get("message", ""))
self.error = error
def changed(before, after):
"""Whether a plan made again differs in what matters from the one the
person saw."""
for key in ("would_move", "safe", "pier_side", "target"):
if before.get(key) != after.get(key):
return True
if sorted(before.get("warnings") or []) != sorted(after.get("warnings") or []):
return True
a, b = before.get("goto") or before, after.get("goto") or after
if a.get("pier_side") != b.get("pier_side"):
return True
for key, most in (("altitude_deg", 1.0), ("hour_angle_hours", 1 / 15)):
if key in a and key in b and abs(a[key] - b[key]) > most:
return True
return False
# --- what the page reads ---------------------------------------------------------
class Reader:
"""The read-only answers, each kept for a little while so that a page
asking every two seconds does not run the doctor every two seconds."""
def __init__(self, demo=False, mode="app"):
self.demo, self.mode, self.kept, self.lock = demo, mode, {}, threading.Lock()
def get(self, name, work, seconds):
with self.lock:
held = self.kept.get(name)
if held and time.time() - held[0] < seconds:
return held[1]
result = interface.run(name, work)
with self.lock:
self.kept[name] = (time.time(), result)
return result
def forget(self, name):
with self.lock:
self.kept.pop(name, None)
def state(self):
import agent
import config
site = (config.load() if config.FILE.exists() else config.example())["site"]["name"]
sky = {}
if self.demo:
import simulator
sky = {"sky": simulator.sky()}
import activity
import schedule
return dict(agent.status(), demo=self.demo, site=site, capabilities=agent.capabilities(),
activity=activity.now(), schedule=schedule.view(),
available=[a for a in ACTIONS if (self.mode == "app" or a not in WORKSTATION)
and not (self.demo and a in NOT_IN_DEMO)],
**sky, **self.about())
def about(self):
"""What this is and how it is set up, for the page's frame."""
import agent
import config
import doctor
hardware = config.hardware()
return {"mode": self.mode, "version": agent.VERSION, "configured": config.FILE.exists(), "rig": config.RIG,
"settings_file": str(config.FILE), "camera_backend": hardware["camera"]["backend"],
"mount_link": doctor.mount_link(), "system": sys.platform}
def session(self):
import agent
try:
return agent.session(include_series=True)
except interface.Refusal:
return {"none": True} # no imaging run yet: not a fault
def catalogue(self):
import mount
import sky
stars = [{"id": name, "alt_id": "", "name": "star", "kind": "star"} for name in mount.STARS]
return {"targets": stars + [{k: t[k] for k in ("id", "alt_id", "name", "kind")}
for t in sky.load_targets()]}
def report(self):
"""The night as the status page shows it: the cards, the conditions,
the timeline's hours, the ranked targets and the weather table."""
import config
import page
import tonight
cfg = config.example() if self.demo or not config.FILE.exists() else config.load()
rep = tonight.build(cfg, demo=self.demo)
w = rep["weather"]
return {
"cards": [dict(zip(("title", "big", "small", "tone"), one)) for one in page.card_data(rep)],
"conditions": page.conditions(rep),
"night": {k: rep[k] for k in ("sunset", "sunrise", "dark_start", "dark_end", "dark_level", "now")},
"moon": rep["moon"],
"hours": [{"time": h["time"], "cloud": h["cloud"], "level": page.level(h["cloud"], 25, 60)}
for h in w["hours"]] if w else [],
"weather_head": tonight.WEATHER_HEAD,
"weather_rows": page.weather_rows(w) if w else [],
"target_head": tonight.TARGET_HEAD,
"targets": [{"id": t["id"], "name": t["name"], "kind": t["kind"], "score": round(t["score"]),
"best": t["best"], "best_alt": round(t["best_alt"]), "direction": t["direction"],
"start": t["start"], "end": t["end"], "tags": t["tags"], "now": t["now"],
"rating": t.get("rating"), "note": t.get("note", ""), "palette": t.get("palette"),
"row": tonight.target_row(i, t)}
for i, t in enumerate(rep["targets"][:40], 1)],
}
def system(self):
"""The state of the kit as the status page's rows."""
import serve
return {"rows": serve.system_status()}
def finished(self):
"""File names of the finished pictures in web/. None in the demo: its
run is made up, and the real ones are not part of it."""
import serve
return [p["file"] for p in serve.pictures()]
def gallery(self):
import serve
return {"pictures": serve.pictures()}
def landmarks(self):
import landmark
return {"landmarks": landmark.listed(), "degrees_per_pixel": landmark.scale()}
def polar(self):
"""The last polar alignment measurement, if there is one."""
import mount
import polaralign
nothing = {"measured": None, "first": polaralign.guidance(0.0, 0.0)["first"]}
if not mount.DRIFT_FILE.exists():
return nothing
saved = json.loads(mount.DRIFT_FILE.read_text(encoding="utf-8"))
found = saved.get("polar")
if not found:
return nothing
import config
import polaralign
settings = config.load() if config.FILE.exists() and not self.demo else config.example()
return {"measured": saved.get("saved"), "azimuth_deg": round(found["azimuth"], 2),
"altitude_deg": round(found["altitude"], 2),
# What to do with your hands about it: which bolt, about how far.
"guidance": polaralign.for_mount(found["azimuth"], found["altitude"], settings)}
def framing(self, name):
"""How a target fits the camera: the field of view from the sensor
and focal length in the settings, and the target's size from the
catalogue where it gives one."""
import config
import mount
cfg = config.hardware()
camera, focal = cfg["camera"], config.focal_length(cfg) # the camera in use through its train
degrees = lambda pixels: math.degrees(pixels * camera["pixel_size_um"] / 1000 / focal)
target = mount.find_target(name)
return {"field_deg": [round(degrees(camera["width"]), 3), round(degrees(camera["height"]), 3)],
"scale_arcsec_px": round(206.265 * camera["pixel_size_um"] / focal, 2),
"size_arcmin": target.get("size"), "minor_arcmin": target.get("minor")}
def settings(self):
"""Every setting the application can change, with its value now."""
import config
if self.mode != "app":
raise interface.Refusal("INVALID_REQUEST", "Settings are changed in the TelescopeYoke application.")
written = config._read(config.EXAMPLE if self.demo or not config.FILE.exists() else config.FILE)
in_use = config._merged(written)
# A setting that may be left blank shows what the file says, blank
# included; the rest show the value in use, default or not. A list
# (["youtube", "twitch"] for the stream) shows as its choice, joined by +.
def shown(value):
return "+".join(map(str, value)) if isinstance(value, list) else value
# [camera] is the 183c's table whichever camera is in use now; a
# profile's own table is its [cameras.NAME].
in_use = dict(in_use, camera=in_use["cameras"][config.LEGACY_CAMERA])
import compendium
return {"file": str(config.FILE), "exists": config.FILE.exists(), "demo": self.demo,
"compendium": compendium.status(),
"fields": [dict({"section": name, "key": key, "label": label, "kind": kind, "help": text,
"value": shown(config.section_of(written if limits.get("optional") else in_use,
name).get(key))},
**limits)
for name, key, label, kind, text, limits in config.SETTINGS]}
def discovery(self):
"""The patrol programmes, the newest patrol's answer, and the
candidates still open, for the Discovery screen."""
import candidates
import patrol
out = {"programmes": [], "latest": None, "open": []}
for name in programmes():
p = patrol.programme(name)
out["programmes"].append({"name": name, "target": p.get("mosaic") or p.get("target"),
"panels": bool(p.get("mosaic")), "minutes": p.get("minutes")})
answers = sorted((config.DATA / "frames").glob("*/*/patrol.json"), key=lambda f: f.stat().st_mtime)
if answers:
found = json.loads(answers[-1].read_text(encoding="utf-8"))
out["latest"] = {"session": found.get("session"), "object": found.get("object"),
"summary": found.get("summary", []), "pictures": found.get("pictures", []),
"age_s": round(time.time() - answers[-1].stat().st_mtime)}
for book in sorted((config.DATA / "candidates").glob("*.json")):
for k in json.loads(book.read_text(encoding="utf-8")).get("candidates", []):
if k.get("open"):
out["open"].append({"id": k["id"], "ra": k["ra"], "dec": k["dec"],
"seen_on": candidates.nights_seen(k), "of": len(k["nights"])})
return out
def knowledge(self):
"""agent.characterise(), with whether each item's action is planned
and confirmed first (`plan`) or simply started."""
import agent
found = agent.characterise()
for item in found["items"]:
item["plan"] = bool(item["action"] and moves(item["action"], {}))
return found
def focus(self):
"""The newest reading on many stars, and `live`: the newest frame's
reading whatever it was (a ring, one star, nothing at all), with its
level and its timing. Either is None if there has been none."""
import focus
out = {}
for key, path in (("reading", focus.FOCUS_FILE), ("live", focus.LIVE_FILE)):
try:
found = json.loads(path.read_text(encoding="utf-8"))
out[key] = dict(found, age_s=round(time.time() - found["saved"]))
except (OSError, ValueError, KeyError):
out[key] = None
return out
def horizon(self):
import config
import horizon
import panorama
cfg = config.load() if config.FILE.exists() and not self.demo else config.example()
low, margin = cfg["horizon"]["min_altitude"], cfg["horizon"]["margin"]
# A demo keeps its own files (demo/) and may show them; a demo page
# over the real ones shows the example's empty horizon instead.
ours = config.DEMO or not self.demo
kept = horizon.measured() if ours else {}
return {"min_altitude": low, "margin": margin, "blocked": cfg["horizon"].get("blocked", []),
"skyline": kept.get("skyline"), "source": kept.get("source"), "surveyed": kept.get("saved"),
"usable": horizon.usable(kept["skyline"], low, margin) if kept else None,
"warnings": kept.get("warnings", []), "in_use": cfg["horizon"]["use_survey"],
"panorama": panorama.describe(panorama.state() if ours else {"pictures": []})}
def read(self, name, query):
import agent
import doctor
demo = self.demo
if name.startswith("target/"):
wanted = unquote(name[len("target/"):])
return interface.run("target", lambda: dict(agent.target(wanted, demo), framing=self.framing(wanted)))
routes = {
"state": (self.state, 2),
"night": (lambda: agent.night(demo), 300),
"targets": (lambda: agent.targets(40, None, False, demo), 300),
"observing": (lambda: agent.observing(demo), 5),
"session": (self.session, 2),
"doctor": (lambda: doctor.report(skip_handset=True), 15),
"catalogue": (self.catalogue, 3600),
"focus": (self.focus, 1),
"horizon": (self.horizon, 1),
"report": (self.report, 300),
"polar": (self.polar, 2),
"landmarks": (self.landmarks, 2),
"settings": (self.settings, 0),
"system": (self.system, 10),
"gallery": (self.gallery, 10),
"rigs": (agent.rigs, 5),
"characterise": (self.knowledge, 15),
"discovery": (self.discovery, 10),
}
if name not in routes:
return None
work, seconds = routes[name]
return self.get(name, work, seconds)
# --- the server ------------------------------------------------------------------
class Handler(BaseHTTPRequestHandler):
"""Serves the page to this computer only. GET reads; POST acts, and needs
the key. See docs/gui.md, "The rule this changes"."""
key = jobs = reader = None
port = 8081
server_version = "telescopeyoke-console"
def log_message(self, *args):
pass
# -- answering
def send(self, status, body, kind="application/json"):
self.send_response(status)
for name, value in HEADERS.items():
self.send_header(name, value)
self.send_header("Content-Type", kind)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def answer(self, result, status=None):
body = json.dumps(result, default=interface.jsonable).encode()
self.send(status or (200 if result["ok"] else 409), body)
def refuse(self, command, refused):
error = {"code": refused.code, "message": refused.message, "retryable": False,
"advice": interface.ERRORS.get(refused.code, (False, ""))[1]}
self.answer(interface.envelope(command, errors=[error]), refused.status)
# -- who is asking
def ours(self):
"""The Host header must be this console's own. A page elsewhere whose
name has been pointed at 127.0.0.1 (DNS rebinding) sends its own."""
return self.headers.get("Host", "") in (f"127.0.0.1:{self.port}", f"localhost:{self.port}")
def keyed(self):
given = self.headers.get("X-Console-Key", "").encode("utf-8", "replace")
return secrets.compare_digest(given, self.key.encode())
def same_origin(self):
origin = self.headers.get("Origin")
return origin is None or origin in (f"http://127.0.0.1:{self.port}", f"http://localhost:{self.port}")
# -- reading