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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.PMR;
using Tango.PMR.Diagnostics;
using Tango.Transport;
using Tango.Transport.Transporters;
using System.Reactive.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Threading;
using Tango.PMR.Common;
using Tango.PMR.Printing;
using System.Reactive.Subjects;
using Tango.PMR.Debugging;
using Tango.Logging;
using Tango.Settings;
using System.IO;
using Tango.BL.Entities;
using Tango.PMR.Hardware;
using Google.Protobuf;
using Tango.PMR.Connection;
using Tango.BL.Enumerations;
using Tango.BL.ColorConversion;
using Tango.PMR.Stubs;
using System.Threading;
namespace Tango.Integration.Operation
{
/// <summary>
/// Represents the Tango machine operator default implementation.
/// </summary>
/// <seealso cref="Tango.Transport.Transporters.BasicTransporter" />
/// <seealso cref="Tango.Integration.Operation.IMachineOperator" />
public class MachineOperator : BasicTransporter, IMachineOperator
{
private bool _diagnosticsSent;
private bool _eventsSent;
private bool _debugSent;
private EmbeddedLogItem _last_embedded_debug_log;
public static String EmbeddedLogsFolder { get; private set; }
public static String EmbeddedLogsTag { get; private set; }
#region Constructors
/// <summary>
/// Initializes the <see cref="MachineOperator"/> class.
/// </summary>
static MachineOperator()
{
if (EmbeddedLogManager == null)
{
EmbeddedLogManager = new LogManager();
EmbeddedLogsTag = "Embedded";
EmbeddedLogsFolder = Path.Combine(Path.GetDirectoryName(SettingsManager.Default.Folder), "Logs", Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.FriendlyName), "Embedded");
Directory.CreateDirectory(EmbeddedLogsFolder);
FileLogger fileLogger = new FileLogger(EmbeddedLogsFolder, EmbeddedLogsTag) { Enabled = true };
EmbeddedLogManager.RegisterLogger(fileLogger);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="MachineOperator"/> class.
/// </summary>
public MachineOperator() : base()
{
DeviceInformation = new DeviceInformation();
MachineEventsStateProvider = new DefaultMachineEventsStateProvider();
EnableEventsNotification = true;
LogEmbeddedDebuggingToFile = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="MachineOperator"/> class.
/// </summary>
/// <param name="adapter">The transport adapter.</param>
public MachineOperator(ITransportAdapter adapter) : this()
{
Adapter = adapter;
}
#endregion
#region Events
/// <summary>
/// Occurs when the machine <see cref="Status" /> has changed.
/// </summary>
public event EventHandler<MachineStatuses> StatusChanged;
/// <summary>
/// Occurs when there is new diagnostics data available.
/// </summary>
public event EventHandler<StartDiagnosticsResponse> DiagnosticsDataAvailable;
/// <summary>
/// Occurs when an events notification has been received from the embedded device.
/// </summary>
public event EventHandler<StartEventsNotificationResponse> EventsNotification;
/// <summary>
/// Occurs when a new debug log is available.
/// </summary>
public event EventHandler<StartDebugLogResponse> DebugLogAvailable;
/// <summary>
/// Occurs when a request has been sent.
/// </summary>
public event EventHandler<IMessage> RequestSent;
/// <summary>
/// Occurs when a response has been sent.
/// </summary>
public event EventHandler<IMessage> ResponseSent;
/// <summary>
/// Occurs when a request has timed out.
/// </summary>
public event EventHandler<RequestFailedEventArgs> RequestFailed;
/// <summary>
/// Occurs when a request response has been received.
/// </summary>
public event EventHandler<IMessage> ResponseReceived;
/// <summary>
/// Occurs when a printing process has started.
/// </summary>
public event EventHandler<PrintingEventArgs> PrintingStarted;
/// <summary>
/// Occurs when a printing process has completed.
/// </summary>
public event EventHandler<PrintingEventArgs> PrintingCompleted;
/// <summary>
/// Occurs when a printing process has failed.
/// </summary>
public event EventHandler<PrintingFailedEventArgs> PrintingFailed;
/// <summary>
/// Occurs when a printing process has been aborted.
/// </summary>
public event EventHandler<PrintingEventArgs> PrintingAborted;
#endregion
#region Properties
/// <summary>
/// Gets or sets the job handling mode.
/// </summary>
public JobHandlerModes JobHandlingMode { get; set; }
private MachineStatuses _status;
/// <summary>
/// Gets the current machine status.
/// </summary>
public MachineStatuses Status
{
get { return _status; }
protected set
{
_status = value;
RaisePropertyChangedAuto();
OnMachineStatusChanged(value);
RaisePropertyChanged(nameof(IsPrinting));
RaisePropertyChanged(nameof(CanPrint));
LogManager.Log("Machine operator status changed: " + _status);
}
}
/// <summary>
/// Gets a value indicating whether this instance is printing.
/// </summary>
public bool IsPrinting
{
get
{
return Status == MachineStatuses.Printing;
}
}
/// <summary>
/// Gets a value indicating whether this instance can print.
/// </summary>
public bool CanPrint
{
get
{
return Status == MachineStatuses.ReadyToDye;
}
}
private Job _runningJob;
/// <summary>
/// Gets the running job.
/// </summary>
public Job RunningJob
{
get { return _runningJob; }
set { _runningJob = value; RaisePropertyChangedAuto(); }
}
private RunningJobStatus _runningJobStatus;
/// <summary>
/// Gets the running job status.
/// </summary>
public RunningJobStatus RunningJobStatus
{
get { return _runningJobStatus; }
set { _runningJobStatus = value; RaisePropertyChangedAuto(); }
}
/// <summary>
/// Gets the embedded device log manager.
/// </summary>
public static LogManager EmbeddedLogManager { get; private set; }
private bool _enableDiagnostics;
/// <summary>
/// Gets or sets a value indicating whether direct the embedded device to send diagnostics messages.
/// </summary>
public bool EnableDiagnostics
{
get { return _enableDiagnostics; }
set
{
if (_enableDiagnostics != value)
{
_enableDiagnostics = value;
RaisePropertyChangedAuto();
OnEnableDiagnosticsChanged(value);
}
}
}
private bool _enableEventsNotification;
/// <summary>
/// Gets or sets a value indicating whether direct the embedded device to send events notification messages.
/// </summary>
public bool EnableEventsNotification
{
get { return _enableEventsNotification; }
set
{
if (_enableEventsNotification != value)
{
_enableEventsNotification = value;
RaisePropertyChangedAuto();
OnEnableEventsNotification(value);
}
}
}
private bool _enableEmbeddedDebugging;
/// <summary>
/// Gets or sets a value indicating whether to allow incoming debugging messages.
/// </summary>
/// <exception cref="System.NotImplementedException">
/// </exception>
public bool EnableEmbeddedDebugging
{
get
{
return _enableEmbeddedDebugging;
}
set
{
if (_enableEmbeddedDebugging != value)
{
_enableEmbeddedDebugging = value;
RaisePropertyChangedAuto();
OnEnableEmbeddedDebuggingChanged(value);
}
}
}
private bool _logEmbeddedDebuggingToFile;
/// <summary>
/// Gets or sets a value indicating whether to automatically save incoming log data from the embedded device.
/// </summary>
public bool LogEmbeddedDebuggingToFile
{
get { return _logEmbeddedDebuggingToFile; }
set
{
_logEmbeddedDebuggingToFile = value; RaisePropertyChangedAuto();
}
}
/// <summary>
/// Gets or sets the machine events state provider used to get notifications about current machine events and errors.
/// </summary>
public IMachineEventsStateProvider MachineEventsStateProvider { get; set; }
/// <summary>
/// Gets the last process parameters table sent to the embedded device.
/// </summary>
public ProcessParametersTable CurrentProcessParameters { get; private set; }
/// <summary>
/// Gets the last hardware configuration sent to the embedded device.
/// </summary>
public HardwareConfiguration CurrentHardwareConfiguration { get; private set; }
private DeviceInformation _deviceInformation;
/// <summary>
/// Gets or sets the embedded device information.
/// </summary>
public DeviceInformation DeviceInformation
{
get { return _deviceInformation; }
set { _deviceInformation = value; RaisePropertyChangedAuto(); }
}
private Machine _machine;
/// <summary>
/// Gets the machine database entity.
/// </summary>
public Machine Machine
{
get { return _machine; }
protected set
{
_machine = value;
RaisePropertyChangedAuto();
}
}
#endregion
#region Virtual Methods
/// <summary>
/// Called when the enable diagnostics property has been changed
/// </summary>
/// <param name="value">if set to <c>true</c> [value].</param>
protected virtual async void OnEnableDiagnosticsChanged(bool value)
{
if (value && State == TransportComponentState.Connected && !_diagnosticsSent)
{
var request = new StartDiagnosticsRequest();
bool responseLogged = false;
_diagnosticsSent = true;
SendContinuousRequest<StartDiagnosticsRequest, StartDiagnosticsResponse>(request).ObserveOn(new NewThreadScheduler()).Subscribe(
(response) =>
{
OnDiagnosticsDataAvailable(response);
if (!responseLogged)
{
LogResponseReceived(response.Message);
responseLogged = true;
}
},
(ex) =>
{
_diagnosticsSent = false;
if (!(ex is ContinuousResponseAbortedException))
{
LogRequestFailed(request, ex);
}
},
() =>
{
_diagnosticsSent = false;
LogManager.Log("Diagnostics response completed!?", LogCategory.Warning);
});
LogRequestSent(request);
}
else if (_diagnosticsSent)
{
_diagnosticsSent = false;
if (State == TransportComponentState.Connected)
{
var req = new StopDiagnosticsRequest();
try
{
LogRequestSent(req);
var res = await SendRequest<StopDiagnosticsRequest, StopDiagnosticsResponse>(req);
LogResponseReceived(res.Message);
}
catch (Exception ex)
{
LogRequestFailed(req, ex);
}
}
}
}
/// <summary>
/// Called when the enable events property has been changed.
/// </summary>
/// <param name="value">if set to <c>true</c> [value].</param>
protected virtual async void OnEnableEventsNotification(bool value)
{
if (value && State == TransportComponentState.Connected && !_eventsSent)
{
var request = new StartEventsNotificationRequest();
bool responseLogged = false;
_eventsSent = true;
SendContinuousRequest<StartEventsNotificationRequest, StartEventsNotificationResponse>(request).ObserveOn(new NewThreadScheduler()).Subscribe(
(response) =>
{
OnEventsNotification(response);
if (!responseLogged)
{
LogResponseReceived(response.Message);
responseLogged = true;
}
},
(ex) =>
{
_eventsSent = false;
if (!(ex is ContinuousResponseAbortedException))
{
LogRequestFailed(request, ex);
}
},
() =>
{
_eventsSent = false;
LogManager.Log("Events Notification response completed!?", LogCategory.Warning);
});
LogRequestSent(request);
}
else if (_eventsSent)
{
_eventsSent = false;
if (State == TransportComponentState.Connected)
{
var req = new StopEventsNotificationRequest();
try
{
LogRequestSent(req);
var res = await SendRequest<StopEventsNotificationRequest, StopEventsNotificationResponse>(req);
LogResponseReceived(res.Message);
}
catch (Exception ex)
{
LogRequestFailed(req, ex);
}
}
}
}
/// <summary>
/// Called when the enable embedded debugging has been changed
/// </summary>
/// <param name="value">if set to <c>true</c> [value].</param>
protected async void OnEnableEmbeddedDebuggingChanged(bool value)
{
if (value && State == TransportComponentState.Connected && !_debugSent)
{
var request = new StartDebugLogRequest();
bool responseLogged = false;
_debugSent = true;
SendContinuousRequest<StartDebugLogRequest, StartDebugLogResponse>(request).ObserveOn(new NewThreadScheduler())
.Subscribe
(
(response) =>
{
if (!responseLogged)
{
LogResponseReceived(response.Message);
responseLogged = true;
}
OnDebugLogAvailable(response);
},
(ex) =>
{
_debugSent = false;
if (!(ex is ContinuousResponseAbortedException))
{
LogRequestFailed(request, ex);
}
},
() =>
{
_debugSent = false;
});
LogRequestSent(request);
}
else if (_debugSent)
{
_debugSent = false;
if (State == TransportComponentState.Connected)
{
var req = new StopDebugLogRequest();
try
{
LogRequestSent(req);
var res = await SendRequest<StopDebugLogRequest, StopDebugLogResponse>(req);
LogResponseReceived(res.Message);
}
catch (Exception ex)
{
LogRequestFailed(req, ex);
}
}
}
}
/// <summary>
/// Invokes the <see cref="DiagnosticsDataAvailable"/> event.
/// </summary>
/// <param name="data">The sensors data.</param>
protected virtual void OnDiagnosticsDataAvailable(StartDiagnosticsResponse data)
{
DiagnosticsDataAvailable?.Invoke(this, data);
}
/// <summary>
/// Called when events notification message has been received.
/// </summary>
/// <param name="response">The response.</param>
protected virtual void OnEventsNotification(StartEventsNotificationResponse response)
{
if (MachineEventsStateProvider != null)
{
MachineEventsStateProvider.ApplyEvents(response.Events);
}
EventsNotification?.Invoke(this, response);
}
/// <summary>
/// Invokes the <see cref="DebugLogAvailable"/> event.
/// </summary>
/// <param name="data">The sensors data.</param>
protected virtual void OnDebugLogAvailable(StartDebugLogResponse data)
{
if (_last_embedded_debug_log == null || _last_embedded_debug_log.DebugLogResponse.Message != data.Message)
{
_last_embedded_debug_log = new EmbeddedLogItem(data);
if (LogEmbeddedDebuggingToFile && EmbeddedLogManager != null)
{
EmbeddedLogManager.Log(_last_embedded_debug_log);
}
DebugLogAvailable?.Invoke(this, data);
}
else
{
_last_embedded_debug_log.Repeated++;
}
}
/// <summary>
/// Called when the request has been sent
/// </summary>
/// <param name="response">The request.</param>
protected virtual void OnRequestSent(IMessage request)
{
RequestSent?.Invoke(this, request);
}
/// <summary>
/// Called when the response has been received
/// </summary>
/// <param name="response">The response.</param>
protected virtual void OnResponseReceived(IMessage response)
{
ResponseReceived?.Invoke(this, response);
}
/// <summary>
/// Called when the response has been sent
/// </summary>
/// <param name="response">The response.</param>
protected virtual void OnResponseSent(IMessage response)
{
ResponseSent?.Invoke(this, response);
}
/// <summary>
/// Called when the request has been failed
/// </summary>
/// <param name="request">The request.</param>
protected virtual void OnRequestFailed(IMessage request, Exception exception)
{
RequestFailed?.Invoke(this, new RequestFailedEventArgs(request, exception));
}
/// <summary>
/// Called when the machine status has been changed
/// </summary>
/// <param name="status">The status.</param>
protected virtual void OnMachineStatusChanged(MachineStatuses status)
{
StatusChanged?.Invoke(this, status);
}
#endregion
#region Override Methods
/// <summary>
/// Called when the component state has changed.
/// </summary>
/// <param name="state">The state.</param>
protected override void OnStateChanged(TransportComponentState state)
{
base.OnStateChanged(state);
if (state != TransportComponentState.Connected)
{
_diagnosticsSent = false;
_debugSent = false;
}
}
/// <summary>
/// Disconnects the machine operator and the underlying transporter.
/// </summary>
/// <returns></returns>
public async override Task Disconnect()
{
if (State == TransportComponentState.Connected)
{
DisconnectRequest request = new DisconnectRequest();
LogRequestSent(request);
try
{
var response = await SendRequest<DisconnectRequest, DisconnectResponse>(request);
LogResponseReceived(response.Message);
Status = MachineStatuses.Standby;
}
catch (Exception ex)
{
LogRequestFailed(request, ex);
}
}
await base.Disconnect();
}
/// <summary>
/// Connects the transport component.
/// </summary>
/// <returns></returns>
public async override Task Connect()
{
await base.Connect();
if (State == TransportComponentState.Connected)
{
ConnectRequest request = new ConnectRequest() { Password = "1234" };
LogRequestSent(request);
try
{
var response = await SendRequest<ConnectRequest, ConnectResponse>(request);
LogResponseReceived(response.Message);
Status = MachineStatuses.ReadyToDye;
DeviceInformation = response.Message.DeviceInformation;
OnEnableDiagnosticsChanged(EnableDiagnostics);
OnEnableEmbeddedDebuggingChanged(EnableEmbeddedDebugging);
OnEnableEventsNotification(EnableEventsNotification);
}
catch (Exception ex)
{
LogRequestFailed(request, ex);
await base.Disconnect();
throw ex;
}
}
}
#endregion
#region Public Methods
/// <summary>
/// Prints the specified job.
/// The process parameters table will be calculated using color conversion gamut region.
/// This method cannot accept brush stops with 'Volume' as color space.
/// </summary>
/// <param name="job">The job.</param>
/// <returns></returns>
public JobHandler Print(Job job)
{
//Check not brush stop has color space 'Volume'.
if (job.Segments.SelectMany(x => x.BrushStops).ToList().Exists(x => x.ColorSpace.Code == ColorSpaces.Volume.ToInt32()))
{
throw new InvalidOperationException("Cannot print a brush stop with volume color space when process parameters table has not been specified.");
}
//Get least common process parameters table index.
int processParametersTableIndex = TangoColorConverter.GetLeastCommonProcessParametersTableIndex(job.Segments.SelectMany(x => x.BrushStops));
if (job.Rml == null)
{
throw new NullReferenceException("Job RML is null");
}
var processGroup = job.Rml.ProcessParametersTablesGroups.FirstOrDefault(x => x.Active);
if (processGroup == null)
{
throw new NullReferenceException("Could not locate an active process parameters tables group for RML " + job.Rml.Name);
}
var processParameters = processGroup.ProcessParametersTables.FirstOrDefault(x => x.TableIndex == processParametersTableIndex);
if (processParameters == null)
{
throw new NullReferenceException("Could not locate process parameters table index " + processParametersTableIndex + " in group " + processGroup.Name + " for RML " + job.Rml.Name);
}
//Perform color correction
foreach (var stop in job.Segments.SelectMany(x => x.BrushStops))
{
if (stop.LiquidVolumes == null)
{
var output = TangoColorConverter.GetSuggestions(stop);
//TODO: Restore this when Mirta conversion is working as expected.
//if (suggestions.OutOfGamut)
//{
// throw new InvalidOperationException("Cannot print a brush stop which is out of gamut.");
//}
stop.SetLiquidVolumes(job.Machine.Configuration, job.Rml, processParameters);
foreach (var outputLiquid in output.SingleCoordinates.OutputLiquids)
{
var liquidVolume = stop.LiquidVolumes.SingleOrDefault(x => x.IdsPack.LiquidType.Code == outputLiquid.LiquidType.ToInt32());
if (liquidVolume == null)
{
throw new NullReferenceException("Liquid volume not found for color conversion output liquid '" + outputLiquid.LiquidType + "'.");
}
liquidVolume.Volume = outputLiquid.Volume;
}
}
}
return Print(job, processParameters);
}
/// <summary>
/// Prints the specified job using the specified job parameters.
/// </summary>
/// <param name="job">The job.</param>
/// <param name="processParameters">Process parameters table</param>
/// <returns></returns>
public JobHandler Print(Job job, ProcessParametersTable processParameters)
{
if (Status != MachineStatuses.ReadyToDye)
{
throw new InvalidOperationException("Could not print while status = " + Status);
}
RunningJob = null;
RunningJobStatus = null;
var originalJob = job;
CurrentProcessParameters = processParameters;
JobRequest request = new JobRequest();
if (job.NumberOfUnits < 1)
{
job.NumberOfUnits = 1;
}
job = job.Clone();
var segments = job.Segments.ToList();
for (int i = 0; i < job.NumberOfUnits - 1; i++)
{
foreach (var s in segments)
{
job.Segments.Add(s);
}
}
JobTicket ticket = new JobTicket();
ticket.EnableInterSegment = job.EnableInterSegment;
ticket.InterSegmentLength = job.InterSegmentLength;
ticket.Length = job.Length;
ticket.WindingMethod = (JobWindingMethod)job.WindingMethod.Code;
ticket.Spool = new JobSpool();
job.SpoolType.MapPrimitivesTo(ticket.Spool);
ticket.Spool.JobSpoolType = (JobSpoolType)job.SpoolType.Code;
ProcessParameters process = new ProcessParameters();
processParameters.MapPrimitivesTo(process);
ticket.ProcessParameters = process;
foreach (var segment in job.Segments)
{
JobSegment jobSegment = new JobSegment();
jobSegment.Length = segment.LengthWithFactor;
jobSegment.Name = segment.Name;
foreach (var stop in segment.BrushStops)
{
JobBrushStop jobStop = new JobBrushStop();
jobStop.Index = stop.StopIndex;
jobStop.OffsetPercent = stop.OffsetPercent;
jobStop.OffsetMeters = stop.OffsetMeters;
if (stop.LiquidVolumes == null)
{
stop.SetLiquidVolumes(job.Machine.Configuration, job.Rml, processParameters);
}
foreach (var liquidVolume in stop.LiquidVolumes)
{
JobDispenser dispenser = new JobDispenser();
dispenser.Index = liquidVolume.IdsPack.PackIndex;
dispenser.Volume = liquidVolume.Volume;
dispenser.DispenserLiquidType = (DispenserLiquidType)liquidVolume.IdsPack.LiquidType.Code;
dispenser.DispenserStepDivision = (DispenserStepDivision)liquidVolume.DispenserStepDivision;
dispenser.NanoliterPerPulse = liquidVolume.IdsPack.DispenserType.NlPerPulse;
dispenser.LiquidMaxNanoliterPerCentimeter = liquidVolume.LiquidMaxNanoliterPerCentimeter;
dispenser.NanoliterPerCentimeter = liquidVolume.NanoliterPerCentimeter;
dispenser.NanolitterPerSecond = liquidVolume.NanoliterPerSecond;
dispenser.PulsePerSecond = liquidVolume.PulsePerSecond;
jobStop.Dispensers.Add(dispenser);
}
jobSegment.BrushStops.Add(jobStop);
}
ticket.Segments.Add(jobSegment);
}
request.JobTicket = ticket;
JobHandler handler = null;
handler = new JobHandler(async () =>
{
try
{
var result = await SendRequest<AbortJobRequest, AbortJobResponse>(new AbortJobRequest());
PrintingAborted?.Invoke(this, new PrintingEventArgs(handler, originalJob));
handler.RaiseCanceled();
}
catch (Exception ex)
{
LogManager.Log(ex, "Failed to cancel job.");
}
}, originalJob, processParameters, JobHandlingMode);
handler.StatusChanged += (x, s) =>
{
RunningJobStatus = s;
};
LogRequestSent(request);
bool responseLogged = false;
SendContinuousRequest<JobRequest, JobResponse>(request, null, TimeSpan.FromSeconds(2)).Subscribe((response) =>
{
handler.RaiseStatusReceived(response.Message.Status);
if (!responseLogged)
{
responseLogged = true;
Status = MachineStatuses.Printing;
RunningJob = originalJob;
PrintingStarted?.Invoke(this, new PrintingEventArgs(handler, originalJob));
LogResponseReceived(response.Message);
}
}, (ex) =>
{
if (!(ex is ContinuousResponseAbortedException))
{
Status = MachineStatuses.ReadyToDye;
if (!handler.IsCanceled)
{
PrintingFailed?.Invoke(this, new PrintingFailedEventArgs(handler, originalJob, ex));
handler.RaiseFailed(ex);
LogRequestFailed(request, ex);
}
}
else
{
Status = MachineStatuses.ReadyToDye;
}
}, () =>
{
Status = MachineStatuses.ReadyToDye;
PrintingCompleted?.Invoke(this, new PrintingEventArgs(handler, originalJob));
handler.RaiseCompleted();
});
return handler;
}
/// <summary>
/// Uploads the specified process parameters to the embedded device.
/// </summary>
/// <param name="processParameters">The process parameters.</param>
/// <returns></returns>
public async Task<UploadProcessParametersResponse> UploadProcessParameters(ProcessParametersTable processParameters)
{
UploadProcessParametersRequest request = new UploadProcessParametersRequest();
request.ProcessParameters = new ProcessParameters();
processParameters.MapPrimitivesTo(request.ProcessParameters);
UploadProcessParametersResponse response = null;
try
{
CurrentProcessParameters = processParameters;
LogRequestSent(request);
response = await SendRequest<UploadProcessParametersRequest, UploadProcessParametersResponse>(request);
LogResponseReceived(response);
}
catch (Exception ex)
{
LogRequestFailed(request, ex);
throw ex;
}
return response;
}
/// <summary>
/// Uploads the specified hardware configuration to the embedded device.
/// </summary>
/// <param name="hardwareVersion">Machine version.</param>
/// <param name="configuration">Machine configuration.</param>
/// <returns></returns>
public async Task<UploadHardwareConfigurationResponse> UploadHardwareConfiguration(HardwareVersion hardwareVersion, Configuration configuration)
{
HardwareConfiguration hardwareConfiguration = new HardwareConfiguration();
foreach (var dancer in hardwareVersion.HardwareDancers)
{
PMR.Hardware.HardwareDancer item = new PMR.Hardware.HardwareDancer();
dancer.MapPrimitivesTo(item);
item.HardwareDancerType = (PMR.Hardware.HardwareDancerType)dancer.HardwareDancerType.Code;
hardwareConfiguration.Dancers.Add(item);
}
foreach (var motor in hardwareVersion.HardwareMotors)
{
PMR.Hardware.HardwareMotor item = new PMR.Hardware.HardwareMotor();
motor.MapPrimitivesTo(item);
item.HardwareMotorType = (PMR.Hardware.HardwareMotorType)motor.HardwareMotorType.Code;
hardwareConfiguration.Motors.Add(item);
}
foreach (var pid in hardwareVersion.HardwarePidControls)
{
PMR.Hardware.HardwarePidControl item = new PMR.Hardware.HardwarePidControl();
pid.MapPrimitivesTo(item);
item.HardwarePidControlType = (PMR.Hardware.HardwarePidControlType)pid.HardwarePidControlType.Code;
hardwareConfiguration.PidControls.Add(item);
}
foreach (var winder in hardwareVersion.HardwareWinders)
{
PMR.Hardware.HardwareWinder item = new PMR.Hardware.HardwareWinder();
winder.MapPrimitivesTo(item);
item.HardwareWinderType = (PMR.Hardware.HardwareWinderType)winder.HardwareWinderType.Code;
hardwareConfiguration.Winders.Add(item);
}
foreach (var sensor in hardwareVersion.HardwareSpeedSensors)
{
PMR.Hardware.HardwareSpeedSensor item = new PMR.Hardware.HardwareSpeedSensor();
sensor.MapPrimitivesTo(item);
item.HardwareSpeedSensorType = (PMR.Hardware.HardwareSpeedSensorType)sensor.HardwareSpeedSensorType.Code;
hardwareConfiguration.SpeedSensors.Add(item);
}
foreach (var blower in hardwareVersion.HardwareBlowers)
{
PMR.Hardware.HardwareBlower item = new PMR.Hardware.HardwareBlower();
blower.MapPrimitivesTo(item);
item.HardwareBlowerType = (PMR.Hardware.HardwareBlowerType)blower.HardwareBlowerType.Code;
hardwareConfiguration.Blowers.Add(item);
}
foreach (var breakSensor in hardwareVersion.HardwareBreakSensors)
{
PMR.Hardware.HardwareBreakSensor item = new PMR.Hardware.HardwareBreakSensor();
breakSensor.MapPrimitivesTo(item);
item.HardwareBreakSensorType = (PMR.Hardware.HardwareBreakSensorType)breakSensor.HardwareBreakSensorType.Code;
hardwareConfiguration.BreakSensors.Add(item);
}
foreach (var idsPack in configuration.NoneEmptyIdsPacks.OrderBy(x => x.PackIndex))
{
PMR.Hardware.HardwareDispenser item = new PMR.Hardware.HardwareDispenser();
idsPack.DispenserType.MapPrimitivesTo(item);
item.HardwareDispenserType = (PMR.Hardware.HardwareDispenserType)idsPack.DispenserType.Code;
item.Index = idsPack.PackIndex;
hardwareConfiguration.Dispensers.Add(item);
}
UploadHardwareConfigurationRequest request = new UploadHardwareConfigurationRequest();
request.HardwareConfiguration = hardwareConfiguration;
UploadHardwareConfigurationResponse response = null;
try
{
CurrentHardwareConfiguration = hardwareConfiguration;
LogRequestSent(request);
response = await SendRequest<UploadHardwareConfigurationRequest, UploadHardwareConfigurationResponse>(request);
LogResponseReceived(response);
}
catch (Exception ex)
{
LogRequestFailed(request, ex);
throw ex;
}
return response;
}
/// <summary>
/// Starts jogging the specified motor.
/// </summary>
/// <param name="request">The request.</param>
/// <returns></returns>
public async Task<MotorJoggingResponse> StartMotorJogging(MotorJoggingRequest request)
{
MotorJoggingResponse response = null;
try
{
LogRequestSent(request);
response = await SendRequest<MotorJoggingRequest, MotorJoggingResponse>(request);
LogResponseReceived(response);
}
catch (Exception ex)
{
LogRequestFailed(request, ex);
throw ex;
}
return response;
}
/// <summary>
/// Stops jogging the specified motor.
/// </summary>
/// <param name="request">The request.</param>
/// <returns></returns>
public async Task<MotorAbortJoggingResponse> StopMotorJogging(MotorAbortJoggingRequest request)
{
LogRequestSent(request);
return await SendRequest<MotorAbortJoggingRequest, MotorAbortJoggingResponse>(request);
}
/// <summary>
/// Starts homing the specified motor.
/// </summary>
/// <param name="request">The request.</param>
/// <returns></returns>
public IObservable<MotorHomingResponse> StartMotorHoming(MotorHomingRequest request)
{
LogRequestSent(request);
return SendContinuousRequest<MotorHomingRequest, MotorHomingResponse>(request).Select(x => x.Message);
}
/// <summary>
/// Stops homing the specified motor.
/// </summary>
/// <param name="request">The request.</param>
/// <returns></returns>
public async Task<MotorAbortHomingResponse> StopMotorHoming(MotorAbortHomingRequest request)
{
LogRequestSent(request);
return await SendRequest<MotorAbortHomingRequest, MotorAbortHomingResponse>(request);
}
/// <summary>
/// Starts jogging the specified dispenser.
/// </summary>
/// <param name="request">The request.</param>
/// <returns></returns>
public async Task<DispenserJoggingResponse> StartDispenserJogging(DispenserJoggingRequest request)
{
LogRequestSent(request);
return await SendRequest<DispenserJoggingRequest, DispenserJoggingResponse>(request);
}
/// <summary>
/// Stops jogging the specified dispenser.
/// </summary>
/// <param name="request">The request.</param>
/// <returns></returns>
public async Task<DispenserAbortJoggingResponse> StopDispenserJogging(DispenserAbortJoggingRequest request)
{
LogRequestSent(request);
return await SendRequest<DispenserAbortJoggingRequest, DispenserAbortJoggingResponse>(request);
}
/// <summary>
/// Starts homing the specified dispenser.
/// </summary>
/// <param name="request">The request.</param>
/// <returns></returns>
public IObservable<DispenserHomingResponse> StartDispenserHoming(DispenserHomingRequest request)
{
LogRequestSent(request);
return SendContinuousRequest<DispenserHomingRequest, DispenserHomingResponse>(request).Select(x => x.Message);
}
/// <summary>
/// Stops homing the specified dispenser.
/// </summary>
/// <param name="request">The request.</param>
/// <returns></returns>
public async Task<DispenserAbortHomingResponse> StopDispenserHoming(DispenserAbortHomingRequest request)
{
LogRequestSent(request);
return await SendRequest<DispenserAbortHomingRequest, DispenserAbortHomingResponse>(request);
}
/// <summary>
/// Turn on/off the specified digital output pin.
/// </summary>
/// <param name="request">The request.</param>
/// <returns></returns>
public async Task<SetDigitalOutResponse> SetDigitalOut(SetDigitalOutRequest request)
{
LogRequestSent(request);
return await SendRequest<SetDigitalOutRequest, SetDigitalOutResponse>(request);
}
/// <summary>
/// Starts jogging the thread motion system.
/// </summary>
/// <param name="request">The request.</param>
/// <returns></returns>
public async Task<ThreadJoggingResponse> StartThreadJogging(ThreadJoggingRequest request)
{
LogRequestSent(request);
return await SendRequest<ThreadJoggingRequest, ThreadJoggingResponse>(request);
}
/// <summary>
/// Stops jogging the thread motion system.
/// </summary>
/// <param name="request">The request.</param>
/// <returns></returns>
public async Task<ThreadAbortJoggingResponse> StopThreadJogging(ThreadAbortJoggingRequest request)
{
LogRequestSent(request);
return await SendRequest<ThreadAbortJoggingRequest, ThreadAbortJoggingResponse>(request);
}
/// <summary>
/// Sets the specified component value.
/// </summary>
/// <param name="request">The request.</param>
/// <returns></returns>
public async Task<SetComponentValueResponse> SetComponentValue(SetComponentValueRequest request)
{
LogRequestSent(request);
return await SendRequest<SetComponentValueRequest, SetComponentValueResponse>(request);
}
/// <summary>
/// Resolves the specified event type.
/// </summary>
/// <param name="eventType">Type of the event.</param>
/// <returns></returns>
public async Task<ResolveEventResponse> ResolveEvent(PMR.Diagnostics.EventType eventType)
{
ResolveEventRequest request = new ResolveEventRequest() { Type = eventType };
LogRequestSent(request);
return await SendRequest<ResolveEventRequest, ResolveEventResponse>(request);
}
/// <summary>
/// Resets the embedded device.
/// </summary>
/// <returns></returns>
public async Task<StubFpgaWriteRegResponse> Reset()
{
StubFpgaWriteRegResponse response = null;
StubFpgaWriteRegRequest request = null;
try
{
request = new StubFpgaWriteRegRequest()
{
Address = 0x60000800 | 0x3D0,
Value = 0x0
};
LogRequestSent(request);
response = await SendRequest<StubFpgaWriteRegRequest, StubFpgaWriteRegResponse>(request);
LogResponseReceived(response);
}
catch (Exception ex)
{
LogRequestFailed(request, ex);
throw ex;
}
Thread.Sleep(1000);
try
{
request = new StubFpgaWriteRegRequest()
{
Address = 0x60000800 | 0x3D0,
Value = 0x1
};
LogRequestSent(request);
response = await SendRequest<StubFpgaWriteRegRequest, StubFpgaWriteRegResponse>(request);
LogResponseReceived(response);
}
catch (Exception ex)
{
LogRequestFailed(request, ex);
throw ex;
}
return response;
}
#endregion
#region Private Methods
/// <summary>
/// Logs the request sent.
/// </summary>
/// <param name="message">The message.</param>
protected void LogRequestSent(IMessage message)
{
LogManager.Log(String.Format("Sending request '{0}'...{1}{2}", message.GetType().Name, Environment.NewLine, message.ToJsonString()));
OnRequestSent(message);
}
/// <summary>
/// Logs the request failed.
/// </summary>
/// <param name="message">The message.</param>
protected void LogRequestFailed(IMessage message, Exception ex)
{
LogManager.Log(String.Format("Request failed '{0}'...{1}{2}{1}{3}", message.GetType().Name, Environment.NewLine, message.ToJsonString(), ex.ToString()), LogCategory.Error);
OnRequestFailed(message, ex);
}
/// <summary>
/// Logs the response received.
/// </summary>
/// <param name="message">The message.</param>
protected void LogResponseReceived(IMessage message)
{
LogManager.Log(String.Format("Response received '{0}'...{1}{2}", message.GetType().Name, Environment.NewLine, message.ToJsonString()));
OnResponseReceived(message);
}
#endregion
}
}
|