-
Notifications
You must be signed in to change notification settings - Fork 0
/
OptronIPolarSolver.cs
232 lines (178 loc) · 6.54 KB
/
OptronIPolarSolver.cs
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
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Text.RegularExpressions;
using System.Threading;
namespace AutoPolarAlign
{
public class OptronIPolarSolver : IPolarAlignmentSolver
{
private static readonly Regex LogRegex = new Regex(@"(?<timestamp>[0-9\s\-:.]+)\sPlateSolved:\s(?<solved>true|false),\sPole:\((?<x>[0-9]+(?:[.,][0-9]+)?),(?<y>[0-9]+(?:[.,][0-9]+)?)\)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
public Vec2 AlignmentOffset { get; private set; } = new Vec2();
public string LogPath { get; set; } = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "iOptron iPolar", "Logs");
public int MaxLogAge { get; set; } = 180;
public float CenterX { get; set; } = 480.0f;
public float CenterY { get; set; } = 640.0f;
public bool StartIPolar { get; set; } = true;
public bool StopIPolar { get; set; } = true;
public OptronIPolarSetup Setup { get; } = new OptronIPolarSetup();
private DirectoryInfo dir = null;
private string lastTimestamp = null;
public void Connect()
{
if (StartIPolar)
{
if (!Setup.Run(out var settings))
{
throw new Exception("Could not set up iPolar application");
}
if (settings.CenterXFound)
{
CenterX = settings.CenterX;
}
if (settings.CenterYFound)
{
CenterY = settings.CenterY;
}
}
dir = new DirectoryInfo(LogPath);
CheckDirectory();
try
{
FindLatestLogFile();
}
catch (Exception ex)
{
throw new Exception("Could not connect to iPolar. Ensure iPolar is running and plate solving", ex);
}
}
private void CheckDirectory()
{
if (dir == null)
{
throw new Exception("iPolar not connected");
}
else if (!dir.Exists)
{
throw new Exception("iPolar log directory " + LogPath + " not found");
}
}
public void Disconnect()
{
if (StopIPolar)
{
Setup.StopIPolar();
}
}
public void Dispose()
{
Disconnect();
}
public bool Solve(bool repeatUntilSuccess)
{
CheckDirectory();
bool success = false;
bool first = true;
using (var watcher = new FileSystemWatcher(LogPath))
using (var waitHandle = new AutoResetEvent(false))
{
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size;
watcher.Changed += (s, e) => waitHandle.Set();
watcher.Created += (s, e) => waitHandle.Set();
watcher.EnableRaisingEvents = true;
while (true)
{
CheckDirectory();
var logFile = FindLatestLogFile();
var log = ReadLastLine(logFile);
success = TryParseLog(log, out bool solveFailure);
if (first && (success || solveFailure))
{
// Skip the first result to ensure that plate solving
// has started only after this method was called
first = false;
continue;
}
if (success || (!repeatUntilSuccess && solveFailure))
{
break;
}
waitHandle.WaitOne(TimeSpan.FromSeconds(0.5 * MaxLogAge));
}
}
return success;
}
private bool TryParseLog(string log, out bool solveFailure)
{
solveFailure = false;
var match = LogRegex.Match(log);
if (match.Success)
{
string timestamp = match.Groups["timestamp"].Value;
if (timestamp == lastTimestamp)
{
return false;
}
if (!float.TryParse(match.Groups["x"].Value.Replace(",", "."), NumberStyles.Float, CultureInfo.InvariantCulture, out var x))
{
return false;
}
if (!float.TryParse(match.Groups["y"].Value.Replace(",", "."), NumberStyles.Float, CultureInfo.InvariantCulture, out var y))
{
return false;
}
if (!bool.TryParse(match.Groups["solved"].Value, out var solved))
{
return false;
}
if (!solved)
{
solveFailure = true;
}
lastTimestamp = timestamp;
if (solveFailure)
{
return false;
}
AlignmentOffset = new Vec2(x - CenterX, y - CenterY);
return true;
}
return false;
}
private FileInfo FindLatestLogFile()
{
var files = dir.GetFiles("*.txt", SearchOption.TopDirectoryOnly);
if (files.Length == 0)
{
throw new Exception("No iPolar log found in " + LogPath);
}
var latestFile = files.OrderByDescending(f => f.LastWriteTime).First();
if ((DateTime.Now - latestFile.LastWriteTime).TotalSeconds > MaxLogAge)
{
throw new Exception("Latest iPolar log " + latestFile.FullName + " is too old");
}
return latestFile;
}
private string ReadLastLine(FileInfo file)
{
try
{
using (PowerShell ps = PowerShell.Create())
{
return ps
.AddCommand("Get-Content")
.AddParameter("Path", file.FullName)
.AddParameter("Tail", 1)
.Invoke()
.FirstOrDefault()?.ToString();
}
}
catch (Exception ex)
{
throw new Exception("Failed reading iPolar log " + file.FullName, ex);
}
}
}
}