-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontroller.cs
1684 lines (1488 loc) · 67.9 KB
/
controller.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
using DAQ;
using DAQ.Analog;
using DAQ.Environment;
using DAQ.HAL;
using NationalInstruments.DAQmx;
using Microsoft.CSharp;
using MOTMaster2.SequenceData;
using Newtonsoft.Json;
using System;
//using IMAQ;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Windows.Threading;
using System.Windows;
//using DataStructures;
using System.Runtime.Serialization.Formatters.Binary;
using UtilsNS;
using ErrorManager;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
namespace MOTMaster2
{
/// <summary>
/// Here's MOTMaster's controller.
///
/// Gets a MOTMasterScript (a script contaning a series of commands like "addEdge" for both digital and analog)
/// from user (either remotely or via UI), compiles it, builds a pattern and sends it
/// to hardware.
/// </summary>
public class Controller : MarshalByRefObject
{
#region Class members
private static string
motMasterPath = (string)Environs.FileSystem.Paths["MOTMasterEXEPath"] + "MOTMaster2.exe";
private static string
daqPath = (string)Environs.FileSystem.Paths["daqDLLPath"];
private static string
scriptListPath = (string)Environs.FileSystem.Paths["scriptListPath"];
private static string
motMasterDataPath = (string)Environs.FileSystem.Paths["DataPath"];
private static string
saveToDirectory = (string)Environs.FileSystem.Paths["MOTMasterDataPath"];
private static string
cameraAttributesPath = (string)Environs.FileSystem.Paths["CameraAttributesPath"];
private static string
hardwareClassPath = (string)Environs.FileSystem.Paths["HardwareClassPath"];
private static string defaultScriptPath = scriptListPath + "\\defaultScript.sm2";
private static string tempScriptPath = scriptListPath + "\\tempScript.sm2";
private static string digitalPGBoard = (string)Environs.Hardware.Boards["multiDAQ"];
public static MMConfig config = (MMConfig)Environs.Hardware.GetInfo("MotMasterConfiguration");
private Thread runThread;
private static Exception runThreadException = null;
public enum RunningState { stopped, running };
private static RunningState _runningStatus = RunningState.stopped;
public static RunningState status
{
get { return _runningStatus; }
set
{
if ((value != _runningStatus) && !Utils.isNull(Application.Current))
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() =>
{
RunStatusEvent(value == RunningState.running);
}));
_runningStatus = value;
}
}
//public List<string> analogChannels;
public List<string> digitalChannels;
public static MOTMasterScript script;
public static GeneralOptions genOptions;
public static Sequence sequenceData;
public MOTMasterSequence sequence;
public static ExperimentData ExpData { get; set; }
public static FileLogger dataLogger;
public static FileLogger paramLogger;
private static NationalInstruments.DAQmx.Task clockTask;
private static DigitalSingleChannelReader myDigitalReader;
public static double acquireTime { get; private set; }
public static bool SendDataRemotely { get; set; }
private bool _AutoLogging;
public bool AutoLogging
{
get { return _AutoLogging; }
set
{
if (value) StartLogging();
else StopLogging();
_AutoLogging = value;
}
}
public static event DataEventHandler MotMasterDataEvent;
public delegate void DataEventHandler(object sender, DataEventArgs d);
private static DAQMxPatternGenerator pg;
private static HSDIOPatternGenerator hs;
private static DAQMxPatternGenerator PCIpg;
private static DAQMxAnalogPatternGenerator apg;
private static MMAIWrapper aip;
private static bool _StaticSequence;
public static bool StaticSequence { get { return genOptions.ForceSeqCharge ? false : _StaticSequence; } set { _StaticSequence = value; } }
private bool hardwareError = false;
private static CameraControllable camera = null;
// private static TranslationStageControllable tstage = null;
private static ExperimentReportable experimentReporter = null;
public static WindfreakSynth microSynth, microSynth2;
//public string ExperimentRunTag { get; set; }
public static MMscan ScanParam { get; set; }
public static int numInterations { get; set; }
private static MuquansController muquans = null;
public static ICEBlocDCS M2DCS;
public static ICEBlocPLL M2PLL;
public PhaseStrobes phaseStrobes;
public static Dictionary<string, object> DCSParams;
MMDataIOHelper ioHelper;
static SequenceBuilder builder;
DataStructures.SequenceData ciceroSequence;
DataStructures.SettingsData ciceroSettings;
public delegate void b4AcquireHandler(long ticks, out double sTime);
public static event b4AcquireHandler Onb4Acquire;
protected static void b4AcquireEvent(long ticks, out double sTime)
{
sTime = -1;
if (Onb4Acquire != null) Onb4Acquire(ticks, out sTime);
}
public delegate void RunStatusHandler(bool running);
public static event RunStatusHandler OnRunStatus;
protected static void RunStatusEvent(bool running)
{
if (OnRunStatus != null) OnRunStatus(running);
}
public delegate void ChnChangeHandler(int chn);
public static event ChnChangeHandler OnChnChange;
protected static void ChnChangeEvent(int chn)
{
if (OnChnChange != null) OnChnChange(chn);
}
#endregion
#region Initialisation
// without this method, any remote connections to this object will time out after
// five minutes of inactivity.
// It just overrides the lifetime lease system completely.
public override Object InitializeLifetimeService()
{
return null;
}
public void StartApplication()
{
LoadEnvironment();
LoadDefaultSequence();
//TODO Analog input config should be moved to GeneralOptions
if (ExpData == null) { ExpData = new ExperimentData(); Controller.UpdateAIValues(); }
CheckHardware(config.Debug);
phaseStrobes = new PhaseStrobes();
ioHelper = new MMDataIOHelper(motMasterDataPath,
(string)Environs.Hardware.GetInfo("Element"));
}
//TODO Set config flags based on if hardware exists
private void CheckHardware(bool debug)
{
if (!config.HSDIOCard) pg = new DAQMxPatternGenerator((string)Environs.Hardware.Boards["digital"]);
else hs = new HSDIOPatternGenerator((string)Environs.Hardware.Boards["hsDigital"]);
apg = new DAQMxAnalogPatternGenerator();
PCIpg = new DAQMxPatternGenerator((string)Environs.Hardware.Boards["multiDAQPCI"]);
aip = new MMAIWrapper((string)Environs.Hardware.Boards["analogIn"]);
digitalChannels = Environs.Hardware.DigitalOutputChannels.Keys.Cast<string>().ToList();
if (config.CameraUsed) camera = (CameraControllable)Activator.GetObject(typeof(CameraControllable),
"tcp://localhost:1172/controller.rem");
// if (config.TranslationStageUsed) tstage = (TranslationStageControllable)Activator.GetObject(typeof(CameraControllable),
// "tcp://localhost:1172/controller.rem");
if (config.ReporterUsed) experimentReporter = (ExperimentReportable)Activator.GetObject(typeof(ExperimentReportable),
"tcp://localhost:1172/controller.rem");
if (config.UseMuquans) { muquans = new MuquansController(); }
if (!config.Debug)
{
microSynth = (WindfreakSynth)Environs.Hardware.Instruments["microwaveSynth"];
microSynth2 = (WindfreakSynth)Environs.Hardware.Instruments["microwaveSynth2"];
}
if (config.UseMSquared)
{
CheckMSquaredHardware();
}
}
private void CheckMSquaredHardware()
{
//if (genOptions.m2Comm == GeneralOptions.M2CommOption.off) return;
if (Environs.Hardware.Instruments.ContainsKey("MSquaredDCS")) M2DCS = (ICEBlocDCS)Environs.Hardware.Instruments["MSquaredDCS"];
else throw new Exception("Cannot find DCS ICE-BLOC");
if (Environs.Hardware.Instruments.ContainsKey("MSquaredPLL")) M2PLL = (ICEBlocPLL)Environs.Hardware.Instruments["MSquaredPLL"];
else throw new Exception("Cannot find PLL ICE-BLOC");
return;
try
{
if (!config.Debug)
{
M2DCS.Connect();
M2PLL.Connect();
M2PLL.StartLink();
M2DCS.StartLink();
//SetMSquaredParameters();
}
}
catch
{
//Set to popup to avoid Exception called when it can't write to a Log
if (genOptions.ExtDvcEnabled["MSquared"])
ErrorMng.warningMsg("Could not set MSquared Parameters", -1, true);
}
}
#endregion
#region Hardware control methods
private void run(MOTMasterSequence sequence)
{
Stopwatch watch = new Stopwatch();
watch.Start();
try
{
if (config.UseMuquans)
{
muquans.StartOutput(); Console.WriteLine("Started muquans at {0}ms", watch.ElapsedMilliseconds);
}
apg.OutputPatternAndWait(sequence.AnalogPattern.Pattern);
Console.WriteLine("Started apg at {0}ms", watch.ElapsedMilliseconds);
if (Controller.genOptions.AIEnabled) aip.StartTask();
if (!config.HSDIOCard) pg.OutputPattern(sequence.DigitalPattern.Pattern, true);
else
{
int[] loopTimes = ((DAQ.Pattern.HSDIOPatternBuilder)sequence.DigitalPattern).LoopTimes;
hs.OutputPattern(sequence.DigitalPattern.Pattern, loopTimes);
Console.WriteLine("Started hs at {0}ms", watch.ElapsedMilliseconds);
}
}
catch
{
releaseHardware();
runThreadException = new Exception("Failed to start output patterns. Releasing hardware");
Console.WriteLine("Failed to start output patterns. Releasing hardware");
}
}
private void ContinueLoop()
{
//Just need to restart the cards
apg.StartPattern();
if (Controller.genOptions.AIEnabled) aip.StartTask();
if (config.HSDIOCard)
{
hs.StartPattern();
}
else
{
throw new NotImplementedException("DAQmx digital cards not currently supported");
}
if (Controller.genOptions.AIEnabled) aip.ReadAnalogDataFromBuffer();
}
private static void initializeHardware(MOTMasterSequence sequence)
{
if (!config.HSDIOCard) pg.Configure(config.DigitalPatternClockFrequency, StaticSequence, true, true, sequence.DigitalPattern.Pattern.Length, true, false);
else hs.Configure(config.DigitalPatternClockFrequency, StaticSequence, true, false);
if (config.UseMuquans) { muquans.Configure(StaticSequence); }
apg.Configure(sequence.AnalogPattern, config.AnalogPatternClockFrequency, StaticSequence);
// Create the task.
clockTask = new NationalInstruments.DAQmx.Task();
DigitalOutputChannel aqcTr = ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["acquisitionTrigger"]); // e.g. Dev3/port0/line23
string triggerLoc = aqcTr.Device + "/port0/line" + aqcTr.line.ToString();
clockTask.Dispose();
if (Controller.genOptions.AIEnabled)
{
aip.Configure(sequence.AIConfiguration, StaticSequence);
aip.AnalogDataReceived += OnAnalogDataReceived;
acquireTime = Double.NaN;
try
{
/* // Create the task.
clockTask = new NationalInstruments.DAQmx.Task();
DigitalOutputChannel aqcTr = ((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels["acquisitionTrigger"]); // e.g. Dev3/port0/line23
string triggerLoc = aqcTr.Device + "/port0/line" + aqcTr.line.ToString();
clockTask.Dispose();
// Create channel
clockTask.DOChannels.CreateChannel(triggerLoc, "", ChannelLineGrouping.OneChannelForEachLine);
// Configure digital change detection timing
clockTask.Timing.ConfigureChangeDetection(triggerLoc, "", SampleQuantityMode.ContinuousSamples, 1000);
// Add the digital change detection event handler
// Use SynchronizeCallbacks to specify that the object
// marshals callbacks across threads appropriately.
clockTask.SynchronizeCallbacks = true;
clockTask.DigitalChangeDetection += new DigitalChangeDetectionEventHandler(clockTask_DigitalChangeDetection);
// Create the reader
myDigitalReader = new DigitalSingleChannelReader(clockTask.Stream);
// Start the task
clockTask.Start();*/
}
catch (DaqException exception)
{
clockTask.Dispose();
MessageBox.Show(exception.Message);
}
}
}
private static void clockTask_DigitalChangeDetection(object sender, DigitalChangeDetectionEventArgs e)
{
try
{
bool triggerLine = myDigitalReader.ReadSingleSampleSingleLine();
double aTime = -1;
//b4AcquireEvent(DateTime.Now.Ticks, out aTime);
acquireTime = (aTime > 0) ? aTime : Double.NaN;
}
catch (DaqException ex)
{
clockTask.Dispose();
MessageBox.Show(ex.Message);
}
}
private void releaseHardware()
{
try
{
//if (StaticSequence) pauseHardware();
if (!config.HSDIOCard) pg.StopPattern();
else hs.StopPattern();
apg.StopPattern();
if (Controller.genOptions.AIEnabled) { aip.StopPattern(); }
if (config.UseMuquans) { muquans.StopOutput(); }//microSynth.Disconnect(); }
}
catch (Exception e)
{
ErrorMng.warningMsg("Error when releasing hardware: " + e.Message, -3, false);
}
}
private void pauseHardware()
{
apg.PauseLoop();
if (Controller.genOptions.AIEnabled) aip.PauseLoop();
if (config.HSDIOCard) hs.PauseLoop();
else throw new NotImplementedException("DAQmx digital cards not currently supported");
}
//private void releaseHardwareLoop()
//{
// if (!config.HSDIOCard) pg.StopPattern();
// else hs.AbortRunning();
// apg.AbortRunning();
// if (Controller.genOptions.AIEnable) aip.AbortRunning();
// if (config.UseMuquans) muquans.StopOutput();
//}
private void clearDigitalPattern(MOTMasterSequence sequence)
{
sequence.DigitalPattern.Clear(); //No clearing required for analog (I think).
}
private void releaseHardwareAndClearDigitalPattern(MOTMasterSequence sequence)
{
clearDigitalPattern(sequence);
releaseHardware();
}
private void ClearPatterns()
{
if (Utils.isNull(sequence)) return;
if (Utils.isNull(sequence.AnalogPattern)) return;
if (Utils.isNull(sequence.DigitalPattern)) return;
sequence.AnalogPattern.Clear();
sequence.DigitalPattern.Clear();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
//private static long[] hwInterferometerInterval = new long[2];
public static Tuple<long, long> InterferometerInterval() // from..to [ticks] relative to beginning of seq
{
Tuple<long, long> rslt = new Tuple<long, long>(-1, -1);
if (ExpData.startSeqTime < 0) return rslt; // no reference point
//if (Utils.isNull(ExpData.InterferometerStepName)) return rslt;
//if (ExpData.InterferometerStepName.Equals("")) return rslt;
long curr = ExpData.startSeqTime; long first = -1; long second = -1;
foreach (SequenceStep step in sequenceData.Steps)
{
if (step.Description.Contains("Interferometer"))
{
if (first < 0)
{
first = curr; // first occurence
second = first;
}
double d = step.evalDuration(true); long l = Utils.sec2tick(d);
second += l;
}
if (step.Enabled) curr += Utils.sec2tick(step.evalDuration(true));
}
//if (hwInterferometerInterval[0] > -1) first = hwInterferometerInterval[0];
//if (hwInterferometerInterval[1] > -1) second = hwInterferometerInterval[1];
rslt = new Tuple<long, long>(first, second);
//hwInterferometerInterval[0] = -1; hwInterferometerInterval[1] = -1;
return rslt;
}
protected static void OnAnalogDataReceived(object sender, EventArgs e)
{
var rawData = config.Debug ? ExpData.GenerateFakeData() : aip.GetAnalogData();
MMexec[] finalData = ConvertDataXYToAxelHub(rawData);
ExperimentData.lastData = Controller.genOptions.AIEnabled ? finalData[0].prms : null;
if (!Controller.genOptions.AIEnabled) return;
if (ExpData.grpMME.cmd.Equals("repeat") && SendDataRemotely)
{
if (Convert.ToInt32(ExpData.grpMME.prms["cycles"]) == (Convert.ToInt32(finalData[0].prms["runID"]) + 1))
{
finalData[0].prms["last"] = 1;
}
}
if (ExpData.grpMME.cmd.Equals("scan") && SendDataRemotely)
{
MMscan mms = new MMscan();
mms.FromDictionary(ExpData.grpMME.prms);
int k = (int)((mms.sTo - mms.sFrom) / mms.sBy);
if (k == (Convert.ToInt32(finalData[0].prms["runID"])))
{
finalData[0].prms["last"] = 1;
}
}
foreach (MMexec mme in finalData)
{
if (SendDataRemotely && (ExpData.startSeqTime > 0))
{
var tm = InterferometerInterval(); Tuple<int, int> ei;
if (ExpData.AnalogSegments.ContainsKey("ExtraInterferometer"))
{
ei = ExpData.AnalogSegments["ExtraInterferometer"]; // pre (before) and post (after) skimming in numPnt; if not they are there then 0
mme.prms["bTime"] = ei.Item1.ToString(); mme.prms["aTime"] = ei.Item2.ToString();
ExpData.AnalogSegments.Remove("ExtraInterferometer");
}
mme.prms["iTime"] = tm.Item1.ToString(); mme.prms["tTime"] = (tm.Item2 - tm.Item1).ToString(); // start in ticks; length in ticks
mme.prms["samplingRate"] = genOptions.AISampleRate.ToString();
}
if (!Utils.isNull(ScanParam))
if (ScanParam.randomized) mme.prms["scan.prm"] = ScanParam.Value;
string dataJson = JsonConvert.SerializeObject(mme, Formatting.Indented);
if (!Utils.isNull(dataLogger)) dataLogger.log("{\"MMExec\":" + dataJson + "},");
if (SendDataRemotely)
{
if (MotMasterDataEvent != null) MotMasterDataEvent(sender, new DataEventArgs(dataJson));
}
dataJson = null;
}
finalData = null;
// if (Controller.genOptions.AIEnable && !config.Debug) aip.ClearBuffer();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
internal void StopRunning(bool force = false)
{
if (!config.Debug)
{
WaitForRunToFinish();
while (IsRunning() && !StaticSequence)
{
WaitForRunToFinish();
if (!hardwareError) releaseHardware();
}
try { if (force || StaticSequence) releaseHardware(); }
catch { }
if (config.UseMuquans)muquans.DisposeAll();
}
StaticSequence = false; //Set this here in case we want to scan after
status = RunningState.stopped;
if (force) ClearPatterns();
}
internal bool CheckForRunErrors()
{
if (runThreadException == null) return false;
else
{
status = RunningState.stopped;
Exception ex = runThreadException;
runThreadException = null;
hardwareError = true;
throw ex;
}
}
#endregion
#region RUN RUN RUN (public & remotable stuff)
/// <summary>
/// This is the guts of MOTMaster.
///
/// - MOTMaster initializes the hardware, faffs a little to prepare the patterns in the
/// builders (e.g. calls "BuildPattern"), and sends the pattern to Hardware.
///
/// -Note that the analog stuff needs a trigger to start!!!! Make sure one of your digital lines is reserved
/// for triggering the analog pattern.
///
/// - Once the experiment is finished, MM releases the hardware.
///
/// - MOTMaster also saves the data to a .zip. This includes: the original MOTMasterScript (.cs), a text file
/// with the parameters in it (IF DIFFERENT FROM THE VALUES IN .cs, THE PARAMETERS IN THE TEXT FILE ARE THE
/// CORRECT VALUES!), another text file with the camera attributes, yet another file (entitled hardware report)
/// which contains the values set by the Hardware controller at the start of the run, and a .png file(s) containing the final image(s).
///
/// -There are 2 ways of using "Run". Run(null) uses the parameters given in the script (.cs file).
/// Run(Dictionary<>) compiles the .cs file but then replaces values in the dictionary. This is to allow
/// the user to inject values after compilation but before sending to hardware. By doing this,
/// the user can scan parameters using a python script, for example.
/// If you call Run(), MOTMaster immediately checks to see if you're running a fresh script
/// or whether you're re-running an old one. In the former case Run(null) is called. In the latter,
/// MOTMaster will fetch the dictionary used in the old experiment and use it as the
/// argument for Run(Dictionary<>). ///
///
/// </summary>
private bool saveEnable = true;
public void SaveToggle(System.Boolean value)
{
//saveEnable = value;
//controllerWindow.SetSaveCheckBox(value);
}
private static void axisControl(int chn, bool xy)
{
int chn0 = chn;
if (sequenceData.Parameters.ContainsKey("swapAxes"))
if (Convert.ToDouble(sequenceData.Parameters["swapAxes"].Value) > 0.5)
{
if (chn == 0) chn0 = 1;
else chn0 = 0;
}
M2DCS.axisControl(chn0,xy);
if (xy) ChnChangeEvent(chn0);
else ChnChangeEvent(2);
/* double PLLFreq = (double)sequenceData.Parameters["PLLFreq"].Value;
double ChirpRate = (double)sequenceData.Parameters["ChirpRate"].Value;
double ChirpDuration = (double)sequenceData.Parameters["ChirpDuration"].Value;
if (xy)
{
switch (chn)
{
case 0:
if (sequenceData.Parameters.ContainsKey("PLLFreqX")) PLLFreq = (double)sequenceData.Parameters["PLLFreqX"].Value;
if (sequenceData.Parameters.ContainsKey("ChirpRateX")) ChirpRate = (double)sequenceData.Parameters["ChirpRateX"].Value;
break;
case 1:
if (sequenceData.Parameters.ContainsKey("PLLFreqY")) PLLFreq = (double)sequenceData.Parameters["PLLFreqY"].Value;
if (sequenceData.Parameters.ContainsKey("ChirpRateY")) ChirpRate = (double)sequenceData.Parameters["ChirpRateY"].Value;
break;
}
}
M2PLL.configure_PLL_profile(PLLFreq * 1e6, ChirpRate * 1e6, ChirpDuration);*/
}
private static int _BatchNumber;
public static int BatchNumber
{
get { return _BatchNumber; }
set
{
_BatchNumber = value;
if (sequenceData.Parameters.ContainsKey("runID")) sequenceData.Parameters["runID"].Value = (double)value;
if (sequenceData.Parameters.ContainsKey("aChn"))
{
if (sequenceData.Parameters.ContainsKey("swapAxes"))
{
sequenceData.Parameters["aChn"].Value = (double)actChannel(value, Convert.ToDouble(sequenceData.Parameters["swapAxes"].Value) > 0.5);
}
else
{
if (actChannel(value) == 0) sequenceData.Parameters["aChn"].Value = 1.0;
else sequenceData.Parameters["aChn"].Value = 0.0;
}
}
if (!config.Debug && config.UseMSquared && genOptions.ExtDvcEnabled["MSquared"])
{
if (Math.Abs(ExpData.axis).Equals(2)) axisControl(actChannel(value), true);
else
{
if (value.Equals(0)) axisControl(ExpData.axis, false); // at start only
}
}
}
}
public void IncrementBatchNumber()
{
BatchNumber++;
}
private string scriptPath = "";
public void SetScriptPath(String path)
{
scriptPath = path;
//controllerWindow.WriteToScriptPath(path);
}
/*
private bool replicaRun = false;
public void SetReplicaRunBool(System.Boolean value)
{
replicaRun = value;
}
private string dictionaryPath = "";
public void SetDictionaryPath(String path)
{
dictionaryPath = path;
}
*/
public bool IsRunning()
{
return status == RunningState.running;
/*
if (status == RunningState.running && !config.Debug)
{
Console.WriteLine("Thread Running");
return true;
}
else
return false;
* */
}
public void RunStart(Dictionary<string, object> paramDict, int myBatchNumber = 0)
{
//runThread = new Thread(delegate()
//{
// try
// {
// this.Run(paramDict);
// }
// catch (ThreadAbortException) { }
// catch (Exception e)
// {
// status = RunningState.stopped;
// throw e;
// }
//});
runThread = new Thread(new ParameterizedThreadStart(this.Run));
runThread.Name = "MOTMaster Controller";
runThread.Priority = ThreadPriority.Highest;
status = RunningState.running;
runThread.Start(paramDict);
//Console.WriteLine("Thread Starting");
}
public void WaitForRunToFinish()
{
if (runThread != null) { runThread.Join(); }
if (IsRunning()) hardwareError = CheckForRunErrors();
// Console.WriteLine("Thread Waiting");
}
/*
public void Run()
{
status = RunningState.running;
Run(replicaRun ? ioHelper.LoadDictionary(dictionaryPath) : null);
}
public void Run(Dictionary<String, Object> dict)
{
Run(dict, batchNumber);
}
*/
public void Run(object dict)
{
Run((Dictionary<string, object>)dict);
}
public void Run(Dictionary<String, Object> dict)
{
Stopwatch watch = new Stopwatch();
//sequence = BuildMMSequence(dict);
if (sequence == null)
{
//Exception has been thrown. Will be passed when CheckForRunErrors is called.
status = RunningState.stopped;
return;
}
if (BatchNumber == 0)
{
if (StaticSequence) hardwareError = !InitialiseHardwareAndPattern(sequence);
InitialiseData(this);
}
// if (hardwareError && !config.Debug) ErrorMng.errorMsg(runThreadException.Message, -5);
PrepareNonDAQHardware();
if (!StaticSequence)
{
hardwareError = InitialiseHardwareAndPattern(sequence);
}
if (config.CameraUsed) waitUntilCameraIsReadyForAcquisition();
Utils.Trace("shot");
watch.Start();
ExpData.startSeqTime = DateTime.Now.Ticks; // move to 277 or 299 ??
//TODO Try WaitForRunToFinish here and nowhere else
if (!config.Debug)
{
if (BatchNumber == 0 || !StaticSequence) runPattern(sequence);
else if (status == RunningState.running) ContinueLoop();
else return;
}
watch.Stop();
if (saveEnable)
{
AcquireDataFromHardware();
}
if (config.CameraUsed) finishCameraControl();
// if (config.TranslationStageUsed) disarmAndReturnTranslationStage();
//if (config.UseMuquans && !config.Debug) microSynth.ChannelA.RFOn = false;
if (Controller.genOptions.AIEnabled || config.Debug) OnAnalogDataReceived(this, new DataEventArgs(BatchNumber));
if (StaticSequence && !config.Debug) pauseHardware();
status = RunningState.stopped;
//Dereferences the MMScan object
//ScanParam = null;
}
private static bool InitialiseHardwareAndPattern(MOTMasterSequence sequence)
{
if (config.UseMMScripts) buildPattern(sequence, (int)script.Parameters["PatternLength"]);
else buildPattern(sequence, (int)builder.Parameters["PatternLength"]);
try
{
if (!config.Debug) initializeHardware(sequence);
}
catch (Exception e)
{
ErrorMng.errorMsg("Could not initialise hardware:" + e.Message, -2, true);
return false;
}
return true;
}
public void BuildMMSequence(Dictionary<String, Object> dict, string scriptPath = null)
{
if (config.UseMMScripts || sequenceData == null)
{
script = prepareScript(scriptPath, dict);
sequence = getSequenceFromScript(script);
}
else
{
if (Controller.genOptions.AIEnabled || config.Debug)
{
if (!sequenceData.Steps.Any(t=>t.GetDigitalData("acquisitionTrigger")))
{
Controller.genOptions.AIEnabled = false;
ErrorMng.warningMsg("acquisitionTrigger is not enabled. Setting AIEnable to false.");
}
else
{
CreateAcquisitionTimeSegments();
}
}
if (!StaticSequence || BatchNumber == 0)
sequence = getSequenceFromSequenceData(dict);
if (sequence == null) { throw runThreadException; }
}
}
/// <summary>
/// Prepares the hardware that is not controlled using DAQmx voltage patterns. Typically, these are experiment specific.
/// </summary>
private static void PrepareNonDAQHardware()
{
if (config.CameraUsed) prepareCameraControl();
// if (config.TranslationStageUsed) armTranslationStageForTimedMotion(script);
if (config.CameraUsed) GrabImage((int)script.Parameters["NumberOfFrames"]);
}
/// <summary>
/// Initialises the objects used to store data from the run !
/// </summary>
private static void InitialiseData(object sender)
{
MMexec mme = InitialCommand(ScanParam);
string initJson = JsonConvert.SerializeObject(mme, Formatting.Indented);
if (!Utils.isNull(paramLogger))
paramLogger.log("{\"MMExec\":" + initJson + "},");
var jm = ExpData.jumboMode();
if (jm == ExperimentData.JumboModes.repeat)
{
}
if (SendDataRemotely && ((jm == ExperimentData.JumboModes.none)))
{
MotMasterDataEvent(sender, new DataEventArgs(initJson));
ExpData.grpMME = mme.Clone();
}
}
[Obsolete("This method encapsulates the old-style data acquisition and will be removed in the future", false)]
private void AcquireDataFromHardware()
{
if (config.CameraUsed)
{
waitUntilCameraAquisitionIsDone();
try
{
checkDataArrived();
}
catch (DataNotArrivedFromHardwareControllerException)
{
ErrorMng.warningMsg("No Data Arrived from Hardware Controller", -10, true);
}
Dictionary<String, Object> report = new Dictionary<string, object>();
if (config.ReporterUsed)
{
report = GetExperimentReport();
//TODO Change save method
}
save(script, scriptPath, imageData, report, BatchNumber);
}
else
{
Dictionary<String, Object> report = new Dictionary<string, object>();
if (config.ReporterUsed)
{
report = GetExperimentReport();
}
if (config.UseMMScripts)
save(builder, motMasterDataPath, report, ExpData.ExperimentName, BatchNumber);
}
}
#endregion
#region private stuff
private void updateSaveDirectory(string newDirectory)
{
saveToDirectory = newDirectory;
if (!Directory.Exists(newDirectory))
{
Directory.CreateDirectory(saveToDirectory);
}
}
//TODO Change the way everything is saved
private void save(MOTMasterScript script, string pathToPattern, byte[,] imageData, Dictionary<String, Object> report, double[,] aiData, int batchNumber)
{
ioHelper.StoreRun(motMasterDataPath, batchNumber, pathToPattern, hardwareClassPath,
script.Parameters, report, cameraAttributesPath, imageData, config.ExternalFilePattern);
}
private void save(MOTMasterScript script, string pathToPattern, byte[][,] imageData, Dictionary<String, Object> report, double[,] aiData, int batchNumber)
{
ioHelper.StoreRun(motMasterDataPath, batchNumber, pathToPattern, hardwareClassPath,
script.Parameters, report, cameraAttributesPath, imageData, config.ExternalFilePattern);
}
private void save(MOTMasterScript script, string pathToPattern, Dictionary<String, Object> report, int batchNumber)
{
ioHelper.StoreRun(motMasterDataPath, batchNumber, pathToPattern, hardwareClassPath,
script.Parameters, report, config.ExternalFilePattern);
}
private void save(MOTMasterScript script, string pathToPattern, byte[][,] imageData, Dictionary<String, Object> report, int batchNumber)
{
ioHelper.StoreRun(motMasterDataPath, batchNumber, pathToPattern, hardwareClassPath,
script.Parameters, report, cameraAttributesPath, imageData, config.ExternalFilePattern);
}
private void save(SequenceBuilder builder, string saveDirectory, Dictionary<string, object> report, string element, int batchNumber)
{
ioHelper.StoreRun(builder, saveDirectory, report, element, batchNumber);
}
private void runPattern(MOTMasterSequence sequence)
{
run(sequence);
if (Controller.genOptions.AIEnabled)
aip.ReadAnalogDataFromBuffer();
if (!StaticSequence) { releaseHardware(); status = RunningState.stopped; }
//else pauseHardware();
}
private void debugRun(MOTMasterSequence sequence)
{
int[] loopTimes = ((DAQ.Pattern.HSDIOPatternBuilder)sequence.DigitalPattern).LoopTimes;
hs.BuildScriptForDebug(sequence.DigitalPattern.Pattern, loopTimes);
}
public static MOTMasterScript prepareScript(string pathToPattern, Dictionary<String, Object> dict)
{
MOTMasterScript script;
CompilerResults results = compileFromFile(pathToPattern);
if (results != null)
{
script = loadScriptFromDLL(results);
if (dict != null)
{
script.EditDictionary(dict);
}
return script;
}
return null;
}
private static void buildPattern(MOTMasterSequence sequence, int patternLength)
{
sequence.DigitalPattern.BuildPattern(patternLength);
sequence.AnalogPattern.BuildPattern();
if (config.UseMuquans) muquans.BuildCommands(sequence.MuquansPattern.commands);
}
#endregion
#region Compiler & Loading DLLs
/// <summary>
/// /// - Once the user has selected a particular implementation of MOTMasterScript,
/// MOTMaster will compile it. Note: the dll is currently stored in a temp folder somewhere.
/// Its pathToPattern can be found in the CompilerResults.PathToAssembly).
/// This newly formed dll contain methods named GetDigitalPattern and GetAnalogPattern.
///
/// - These are called by the script's "GetSequence". GetSequence always returns a
/// "MOTMasterSequence", which comprises a PatternBuilder32 and an AnalogPatternBuilder.