aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Utilities/Tango.LogViewer.UI/ViewModels/MainViewVM.cs
blob: edcdfd241325206b123b465735b31cf9902c5e1c (plain)
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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.Core.Commands;
using Tango.Logging;
using Tango.SharedUI;
using Tango.SharedUI.Components;
using Microsoft.WindowsAPICodePack.Dialogs;
using System.ComponentModel;
using System.Windows.Data;
using System.Diagnostics;
using System.IO;
using Tango.LogViewer.UI.LogViewerFileParser;
using System.Globalization;
using System.Windows.Input;
using System.Windows;

namespace Tango.LogViewer.UI.ViewModels
{
    public class MainViewVM : ViewModel
    {

        private LogViewerManager _logViewerManager;
        #region Properties
        public SelectedObjectCollection<LogCategory> SelectedLogCategories { get; set; }

        private TimeSpan? _endSelectedTime;
        /// <summary>
        /// Gets or sets the end selected time of time picker.
        /// </summary>
        public TimeSpan? EndSelectedTime
        {
            get { return _endSelectedTime; }
            set
            {
                _endSelectedTime = value;
                RaisePropertyChangedAuto();
                ApplyLogsFilter();
            }
        }

        private TimeSpan? _startSelectedTime;
        /// <summary>
        /// Gets or sets the start selected time of time picker.
        /// </summary>
        public TimeSpan? StartSelectedTime
        {
            get { return _startSelectedTime; }
            set
            {
                _startSelectedTime = value;
                RaisePropertyChangedAuto();
                ApplyLogsFilter();
            }
        }

        private String _filter;
        /// <summary>
        /// Gets or sets the filter for log message.
        /// </summary>
        public String Filter
        {
            get { return _filter; }
            set
            {
                _filter = value;
                RaisePropertyChangedAuto();
                ApplyLogsFilter();
            }
        }

        private ObservableCollection<LogItemBase> _logs;
        /// <summary>
        /// Gets or sets the collection of LogItemBase after parsing log files.
        /// </summary>
        public ObservableCollection<LogItemBase> Logs
        {
            get { return _logs; }
            set { _logs = value; RaisePropertyChangedAuto(); }
        }

        private ICollectionView _logsViewSource;

        /// <summary>
        /// Wrapper around the Logs collection that provides filtering
        /// </summary>
        public ICollectionView LogsViewSource
        {
            get { return _logsViewSource; }
            set { _logsViewSource = value; RaisePropertyChangedAuto(); }
        }

        private LogItemBase _selectedLog;
        /// <summary>
        /// Gets or sets the selected log.
        /// </summary>
        public LogItemBase SelectedLog
        {
            get { return _selectedLog; }
            set { _selectedLog = value; RaisePropertyChangedAuto(); Message = _selectedLog != null ? _selectedLog.Message : ""; }
        }


        private string _fileName;
        /// <summary>
        /// Gets or sets the full path of the open file to display in Status bar.
        /// </summary>
        public string FileName
        {
            get { return _fileName; }
            set { _fileName = value; RaisePropertyChangedAuto(); }
        }

        private int _countOfSet;
        /// <summary>
        /// Gets or sets the count of file set to display in Status bar.
        /// </summary>
        public int CountOfSet
        {
            get { return _countOfSet; }
            set { _countOfSet = value; RaisePropertyChangedAuto(); }
        }

        private string _message;
        /// <summary>
        /// Gets the message of selected log item to display in right panel.
        /// </summary>
        public string Message
        {
            get { return _message; }
            set { _message = value; RaisePropertyChangedAuto(); }

        }
        private bool _isEmbeddedLog;

        public bool IsEmbeddedLog
        {
            get { return _isEmbeddedLog; }
            set { _isEmbeddedLog = value; RaisePropertyChangedAuto(); }
        }

        private bool _isSet;
        /// <summary>
        /// Gets or sets a value indicating whether set of files.
        /// </summary>
        public bool IsSet
        {
            get { return _isSet; }
            set { _isSet = value; RaisePropertyChangedAuto(); }
        }

        private bool _loading;

        public bool Loading
        {
            get { return _loading; }
            set { _loading = value; RaisePropertyChangedAuto(); }
        }

        public CultureInfo Culture { get; set; }

        #endregion

        public RelayCommand OpeFileLogCommand { get; set; }

