aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Integration/JobRuns/BasicJobRunsLogger.cs
blob: e128a594932cac0edd7d414c4ca1c6956a689942 (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
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
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Tango.BL;
using Tango.BL.Builders;
using Tango.BL.DTO;
using Tango.BL.Entities;
using Tango.BL.Enumerations;
using Tango.Core;
using Tango.Core.ExtensionMethods;
using Tango.Integration.Operation;
using Tango.PMR.MachineStatus;
using Tango.PMR.Printing;

namespace Tango.Integration.JobRuns
{
    /// <summary>
    /// Represents a basic database job runs logger.
    /// </summary>
    /// <seealso cref="Tango.Integration.JobRuns.IJobRunsLogger" />
    public class BasicJobRunsLogger : ExtendedObject, IJobRunsLogger
    {
        private Job _job;
        private Machine _defaultMachine;
        private List<MachinesEvent> _currentJobEvents;
        private MachineStatus _startMachineStatus;
        private JobTicket _jobTicket;

        public event EventHandler<JobRunAvailableEventArgs> JobRunAvailable;

        #region Properties

        /// <summary>
        /// Gets the machine operator.
        /// </summary>
        public IMachineOperator MachineOperator { get; private set; }

        /// <summary>
        /// Gets a value indicating whether this instance is started.
        /// </summary>
        public bool IsStarted { get; private set; }

        /// <summary>
        /// Gets or sets the job designations of which the logger should log (supports multiple flags).
        /// </summary>
        public JobDesignations JobDesignationFilter { get; set; }

        /// <summary>
        /// Gets or sets the job run source when logging job runs.
        /// </summary>
        public JobSource JobSource { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether create job run files with job ticket information and more.
        /// </summary>
        public bool CreateJobRunsFiles { get; set; }

        /// <summary>
        /// Gets or sets the job runs files folder.
        /// </summary>
        public String JobRunsFolder { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="BasicJobRunsLogger"/> class.
        /// </summary>
        /// <param name="machineOperator">The machine operator.</param>
        public BasicJobRunsLogger(IMachineOperator machineOperator)
        {
            JobDesignationFilter = JobDesignations.Default | JobDesignations.SampleDye | JobDesignations.FineTuning;
            MachineOperator = machineOperator;
            Init();
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Initializes this instance.
        /// </summary>
        private void Init()
        {
            MachineOperator.PrintingStarted -= Machine_PrintingStarted;
            MachineOperator.PrintingStarted += Machine_PrintingStarted;
            MachineOperator.PrintingCompleted -= Machine_PrintingCompleted;
            MachineOperator.PrintingCompleted += Machine_PrintingCompleted;
            MachineOperator.PrintingAborted -= Machine_PrintingAborted;
            MachineOperator.PrintingAborted += Machine_PrintingAborted;
            MachineOperator.PrintingFailed -= Machine_PrintingFailed;
            MachineOperator.PrintingFailed += Machine_PrintingFailed;
            MachineOperator.HeadCleaningEnded += MachineOperator_HeadCleaningEnded;
            MachineOperator.MachineEventsStateProvider.EventsReceived -= MachineEventsStateProvider_EventsReceived;
            MachineOperator.MachineEventsStateProvider.EventsReceived += MachineEventsStateProvider_EventsReceived;

            _currentJobEvents = new List<MachinesEvent>();

            JobRunsFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                            "Twine", "Tango", "JobRuns Extended Info");
        }

        private void MachineEventsStateProvider_EventsReceived(object sender, IEnumerable<MachinesEvent> events)
        {
            foreach (var item in events.ToList())
            {
                _currentJobEvents.Add(item);
            }
        }

        private bool ShouldLog()
        {
            return IsStarted && _job != null && JobDesignationFilter.HasFlag(_job.Designation);
        }

        private void InsertJobRun(PrintingEventArgs e, JobRunStatus status, Exception exception)
        {
            if (!e.IsResumingJob)
            {
                if (ShouldLog())
                {
                    if (e.Job.Guid == _job.Guid)
                    {
                        Task.Factory.StartNew(() =>
                        {
                            try
                            {
                                using (var db = ObservablesContext.CreateDefault())
                                {
                                    var colorSpaces = db.ColorSpaces.ToList();

                                    JobRun run = new JobRun();

                                    run.UserGuid = _job.UserGuid;
                                    run.StartDate = e.StartDate;
                                    run.UploadingStartDate = e.UploadingStartTime;
                                    run.HeatingStartDate = e.HeatingStartTime;
                                    run.ActualStartDate = e.ActualStartTime;
                                    run.EndDate = DateTime.UtcNow;
                                    run.JobName = _job.Name;
                                    run.Source = JobSource;
                                    run.Designation = _job.Designation;
                                    run.JobGuid = _job.Guid;
                                    run.RmlGuid = _job.RmlGuid;
                                    run.MachineGuid = _job.MachineGuid;
                                    run.JobRunStatus = status;
                                    run.EndPosition = e.JobHandler.Status.Progress;
                                    run.NumberOfUnits = _job.NumberOfUnits;
                                    run.JobLength = e.JobHandler.Status.TotalProgress;
                                    run.JobLogicalLength = e.Job.Length;
                                    run.LiquidQuantities = e.LiquidQuantities;
                                    run.IsGradient = _job.Segments.Any(x => x.BrushStops.Count > 1);
                                    run.GradientResolutionCm = MachineOperator.GradientGenerationConfiguration.ResolutionCM;
                                    run.ActualStartPosition = e.Job.ResumeStartPosition;
                                    run.ActualEndPosition = e.JobHandler.Status.ProgressMinusSettingUp;

                                    if (_defaultMachine != null)
                                    {
                                        run.MachineType = _defaultMachine.MachineType;
                                    }
                                    else if (_job.Machine != null)
                                    {
                                        run.MachineType = _job.Machine.MachineType;
                                    }

                                    var jobFile = e.Job.ToJobFileWhenLoaded();

                                    try
                                    {
                                        if (_job.Designation == JobDesignations.FineTuning)
                                        {
                                            jobFile.Segments.First().BrushStops.First().ColorSpaceGuid = colorSpaces.First(x => x.Code == (int)ColorSpaces.LAB).Guid;
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        LogManager.Log(ex, "Error setting brush stop color space to LAB on fine tuning job run (JobFileString).");
                                    }

                                    run.JobString = jobFile.ToString();

                                    run.ApplicationVersion = Assembly.GetEntryAssembly().GetName().Version.ToString();
                                    run.FirmwareVersion = MachineOperator.DeviceInformation?.Version;
                                    run.CeVersion = _job.Rml.ColorConversionVersion.ToString();
                                    run.ProcessParametersTableGuid = MachineOperator.CurrentProcessParameters?.Guid;

                                    //Set liquid quantities
                                    SetJobRunLiquidQuantities(run, run.LiquidQuantities);

                                    if (exception != null)
                                    {
                                        run.FailedMessage = exception.FlattenMessage();
                                    }

                                    if (_job.Designation == JobDesignations.FineTuning)
                                    {
                                        try
                                        {
                                            run.FineTuningString = JsonConvert.SerializeObject(_job.VectorFineTuningRunModel);
                                        }
                                        catch (Exception ex)
                                        {
                                            LogManager.Log(ex, "Error serializing fine tuning model for job run.");
                                        }
                                    }

                                    db.JobRuns.Add(run);

                                    e.Job.LastRun = DateTime.UtcNow;
                                    _job.LastRun = DateTime.UtcNow;

                                    var job = db.Jobs.SingleOrDefault(x => x.Guid == _job.Guid);

                                    if (job != null)
                                    {
                                        job.LastRun = DateTime.UtcNow;
                                    }

                                    LogManager.Log($"Inserting job run for '{run.JobName}'...\n{run.ToJsonString(nameof(JobRun.JobString), nameof(JobRun.LiquidQuantityString))}");

                                    db.SaveChanges();

                                    JobRunInfo jobRunInfo = new JobRunInfo();
                                    jobRunInfo.JobRunID = run.ID;
                                    jobRunInfo.JobTicket = _jobTicket;
                                    jobRunInfo.Events = _currentJobEvents.Select(x => MachinesEventDTO.FromObservable(x)).ToList();
                                    jobRunInfo.StartMachineStatus = _startMachineStatus;
                                    jobRunInfo.EndMachineStatus = MachineOperator.MachineStatus?.Clone();

                                    if (CreateJobRunsFiles)
                                    {
                                        try
                                        {
                                            Directory.CreateDirectory(JobRunsFolder);

                                            String json = jobRunInfo.ToJsonString();
                                            File.WriteAllText(Path.Combine(JobRunsFolder, $"{run.ID}.run"), json);

                                            LogManager.Log($"JobRun extended info file '{run.ID}' created.");
                                        }
                                        catch (Exception ex)
                                        {
                                            LogManager.Log(ex, "Error creating job run extended info file.");
                                        }
                                    }

                                    JobRunAvailable?.Invoke(this, new JobRunAvailableEventArgs() { JobRunInfo = jobRunInfo, JobRun = run });
                                }
                            }
                            catch (Exception ex)
                            {
                                LogManager.Log(ex, "Error logging the last job run to the database.");
                            }
                        });
                    }
                }
            }
            else
            {
                using (ObservablesContext db = ObservablesContext.CreateDefault())
                {
                    try
                    {
                        var run = db.JobRuns.OrderByDescending(x => x.LastUpdated).FirstOrDefault(x => x.JobGuid == _job.Guid);

                        if (run == null)
                        {
                            LogManager.Log($"Error updating job run by resumed job. Could not locate the existing job run by job guid '{_job.Guid}'.");
                            return;
                        }

                        run.LastUpdated = DateTime.UtcNow;
                        run.EndDate = DateTime.UtcNow;
                        run.JobRunStatus = status;
                        run.EndPosition = e.JobHandler.Status.Progress;
                        run.JobLength = e.JobHandler.Status.TotalProgress;
                        run.ActualEndPosition = e.JobHandler.Status.ProgressMinusSettingUp;

                        if (exception != null)
                        {
                            run.FailedMessage = exception.FlattenMessage();
                        }
                        else
                        {
                            run.FailedMessage = null;
                        }

                        var newQuantities = e.LiquidQuantities.ToList();
                        var oldQuantities = run.LiquidQuantities.ToList();

                        SetJobRunLiquidQuantities(run, newQuantities, update: true);

                        //Append liquid quantities string.
                        foreach (var newQuantity in newQuantities)
                        {
                            var oldQuantity = oldQuantities.FirstOrDefault(x => x.LiquidType == newQuantity.LiquidType);
                            if (oldQuantity != null)
                            {
                                oldQuantity.Quantity += newQuantity.Quantity;
                            }
                            else
                            {
                                oldQuantities.Add(newQuantity);
                            }
                        }

                        run.LiquidQuantities = oldQuantities;

                        db.SaveChanges();

                        //TODO: Needs to resubmit this to Azure! Then in Azure Distinct by job run ID, by job guid, by latest!

                        JobRunInfo jobRunInfo = null;

                        if (CreateJobRunsFiles)
                        {
                            try
                            {
                                String jobInfoPath = Path.Combine(JobRunsFolder, $"{run.ID}.run");

                                if (File.Exists(jobInfoPath))
                                {
                                    String json = File.ReadAllText(jobInfoPath);
                                    jobRunInfo = JsonConvert.DeserializeObject<JobRunInfo>(json);
                                    jobRunInfo.Events.AddRange(_currentJobEvents.Select(x => MachinesEventDTO.FromObservable(x)).ToList());
                                    jobRunInfo.EndMachineStatus = MachineOperator.MachineStatus?.Clone();
                                    File.WriteAllText(jobInfoPath, jobRunInfo.ToJsonString());
                                }
                            }
                            catch (Exception ex)
                            {
                                LogManager.Log(ex, "Error while trying to update jobrun info file after job resume.");
                            }
                        }

                        JobRunAvailable?.Invoke(this, new JobRunAvailableEventArgs() { JobRunInfo = jobRunInfo, JobRun = run });
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, "Error while trying to update jobrun by resumed job.");
                    }
                }
            }
        }

        private void InsertHeadCleaningJobRun(HeadCleaningEndedEventArgs e)
        {
            if (IsStarted && _defaultMachine != null)
            {
                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        using (var db = ObservablesContext.CreateDefault())
                        {
                            JobRun run = new JobRun();

                            run.IsHeadCleaning = true;
                            run.StartDate = e.StartDate;
                            run.UploadingStartDate = e.StartDate;
                            run.HeatingStartDate = e.StartDate;
                            run.ActualStartDate = e.StartDate;
                            run.EndDate = DateTime.UtcNow;
                            run.JobName = "HEAD CLEANING";
                            run.Source = JobSource;
                            run.MachineGuid = _defaultMachine.Guid;
                            run.JobRunStatus = e.Status;
                            run.EndPosition = e.EndPosition;
                            run.JobLength = e.Length;
                            run.LiquidQuantities = e.LiquidQuantities;

                            SetJobRunLiquidQuantities(run, run.LiquidQuantities);

                            //if (exception != null)
                            //{
                            //    run.FailedMessage = exception.FlattenMessage();
                            //}

                            db.JobRuns.Add(run);

                            LogManager.Log($"Inserting head cleaning job run...\n{run.ToJsonString(nameof(JobRun.JobString), nameof(JobRun.LiquidQuantityString))}");

                            db.SaveChanges();
                        }
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, "Error logging the last head cleaning job run to the database.");
                    }
                });
            }
        }

        private void SetJobRunLiquidQuantities(JobRun run, List<BL.ValueObjects.JobRunLiquidQuantity> quantities, bool update = false)
        {
            if (run == null || quantities == null)
                return;

            // Map each LiquidType to the corresponding JobRun property updater
            var setters = new Dictionary<LiquidTypes, Action<long>>
            {
                { LiquidTypes.Cyan,               q => run.CyanQuantity = update ? run.CyanQuantity + q : q },
                { LiquidTypes.Magenta,            q => run.MagentaQuantity = update ? run.MagentaQuantity + q : q },
                { LiquidTypes.Yellow,             q => run.YellowQuantity = update ? run.YellowQuantity + q : q },
                { LiquidTypes.Black,              q => run.BlackQuantity = update ? run.BlackQuantity + q : q },
                { LiquidTypes.Transparent,     q => run.TransparentQuantity = update ? run.TransparentQuantity + q : q },
                { LiquidTypes.Lubricant,          q => run.LubricantQuantity = update ? run.LubricantQuantity + q : q },
                { LiquidTypes.Cleaner,            q => run.CleanerQuantity = update ? run.CleanerQuantity + q : q },
                { LiquidTypes.LightCyan,          q => run.LightCyanQuantity = update ? run.LightCyanQuantity + q : q },
                { LiquidTypes.LightMagenta,       q => run.LightMagentaQuantity = update ? run.LightMagentaQuantity + q : q },
                { LiquidTypes.LightYellow,        q => run.LightYellowQuantity = update ? run.LightYellowQuantity + q : q },
                { LiquidTypes.Blue,               q => run.BlueQuantity = update ? run.BlueQuantity + q : q },
                { LiquidTypes.LightBlue,          q => run.LightBlueQuantity = update ? run.LightBlueQuantity + q : q },
                { LiquidTypes.Orange,             q => run.OrangeQuantity = update ? run.OrangeQuantity + q : q },
                { LiquidTypes.LightOrange,        q => run.LightOrangeQuantity = update ? run.LightOrangeQuantity + q : q },
                { LiquidTypes.Rubine,             q => run.RubineQuantity = update ? run.RubineQuantity + q : q },
                { LiquidTypes.LightRubine,        q => run.LightRubineQuantity = update ? run.LightRubineQuantity + q : q },
                { LiquidTypes.Navy,               q => run.NavyQuantity = update ? run.NavyQuantity + q : q },
                { LiquidTypes.Violet,             q => run.VioletQuantity = update ? run.VioletQuantity + q : q },
                { LiquidTypes.TWCyan,             q => run.TwCyanQuantity = update ? run.VioletQuantity + q : q }
            };

            foreach (var liquidType in setters.Keys)
            {
                var quantityObj = quantities.SingleOrDefault(x => x.LiquidType == liquidType);
                var quantity = quantityObj?.Quantity ?? 0;
                setters[liquidType](quantity);
            }
        }


        #endregion

        #region Public Methods

        /// <summary>
        /// Starts the logger.
        /// </summary>
        public void Start()
        {
            IsStarted = true;
        }

        /// <summary>
        /// Stops the logger.
        /// </summary>
        public void Stop()
        {
            IsStarted = false;
        }

        /// <summary>
        /// Sets the head cleaning parameters.
        /// </summary>
        /// <param name="machine">The machine.</param>
        public void SetDefaultMachine(Machine machine)
        {
            _defaultMachine = machine;
        }

        #endregion

        #region Event Handlers

        private void Machine_PrintingFailed(object sender, PrintingFailedEventArgs e)
        {
            InsertJobRun(e, JobRunStatus.Failed, e.Exception);
        }

        private void Machine_PrintingAborted(object sender, PrintingEventArgs e)
        {
            InsertJobRun(e, JobRunStatus.Aborted, null);
        }

        private void Machine_PrintingCompleted(object sender, PrintingEventArgs e)
        {
            InsertJobRun(e, JobRunStatus.Completed, null);
        }

        private void Machine_PrintingStarted(object sender, PrintingEventArgs e)
        {
            _job = e.Job;
            _currentJobEvents = new List<MachinesEvent>();
            _startMachineStatus = MachineOperator.MachineStatus?.Clone();
            _jobTicket = e.JobHandler.JobTicket;
        }

        private void MachineOperator_HeadCleaningEnded(object sender, HeadCleaningEndedEventArgs e)
        {
            InsertHeadCleaningJobRun(e);
        }

        #endregion
    }
}