-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPolarAlignmentDockableVM.cs
More file actions
1249 lines (1078 loc) · 61.6 KB
/
Copy pathPolarAlignmentDockableVM.cs
File metadata and controls
1249 lines (1078 loc) · 61.6 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
using System;
using Math = System.Math;
using NINA.WPF.Base.ViewModel;
using NINA.Profile.Interfaces;
using NINA.WPF.Base.Interfaces.Mediator;
using NINA.Equipment.Interfaces.Mediator;
using NINA.Equipment.Model;
using NINA.Core.Model.Equipment;
using NINA.Equipment.Equipment.MyCamera;
using NINA.Equipment.Equipment.MyTelescope;
using NINA.Core.Utility.Notification;
using NINA.PlateSolving;
using NINA.PlateSolving.Interfaces;
using NINA.Astrometry;
using NINA.Core.Model;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Windows.Media;
using System.Windows.Input;
using NirZonshine.NINA.TwoPointPolarAlignment.Domain;
using NirZonshine.NINA.TwoPointPolarAlignment.Services;
namespace NirZonshine.NINA.TwoPointPolarAlignment {
public class RelayCommand : ICommand {
private readonly Action<object> execute;
private readonly Func<object, bool> canExecute;
public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null) {
this.execute = execute ?? throw new ArgumentNullException(nameof(execute));
this.canExecute = canExecute;
}
public bool CanExecute(object parameter) => canExecute == null || canExecute(parameter);
public void Execute(object parameter) => execute(parameter);
public event EventHandler CanExecuteChanged {
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
}
public enum RotationMethod {
Automatic,
Manual
}
public enum RotationDirection {
East,
West
}
public enum StartingPointMode {
StartAtHome,
PreRotateHalfRange
}
public enum AltitudeKnobDirection {
UpArrow,
Clockwise,
AntiClockwise
}
public enum AzimuthKnobDirection {
LeftRightArrow,
Clockwise,
AntiClockwise
}
public enum ExposuresPerPoint {
Single = 1,
Double = 2,
Triple = 3
}
[Export(typeof(global::NINA.Equipment.Interfaces.ViewModel.IDockableVM))]
[Export(typeof(PolarAlignmentDockableVM))]
public class PolarAlignmentDockableVM : DockableVM, ICameraConsumer, ITelescopeConsumer {
public static PolarAlignmentDockableVM Instance { get; private set; }
private readonly SettingsManager _settingsManager;
public SettingsManager SettingsManager => _settingsManager;
private ImageSource lastFrame;
private string logs = "[System] Waiting for user interaction...";
private ICommand startAlignmentCommand;
private string azimuthError = "--' --\"";
private string altitudeError = "--' --\"";
private double totalErrorValue = 0.0;
private string totalError = "--' --\"";
private Brush totalErrorColor = Brushes.LightCoral;
private Brush totalErrorRatingColor = Brushes.LightCoral;
private string azimuthInstruction = "Waiting...";
private string altitudeInstruction = "Waiting...";
private string totalErrorRating = "Waiting...";
private bool isRunning = false;
private bool requestedHome = false;
private int _taskExecutingFlag = 0; // 0 = idle, 1 = executing (Interlocked for thread-safe access)
private bool isPreviousAlignmentDimmed = false;
// T-3 Fix: Removed duplicate _hardwareInterlock — the controller owns the single interlock instance.
// T-3 Fix: ExecuteHardwareOperationAsync removed from VM — HomeAlignment now calls mediator directly.
// The controller's _hardwareInterlock guards all workflow hardware ops.
private System.Threading.CancellationTokenSource alignmentCts;
private Coordinates lastStoppedCoordinates;
private RotationDirection? lastStoppedDirection;
private bool isAltitudePriority = false;
private bool isAzimuthPriority = false;
private bool isBlindSolvingActive = false;
private string statusIndicatorText = "Ready to Start";
private Brush statusIndicatorColor = StatusIdleColor;
private readonly ICameraMediator cameraMediator;
private readonly ITelescopeMediator telescopeMediator;
private readonly IPlateSolverFactory plateSolverFactory;
private readonly IImagingMediator imagingMediator;
private readonly IFilterWheelMediator filterWheelMediator;
private readonly System.Windows.Threading.DispatcherTimer statusTimer;
private CameraInfo currentCameraInfo;
private TelescopeInfo currentTelescopeInfo;
private bool lastIsCameraConnected;
private bool lastIsMountConnected;
private readonly NirZonshine.NINA.TwoPointPolarAlignment.Solvers.IPolarSolver _polarSolver = new NirZonshine.NINA.TwoPointPolarAlignment.Solvers.TwoPointPolarSolver();
private static Brush CreateFrozenBrush(string hex) {
try {
var b = new SolidColorBrush((Color)ColorConverter.ConvertFromString(hex));
b.Freeze();
return b;
} catch { return Brushes.SkyBlue; }
}
private static readonly Brush StatusIdleColor = CreateFrozenBrush("#72BDFF");
private static readonly Brush StatusWarningColor = CreateFrozenBrush("#FBBF24");
private static readonly Brush StatusSuccessColor = CreateFrozenBrush("#22C55E");
private static readonly Brush StatusFailureColor = CreateFrozenBrush("#EF4444");
private static readonly Brush StatusProgressColor = CreateFrozenBrush("#6366F1");
private static readonly Brush StatusTrackingColor = CreateFrozenBrush("#A855F7");
private void SetStatus(string text, Brush color) {
System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() => {
StatusIndicatorText = text;
StatusIndicatorColor = color;
}));
}
private readonly IProfileService _profileService;
[ImportingConstructor]
public PolarAlignmentDockableVM(IProfileService profileService, ICameraMediator cameraMediator, ITelescopeMediator telescopeMediator, IPlateSolverFactory plateSolverFactory, IImagingMediator imagingMediator, IFilterWheelMediator filterWheelMediator) : base(profileService) {
Instance = this;
this._profileService = profileService;
this.cameraMediator = cameraMediator;
this.telescopeMediator = telescopeMediator;
this.plateSolverFactory = plateSolverFactory;
this.imagingMediator = imagingMediator;
this.filterWheelMediator = filterWheelMediator;
cameraMediator.RegisterConsumer(this);
telescopeMediator.RegisterConsumer(this);
Title = "2-Point Polar Alignment";
// Initialize connection states
lastIsCameraConnected = IsCameraConnected;
lastIsMountConnected = IsMountConnected;
// Start a lightweight 1-second status polling timer as a bulletproof mechanism for equipment connection changes
statusTimer = new System.Windows.Threading.DispatcherTimer {
Interval = TimeSpan.FromSeconds(1)
};
statusTimer.Tick += StatusTimer_Tick;
statusTimer.Start();
// Set the custom 2-Point Polar Alignment icon (simplified arc and two stars for maximum clarity at 16x16 resolution)
var group = new GeometryGroup();
// 1. Curved tracking arc
group.Children.Add(Geometry.Parse("M3,12 A9,9 0 0,1 12,3"));
// 2. Left Star (9 o'clock)
group.Children.Add(Geometry.Parse("M3,9.5 L4.2,11.8 L6.8,11.8 L4.7,13.3 L5.5,15.6 L3,14.1 L0.5,15.6 L1.3,13.3 L-0.8,11.8 L1.8,11.8 Z"));
// 3. Top Star (12 o'clock)
group.Children.Add(Geometry.Parse("M12,0.5 L13.2,2.8 L15.8,2.8 L13.7,4.3 L14.5,6.6 L12,5.1 L9.5,6.6 L10.3,4.3 L8.2,2.8 L10.8,2.8 Z"));
group.Freeze(); // Crucial for cross-thread WPF access
ImageGeometry = group;
_settingsManager = new SettingsManager(profileService);
_settingsManager.PropertyChanged += SettingsManager_PropertyChanged;
}
private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e) {
RaisePropertyChanged(e.PropertyName);
if (e.PropertyName == nameof(Method)) {
RaisePropertyChanged(nameof(ShowMountWarning));
RaisePropertyChanged(nameof(CanRun));
RaisePropertyChanged(nameof(CanStart));
}
}
public override bool IsTool => true;
public bool IsCameraConnected => (currentCameraInfo?.Connected ?? cameraMediator?.GetInfo()?.Connected ?? false);
public bool IsMountConnected => (currentTelescopeInfo?.Connected ?? telescopeMediator?.GetInfo()?.Connected ?? false);
public bool CanRun => IsCameraConnected && (Method == RotationMethod.Manual || IsMountConnected);
public bool ShowMountWarning => !IsMountConnected && Method != RotationMethod.Manual;
private void StatusTimer_Tick(object sender, EventArgs e) {
var currentCamera = IsCameraConnected;
var currentMount = IsMountConnected;
if (currentCamera != lastIsCameraConnected) {
lastIsCameraConnected = currentCamera;
RaisePropertyChanged(nameof(IsCameraConnected));
RaisePropertyChanged(nameof(CanRun));
RaisePropertyChanged(nameof(CanStart));
}
if (currentMount != lastIsMountConnected) {
lastIsMountConnected = currentMount;
RaisePropertyChanged(nameof(IsMountConnected));
RaisePropertyChanged(nameof(ShowMountWarning));
RaisePropertyChanged(nameof(CanRun));
RaisePropertyChanged(nameof(CanStart));
RaisePropertyChanged(nameof(CanHome));
}
}
public void UpdateDeviceInfo(CameraInfo deviceInfo) {
currentCameraInfo = deviceInfo;
System.Windows.Application.Current.Dispatcher.InvokeAsync(() => {
RaisePropertyChanged(nameof(IsCameraConnected));
RaisePropertyChanged(nameof(CanRun));
RaisePropertyChanged(nameof(CanStart));
});
}
public void UpdateDeviceInfo(TelescopeInfo deviceInfo) {
currentTelescopeInfo = deviceInfo;
System.Windows.Application.Current.Dispatcher.InvokeAsync(() => {
RaisePropertyChanged(nameof(IsMountConnected));
RaisePropertyChanged(nameof(ShowMountWarning));
RaisePropertyChanged(nameof(CanRun));
RaisePropertyChanged(nameof(CanStart));
RaisePropertyChanged(nameof(CanHome));
});
}
public void Dispose() {
try { StopAlignment(); }
catch (Exception ex) { global::NINA.Core.Utility.Logger.Error($"[2-Point Polar Alignment] Dispose.StopAlignment failed: {ex.Message}"); }
try {
if (statusTimer != null) {
statusTimer.Tick -= StatusTimer_Tick;
statusTimer.Stop();
}
}
catch (Exception ex) { global::NINA.Core.Utility.Logger.Error($"[2-Point Polar Alignment] Dispose.TimerStop failed: {ex.Message}"); }
// M-1 Fix: Detach SettingsManager events and dispose to release ProfileChanged subscription
try {
_settingsManager.PropertyChanged -= SettingsManager_PropertyChanged;
_settingsManager.Dispose();
}
catch (Exception ex) { global::NINA.Core.Utility.Logger.Error($"[2-Point Polar Alignment] Dispose.SettingsManager failed: {ex.Message}"); }
try { cameraMediator.RemoveConsumer(this); }
catch (Exception ex) { global::NINA.Core.Utility.Logger.Error($"[2-Point Polar Alignment] Dispose.RemoveCameraConsumer failed: {ex.Message}"); }
try { telescopeMediator.RemoveConsumer(this); }
catch (Exception ex) { global::NINA.Core.Utility.Logger.Error($"[2-Point Polar Alignment] Dispose.RemoveTelescopeConsumer failed: {ex.Message}"); }
}
private NirZonshine.NINA.TwoPointPolarAlignment.TwoPointPolarAlignmentSequenceItem runningSequenceItem;
public NirZonshine.NINA.TwoPointPolarAlignment.TwoPointPolarAlignmentSequenceItem RunningSequenceItem {
get => runningSequenceItem;
set {
runningSequenceItem = value;
RaisePropertyChanged(nameof(RunningSequenceItem));
RaisePropertyChanged(nameof(IsRunningFromSequence));
RaisePropertyChanged(nameof(CanEditSettings));
RaisePropertyChanged(nameof(ExposureTime));
RaisePropertyChanged(nameof(Gain));
RaisePropertyChanged(nameof(Filter));
RaisePropertyChanged(nameof(RotationAmount));
}
}
public bool IsRunningFromSequence => RunningSequenceItem != null;
public bool CanEditSettings => !IsRunning && !IsRunningFromSequence;
private ICommand resumeSequenceCommand;
public ICommand ResumeSequenceCommand => resumeSequenceCommand ??= new RelayCommand(o => {
ResumeSequence();
});
public void ResumeSequence() {
if (IsRunningFromSequence && RunningSequenceItem != null) {
Log("[Sequence] Operator requested sequence resume. Advancing sequence...");
RunningSequenceItem.Resume();
}
}
public double RotationAmount {
get => _settingsManager.RotationAmount;
set => _settingsManager.RotationAmount = value;
}
public RotationMethod Method {
get => _settingsManager.Method;
set => _settingsManager.Method = value;
}
public RotationDirection Direction {
get => _settingsManager.Direction;
set => _settingsManager.Direction = value;
}
public StartingPointMode StartingPoint {
get => _settingsManager.StartingPoint;
set => _settingsManager.StartingPoint = value;
}
public double? ExposureTime {
get => _settingsManager.ExposureTime;
set => _settingsManager.ExposureTime = value;
}
public int? Gain {
get => _settingsManager.Gain;
set => _settingsManager.Gain = value;
}
public ImageSource LastFrame {
get => lastFrame;
set {
lastFrame = value;
RaisePropertyChanged(nameof(LastFrame));
}
}
public string Filter {
get => _settingsManager.Filter;
set => _settingsManager.Filter = value;
}
public AltitudeKnobDirection AltKnobDirection {
get => _settingsManager.AltKnobDirection;
set {
_settingsManager.AltKnobDirection = value;
}
}
public AzimuthKnobDirection AzKnobDirection {
get => _settingsManager.AzKnobDirection;
set {
_settingsManager.AzKnobDirection = value;
}
}
public ExposuresPerPoint ExposuresPerPoint {
get => _settingsManager.ExposuresPerPoint;
set => _settingsManager.ExposuresPerPoint = value;
}
public bool IsBlindSolvingActive {
get => isBlindSolvingActive;
set {
isBlindSolvingActive = value;
RaisePropertyChanged(nameof(IsBlindSolvingActive));
}
}
public string Binning {
get => _settingsManager.Binning;
set => _settingsManager.Binning = value;
}
public int? Offset {
get => _settingsManager.Offset;
set => _settingsManager.Offset = value;
}
public int PlateSolveRetries {
get => _settingsManager.PlateSolveRetries;
set => _settingsManager.PlateSolveRetries = value;
}
public bool OverrideMountHome {
get => _settingsManager.OverrideMountHome;
set {
_settingsManager.OverrideMountHome = value;
RaisePropertyChanged(nameof(OverrideMountHome));
RaisePropertyChanged(nameof(OverrideMountHomeIndex));
}
}
public int OverrideMountHomeIndex {
get => _settingsManager.OverrideMountHome ? 1 : 0;
set {
_settingsManager.OverrideMountHome = (value == 1);
RaisePropertyChanged(nameof(OverrideMountHome));
RaisePropertyChanged(nameof(OverrideMountHomeIndex));
}
}
public string Logs {
get => logs;
set {
logs = value;
RaisePropertyChanged(nameof(Logs));
}
}
public string AzimuthError {
get => azimuthError;
set {
azimuthError = value;
RaisePropertyChanged(nameof(AzimuthError));
}
}
public string AltitudeError {
get => altitudeError;
set {
altitudeError = value;
RaisePropertyChanged(nameof(AltitudeError));
}
}
public double TotalErrorValue {
get => totalErrorValue;
set {
totalErrorValue = value;
RaisePropertyChanged(nameof(TotalErrorValue));
}
}
public string TotalError {
get => totalError;
set {
totalError = value;
RaisePropertyChanged(nameof(TotalError));
}
}
public Brush TotalErrorColor {
get => totalErrorColor;
set {
totalErrorColor = value;
RaisePropertyChanged(nameof(TotalErrorColor));
}
}
public Brush TotalErrorRatingColor {
get => totalErrorRatingColor;
set {
totalErrorRatingColor = value;
RaisePropertyChanged(nameof(TotalErrorRatingColor));
}
}
public bool IsPreviousAlignmentDimmed {
get => isPreviousAlignmentDimmed;
set {
isPreviousAlignmentDimmed = value;
RaisePropertyChanged(nameof(IsPreviousAlignmentDimmed));
}
}
public string StatusIndicatorText {
get => statusIndicatorText;
set {
statusIndicatorText = value;
RaisePropertyChanged(nameof(StatusIndicatorText));
}
}
public Brush StatusIndicatorColor {
get => statusIndicatorColor;
set {
statusIndicatorColor = value;
RaisePropertyChanged(nameof(StatusIndicatorColor));
}
}
public bool IsAltitudePriority {
get => isAltitudePriority;
set {
isAltitudePriority = value;
RaisePropertyChanged(nameof(IsAltitudePriority));
}
}
public bool IsAzimuthPriority {
get => isAzimuthPriority;
set {
isAzimuthPriority = value;
RaisePropertyChanged(nameof(IsAzimuthPriority));
}
}
public string AzimuthInstruction {
get => azimuthInstruction;
set {
azimuthInstruction = value;
RaisePropertyChanged(nameof(AzimuthInstruction));
}
}
public string AltitudeInstruction {
get => altitudeInstruction;
set {
altitudeInstruction = value;
RaisePropertyChanged(nameof(AltitudeInstruction));
}
}
public string TotalErrorRating {
get => totalErrorRating;
set {
totalErrorRating = value;
RaisePropertyChanged(nameof(TotalErrorRating));
}
}
private bool isReversedFlowActive = false;
public bool IsReversedFlowActive {
get => isReversedFlowActive;
set {
isReversedFlowActive = value;
RaisePropertyChanged(nameof(IsReversedFlowActive));
}
}
public bool EnableOnePointAlignment {
get => _settingsManager.EnableOnePointAlignment;
set => _settingsManager.EnableOnePointAlignment = value;
}
public bool IsRunning {
get => isRunning;
set {
isRunning = value;
RaisePropertyChanged(nameof(IsRunning));
RaisePropertyChanged(nameof(CanStart));
RaisePropertyChanged(nameof(CanHome));
}
}
public bool CanStart => CanRun && !IsRunning && Volatile.Read(ref _taskExecutingFlag) == 0;
public bool CanHome => IsRunning || IsMountConnected;
public ICommand StartAlignmentCommand => startAlignmentCommand ??= new RelayCommand(o => {
if (!IsRunning && Volatile.Read(ref _taskExecutingFlag) == 0) {
StartAlignment();
}
});
private ICommand stopAlignmentCommand;
public ICommand StopAlignmentCommand => stopAlignmentCommand ??= new RelayCommand(o => {
StopAlignment();
});
public void StopAlignment() {
if (IsRunning) {
Log("Stop requested by user. Aborting alignment sequence...");
try {
alignmentCts?.Cancel();
} catch { }
IsRunning = false;
try {
if (telescopeMediator != null && telescopeMediator.GetInfo()?.Connected == true) {
telescopeMediator.StopSlew();
Log("Mount slew stopped immediately.");
}
} catch (Exception ex) {
global::NINA.Core.Utility.Logger.Error($"[2-Point Polar Alignment] StopSlew failed: {ex.Message}");
}
}
}
private ICommand homeAlignmentCommand;
public ICommand HomeAlignmentCommand => homeAlignmentCommand ??= new RelayCommand(o => {
HomeAlignment();
});
public void HomeAlignment() {
if (IsRunning) {
requestedHome = true;
StopAlignment();
} else if (IsMountConnected && Interlocked.CompareExchange(ref _taskExecutingFlag, 1, 0) == 0) {
RaisePropertyChanged(nameof(CanStart));
Task.Run(async () => {
SetStatus("Homing", StatusWarningColor);
try {
if (OverrideMountHome) {
var currentPosition = telescopeMediator.GetCurrentPosition();
if (_profileService?.ActiveProfile?.AstrometrySettings != null && currentPosition != null) {
bool isNorthern = _profileService.ActiveProfile.AstrometrySettings.Latitude >= 0;
bool targetIsNorthern = _settingsManager.PolarHomeDec >= 0;
if (isNorthern != targetIsNorthern) {
// Auto-reset Polar Home to current position when hemisphere changed
bool isNearPole = Math.Abs(Math.Abs(currentPosition.Dec) - 90.0) < 1.0;
if (isNearPole) {
_settingsManager.PolarHomeRA = currentPosition.RA;
_settingsManager.PolarHomeDec = currentPosition.Dec;
Log($"[Polar Home] Hemisphere change detected. Auto-relocked Custom Polar Home to RA: {currentPosition.RA:F2}h, Dec: {currentPosition.Dec:F2}° (new hemisphere).");
} else {
string hemisphereCurrent = isNorthern ? "Northern" : "Southern";
string hemisphereTarget = targetIsNorthern ? "Northern" : "Southern";
string currentPole = isNorthern ? "North" : "South";
string err = $"Hemisphere Mismatch: The locked Custom Polar Home is in the {hemisphereTarget} Hemisphere ({_settingsManager.PolarHomeDec:F2}°), but your mount is currently configured for the {hemisphereCurrent} Hemisphere.\n\n" +
$"Please manually slew near the {currentPole} Celestial Pole and click 'Lock Polar Home' to update your starting position.";
ShowNinaStyledMessageBox("Hemisphere Mismatch", err);
Log($"[Error] Custom Home Slew aborted: hemisphere mismatch (current: {hemisphereCurrent}, target: {hemisphereTarget}).");
return;
}
}
}
Log("Dispatching custom Polar Home slew command...");
var epoch = currentPosition?.Epoch ?? global::NINA.Astrometry.Epoch.J2000;
var coords = new global::NINA.Astrometry.Coordinates(
_settingsManager.PolarHomeRA,
_settingsManager.PolarHomeDec,
epoch,
global::NINA.Astrometry.Coordinates.RAType.Hours
);
// T-3 Fix: Direct mediator call — VM no longer owns a hardware interlock
await telescopeMediator.SlewToCoordinatesAsync(coords, System.Threading.CancellationToken.None);
try { telescopeMediator.SetTrackingEnabled(false); } catch { }
Log("Successfully slewed to Custom Polar Home Position.");
} else {
var info = telescopeMediator.GetInfo();
var currentPosition = telescopeMediator.GetCurrentPosition();
if (info != null && info.AtHome && currentPosition != null && Math.Abs(currentPosition.Dec) < 45.0) {
string err = "Your mount's native Home position is pointing away from the Celestial Pole (near the Equator/Horizon).\n\n" +
"Native homing is disabled to prevent incorrect positioning. Please enable 'Override Mount Home' in settings and slew your mount to its Polar Home position near the pole.";
ShowNinaStyledMessageBox("Homing Disabled", err);
Log("[Error] Homing command aborted: native home position points away from Celestial Pole. Please enable 'Override Mount Home' in settings.");
return;
}
Log("Dispatching native FindHome command to mount controller...");
// T-3 Fix: Direct mediator call — VM no longer owns a hardware interlock
await telescopeMediator.FindHome(new Progress<global::NINA.Core.Model.ApplicationStatus>(), System.Threading.CancellationToken.None);
try { telescopeMediator.SetTrackingEnabled(false); } catch { }
Log("Successfully returned to Home Position.");
}
} catch (Exception ex) {
Log($"[Error] Failed to complete Home directive: {ex.Message}");
} finally {
SetStatus("Ready to Start", StatusIdleColor);
Interlocked.Exchange(ref _taskExecutingFlag, 0);
RaisePropertyChanged(nameof(CanStart));
}
});
}
}
private ICommand lockPolarHomeCommand;
public ICommand LockPolarHomeCommand => lockPolarHomeCommand ??= new RelayCommand(o => {
LockPolarHome();
});
public void LockPolarHome() {
if (!IsMountConnected) {
Log("[Error] Cannot lock Polar Home: Telescope is not connected.");
return;
}
var currentPosition = telescopeMediator.GetCurrentPosition();
if (currentPosition == null) {
Log("[Error] Cannot lock Polar Home: Could not retrieve current position.");
return;
}
bool isNearPole = Math.Abs(Math.Abs(currentPosition.Dec) - 90.0) < 1.0;
if (!isNearPole) {
ShowNinaStyledMessageBox("Invalid Position", "Cannot lock Polar Home. Declination must be very close to the Celestial Pole (90°).");
Log($"[Error] Cannot lock Polar Home: Declination ({currentPosition.Dec:F2}°) is not close to 90°.");
return;
}
_settingsManager.PolarHomeRA = currentPosition.RA;
_settingsManager.PolarHomeDec = currentPosition.Dec;
Log($"[Polar Home] Locked new Custom Polar Home at RA: {currentPosition.RA:F2}h, Dec: {currentPosition.Dec:F2}°");
ShowNinaStyledMessageBox("Success", $"Custom Polar Home successfully locked at:\nRA: {currentPosition.RA:F2}h\nDec: {currentPosition.Dec:F2}°");
}
public void Log(string message) {
// W-2 Fix: Marshal Logs += to UI thread so PropertyChanged fires on the dispatcher
var formatted = $"\n[{DateTime.Now:HH:mm:ss}] {message}";
global::NINA.Core.Utility.Logger.Info($"[2-Point Polar Alignment] {message}");
System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() => {
Logs += formatted;
}));
}
private bool ShowNinaStyledMessageBox(string title, string message, bool isYesNo = false) {
bool result = false;
System.Windows.Application.Current.Dispatcher.Invoke(() => {
var dialog = new System.Windows.Window {
Title = title,
Width = 430,
Height = 180,
SizeToContent = System.Windows.SizeToContent.Height,
WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner,
ResizeMode = System.Windows.ResizeMode.NoResize,
WindowStyle = System.Windows.WindowStyle.None,
AllowsTransparency = true,
Background = System.Windows.Media.Brushes.Transparent,
Topmost = true,
ShowInTaskbar = false
};
try { dialog.Owner = System.Windows.Application.Current.MainWindow; } catch { }
var mainBorder = new System.Windows.Controls.Border {
Background = new SolidColorBrush(Color.FromRgb(0x1A, 0x1A, 0x22)),
BorderBrush = new SolidColorBrush(Color.FromRgb(0x3D, 0x3D, 0x50)),
BorderThickness = new System.Windows.Thickness(1),
CornerRadius = new System.Windows.CornerRadius(12),
Effect = new System.Windows.Media.Effects.DropShadowEffect { Color = Colors.Black, BlurRadius = 30, ShadowDepth = 0, Opacity = 0.6 },
Padding = new System.Windows.Thickness(0,0,0,20)
};
var grid = new System.Windows.Controls.Grid();
grid.RowDefinitions.Add(new System.Windows.Controls.RowDefinition { Height = new System.Windows.GridLength(45) }); // Header
grid.RowDefinitions.Add(new System.Windows.Controls.RowDefinition { Height = System.Windows.GridLength.Auto }); // Message
grid.RowDefinitions.Add(new System.Windows.Controls.RowDefinition { Height = System.Windows.GridLength.Auto }); // Buttons
var headerColor = Color.FromRgb(0x22, 0xC5, 0x5E); // Default Green
if (title.Contains("Error") || title.Contains("Invalid") || title.Contains("Failed") || title.Contains("Required")) {
headerColor = Color.FromRgb(0xE1, 0x1D, 0x48); // Rose Red
} else if (title.Contains("Warning")) {
headerColor = Color.FromRgb(0xF5, 0x9E, 0x0B); // Amber Orange
}
var header = new System.Windows.Controls.Border {
Background = new SolidColorBrush(headerColor),
CornerRadius = new System.Windows.CornerRadius(12, 12, 0, 0),
Padding = new System.Windows.Thickness(20, 0, 20, 0)
};
var headerTxt = new System.Windows.Controls.TextBlock {
Text = title, VerticalAlignment = System.Windows.VerticalAlignment.Center,
FontSize = 15, FontWeight = System.Windows.FontWeights.Bold, Foreground = System.Windows.Media.Brushes.White
};
header.Child = headerTxt;
System.Windows.Controls.Grid.SetRow(header, 0);
grid.Children.Add(header);
var msgTxt = new System.Windows.Controls.TextBlock {
Text = message, Margin = new System.Windows.Thickness(25, 25, 25, 25),
TextWrapping = System.Windows.TextWrapping.Wrap, Foreground = System.Windows.Media.Brushes.WhiteSmoke,
FontSize = 13, LineHeight = 18
};
System.Windows.Controls.Grid.SetRow(msgTxt, 1);
grid.Children.Add(msgTxt);
var btnStack = new System.Windows.Controls.StackPanel {
Orientation = System.Windows.Controls.Orientation.Horizontal,
HorizontalAlignment = System.Windows.HorizontalAlignment.Right,
Margin = new System.Windows.Thickness(0, 0, 25, 5)
};
System.Windows.Controls.Grid.SetRow(btnStack, 2);
grid.Children.Add(btnStack);
System.Windows.Controls.ControlTemplate CreateNinaBtnTemplate(Color baseClr) {
var t = new System.Windows.Controls.ControlTemplate(typeof(System.Windows.Controls.Button));
var b = new System.Windows.FrameworkElementFactory(typeof(System.Windows.Controls.Border));
b.SetValue(System.Windows.Controls.Border.CornerRadiusProperty, new System.Windows.CornerRadius(6));
b.SetValue(System.Windows.Controls.Border.BackgroundProperty, new SolidColorBrush(baseClr));
var g = new System.Windows.FrameworkElementFactory(typeof(System.Windows.Controls.Grid));
var gl = new System.Windows.FrameworkElementFactory(typeof(System.Windows.Controls.Border));
gl.SetValue(System.Windows.Controls.Border.BackgroundProperty, System.Windows.Media.Brushes.White);
gl.SetValue(System.Windows.Controls.Border.CornerRadiusProperty, new System.Windows.CornerRadius(6));
gl.SetValue(System.Windows.UIElement.OpacityProperty, 0.0);
gl.Name = "glow";
var cp = new System.Windows.FrameworkElementFactory(typeof(System.Windows.Controls.ContentPresenter));
cp.SetValue(System.Windows.FrameworkElement.HorizontalAlignmentProperty, System.Windows.HorizontalAlignment.Center);
cp.SetValue(System.Windows.FrameworkElement.VerticalAlignmentProperty, System.Windows.VerticalAlignment.Center);
cp.SetValue(System.Windows.Controls.ContentPresenter.MarginProperty, new System.Windows.Thickness(15, 0, 15, 0));
g.AppendChild(gl); g.AppendChild(cp); b.AppendChild(g);
t.VisualTree = b;
var h = new System.Windows.Trigger { Property = System.Windows.UIElement.IsMouseOverProperty, Value = true };
h.Setters.Add(new System.Windows.Setter(System.Windows.UIElement.OpacityProperty, 0.15, "glow"));
t.Triggers.Add(h);
return t;
}
var okBtn = new System.Windows.Controls.Button {
Content = isYesNo ? "Yes, Engaged Rescue" : "Acknowledged", MinWidth = 90, Height = 32, Margin = new System.Windows.Thickness(10, 0, 0, 0),
Foreground = System.Windows.Media.Brushes.White, FontWeight = System.Windows.FontWeights.Bold, Cursor = System.Windows.Input.Cursors.Hand,
Template = CreateNinaBtnTemplate(headerColor)
};
okBtn.Click += (s, e) => { result = true; dialog.DialogResult = true; dialog.Close(); };
if (isYesNo) {
var noBtn = new System.Windows.Controls.Button {
Content = "Cancel / Abort", MinWidth = 90, Height = 32,
Foreground = System.Windows.Media.Brushes.White, FontWeight = System.Windows.FontWeights.Bold, Cursor = System.Windows.Input.Cursors.Hand,
Template = CreateNinaBtnTemplate(Color.FromRgb(0x3D, 0x3D, 0x50))
};
noBtn.Click += (s, e) => { result = false; dialog.DialogResult = false; dialog.Close(); };
btnStack.Children.Add(noBtn);
}
btnStack.Children.Add(okBtn);
mainBorder.Child = grid;
dialog.Content = mainBorder;
dialog.ShowDialog();
});
return result;
}
public void StartAlignment() {
if (Interlocked.CompareExchange(ref _taskExecutingFlag, 1, 0) != 0) {
return;
}
IsReversedFlowActive = false;
IsPreviousAlignmentDimmed = true;
IsRunning = true;
alignmentCts = new System.Threading.CancellationTokenSource();
RaisePropertyChanged(nameof(CanStart));
bool isLiveAdjusting = false;
int stableCount = 0;
// W-3 Fix: Construct Progress<T> on the UI thread so callbacks marshal via SynchronizationContext
var progress = new Progress<AlignmentProgressReport>(report => {
if (report.LogMessage != null) Log(report.LogMessage);
if (report.IsReversedFlowActive.HasValue) IsReversedFlowActive = report.IsReversedFlowActive.Value;
if (report.IsBlindSolvingActive.HasValue) IsBlindSolvingActive = report.IsBlindSolvingActive.Value;
if (report.HasSuccessfulAlignmentReached) {
isLiveAdjusting = true;
}
if (report.StatusText != null && report.StatusColorHex != null) {
// Update dashboard status in GUI
if (IsRunningFromSequence && RunningSequenceItem != null && RunningSequenceItem.AutoCompleteTolerance > 0.0 && isLiveAdjusting) {
if (report.StatusText == "Could not solve") {
stableCount = 0;
Log($"[Sequence] Plate solve failed. Resetting stable count (Stable: {stableCount}/{RunningSequenceItem.AutoCompleteStableExposures})");
SetStatus($"Could Not Solve (Stable: 0/{RunningSequenceItem.AutoCompleteStableExposures})", StatusFailureColor);
} else {
SetStatus(report.StatusText, CreateFrozenBrush(report.StatusColorHex));
}
} else {
SetStatus(report.StatusText, CreateFrozenBrush(report.StatusColorHex));
}
}
if (report.AltitudeError != null) {
AltitudeError = report.AltitudeError;
IsPreviousAlignmentDimmed = false;
}
if (report.AzimuthError != null) AzimuthError = report.AzimuthError;
if (report.TotalError != null) {
TotalError = report.TotalError;
if (RunningSequenceItem != null) {
RunningSequenceItem.CurrentErrorDisplay = report.TotalError;
if (report.TotalErrorRatingColorHex != null) {
RunningSequenceItem.CurrentErrorColorHex = report.TotalErrorRatingColorHex;
}
}
}
if (report.TotalErrorValue > 0) {
TotalErrorValue = report.TotalErrorValue;
if (IsRunningFromSequence && RunningSequenceItem != null) {
if (RunningSequenceItem.MeasureOnly) {
Log("[Sequence] Measurement Only mode active. Target measured. Auto-advancing...");
RunningSequenceItem.Resume();
}
else if (RunningSequenceItem.AutoCompleteTolerance > 0.0 && isLiveAdjusting) {
if (report.TotalErrorValue <= RunningSequenceItem.AutoCompleteTolerance) {
stableCount++;
Log($"[Sequence] Error ({report.TotalErrorValue:F2}′) is below tolerance ({RunningSequenceItem.AutoCompleteTolerance:F2}′). Stable count: {stableCount}/{RunningSequenceItem.AutoCompleteStableExposures}");
// Override status text on dashboard
SetStatus($"Adjusting (Stable: {stableCount}/{RunningSequenceItem.AutoCompleteStableExposures} | Error: {report.TotalErrorValue:F2}′)", StatusTrackingColor);
if (stableCount >= RunningSequenceItem.AutoCompleteStableExposures) {
Log($"[Sequence] Target alignment achieved and stable. Auto-advancing...");
RunningSequenceItem.Resume();
}
} else {
if (stableCount > 0) {
Log($"[Sequence] Error ({report.TotalErrorValue:F2}′) rose above tolerance ({RunningSequenceItem.AutoCompleteTolerance:F2}′). Resetting stable count.");
}
stableCount = 0;
SetStatus($"Adjusting (Stable: 0/{RunningSequenceItem.AutoCompleteStableExposures} | Error: {report.TotalErrorValue:F2}′)", StatusWarningColor);
}
}
}
}
if (report.AltitudeInstruction != null) AltitudeInstruction = report.AltitudeInstruction;
if (report.AzimuthInstruction != null) AzimuthInstruction = report.AzimuthInstruction;
IsAltitudePriority = report.IsAltitudePriority;
IsAzimuthPriority = report.IsAzimuthPriority;
if (report.TotalErrorRating != null) TotalErrorRating = report.TotalErrorRating;
if (report.TotalErrorRatingColorHex != null) TotalErrorRatingColor = CreateFrozenBrush(report.TotalErrorRatingColorHex);
if (report.TotalErrorValue > 0 && report.TotalErrorRatingColorHex != null) {
TotalErrorColor = CreateFrozenBrush(report.TotalErrorRatingColorHex);
}
});
Task.Run(async () => {
try {
await StartAlignmentAsync(progress);
} catch (OperationCanceledException) {
Log("Alignment sequence successfully aborted.");
Notification.ShowSuccess("2-Point Polar Alignment: Sequence aborted successfully!");
try {
if (telescopeMediator != null && telescopeMediator.GetInfo()?.Connected == true) {
var pos = telescopeMediator.GetCurrentPosition();
if (pos != null) {
lastStoppedCoordinates = pos;
lastStoppedDirection = IsReversedFlowActive ?
(Direction == RotationDirection.East ? RotationDirection.West : RotationDirection.East) :
Direction;
Log($"[Smart Restart] Saved last stopped position: RA {pos.RA:F2}h, Dec {pos.Dec:F2}° (Direction: {lastStoppedDirection})");
}
}
} catch { }
} catch (Exception ex) {
Log($"[Error] Alignment failed: {ex.Message}");
Notification.ShowError($"Alignment failed: {ex.Message}");
} finally {
bool triggerHome = requestedHome;
requestedHome = false;
try {
if (lastStoppedCoordinates == null && telescopeMediator != null && telescopeMediator.GetInfo()?.Connected == true) {
var pos = telescopeMediator.GetCurrentPosition();
if (pos != null) {
lastStoppedCoordinates = pos;
lastStoppedDirection = IsReversedFlowActive ?
(Direction == RotationDirection.East ? RotationDirection.West : RotationDirection.East) :
Direction;
Log($"[Smart Restart] Saved last stopped position: RA {pos.RA:F2}h, Dec {pos.Dec:F2}° (Direction: {lastStoppedDirection})");
}
}
} catch { }
// If running from sequence, and alignment terminates without resume, wake sequencer up as aborted
if (IsRunningFromSequence && RunningSequenceItem != null) {
RunningSequenceItem.ResumeTcs?.TrySetResult(false);
}
IsRunning = false;
Interlocked.Exchange(ref _taskExecutingFlag, 0);
RaisePropertyChanged(nameof(CanStart));
var oldCts = Interlocked.Exchange(ref alignmentCts, null);
oldCts?.Dispose();
if (triggerHome) {
Log("Waiting for mount to complete deceleration and come to a complete stop...");
int maxPolls = 25; // 5.0 seconds maximum timeout
int poll = 0;
while (telescopeMediator != null && telescopeMediator.GetInfo()?.Slewing == true && poll < maxPolls) {
await Task.Delay(200);
poll++;
}
HomeAlignment();
}
}
});
}
private async Task StartAlignmentAsync(IProgress<AlignmentProgressReport> progress) {
var cts = alignmentCts ?? throw new InvalidOperationException("Alignment CTS was not initialized.");
var controller = new NirZonshine.NINA.TwoPointPolarAlignment.Workflow.AlignmentWorkflowController(
_profileService, cameraMediator, telescopeMediator, plateSolverFactory, imagingMediator, filterWheelMediator, _polarSolver, _settingsManager
);
controller.OnManualRotationRequested = async (context, targetDegrees, direction, initialCoords, sequence, captureSolver, isSimulation) => {