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
831using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Tango.BL;
using Tango.Core;
using Tango.Core.Commands;
using Tango.Core.ExtensionMethods;
using Tango.Core.Helpers;
using Tango.Core.Threading;
using Tango.Explorer;
using Tango.Integration.ExternalBridge;
using Tango.PMR.FirmwareUpgrade;
using Tango.PPC.Common;
using Tango.PPC.Common.Application;
using Tango.PPC.Common.ExternalBridge;
using Tango.PPC.Common.MachineUpdate;
using Tango.PPC.Common.Navigation;
using Tango.PPC.Common.Notifications;
using Tango.PPC.Common.Publish;
using Tango.PPC.Common.Web;
using Tango.PPC.Shared.RemoteUpgrade;
using Tango.PPC.UI.Dialogs;
using Tango.PPC.UI.Notifications.NotificationItems;
using Tango.PPC.UI.ViewsContracts;
using Tango.Transport;
namespace Tango.PPC.UI.ViewModels
{
public class MachineUpdateViewVM : PPCViewModel<IMachineUpdateView>, IExternalBridgeRequestHandler
{
public enum MachineUpdateView
{
UpdateCheckView,
UpdateCheckErrorView,
UpdateAvailableView,
UpToDateView,
UpdateProgressView,
UpdateDbProgressView,
UpdateCompletedView,
UpdateFailedView,
UpdateFromPackageView,
UpdateFailedFromPackageView,
}
private MachineUpdateResult _update_result;
private DbCompareResult _db_compare_result;
private bool _isChecking;
private CheckForUpdateResponse _checkUpdateResponse;
private UpdateAvailableNotificationItem _updateNotificationItem;
#region Properties
/// <summary>
/// Gets or sets the machine update manager.
/// </summary>
public IMachineUpdateManager MachineUpdateManager { get; set; }
private String _latestVersion;
/// <summary>
/// Gets or sets the latest version.
/// </summary>
public String LatestVersion
{
get { return _latestVersion; }
set { _latestVersion = value; RaisePropertyChangedAuto(); }
}
private bool _isDbUpdate;
/// <summary>
/// Gets or sets a value indicating whether this instance is database update.
/// </summary>
public bool IsDbUpdate
{
get { return _isDbUpdate; }
set { _isDbUpdate = value; RaisePropertyChangedAuto(); }
}
private String _failedError;
/// <summary>
/// Gets or sets the setup failed error.
/// </summary>
public String FailedError
{
get { return _failedError; }
set { _failedError = value; RaisePropertyChangedAuto(); }
}
#endregion
#region Commands
/// <summary>
/// Gets or sets the complete command.
/// </summary>
public RelayCommand CompleteCommand { get; set; }
/// <summary>
/// Gets or sets the install command.
/// </summary>
public RelayCommand UpdateCommand { get; set; }
/// <summary>
/// Gets or sets the restart command.
/// </summary>
public RelayCommand RestartCommand { get; set; }
/// <summary>
/// Gets or sets the close command.
/// </summary>
public RelayCommand CloseCommand { get; set; }
/// <summary>
/// Gets or sets to application command.
/// </summary>
public RelayCommand ToApplicationCommand { get; set; }
#endregion
#region Constructors
public MachineUpdateViewVM(IMachineUpdateManager machineUpdateManager, IPPCExternalBridgeService externalBridge, IPPCApplicationManager applicationManager, INavigationManager navigationManager, INotificationProvider notificationProvider)
{
MachineUpdateManager = machineUpdateManager;
externalBridge.RegisterRequestHandler(this);
CompleteCommand = new RelayCommand(CompleteUpdate);
UpdateCommand = new RelayCommand(Update);
RestartCommand = new RelayCommand(CheckForUpdates);
CloseCommand = new RelayCommand(() =>
{
NavigationManager.NavigateTo(Common.Navigation.NavigationView.HomeModule);
NavigateTo(MachineUpdateView.UpdateCheckView);
});
ToApplicationCommand = new RelayCommand(() =>
{
NavigationManager.NavigateTo(Common.Navigation.NavigationView.HomeModule);
NavigateTo(MachineUpdateView.UpdateCheckView);
});
machineUpdateManager.UpdateAvailable += MachineUpdateManager_UpdateAvailable;
NavigationManager = navigationManager;
NotificationProvider = notificationProvider;
ApplicationManager = applicationManager;
ApplicationManager.UpdaterFailed += ApplicationManager_UpdaterFailed;
}
#endregion
#region Update
public async void CheckForUpdates()
{
await NavigateTo(MachineUpdateView.UpdateCheckView);
if (_isChecking) return;
try
{
_isChecking = true;
IsDbUpdate = false;
await Task.Delay(2000);
if (!await ConnectivityProvider.CheckInternetConnection())
{
_isChecking = false;
await NavigateTo(MachineUpdateView.UpdateCheckErrorView);
return;
}
var response = await MachineUpdateManager.CheckForUpdate();
try
{
if (response.UsedNotExistingRmlsGuids.Count > 0)
{
using (ObservablesContext db = ObservablesContext.CreateDefault())
{
var arr = response.UsedNotExistingRmlsGuids.ToArray();
var jobs = await db.Jobs.Where(x => arr.Contains(x.RmlGuid)).ToListAsync();
FailedError = $"The following jobs must be removed or change thread type before the system can be updated:\n{String.Join("\n", jobs.Select(x => x.Name))}";
_isChecking = false;
await NavigateTo(MachineUpdateView.UpdateFailedView);
return;
}
}
}
catch (Exception ex)
{
LogManager.Log(ex, "Error on used RML check procedure.");
}
_checkUpdateResponse = response;
if (response.IsUpdateAvailable)
{
LatestVersion = response.Version;
await NavigateTo(MachineUpdateView.UpdateAvailableView);
}
else if (response.IsDatabaseUpdateAvailable)
{
IsDbUpdate = true;
_db_compare_result = new DbCompareResult()
{
RequiresUpdate = true,
UpdateDBResponse = response.UpdateDBResponse
};
await NavigateTo(MachineUpdateView.UpdateAvailableView);
}
else
{
_db_compare_result = await MachineUpdateManager.UpdateDBCheck();
if (_db_compare_result.RequiresUpdate)
{
IsDbUpdate = true;
await NavigateTo(MachineUpdateView.UpdateAvailableView);
}
else
{
await NavigateTo(MachineUpdateView.UpToDateView);
}
}
}
catch (Exception ex)
{
FailedError = ex.FlattenMessage();
LogManager.Log(ex, "Error while trying to check for updates.");
await NavigateTo(MachineUpdateView.UpdateFailedView);
}
finally
{
_isChecking = false;
}
}
private async void Update()
{
if (!IsDbUpdate)
{
await NavigateTo(MachineUpdateView.UpdateProgressView);
LogManager.Log("Starting machine update...");
try
{
_update_result = await MachineUpdateManager.Update(_checkUpdateResponse.SetupFirmware, _checkUpdateResponse.SetupFPGA);
LogManager.Log("Machine update completed.");
await NavigateTo(MachineUpdateView.UpdateCompletedView);
}
catch (Exception ex)
{
FailedError = ex.FlattenMessage();
LogManager.Log(ex, "Machine update failed.");
await NavigateTo(MachineUpdateView.UpdateFailedView);
}
}
else
{
await NavigateTo(MachineUpdateView.UpdateDbProgressView);
LogManager.Log("Starting database update...");
try
{
await MachineUpdateManager.UpdateDB(_db_compare_result);
LogManager.Log("Database update completed.");
await NavigateTo(MachineUpdateView.UpdateCompletedView);
}
catch (Exception ex)
{
FailedError = ex.FlattenMessage();
LogManager.Log(ex, "Database update failed.");
await NavigateTo(MachineUpdateView.UpdateFailedView);
}
}
}
#endregion
#region Complete
private void CompleteUpdate()
{
LogManager.Log("Completing machine update...");
if (IsDbUpdate || !_update_result.RequiresBinariesUpdate)
{
LogManager.Log("Restarting Application...");
ApplicationManager.Restart();
}
else
{
String updater_exe = Path.Combine(_update_result.UpdatePackagePath, "Tango.PPC.Updater.exe");
ApplicationManager.UpdateApplication(updater_exe, PathHelper.GetStartupPath());
}
}
#endregion
#region Override Methods
/// <summary>
/// Called when the application has been started.
/// </summary>
public override void OnApplicationStarted()
{
}
/// <summary>
/// Navigates to the specified view.
/// </summary>
/// <param name="view">The view.</param>
private Task NavigateTo(MachineUpdateView view)
{
return View.NavigateTo(view);
}
/// <summary>
/// Called when the application is ready and all modules views are loaded.
/// </summary>
public override void OnApplicationReady()
{
base.OnApplicationReady();
StorageProvider.RegisterFileHandler(ExplorerFileDefinition.Update.Extension, HandleSoftwareUpdatePackageLoaded);
StorageProvider.RegisterFileHandler(ExplorerFileDefinition.Firmware.Extension, HandleFirmwareUpgradeLoaded);
if (ApplicationManager.IsAfterUpdate)
{
RunPostUpdatePackages();
}
else
{
MachineUpdateManager.EnableAutoCheckForUpdates = true;
}
}
/// <summary>
/// Called when the navigation system has navigated to this VM view.
/// </summary>
public override void OnNavigatedTo()
{
base.OnNavigatedTo();
if (_updateNotificationItem != null)
{
_updateNotificationItem.Close();
_updateNotificationItem = null;
}
}
#endregion
#region Post Update Packages
private async void RunPostUpdatePackages()
{
await Task.Delay(1000);
LogManager.Log("Application was loaded after an update. Checking for required post-update packages...");
bool required = false;
try
{
required = await MachineUpdateManager.PostUpdatePackagesRequired();
}
catch (Exception ex)
{
LogManager.Log(ex, "Error checking for post-update packages.");
}
if (required)
{
LogManager.Log("Post-update packages found and needs to be installed. Navigating to machine update and running post-update packages...");
await NavigationManager.NavigateTo(Common.Navigation.NavigationView.MachineUpdateView);
await NavigateTo(MachineUpdateView.UpdateProgressView);
try
{
var result = await MachineUpdateManager.RunPostUpdatePackages();
LogManager.Log("Post-update packages installed successfully.");
await Task.Delay(2000);
if (result.RestartRequired)
{
LogManager.Log("Restart required. Restarting...");
ApplicationManager.Restart();
}
else
{
await NavigationManager.NavigateTo(Common.Navigation.NavigationView.LayoutView);
}
}
catch (Exception ex)
{
LogManager.Log(ex, "Error occurred while running post-update packages.");
}
}
else
{
LogManager.Log("No post-update packages installation required.");
}
}
#endregion
#region Handle USB Update
private async void HandleSoftwareUpdatePackageLoaded(List<ExplorerFileItem> fileItems)
{
var fileItem = fileItems.FirstOrDefault();
if (fileItem == null) return;
PublishInfo packageFile = null;
LogManager.Log("TUP file loaded from storage...");
try
{
packageFile = await MachineUpdateManager.GetUpdatePackageFileInfo(fileItem.Path);
}
catch (Exception ex)
{pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */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.PMR.Stubs;
using System.Threading;
using Tango.Integration.Storage;
using Ionic.Zip;
using Tango.Core.Threading;
using Tango.PMR.IO;
using Tango.Integration.Upgrade;
using Tango.PMR.FirmwareUpgrade;
using Tango.Integration.Logging;
using Tango.Integration.JobRuns;
using Tango.FirmwareUpdateLib.WPF;
using Tango.FirmwareUpdateLib;
using Tango.Core.ExtensionMethods;
using Tango.ColorConversion;
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
{
public const String FIRMWARE_UPGRADE_FOLDER_NAME = "UpgradePackage";
public const String FIRMWARE_UPGRADE_CONFIG_FILE_NAME = "package.cfg";
public const String JOB_DESCRIPTION_FILE_NAME = "job_segments.jdf";
private bool _diagnosticsSent;
private bool _eventsSent;
private bool _debugSent;
private EmbeddedLogItem _last_embedded_debug_log;
private static RunningJobStatus _last_job_status;
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();
JobRunsLogger = new BasicJobRunsLogger(this);
JobRunsLogger.Start();
EnableEventsNotification = true;
EnableJobResume = true;
LogEmbeddedDebuggingToFile = true;
FirmwareUpgradeMode = FirmwareUpgradeModes.DFU | FirmwareUpgradeModes.TFP_PACKAGE;
GradientGenerationConfiguration = new DefaultGradientGenerationConfiguration();
}
/// <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>
/// Reports about the job printing preparation progress.
/// </summary>
public event EventHandler<PreparingJobProgressEventArgs> PreparingJobProgress;
/// <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;
/// <summary>
/// Occurs when a printing process has ended.
/// </summary>
public event EventHandler<PrintingEventArgs> PrintingEnded;
/// <summary>
/// Occurs when the machine operator has detected that a job is in progress after connecting to the machine.
/// </summary>
public event EventHandler<ResumingJobEventArgs> ResumingJob;
#endregion
#region Properties
/// <summary>
/// Gets or sets the job handling mode.
/// </summary>
public JobHandlerModes JobHandlingMode { get; set; }
/// <summary>
/// Gets or sets the job upload strategy.
/// </summary>
public JobUploadStrategy JobUploadStrategy { get; set; }
private MachineStatuses _status;
/// <summary>
/// Gets the current machine status.
/// </summary>
public MachineStatuses Status
{
get { return _status; }
protected set
{
if (_status != value)
{
_status = value;
RaisePropertyChangedAuto();
OnMachineStatusChanged(value);
RaisePropertyChanged(nameof(IsPrinting));
RaisePropertyChanged(nameof(CanPrint));
LogManager.Log("Machine operator status changed: " + _status);
}
}
}
/// <summary>
/// Gets or sets the firmware upgrade mode.
/// </summary>
public FirmwareUpgradeModes FirmwareUpgradeMode { get; set; }
/// <summary>
/// Gets a value indicating whether this instance is printing.
/// </summary>
public bool IsPrinting
{
get
{
return Status == MachineStatuses.Printing || Status == MachineStatuses.GettingReady;
}
}
/// <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 _enableJobResume;
/// <summary>
/// Gets or sets a value indicating whether to check whether a job is in progress after connection was successful.
/// </summary>
public bool EnableJobResume
{
get
{
return _enableJobResume;
}
set
{
_enableJobResume = value; RaisePropertyChangedAuto();
}
}
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 or sets the job runs logger.
/// </summary>
public IJobRunsLogger JobRunsLogger { 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 IGradientGenerationConfiguration _gradientGenerationConfiguration;
/// <summary>
/// Gets or sets the gradients generation configuration.
/// </summary>
public IGradientGenerationConfiguration GradientGenerationConfiguration
{
get { return _gradientGenerationConfiguration; }
set { _gradientGenerationConfiguration = 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++;
if (LogEmbeddedDebuggingToFile && EmbeddedLogManager != null)
{
EmbeddedLogManager.Log(new EmbeddedLogItem(data));
}
}
}
/// <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;
Status = MachineStatuses.Disconnected;
}
}
/// <summary>
/// Disconnects the machine operator and the underlying transporter.
/// </summary>
/// <returns></returns>
public async override Task Disconnect()
{
if (Status == MachineStatuses.Upgrading) return;
if (State == TransportComponentState.Connected)
{
DisconnectRequest request = new DisconnectRequest();
LogRequestSent(request);
try
{
var response = await SendRequest<DisconnectRequest, DisconnectResponse>(request);
LogResponseReceived(response.Message);
Status = MachineStatuses.Disconnected;
}
catch (Exception ex)
{
LogRequestFailed(request, ex);
}
}
if (MachineEventsStateProvider != null)
{
MachineEventsStateProvider.Reset();
}
await base.Disconnect();
}
/// <summary>
/// Connects the transport component.
/// </summary>
/// <returns></returns>
public async override Task Connect()
{
var keep_alive = UseKeepAlive;
UseKeepAlive = false;
if (Status != MachineStatuses.Upgrading)
{
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);
if (Status != MachineStatuses.Upgrading)
{
Status = MachineStatuses.ReadyToDye;
}
DeviceInformation = response.Message.DeviceInformation;
_diagnosticsSent = false;
_eventsSent = false;
_debugSent = false;
OnEnableDiagnosticsChanged(EnableDiagnostics);
OnEnableEmbeddedDebuggingChanged(EnableEmbeddedDebugging);
OnEnableEventsNotification(EnableEventsNotification);
if (EnableJobResume)
{
ResumeJob();
}
}
catch (Exception ex)
{
LogRequestFailed(request, ex);
await base.Disconnect();
throw ex;
}
finally
{
UseKeepAlive = keep_alive;
}
}
}
#endregion
#region Private Methods
private async void ResumeJob()
{
LogManager.Log("Checking if a job is in progress...");
try
{
var res = await SendRequest<CurrentJobRequest, CurrentJobResponse>(new CurrentJobRequest());
if (res.Message.IsJobInProgress)
{
JobTicket jobTicket = res.Message.JobTicket;
ProcessParametersTable processParameters = new ProcessParametersTable();
jobTicket.ProcessParameters.MapPrimitivesTo(processParameters);
ResumingJobEventArgs args = new ResumingJobEventArgs((job) =>
{
if (Status != MachineStatuses.ReadyToDye)
{
throw new InvalidOperationException("Could not print while status = " + Status);
}
RunningJob = null;
RunningJobStatus = null;
var originalJob = job;
CurrentProcessParameters = processParameters;
var request = new ResumeCurrentJobRequest();
JobHandler handler = null;
handler = new JobHandler(async () =>
{
try
{
var result = await SendRequest<AbortJobRequest, AbortJobResponse>(new AbortJobRequest());
PrintingAborted?.Invoke(this, new PrintingEventArgs(handler, originalJob));
PrintingEnded?.Invoke(this, new PrintingEventArgs(handler, originalJob));
handler.RaiseCanceled();
}
catch (Exception ex)
{
LogManager.Log(ex, "Failed to cancel job.");
}
}, originalJob, jobTicket, processParameters, JobHandlingMode);
handler.StatusChanged += (x, s) =>
{
RunningJobStatus = s;
};
LogRequestSent(request);
bool responseLogged = false;
Thread.Sleep(500); //Just wait maybe Shlomo is getting this message to fast after restart ?
bool completed = false;
SendContinuousRequest<ResumeCurrentJobRequest, ResumeCurrentJobResponse>(request, null, TimeSpan.FromSeconds(2)).Subscribe((response) =>
{
if (!completed)
{
if (!responseLogged)
{
if (_last_job_status != null)
{
_last_job_status.IsCanceled = false;
_last_job_status.IsCompleted = false;
_last_job_status.IsFailed = false;
handler.Status = _last_job_status;
}
}
handler.RaiseStatusReceived(response.Message.Status);
if (!responseLogged)
{
Status = MachineStatuses.GettingReady;
responseLogged = true;
RunningJob = originalJob;
PrintingStarted?.Invoke(this, new PrintingEventArgs(handler, originalJob));
LogResponseReceived(response.Message);
}
if (JobHandlingMode == JobHandlerModes.SettingUp)
{
if (response.Message.Status.Progress > jobTicket.ProcessParameters.DryerBufferLength)
{
if (!completed)
{
Status = MachineStatuses.Printing;
}
}
}
else
{
if (response.Message.Status.Progress > 0)
{
if (!completed)
{
Status = MachineStatuses.Printing;
}
}
}
}
}, (ex) =>
{
if (!completed)
{
completed = true;
if (!(ex is ContinuousResponseAbortedException))
{
Status = MachineStatuses.ReadyToDye;
if (!handler.IsCanceled)
{
PrintingFailed?.Invoke(this, new PrintingFailedEventArgs(handler, originalJob, ex));
PrintingEnded?.Invoke(this, new PrintingEventArgs(handler, originalJob));
handler.RaiseFailed(ex);
LogRequestFailed(request, ex);
}
}
else
{
Status = MachineStatuses.ReadyToDye;
}
}
}, () =>
{
if (!completed)
{
completed = true;
Status = MachineStatuses.ReadyToDye;
PrintingCompleted?.Invoke(this, new PrintingEventArgs(handler, originalJob));
PrintingEnded?.Invoke(this, new PrintingEventArgs(handler, originalJob));
handler.RaiseCompleted();
}
});
return handler;
});
args.JobGuid = jobTicket.Guid;
ResumingJob?.Invoke(this, args);
}
}
catch (Exception ex)
{
LogManager.Log(ex);
}
}
/// <summary>
/// Logs the request sent.
/// </summary>
/// <param name="message">The message.</param>
protected void LogRequestSent(IMessage message)
{
if (!(message is FileChunkUploadRequest) && !(message is FileDownloadRequest))
{
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)
{
if (!(message is FileChunkUploadResponse) && !(message is FileDownloadResponse))
{
LogManager.Log(String.Format("Response received '{0}'...{1}{2}", message.GetType().Name, Environment.NewLine, message.ToJsonString()));
OnResponseReceived(message);
}
}
/// <summary>
/// Creates a PMR job segment.
/// </summary>
/// <param name="segment">The segment.</param>
/// <returns></returns>
private JobSegment CreatePMRJobSegment(Segment segment, Job job, ProcessParametersTable processParameters)
{
LogManager.Log($"Converting segment {segment.SegmentIndex} to PMR segment...");
JobSegment jobSegment = new JobSegment();
jobSegment.Length = segment.LengthWithFactor;
jobSegment.Name = segment.Name;
var stops = segment.BrushStops.ToList();
if (GradientGenerationConfiguration != null && GradientGenerationConfiguration.IsEnabled && segment.BrushStops.Count > 1)
{
LogManager.Log($"Generate segment {segment.SegmentIndex} gradient...");
stops = GradientGenerationConfiguration.Generate(segment, job, processParameters, (e) =>
{
PreparingJobProgress?.Invoke(this, e);
});
LogManager.Log($"Gradient generated.");
}
foreach (var stop in stops)
{
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;
if (liquidVolume.DispenserStepDivision != BL.Dispensing.DispenserStepDivisions.Auto)
{
dispenser.NanoliterPerPulse = liquidVolume.NanoliterPerStep;
}
else
{
dispenser.NanoliterPerPulse = liquidVolume.IdsPack.Dispenser.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);
}
return jobSegment;
}
private void ContinueSingleSpoolJob(Segment segment, Job job, ProcessParametersTable processParameters, JobHandler handler)
{
JobRequest request = new JobRequest();
JobTicket ticket = new JobTicket();
ticket.Guid = handler.Job.Guid;
ticket.EnableInterSegment = job.EnableInterSegment;
ticket.InterSegmentLength = job.InterSegmentLength;
ticket.Length = segment.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;
ticket.Segments.Add(CreatePMRJobSegment(segment, job, processParameters));
request.JobTicket = ticket;
LogRequestSent(request);
bool responseLogged = false;
var previous_segments_length = job.Segments.Where(x => x.SegmentIndex < segment.SegmentIndex).Sum(x => x.Length);
SendContinuousRequest<JobRequest, JobResponse>(request, null, TimeSpan.FromSeconds(2)).Subscribe((response) =>
{
response.Message.Status.Progress += previous_segments_length;
handler.RaiseStatusReceived(response.Message.Status);
if (!responseLogged && segment == job.OrderedSegments.First())
{
responseLogged = true;
Status = MachineStatuses.Printing;
RunningJob = handler.Job;
PrintingStarted?.Invoke(this, new PrintingEventArgs(handler, handler.Job));
LogResponseReceived(response.Message);
}
}, (ex) =>
{
if (!(ex is ContinuousResponseAbortedException))
{
Status = MachineStatuses.ReadyToDye;
if (!handler.IsCanceled)
{
PrintingFailed?.Invoke(this, new PrintingFailedEventArgs(handler, handler.Job, ex));
PrintingEnded?.Invoke(this, new PrintingEventArgs(handler, handler.Job));
handler.RaiseFailed(ex);
LogRequestFailed(request, ex);
}
}
else
{
Status = MachineStatuses.ReadyToDye;
}
}, () =>
{
if (segment == job.OrderedSegments.Last())
{
Status = MachineStatuses.ReadyToDye;
PrintingCompleted?.Invoke(this, new PrintingEventArgs(handler, handler.Job));
PrintingEnded?.Invoke(this, new PrintingEventArgs(handler, handler.Job));
handler.RaiseCompleted();
}
else
{
handler.RaiseSpoolChangeRequired(() =>
{
ContinueSingleSpoolJob(segment.GetNextSegment(), job, processParameters, handler);
}, () =>
{
PrintingAborted?.Invoke(this, new PrintingEventArgs(handler, handler.Job));
PrintingEnded?.Invoke(this, new PrintingEventArgs(handler, handler.Job));
Status = MachineStatuses.ReadyToDye;
handler.RaiseCanceled();
});
}
});
}
#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 Task<JobHandler> Print(Job job)
{
IColorConverter converter = new DefaultColorConverter();
var jobSegments = job.OrderedSegments;
//Check not brush stop has color space 'Volume'.
if (jobSegments.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.");
}
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 = converter.GetRecommendedProcessParameters(job);
if (processParameters == null)
{
throw new NullReferenceException("Could not locate any process parameters table in group " + processGroup.Name + " for RML " + job.Rml.Name);
}
//Perform color correction
foreach (var stop in jobSegments.SelectMany(x => x.BrushStops))
{
if (stop.LiquidVolumes == null)
{
if (stop.BrushColorSpace == ColorSpaces.RGB || stop.BrushColorSpace == ColorSpaces.LAB)
{
var output = converter.Convert(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;
}
}
else if (stop.BrushColorSpace == ColorSpaces.Twine || stop.BrushColorSpace == ColorSpaces.Coats)
{
if (stop.ColorCatalog != null)
{
stop.SetLiquidVolumes(job.Machine.Configuration, job.Rml, processParameters);
if (stop.ColorCatalog.Cyan > 0)
{
var liquidVolume = stop.LiquidVolumes.SingleOrDefault(x => x.IdsPack.LiquidType.Code == LiquidTypes.Cyan.ToInt32());
if (liquidVolume == null)
{
throw new NullReferenceException("Liquid volume not found for color conversion output liquid '" + LiquidTypes.Cyan + "'.");
}
liquidVolume.Volume = stop.ColorCatalog.Cyan;
}
if (stop.ColorCatalog.Magenta > 0)
{
var liquidVolume = stop.LiquidVolumes.SingleOrDefault(x => x.IdsPack.LiquidType.Code == LiquidTypes.Magenta.ToInt32());
if (liquidVolume == null)
{
throw new NullReferenceException("Liquid volume not found for color conversion output liquid '" + LiquidTypes.Magenta + "'.");
}
liquidVolume.Volume = stop.ColorCatalog.Magenta;
}
if (stop.ColorCatalog.Yellow > 0)
{
var liquidVolume = stop.LiquidVolumes.SingleOrDefault(x => x.IdsPack.LiquidType.Code == LiquidTypes.Yellow.ToInt32());
if (liquidVolume == null)
{
throw new NullReferenceException("Liquid volume not found for color conversion output liquid '" + LiquidTypes.Yellow + "'.");
}
liquidVolume.Volume = stop.ColorCatalog.Yellow;
}
if (stop.ColorCatalog.Black > 0)
{
var liquidVolume = stop.LiquidVolumes.SingleOrDefault(x => x.IdsPack.LiquidType.Code == LiquidTypes.Black.ToInt32());
if (liquidVolume == null)
{
throw new NullReferenceException("Liquid volume not found for color conversion output liquid '" + LiquidTypes.Black + "'.");
}
liquidVolume.Volume = stop.ColorCatalog.Black;
}
}
else
{
throw new InvalidOperationException($"No catalog item specified for segment color.");
}
}
else
{
throw new InvalidOperationException($"Unsupported color space {stop.BrushColorSpace}.");
}
}
if (job.EnableLubrication)
{
var lubricantVolume = stop.LiquidVolumes.SingleOrDefault(x => x.IdsPack != null && x.IdsPack.LiquidType != null && x.IdsPack.LiquidType.Code == LiquidTypes.Lubricant.ToInt32());
if (lubricantVolume != null)
{
lubricantVolume.Volume = 100;
}
}
}
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 Task<JobHandler> Print(Job job, ProcessParametersTable processParameters)
{
return Task.Factory.StartNew(() =>
{
if (Status != MachineStatuses.ReadyToDye)
{
throw new InvalidOperationException("Could not print while status = " + Status);
}
LogManager.Log($"Executing job '{job.Name}'...");
RunningJob = null;
RunningJobStatus = null;
var originalJob = job;
var clonedJob = job.Clone();
clonedJob.Guid = job.Guid;
CurrentProcessParameters = processParameters;
JobRequest request = new JobRequest();
if (job.NumberOfUnits < 1)
{
job.NumberOfUnits = 1;
}
job = job.Clone();
job.Guid = originalJob.Guid;
int max = job.OrderedSegments.Last().SegmentIndex + 1;
var segments = job.OrderedSegments.ToList();
for (int i = 0; i < job.NumberOfUnits - 1; i++)
{
foreach (var s in segments)
{
var cloned = s.Clone(job);
cloned.SegmentIndex = max++;
job.Segments.Add(cloned);
}
}
JobTicket ticket = new JobTicket();
ticket.Guid = originalJob.Guid;
ticket.EnableInterSegment = job.EnableInterSegment;
ticket.InterSegmentLength = Math.Max(job.InterSegmentLength, 1);
ticket.EnableLubrication = job.EnableLubrication;
ticket.Length = job.Length;
ticket.WindingMethod = (JobWindingMethod)job.WindingMethod.Code;
ticket.Spool = new JobSpool();
job.SpoolType.MapPrimitivesTo(ticket.Spool);
var spool = job.Machine.Spools.SingleOrDefault(x => x.SpoolType == job.SpoolType);
if (spool == null)
{
throw new InvalidOperationException("Job spool type is not registered with this machine.");
}
else
{
spool.MapPrimitivesTo(ticket.Spool);
}
ticket.Spool.JobSpoolType = (JobSpoolType)job.SpoolType.Code;
ProcessParameters process = new ProcessParameters();
processParameters.MapPrimitivesTo(process);
ticket.ProcessParameters = process;
JobHandler handler = null;
bool canceled = false;
bool requestSent = false;
handler = new JobHandler(async () =>
{
try
{
if (!canceled)
{
canceled = true;
LogManager.Log($"Aborting current gradient generation...");
GradientGenerationConfiguration.AbortCurrentGeneration();
if (requestSent)
{
var result = await SendRequest<AbortJobRequest, AbortJobResponse>(new AbortJobRequest());
}
PrintingAborted?.Invoke(this, new PrintingEventArgs(handler, clonedJob));
PrintingEnded?.Invoke(this, new PrintingEventArgs(handler, clonedJob));
handler.RaiseCanceled();
}
}
catch (Exception ex)
{
LogManager.Log(ex, "Failed to cancel job.");
}
}, clonedJob, ticket, processParameters, JobHandlingMode);
handler.StatusChanged += (x, s) =>
{
RunningJobStatus = s;
};
if (!job.IsAllSegmentsPerSpool)
{
ContinueSingleSpoolJob(job.OrderedSegments.First(), job, processParameters, handler);
return handler;
}
ThreadFactory.StartNew(async () =>
{
Status = MachineStatuses.GettingReady;
RunningJob = clonedJob;
PrintingStarted?.Invoke(this, new PrintingEventArgs(handler, clonedJob));
Thread.Sleep(100);
handler.RaiseStatusReceived(new JobStatus()
{
CurrentSegmentIndex = 0,
Progress = 0,
Message = "Preparing Job...",
});
foreach (var segment in originalJob.OrderedSegments)
{
try
{
ticket.Segments.Add(CreatePMRJobSegment(segment, originalJob, processParameters));
}
catch (Exception ex)
{
handler.RaiseFailed(ex);
Status = MachineStatuses.ReadyToDye;
return;
}
if (handler.IsCanceled)
{
Status = MachineStatuses.ReadyToDye;
return;
}
}
if (handler.IsCanceled)
{
Status = MachineStatuses.ReadyToDye;
return;
}
var segs = new List<JobSegment>();
for (int i = 0; i < job.NumberOfUnits; i++)
{
foreach (var s in ticket.Segments)
{
var cloned = s.Clone();
segs.Add(cloned);
}
}
if (segs.Count > 0)
{
ticket.Segments.Clear();
ticket.Segments.AddRange(segs);
}
request.JobTicket = ticket.Clone();
request.JobTicket.UploadStrategy = JobUploadStrategy;
//Use this if you want to log the entire job...
var logRequest = request.Clone();
LogManager.Log($"Job upload method is set to {JobUploadStrategy}...");
var oldKeepAlive = UseKeepAlive;
if (JobUploadStrategy == JobUploadStrategy.JobDescriptionFile)
{
LogManager.Log("Generating job description file...");
try
{
request.JobTicket.Segments.Clear();
JobDescriptionFile jobDescriptionFile = new JobDescriptionFile(ticket.Segments);
MemoryStream ms = jobDescriptionFile.ToStream();
handler.RaiseStatusReceived(new JobStatus()
{
CurrentSegmentIndex = 0,
Progress = 0,
Message = "Uploading job description file...",
});
LogManager.Log("Creating storage API manager...");
var storage = CreateStorageManager();
//Suppress keep alive while job uploads.
//storage.SuppressKeepAliveWhileFileUploads = true;
UseKeepAlive = false; //This is a work around for Shlomo not managing to keep alive while parsing the file.
LogManager.Log("Getting storage drive information...");
var storageInfo = await storage.GetStorageDrive();
LogManager.Log("Getting root folder information...");
var root_folder = await storage.GetRootFolder();
var existing_item = root_folder.Items.SingleOrDefault(x => x.Name == JOB_DESCRIPTION_FILE_NAME);
if (existing_item != null)
{
LogManager.Log("Removing previous job description file...");
await storage.DeleteItem(existing_item);
}
String job_file_path = Path.Combine(storageInfo.Root, JOB_DESCRIPTION_FILE_NAME);
LogManager.Log($"Uploading job description file '{job_file_path}' of size: {ms.Length}");
await storage.UploadFileSync(job_file_path, ms);
LogManager.Log("Job upload completed successfully.");
ms.Dispose();
request.JobTicket.JobDescriptionFile = job_file_path;
}
catch (Exception ex)
{
UseKeepAlive = oldKeepAlive;
Status = MachineStatuses.ReadyToDye;
PrintingFailed?.Invoke(this, new PrintingFailedEventArgs(handler, clonedJob, ex));
PrintingEnded?.Invoke(this, new PrintingEventArgs(handler, clonedJob));
handler.RaiseFailed(ex);
LogRequestFailed(request, ex);
return;
}
}
if (handler.IsCanceled)
{
UseKeepAlive = oldKeepAlive;
Status = MachineStatuses.ReadyToDye;
return;
}
LogRequestSent(request);
bool responseLogged = false;
bool completed = false; //Use this in case Shlomo is sending progress after completion.
SendContinuousRequest<JobRequest, JobResponse>(request, null, TimeSpan.FromSeconds(2)).Subscribe((response) =>
{
if (!completed)
{
handler.RaiseStatusReceived(response.Message.Status);
_last_job_status = handler.Status;
if (response.Message.Status.Progress > 0)
{
if (oldKeepAlive != UseKeepAlive)
{
UseKeepAlive = oldKeepAlive;
}
}
if (!responseLogged)
{
requestSent = true;
responseLogged = true;
LogResponseReceived(response.Message);
}
if (JobHandlingMode == JobHandlerModes.SettingUp)
{
if (response.Message.Status.Progress > request.JobTicket.ProcessParameters.DryerBufferLength)
{
if (!completed)
{
Status = MachineStatuses.Printing;
}
}
}
else
{
if (response.Message.Status.Progress > 0)
{
if (!completed)
{
Status = MachineStatuses.Printing;
}
}
}
}
}, (ex) =>
{
if (!completed)
{
completed = true;
UseKeepAlive = oldKeepAlive;
if (!(ex is ContinuousResponseAbortedException))
{
Status = MachineStatuses.ReadyToDye;
if (!handler.IsCanceled)
{
PrintingFailed?.Invoke(this, new PrintingFailedEventArgs(handler, clonedJob, ex));
PrintingEnded?.Invoke(this, new PrintingEventArgs(handler, clonedJob));
handler.RaiseFailed(ex);
LogRequestFailed(request, ex);
}
}
else
{
Status = MachineStatuses.ReadyToDye;
}
}
}, () =>
{
if (!completed)
{
completed = true;
UseKeepAlive = oldKeepAlive;
Status = MachineStatuses.ReadyToDye;
PrintingCompleted?.Invoke(this, new PrintingEventArgs(handler, clonedJob));
PrintingEnded?.Invoke(this, new PrintingEventArgs(handler, clonedJob));
handler.RaiseCompleted();
}
});
});
return handler;
});
}
/// <summary>
/// Executes a print stub for emulating a full 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>
/// <exception cref="InvalidOperationException">
/// Cannot print a brush stop with volume color space when process parameters table has not been specified.
/// or
/// Could not print while status = " + Status
/// </exception>
/// <exception cref="NullReferenceException">
/// Job RML is null
/// or
/// Could not locate an active process parameters tables group for RML " + job.Rml.Name
/// or
/// Could not locate process parameters table index " + processParametersTableIndex + " in group " + processGroup.Name + " for RML " + job.Rml.Name
/// or
/// Liquid volume not found for color conversion output liquid '" + outputLiquid.LiquidType + "'.
/// </exception>
public Task<JobHandler> PrintStub(Job job)
{
return Task.Factory.StartNew<JobHandler>(() =>
{
//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 = 0;
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)
{
stop.SetLiquidVolumes(job.Machine.Configuration, job.Rml, processParameters);
}
foreach (var liquidVolume in stop.LiquidVolumes)
{
liquidVolume.Volume = 10;
}
}
if (Status != MachineStatuses.ReadyToDye)
{
throw new InvalidOperationException("Could not print while status = " + Status);
}
RunningJob = null;
RunningJobStatus = null;
var originalJob = job;
CurrentProcessParameters = processParameters;
StubJobRequest request = new StubJobRequest();
if (job.NumberOfUnits < 1)
{
job.NumberOfUnits = 1;
}
job = job.Clone();
var segments = job.OrderedSegments.ToList();
for (int i = 0; i < job.NumberOfUnits - 1; i++)
{
foreach (var s in segments)
{
job.Segments.Add(s);
}
}
JobTicket ticket = new JobTicket();
ticket.Guid = originalJob.Guid;
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.OrderedSegments)
{
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.Dispenser.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<StubAbortJobRequest, StubAbortJobResponse>(new StubAbortJobRequest());
PrintingAborted?.Invoke(this, new PrintingEventArgs(handler, originalJob));
PrintingEnded?.Invoke(this, new PrintingEventArgs(handler, originalJob));
handler.RaiseCanceled();
}
catch (Exception ex)
{
LogManager.Log(ex, "Failed to cancel job.");
}
}, originalJob, ticket, processParameters, JobHandlingMode);
handler.StatusChanged += (x, s) =>
{
RunningJobStatus = s;
};
LogRequestSent(request);
bool responseLogged = false;
SendContinuousRequest<StubJobRequest, StubJobResponse>(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));
PrintingEnded?.Invoke(this, new PrintingEventArgs(handler, originalJob));
handler.RaiseFailed(ex);
LogRequestFailed(request, ex);
}
}
else
{
Status = MachineStatuses.ReadyToDye;
}
}, () =>
{
Status = MachineStatuses.ReadyToDye;
PrintingCompleted?.Invoke(this, new PrintingEventArgs(handler, originalJob));
PrintingEnded?.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.Where(x => x.Active))
{
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.Where(x => x.Active))
{
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.Where(x => x.Active))
{
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.Where(x => x.Active))
{
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.Where(x => x.Active))
{
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.Where(x => x.Active))
{
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.Where(x => x.Active))
{
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();
item.Capacity = idsPack.Dispenser.DispenserType.Capacity;
item.HardwareDispenserType = (PMR.Hardware.HardwareDispenserType)idsPack.Dispenser.DispenserType.Code;
item.Index = idsPack.PackIndex;
item.NlPerPulse = idsPack.Dispenser.NlPerPulse;
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>
/// Sets the state of the specified heater type.
/// </summary>
/// <param name="heater">The heater.</param>
/// <param name="setPoint">Set point temperature.</param>
/// <returns></returns>
public async Task<SetHeaterStateResponse> SetHeaterState(HeaterType heater, double setPoint)
{
SetHeaterStateResponse response = null;
SetHeaterStateRequest request = new SetHeaterStateRequest()
{
HeaterType = heater,
SetPoint = setPoint,
IsActive = true,
};
try
{
LogRequestSent(request);
response = await SendRequest<SetHeaterStateRequest, SetHeaterStateResponse>(request);
LogResponseReceived(response);
}
catch (Exception ex)
{
LogRequestFailed(request, ex);
throw ex;
}
return response;
}
/// <summary>
/// Sets the state of the specified blower.
/// </summary>
/// <param name="blower">The blower.</param>
/// <param name="isActive">Blower on/off.</param>
/// <param name="voltage">The voltage in millivolts.</param>
/// <returns></returns>
public async Task<SetBlowerStateResponse> SetBlowerState(PMR.Hardware.HardwareBlowerType blower, bool isActive, double voltage)
{
SetBlowerStateResponse response = null;
SetBlowerStateRequest request = new SetBlowerStateRequest()
{
BlowerType = blower,
Voltage = voltage,
IsActive = isActive,
};
try
{
LogRequestSent(request);
response = await SendRequest<SetBlowerStateRequest, SetBlowerStateResponse>(request);
LogResponseReceived(response);
}
catch (Exception ex)
{
LogRequestFailed(request, ex);
throw ex;
}
return response;
}
/// <summary>
/// Sets the state of the specified valve type.
/// </summary>
/// <param name="valve">The valve.</param>
/// <param name="state">Valve state.</param>
/// <returns></returns>
public async Task<SetValveStateResponse> SetValveState(ValveType valve, ValveStateCode state)
{
SetValveStateResponse response = null;
SetValveStateRequest request = new SetValveStateRequest()
{
ValveType = valve,
State = state,
};
try
{
LogRequestSent(request);
response = await SendRequest<SetValveStateRequest, SetValveStateResponse>(request);
LogResponseReceived(response);
}
catch (Exception ex)
{
LogRequestFailed(request, ex);
throw ex;
}
return response;
}
/// <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;
}
/// <summary>
/// Resets the device through the DFU channel.
/// </summary>
/// <returns></returns>
public Task ResetDFU()
{
return Task.Factory.StartNew(() =>
{
LogManager.Log("Performing device reset through DFU...");
//LogManager.Log("Disconnecting Operator...");
//Disconnect().Wait();
//LogManager.Log("Operator disconnected.");
FirmwareUpdateManager updateManager = new FirmwareUpdateManager();
LogManager.Log("Initializing DFU API...");
updateManager.Initialize();
LogManager.Log("Enumerating DFU devices...");
var device = updateManager.GetAvailableDevices(false).Where(x => !x.DeviceName.Contains("In-Circuit Debug Interface")).FirstOrDefault();
if (device != null)
{
LogManager.Log($"DFU device found: '{device.DeviceName}'.");
LogManager.Log("Switching to DFU mode...");
device.SwitchToDFUMode();
Thread.Sleep(6000);
LogManager.Log("Reattaching to DFU device...");
device = updateManager.GetAvailableDevices(false).Where(x => !x.DeviceName.Contains("In-Circuit Debug Interface")).FirstOrDefault();
if (device != null)
{
LogManager.Log("Resetting device...");
device.Reset();
Thread.Sleep(1000);
LogManager.Log("Reset completed.");
}
else
{
throw LogManager.Log(new Exception("DFU device not found."));
}
}
else
{
throw LogManager.Log(new Exception("DFU device not found."));
}
});
}
/// <summary>
/// Creates a storage manager for managing the machine file system.
/// </summary>
/// <returns></returns>
public StorageManager CreateStorageManager()
{
return new StorageManager(this);
}
/// <summary>
/// Upgrades the firmware.
/// </summary>
/// <param name="tfpStream">The TFP stream (Tango Firmware Package File).</param>
/// <returns></returns>
public async Task<FirmwareUpgradeHandler> UpgradeFirmware(Stream tfpStream)
{
bool cancel = false;
ZipFile zip = null;
Action abortAction = null;
var upgradeHandler = new FirmwareUpgradeHandler(() =>
{
cancel = true;
abortAction?.Invoke();
});
try
{
if (Status != MachineStatuses.ReadyToDye)
{
throw LogManager.Log(new InvalidOperationException($"Could not perform firmware upgrade while operator status is '{Status}'."));
}
var package_info = await GetFirmwarePackageInfo(tfpStream);
tfpStream.Position = 0;
zip = ZipFile.Read(tfpStream);
var storage = CreateStorageManager();
var drive = await storage.GetStorageDrive();
var root = await storage.GetRootFolder();
var existing_folder = root.Items.SingleOrDefault(x => x.Name == FIRMWARE_UPGRADE_FOLDER_NAME);
if (existing_folder != null)
{
await storage.DeleteItem(existing_folder);
}
String package_folder = Path.Combine(drive.Root, FIRMWARE_UPGRADE_FOLDER_NAME);
await storage.CreateFolder(package_folder);
List<StorageFileHandler> handlers = new List<StorageFileHandler>();
List<ZipEntry> entries = zip.Entries.ToList();
List<Stream> streams = new List<Stream>();
var keepAlive = UseKeepAlive;
UseKeepAlive = false;
Action upgradeDFU = null;
Action uploadNext = null;
Action validate = null;
Action activate = null;
Action postActivation = null;
Status = MachineStatuses.Upgrading;
abortAction = new Action(() =>
{
Status = MachineStatuses.ReadyToDye;
});
upgradeDFU = new Action(() =>
{
try
{
if (FirmwareUpgradeMode.HasFlag(FirmwareUpgradeModes.DFU))
{
var mcuEntry = zip.Entries.Single(x => x.FileName == package_info.FileDescriptors.Single(y => y.Destination == VersionFileDestination.Mcu).FileName);
MemoryStream ms = new MemoryStream();
mcuEntry.Extract(ms);
ms.Position = 0;
byte[] data = ms.ToArray();
ms.Dispose();
FirmwareUpgradeManager upgradeManager = new FirmwareUpgradeManager();
upgradeManager.UpgradeProgress += (sender, e) =>
{
upgradeHandler.Total = (long)e.Total;
upgradeHandler.RaiseProgress((long)e.Progress, FirmwareUpgradeStatus.Upgrading, e.State.ToDescription());
};
Adapter.Disconnect().Wait();
if (MachineEventsStateProvider != null)
{
MachineEventsStateProvider.Reset();
}
upgradeManager.PerformUpgrade(data).Wait();
upgradeHandler.RaiseProgress(100, FirmwareUpgradeStatus.Upgrading, "Waiting for the device...");
Thread.Sleep(5000);
upgradeHandler.RaiseProgress(100, FirmwareUpgradeStatus.Upgrading, "Connecting...");
Adapter.Connect().Wait();
Connect().Wait();
upgradeHandler.RaiseProgress(100, FirmwareUpgradeStatus.Upgrading, "Connected.");
Thread.Sleep(2000);
upgradeHandler.RaiseProgress(100, FirmwareUpgradeStatus.Upgrading, "Waiting...");
Thread.Sleep(2000);
Status = MachineStatuses.Upgrading;
}
if (FirmwareUpgradeMode.HasFlag(FirmwareUpgradeModes.TFP_PACKAGE))
{
upgradeHandler.Total = zip.Entries.Sum(x => x.UncompressedSize);
uploadNext();
}
else
{
postActivation();
}
}
catch (Exception ex)
{
Status = MachineStatuses.ReadyToDye;
upgradeHandler.RaiseFailed(ex);
return;
}
});
uploadNext = new Action(() =>
{
if (entries.Count > 0)
{
try
{
var entry = entries.First();
entries.Remove(entry);
var reader = entry.OpenReader();
streams.Add(reader);
var handler = storage.UploadFile(Path.Combine(package_folder, entry.FileName), reader).Result;
handlers.Add(handler);
handler.Canceled += (_, __) => { upgradeHandler.RaiseCanceled(); cancel = true; abortAction(); };
handler.Completed += (_, __) => uploadNext();
handler.Failed += (_, failedEx) => { upgradeHandler.RaiseFailed(failedEx); cancel = true; abortAction(); };
handler.Progress += (_, e) =>
{
if (cancel)
{
handler.Cancel();
return;
}
upgradeHandler.RaiseProgress(upgradeHandler.Current + e.Delta, FirmwareUpgradeStatus.Uploading, $"Uploading '{entry.FileName}'...");
};
}
catch (Exception ex)
{
abortAction();
upgradeHandler.RaiseFailed(ex);
}
}
else
{
validate();
}
});
validate = new Action(() =>
{
try
{
streams.ForEach(x => x.Dispose());
upgradeHandler.RaiseProgress(upgradeHandler.Total, FirmwareUpgradeStatus.Validating, "Validating version...");
var validateRequest = new ValidateVersionRequest();
validateRequest.Path = package_folder;
var validateResponse = SendRequest<ValidateVersionRequest, ValidateVersionResponse>(validateRequest, TimeSpan.FromSeconds(10)).Result;
activate();
}
catch (Exception ex)
{
upgradeHandler.RaiseFailed(ex);
}
});
activate = new Action(() =>
{
try
{
upgradeHandler.RaiseProgress(upgradeHandler.Total, FirmwareUpgradeStatus.Activating, "Activating version...");
var activateRequest = new ActivateVersionRequest();
activateRequest.Path = package_folder;
var activateResponse = SendRequest<ActivateVersionRequest, ActivateVersionResponse>(activateRequest, TimeSpan.FromSeconds(10)).Result;
postActivation();
}
catch (Exception ex)
{
upgradeHandler.RaiseFailed(ex);
}
});
postActivation = new Action(() =>
{
upgradeHandler.RaiseCompleted();
Status = MachineStatuses.ReadyToDye;
UseKeepAlive = keepAlive;
});
ThreadFactory.StartNew(() =>
{
upgradeDFU();
});
return upgradeHandler;
}
catch (Exception)
{
if (zip != null)
{
zip.Dispose();
}
throw;
}
}
/// <summary>
/// Validates the firmware package integrity.
/// </summary>
/// <param name="tfpStream">The TFP (Tango Firmware Package File) stream.</param>
/// <returns></returns>
public Task<VersionPackageDescriptor> GetFirmwarePackageInfo(Stream tfpStream)
{
return Task.Factory.StartNew<VersionPackageDescriptor>(() =>
{
using (ZipFile zip = ZipFile.Read(tfpStream))
{
var reader = zip.Entries.SingleOrDefault(x => x.FileName == FIRMWARE_UPGRADE_CONFIG_FILE_NAME).OpenReader();
var info = VersionPackageDescriptor.Parser.ParseFrom(reader);
reader.Close();
reader.Dispose();
return info;
}
});
}
/// <summary>
/// Directs the embedded device to validate the last uploaded firmware package.
/// </summary>
/// <returns></returns>
public async Task ValidateFirmwareVersion(String path)
{
var validateRequest = new ValidateVersionRequest();
validateRequest.Path = path;
await SendRequest<ValidateVersionRequest, ValidateVersionResponse>(validateRequest, TimeSpan.FromSeconds(10));
}
/// <summary>
/// Directs the embedded device to validate the last uploaded firmware package.
/// </summary>
/// <returns></returns>
public async Task ActivateFirmwareVersion(String path)
{
var activateRequest = new ActivateVersionRequest();
activateRequest.Path = path;
await SendRequest<ActivateVersionRequest, ActivateVersionResponse>(activateRequest, TimeSpan.FromSeconds(10));
}
#endregion
}
}
|