        #region Constructors
        public MainViewVM()
        {
            Culture = new CultureInfo("he-IL");

            SelectedLogCategories = new SelectedObjectCollection<LogCategory>(new ObservableCollection<LogCategory>()
            {
                LogCategory.Info,
                LogCategory.Warning,
                LogCategory.Error,
                LogCategory.Critical,
                LogCategory.Debug,
            }, new ObservableCollection<LogCategory>()
            {
                LogCategory.Info,
                LogCategory.Warning,
                LogCategory.Error,
                LogCategory.Critical,
                LogCategory.Debug,
            });
            _logViewerManager = new LogViewerManager();
            IsSet = false;
            IsEmbeddedLog = false;
            Loading = false;
            Clear();
            OpeFileLogCommand = new RelayCommand(OpenLogFile);
            SelectedLogCategories.SynchedSource.CollectionChanged += (_, __) =>
            {
                ApplyLogsFilter();
            };
        }
        #endregion

        #region Loading
        /// <summary>
        /// Clears the all filters. Set filter properties to init state.
        /// </summary>
        private void Clear()
        {
            FileName = "";
            StartSelectedTime = null;
            EndSelectedTime = null;
            Filter = "";
            SelectedLog = null;
            SelectedLogCategories.SynchedSource = SelectedLogCategories.Source;
            CountOfSet = 0;
            IsSet = false;
            if (Logs != null)
            {
                Logs.Clear();
                RaisePropertyChanged("Logs");
            }

        }

        /// <summary>
        /// Opens the log file from menu.
        /// </summary>
        private void OpenLogFile()
        {
            var dialog = new CommonOpenFileDialog()
            {
                Multiselect = false,
                EnsureFileExists = true,

            };
            dialog.Filters.Add(new CommonFileDialogFilter("Log files", "*.log"));
            CommonFileDialogResult result = dialog.ShowDialog();
            if (result == CommonFileDialogResult.Ok)
            {
                LoadLogFile(dialog.FileName);
            }
        }

        /// <summary>
        /// Loads the log file from menu or command line.
        /// </summary>
        public async void LoadLogFile(String fileName)
        {
            try
            {
                Clear();
                Loading = true;

                Mouse.OverrideCursor = Cursors.Wait;
                _logViewerManager.InitLogFile(fileName);
                List<LogItemBase> logs = new List<LogItemBase>();
                await Task.Factory.StartNew(() =>
                {
                    logs.AddRange(_logViewerManager.Parse());
                });

                CountOfSet = _logViewerManager.CountOfSet;
                IsSet = CountOfSet > 0 ? true : false;
                IsEmbeddedLog = _logViewerManager.IsEmbeddedLog;
                FileName = _logViewerManager.FileName;
                Logs = new ObservableCollection<LogItemBase>(logs);
                LogsViewSource = CollectionViewSource.GetDefaultView(Logs);
                StartSelectedTime = Logs.Min(x => x.TimeStamp).TimeOfDay;
                EndSelectedTime = Logs.Max(x => x.TimeStamp).TimeOfDay;
                ApplyLogsFilter();
            }
            catch (Exception ex)
            {
                Mouse.OverrideCursor = null;
                Loading = false;
                MessageBox.Show(ex.FlattenMessage());
            }
            finally
            {
                Mouse.OverrideCursor = null;
                Loading = false;
            }
        }


        #endregion

        #region Filtering
        /// <summary>
        /// Applies the all filters( time, categories,filter massage) to view.
        /// </summary>
        private void ApplyLogsFilter()
        {
            if (LogsViewSource != null)
            {
                LogsViewSource.Filter = (x) =>
                            {
                                LogItemBase log = x as LogItemBase;
                                return (SelectedLogCategories.SynchedSource.Contains(log.Category) && (String.IsNullOrWhiteSpace(Filter) || log.Message.ToLower().Contains(Filter.ToLower()))
                                && (StartSelectedTime == null || StartSelectedTime == TimeSpan.Zero || log.TimeStamp.TimeOfDay >= StartSelectedTime) && (EndSelectedTime == null || EndSelectedTime == TimeSpan.Zero || log.TimeStamp.TimeOfDay <= EndSelectedTime));
                            };
            }

        }
        #endregion

    }
}
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(); } } #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.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(); 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> /// 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> /// 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 } }