-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDriver.cs
1421 lines (1191 loc) · 50.3 KB
/
Driver.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
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
//tabs=4
// --------------------------------------------------------------------------------
//
// ASCOM Focuser driver for StellarFocus
//
// Description: Driver for StellarFocus
//
// Implements: ASCOM Focuser interface version: 1.0
// Author: (BDM) Brian Moyer ([email protected])
//
// Edit Log:
//
// Date Who Vers Description
// ----------- --- ----- -------------------------------------------------------
// 07/10/2015 BDM 6.0.0 Initial edit, created from ASCOM driver template
// --------------------------------------------------------------------------------
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Runtime.InteropServices;
using System.IO.Ports;
using System.Threading;
using ASCOM;
using ASCOM.Astrometry;
using ASCOM.Astrometry.AstroUtils;
using ASCOM.Utilities;
using ASCOM.DeviceInterface;
using System.Globalization;
using System.Collections;
namespace ASCOM.StellarFocus
{
//
// DeviceID is ASCOM.StellarFocus.Focuser
//
// The Guid attribute sets the CLSID for ASCOM.StellarFocus.Focuser
// The ClassInterface/None attribute prevents an empty interface called
// _StellarFocus from being created and used as the [default] interface
//
/// <summary>
/// ASCOM Focuser Driver for StellarFocus.
/// </summary>
[Guid("b89794d0-b655-4acc-afd1-260399f528b4")]
[ClassInterface(ClassInterfaceType.None)]
public class Focuser : IFocuserV2
{
/// <summary>
/// ASCOM DeviceID (COM ProgID) for this driver.
/// The DeviceID is used by ASCOM applications to load the driver at runtime.
/// </summary>
internal static string driverID = "ASCOM.StellarFocus.Focuser";
// TODO Change the descriptive string for your driver then remove this line
/// <summary>
/// Driver description that displays in the ASCOM Chooser.
/// </summary>
private static string driverDescription = "Focuser Driver for Stellar Focus.";
internal static string comPortProfileName = "COM Port"; // Constants used for Profile persistence
internal static string comPortDefault = "COM1";
internal static string traceStateProfileName = "Trace Level";
internal static string traceStateDefault = "false";
internal static string TempCoeffProfileName = "Temperature Coeff";
internal static string TempCoeffDefault = "0";
internal static string TempCompEnabledProfileName = "Temperature Comp";
internal static string TempCompEnabledDefault = "false";
internal static string MaxVelProfileName = "Maximum Velocity";
internal static string MaxVelDefault = "500";
internal static string AccelProfileName = "Acceleration";
internal static string AccelDefault = "500";
internal static string IdleOffProfileName = "Idle Off";
internal static string IdleOffDefault = "true";
internal static string ReverseProfileName = "Reverse";
internal static string ReverseDefault = "false";
internal static string HomeProfileName = "Home";
internal static string HomeDefault = "false";
internal static string InvertHomeProfileName = "Invert Home";
internal static string InvertHomeDefault = "false";
internal static string HomeDirectionProfileName = "Home Direction";
internal static string HomeDirectionDefault = "false";
internal static string HomeVelProfileName = "Home Vel";
internal static string HomeVelDefault = "250";
internal static string HomeUseSwitchProfileName = "true";
internal static string HomeUseSwitchDefault = "true";
internal static string HomeDistanceProfileName = "Home Distance";
internal static string HomeDistanceDefault = "0";
internal static string HomePositionProfileName = "Home Position";
internal static string HomePositionDefault = "0";
private const int PositionMax = 65535;
private const int IncrementMax = 65535;
private const int MaxVelMax = 2000;
private const double VelScale = 1;
private const int AccelMax = 12700;
private const double AccelScale = 0.001;
private const double TempCoeffMax = 20479;
private const double TempCoeffMin = -20480;
private const double TempCoeffScale = 1.6;
private const double TempScale = 0.1;
private const int TempErrorValue = -4097;
internal static string comPort; // Variables to hold the currrent device configuration
internal static bool traceState;
private static double pTempCoeff;
internal static double TempCoeff
{
set
{
if(value > TempCoeffMax || value < TempCoeffMin) throw new ASCOM.DriverException("Temperature coefficient must be between " +
TempCoeffMin.ToString() + " and " + TempCoeffMax.ToString() + ".");
else pTempCoeff = value;
}
get
{
return pTempCoeff;
}
}
internal static bool TempCompEnabled;
private static double pMaxVel;
internal static double MaxVel
{
set
{
if (value > MaxVelMax || value <= 0) throw new ASCOM.DriverException("Maximum velocity must be between " +
(1 / VelScale).ToString() + " and " + (MaxVelMax / VelScale).ToString() + ".");
else pMaxVel = value;
}
get
{
return pMaxVel;
}
}
private static double pAccel;
internal static double Accel
{
set
{
if (value > AccelMax || value <= 0) throw new ASCOM.DriverException("Maximum acceleration must be between " +
(1 / AccelScale).ToString() + " and " + (AccelMax / AccelScale).ToString() + ".");
else pAccel = value;
}
get
{
return pAccel;
}
}
internal static bool IdleOff;
internal static bool Reverse;
internal static bool Home;
internal static bool InvertHome;
internal static bool HomeDirection;
internal bool CancelHome;
internal bool Homing;
//0-Disconnected 1-Connecting 2-Connected
internal int ConnectStatus;
private static double pHomeVel;
internal static double HomeVel
{
set
{
if (value > MaxVelMax || value <= 0) throw new ASCOM.DriverException("Home velocity must be between " +
(1 / VelScale).ToString() + " and " + (MaxVelMax / VelScale).ToString() + ".");
else pHomeVel = value;
}
get
{
return pHomeVel;
}
}
internal static bool HomeUseSwitch;
private static int pHomeDistance;
internal static int HomeDistance
{
set
{
if (value > IncrementMax || value < 0) throw new ASCOM.DriverException("Home distance must be between 0 and " +
IncrementMax.ToString() + ".");
else pHomeDistance = value;
}
get
{
return pHomeDistance;
}
}
private static int pHomePosition;
internal static int HomePosition
{
set
{
if (value > IncrementMax || value < 0) throw new ASCOM.DriverException("Home position must be between 0 and " +
PositionMax.ToString() + ".");
else pHomePosition = value;
}
get
{
return pHomePosition;
}
}
private ASCOM.Utilities.Serial serialPort;
private object serLock = new object();
/// <summary>
/// Private variable to hold the connected state
/// </summary>
private bool connectedState;
/// <summary>
/// Private variable to hold an ASCOM Utilities object
/// </summary>
private Util utilities;
/// <summary>
/// Private variable to hold an ASCOM AstroUtilities object to provide the Range method
/// </summary>
private AstroUtils astroUtilities;
/// <summary>
/// Private variable to hold the trace logger object (creates a diagnostic log file with information that you specify)
/// </summary>
private TraceLogger tl;
/// <summary>
/// Initializes a new instance of the <see cref="StellarFocus"/> class.
/// Must be public for COM registration.
/// </summary>
public Focuser()
{
ReadProfile(); // Read device configuration from the ASCOM Profile store
tl = new TraceLogger("", "StellarFocus");
tl.Enabled = traceState;
tl.LogMessage("Focuser", "Starting initialisation");
connectedState = false; // Initialise connected to false
utilities = new Util(); //Initialise util object
astroUtilities = new AstroUtils(); // Initialise astro utilities object
serialPort = new ASCOM.Utilities.Serial();
ConnectStatus = 0;
Homing = false;
tl.LogMessage("Focuser", "Completed initialisation");
}
//
// PUBLIC COM INTERFACE IFocuserV2 IMPLEMENTATION
//
#region Common properties and methods.
/// <summary>
/// Displays the Setup Dialog form.
/// If the user clicks the OK button to dismiss the form, then
/// the new settings are saved, otherwise the old values are reloaded.
/// </summary>
public void SetupDialog()
{
if (IsConnected)
System.Windows.Forms.MessageBox.Show("Already connected, be careful with configuration changes.");
using (SetupDialogForm F = new SetupDialogForm())
{
var result = F.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
WriteProfile(); // Persist device configuration values to the ASCOM Profile store
}
else
{
ReadProfile();
}
}
}
public ArrayList SupportedActions
{
get
{
tl.LogMessage("SupportedActions Get", "Returning empty arraylist");
return new ArrayList();
}
}
public string Action(string actionName, string actionParameters)
{
throw new ASCOM.ActionNotImplementedException("Action " + actionName + " is not implemented by this driver");
}
public void CommandBlind(string command, bool raw)
{
throw new ASCOM.MethodNotImplementedException("CommandBlind");
}
public bool CommandBool(string command, bool raw)
{
throw new ASCOM.MethodNotImplementedException("CommandBool");
}
public string CommandString(string command, bool raw)
{
throw new ASCOM.MethodNotImplementedException("CommandString");
}
public void Dispose()
{
lock (serLock)
{
if (serialPort.Connected)
{
try
{
serialPort.Connected = false;
}
catch { }
}
serialPort.Dispose();
}
serLock = null;
// Clean up the tracelogger and util objects
tl.Enabled = false;
tl.Dispose();
utilities.Dispose();
astroUtilities.Dispose();
}
public bool Connected
{
get
{
tl.LogMessage("Connected Get", IsConnected.ToString());
return IsConnected;
}
set
{
tl.LogMessage("Connected Set", value.ToString());
if (value == IsConnected)
return;
if (value)
{
tl.LogMessage("Connected Set", "Connecting to port " + comPort);
ConnectStatus = 1;
lock (serLock)
{
//Set up serial port options and try opening the port
serialPort.PortName = comPort;
serialPort.Speed = SerialSpeed.ps115200;
serialPort.Parity = SerialParity.None;
serialPort.DataBits = 8;
serialPort.StopBits = SerialStopBits.One;
serialPort.Handshake = SerialHandshake.None;
serialPort.ReceiveTimeoutMs = 2000;
try
{
serialPort.Connected = true;
}
catch (Exception e)
{
ConnectStatus = 0;
throw new ASCOM.DriverException("Could not open COM port: " + comPort, e);
}
}
//Get the controller's configuration
byte[] recData, serData;
serData = new byte[1];
serData[0] = 0x05;
connectedState = true;
try
{
recData = SendCommand(serData, 6);
}
catch
{
lock (serLock)
{
connectedState = false;
if (serialPort.Connected)
{
try
{
serialPort.Connected = false;
}
catch { }
}
}
ConnectStatus = 0;
throw;
}
byte[] intBytes;
intBytes = new byte[2];
//Extract the current temp coefficient
intBytes[0] = recData[1];
intBytes[1] = recData[2];
if (!BitConverter.IsLittleEndian) Array.Reverse(intBytes);
Int16 CurrTempCoeff;
CurrTempCoeff = BitConverter.ToInt16(intBytes, 0);
//Decide if temp comp is enabled and set the driver's coefficient if it is
TempCompEnabled = false;
if (CurrTempCoeff != 0)
{
TempCoeff = Convert.ToDouble(CurrTempCoeff) / TempCoeffScale;
TempCompEnabled = true;
}
//Extract the motor parameters
IdleOff = false;
if(recData[3] != 0) IdleOff = true;
Accel = Convert.ToDouble(recData[4]) / AccelScale;
intBytes[0] = recData[5];
intBytes[1] = recData[6];
if (!BitConverter.IsLittleEndian) Array.Reverse(intBytes);
MaxVel = Convert.ToDouble(BitConverter.ToUInt16(intBytes, 0)) / VelScale;
if (Home) FindHome();
ConnectStatus = 2;
}
else
{
connectedState = false;
tl.LogMessage("Connected Set", "Disconnecting from port " + comPort);
lock (serLock)
{
if (serialPort.Connected) serialPort.Connected = false;
}
ConnectStatus = 0;
}
}
}
public string Description
{
get
{
tl.LogMessage("Description Get", driverDescription);
return driverDescription;
}
}
public string DriverInfo
{
get
{
Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
string driverInfo = "Information about the driver itself. Version: " + String.Format(CultureInfo.InvariantCulture, "{0}.{1}", version.Major, version.Minor);
tl.LogMessage("DriverInfo Get", driverInfo);
return driverInfo;
}
}
public string DriverVersion
{
get
{
Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
string driverVersion = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", version.Major, version.Minor);
tl.LogMessage("DriverVersion Get", driverVersion);
return driverVersion;
}
}
public short InterfaceVersion
{
// set by the driver wizard
get
{
tl.LogMessage("InterfaceVersion Get", "2");
return Convert.ToInt16("2");
}
}
public string Name
{
get
{
string name = "StellarFocus Driver";
tl.LogMessage("Name Get", name);
return name;
}
}
#endregion
#region IFocuser Implementation
public double StepSize
{
get
{
tl.LogMessage("StepSize Get", "Not implemented");
throw new ASCOM.PropertyNotImplementedException("StepSize", false);
}
}
public int MaxIncrement
{
get
{
tl.LogMessage("MaxIncrement Get", PositionMax.ToString());
return IncrementMax; // Maximum change in one move
}
}
public int MaxStep
{
get
{
tl.LogMessage("MaxStep Get", PositionMax.ToString());
return PositionMax; // Maximum extent of the focuser (0 - PositionMax)
}
}
public bool Absolute
{
get
{
tl.LogMessage("Absolute Get", true.ToString());
return true; // This is an absolute focuser
}
}
public void Halt()
{
tl.LogMessage("Halt", "Halting focuser movement.");
//Send halt command
byte[] serData;
serData = new byte[1];
serData[0] = 0x03;
SendCommand(serData, 0);
}
public bool IsMoving
{
get
{
//Get position and motion status
byte[] recData, serData;
serData = new byte[1];
serData[0] = 0x0B;
recData = SendCommand(serData, 1);
tl.LogMessage("IsMoving Get", Convert.ToBoolean(recData[1]).ToString());
return Convert.ToBoolean(recData[1]);
}
}
public bool Link
{
get
{
tl.LogMessage("Link Get", this.Connected.ToString());
return this.Connected; // Direct function to the connected method, the Link method is just here for backwards compatibility
}
set
{
tl.LogMessage("Link Set", value.ToString());
this.Connected = value; // Direct function to the connected method, the Link method is just here for backwards compatibility
}
}
public void Move(int Position)
{
tl.LogMessage("Move", Position.ToString());
if (TempCompEnabled) throw new ASCOM.InvalidOperationException("Attempted focuser move while temperature compensation is active.");
if(Position > PositionMax || Position < 0) throw new ASCOM.DriverException("Position must be between 0 and " + PositionMax.ToString() + ".");
byte[] recData, serData, posBytes;
serData = new byte[3];
//Reverse if necessary
if (Reverse) Position = MaxStep - Position;
//Shift the position we send so it's centered around focuserSteps/2
Position = Position - (PositionMax + 1) / 2;
posBytes = BitConverter.GetBytes(Convert.ToInt16(Position));
if (!BitConverter.IsLittleEndian) Array.Reverse(posBytes);
//First byte is length, command in upper and lower nibble respectively
serData[0] = Convert.ToByte(16 * (serData.Length - 1) + 0x02);
Buffer.BlockCopy(posBytes, 0, serData, 1, posBytes.Length);
//Send the command and get the response
recData = SendCommand(serData, 2);
//Validate the received data
bool failed = false;
for (int i = 1; i < serData.Length; i++)
{
if (recData[i] != serData[i]) failed = true;
}
if (failed)
{
string fmtSent = ByteArrayString(serData);
string fmtData = ByteArrayString(recData);
throw new ASCOM.DriverException("Error setting position. " +
"\n" + fmtSent + " - Expected" +
"\n" + fmtData + " - Received");
}
}
public int Position
{
get
{
//Request position
byte[] recData, serData;
serData = new byte[1];
serData[0] = 0x01;
recData = SendCommand(serData, 2);
byte[] posBytes = new byte[2];
//Extract the position bytes
posBytes[0] = recData[1];
posBytes[1] = recData[2];
if (!BitConverter.IsLittleEndian) Array.Reverse(posBytes);
int pos = Convert.ToInt32(BitConverter.ToInt16(posBytes, 0)) + (PositionMax + 1) / 2;
//Reverse if necessary
if (Reverse) pos = MaxStep - pos;
// Return the focuser position, centered around the midway point in our range
return pos;
}
}
public bool TempComp
{
get
{
tl.LogMessage("TempComp Get", TempCompEnabled.ToString());
return TempCompEnabled;
}
set
{
tl.LogMessage("TempComp Set", value.ToString());
byte[] recData, serData, tempBytes;
serData = new byte[3];
//Calculate the coefficient to send out
if (value) tempBytes = BitConverter.GetBytes(Convert.ToInt16(TempCoeff * TempCoeffScale));
else tempBytes = BitConverter.GetBytes(Convert.ToInt16(0));
if (!BitConverter.IsLittleEndian) Array.Reverse(tempBytes);
//First byte is length, command in upper and lower nibble respectively
serData[0] = Convert.ToByte(16 * (serData.Length - 1) + 0x04);
Buffer.BlockCopy(tempBytes, 0, serData, 1, tempBytes.Length);
//Send the command and get the response
recData = SendCommand(serData, 2);
//Validate the received data
bool failed = false;
for (int i = 1; i < serData.Length; i++)
{
if (recData[i] != serData[i]) failed = true;
}
if (failed)
{
TempCompEnabled = true;
if (recData[1] == 0 && recData[2] == 0) TempCompEnabled = false;
string fmtSent = ByteArrayString(serData);
string fmtData = ByteArrayString(recData);
throw new ASCOM.DriverException("Error setting temperature compensation coefficient. " +
"\n" + fmtSent + " - Expected" +
"\n" + fmtData + " - Received");
}
TempCompEnabled = value;
}
}
public bool TempCompAvailable
{
get
{
tl.LogMessage("TempCompAvailable Get", true.ToString());
return true;
}
}
public double Temperature
{
get
{
byte[] recData, serData;
serData = new byte[1];
serData[0] = 0x0A;
//Get data from the controller
recData = SendCommand(serData, 2);
short TempInt;
double Temp;
byte[] tempBytes = new byte[2];
//Extract the integer temp value
tempBytes[0] = recData[1];
tempBytes[1] = recData[2];
if (!BitConverter.IsLittleEndian) Array.Reverse(tempBytes);
TempInt = BitConverter.ToInt16(tempBytes, 0);
//Check for a disconnected sensor and scale the temp if not
if (TempInt == TempErrorValue) throw new ASCOM.DriverException("Temperature sensor read error.");
else Temp = Convert.ToDouble(TempInt) * TempScale;
tl.LogMessage("Temperature Get", Temp.ToString());
return Temp;
}
}
#endregion
#region Private properties and methods
// here are some useful properties and methods that can be used as required
// to help with driver development
#region ASCOM Registration
// Register or unregister driver for ASCOM. This is harmless if already
// registered or unregistered.
//
/// <summary>
/// Register or unregister the driver with the ASCOM Platform.
/// This is harmless if the driver is already registered/unregistered.
/// </summary>
/// <param name="bRegister">If <c>true</c>, registers the driver, otherwise unregisters it.</param>
private static void RegUnregASCOM(bool bRegister)
{
using (var P = new ASCOM.Utilities.Profile())
{
P.DeviceType = "Focuser";
if (bRegister)
{
P.Register(driverID, driverDescription);
}
else
{
P.Unregister(driverID);
}
}
}
/// <summary>
/// This function registers the driver with the ASCOM Chooser and
/// is called automatically whenever this class is registered for COM Interop.
/// </summary>
/// <param name="t">Type of the class being registered, not used.</param>
/// <remarks>
/// This method typically runs in two distinct situations:
/// <list type="numbered">
/// <item>
/// In Visual Studio, when the project is successfully built.
/// For this to work correctly, the option <c>Register for COM Interop</c>
/// must be enabled in the project settings.
/// </item>
/// <item>During setup, when the installer registers the assembly for COM Interop.</item>
/// </list>
/// This technique should mean that it is never necessary to manually register a driver with ASCOM.
/// </remarks>
[ComRegisterFunction]
public static void RegisterASCOM(Type t)
{
RegUnregASCOM(true);
}
/// <summary>
/// This function unregisters the driver from the ASCOM Chooser and
/// is called automatically whenever this class is unregistered from COM Interop.
/// </summary>
/// <param name="t">Type of the class being registered, not used.</param>
/// <remarks>
/// This method typically runs in two distinct situations:
/// <list type="numbered">
/// <item>
/// In Visual Studio, when the project is cleaned or prior to rebuilding.
/// For this to work correctly, the option <c>Register for COM Interop</c>
/// must be enabled in the project settings.
/// </item>
/// <item>During uninstall, when the installer unregisters the assembly from COM Interop.</item>
/// </list>
/// This technique should mean that it is never necessary to manually unregister a driver from ASCOM.
/// </remarks>
[ComUnregisterFunction]
public static void UnregisterASCOM(Type t)
{
RegUnregASCOM(false);
}
#endregion
/// <summary>
/// Writes motor parameters to EEPROM
/// </summary>
internal void WriteMotorParams()
{
byte[] serData, recData;
serData = new byte[5];
//Convert values to bytes
byte[] intBytes = BitConverter.GetBytes(Convert.ToUInt16(MaxVel * VelScale));
if (!BitConverter.IsLittleEndian) Array.Reverse(intBytes);
Buffer.BlockCopy(intBytes, 0, serData, 1, intBytes.Length);
serData[3] = Convert.ToByte(Accel * AccelScale);
if (serData[3] == 0) serData[3] = 1;
serData[4] = 0;
if (IdleOff) serData[4] = 1;
//First byte is length, command in upper and lower nibble respectively
serData[0] = Convert.ToByte(16 * (serData.Length - 1) + 0x06);
//Send everything over
recData = SendCommand(serData, 4);
//Validate the received data
bool failed = false;
for (int i = 1; i < serData.Length; i++)
{
if (recData[i] != serData[i]) failed = true;
}
if (failed)
{
string fmtSent = ByteArrayString(serData);
string fmtData = ByteArrayString(recData);
throw new ASCOM.DriverException("Error setting motor parameters. " +
"\n" + fmtSent + " - Expected" +
"\n" + fmtData + " - Received");
}
}
/// <summary>
/// Handles sending a command and receiving the response
/// </summary>
private byte[] SendCommand(byte[] serData, int expectBytes)
{
//Just give up if we don't even think we're connected
if (connectedState == false) throw new ASCOM.NotConnectedException("Not connected.");
//Try to take the serial port
lock (serLock)
{
//If the port is not already open, release our mutex and error out
if (!serialPort.Connected)
{
throw new ASCOM.NotConnectedException("Not connected");
}
//Try to send/receive and pass any exceptions upstream
int recBytes = 1;
int tryCount = 0;
const int retries = 2;
byte cmdByte = new byte();
byte[] response = null;
while (true)
{
tryCount++;
//Try to send the command and data
try
{
serialPort.ClearBuffers();
serialPort.TransmitBinary(serData);
}
catch (Exception e)
{
throw new ASCOM.DriverException("Serial port error while sending command.", e);
}
//Lot what we sent if logging is on
if (traceState)
{
string fmtSent = ByteArrayString(serData);
tl.LogMessage("SendCommand", "Sent: " + fmtSent);
}
//Try to receive the command byte of the response
try
{
cmdByte = serialPort.ReceiveByte();
}
catch (Exception e)
{
if (traceState) tl.LogMessage("SendCommand", "Error: Receive command byte timed out.");
if (tryCount < retries) continue;
if (traceState) tl.LogMessage("SendCommand", "Error: Giving up.");
throw new ASCOM.DriverException("Error receiving response command.", e);
}
//Figure out what command was returned and how many data bytes to expect
int responseBytes = (byte)((cmdByte >> 4) & 0x0F);
response = new byte[responseBytes + 1];
response[0] = cmdByte;
cmdByte = (byte)(cmdByte & 0x0F);
//Try to receive data bytes
while (recBytes < responseBytes + 1)
{
try
{
response[recBytes] = serialPort.ReceiveByte();
recBytes++;
}
catch (Exception e)
{
string fmtData;
if (response != null)
{
fmtData = ByteArrayString(response);
}
else
{
fmtData = "Nothing";
}
throw new ASCOM.DriverException("Error receiving response data, received response: " + fmtData, e);
}
}
//Log what we received if logging is on
if (traceState)
{
string fmtData = "";
for (int i = 0; i < response.Length; i++)
{
fmtData = fmtData + response[i].ToString("X2") + " ";
}
tl.LogMessage("SendCommand", "Recd: " + fmtData);
}
//Received a command timeout response
if (cmdByte == 0x0)
{
if (traceState) tl.LogMessage("SendCommand", "Error: Received command timed out.");
if (tryCount < retries) continue;