aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Integration/Operation/MachineOperator.cs
blob: 7ee390aff8b0a8c23b876ea3bc401e179785f981 (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
3
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;
using Tango.BL;
using Tango.BL.Builders;
using Tango.BL.Entities;
using Tango.Core.DI;
using Tango.Integration.ExternalBridge;
using Tango.Integration.Operation;
using Tango.PPC.Common;
using Tango.PPC.Common.Application;
using Tango.PPC.Common.Authentication;
using Tango.PPC.Common.ExternalBridge;
using Tango.PPC.Common.Modules;
using Tango.PPC.Common.Navigation;
using Tango.PPC.Common.Notifications;
using Tango.PPC.Common.WatchDog;
using Tango.PPC.UI.Dialogs;
using Tango.SharedUI;
using System.Data.Entity;
using Tango.PPC.UI.AppBarItems;
using Tango.PPC.Common.Notifications.NotificationItems;
using Tango.Core.Commands;
using System.Timers;

namespace Tango.PPC.UI.ViewModels
{
    /// <summary>
    /// Represents the PPC main view model.
    /// </summary>
    /// <seealso cref="Tango.PPC.Common.PPCViewModel" />
    public class MainViewVM : PPCViewModel
    {
        private DispatcherTimer _date_timer;
        private bool _isPowerUpDialogShown;
        private bool _isThreadLoadingShown;
        private PowerUpAppBarItem _powerUpAppBar;
        private bool _started;
        private MessageNotificationItem _headTypeNotification;
        private Timer _screenSaverTimer;

        private DateTime _currentDateTime;
        /// <summary>
        /// Gets or sets the current date time.
        /// </summary>
        public DateTime CurrentDateTime
        {
            get { return _currentDateTime; }
            set { _currentDateTime = value; RaisePropertyChangedAuto(); }
        }

        private bool _isScreenSaverOn;
        public bool IsScreenSaverOn
        {
            get { return _isScreenSaverOn; }
            set { _isScreenSaverOn = value; RaisePropertyChangedAuto(); }
        }

        public RelayCommand ScreenSaverExitCommand { get; set; }

        public MainViewVM()
        {
            _date_timer = new DispatcherTimer();
            _date_timer.Interval = TimeSpan.FromSeconds(1);
            _date_timer.Tick += _date_timer_Tick;
            _date_timer.Start();

            _headTypeNotification = new MessageNotificationItem();
            _headTypeNotification.CanClose = false;
            _headTypeNotification.MessageType = MessageNotificationItem.MessageNotificationItemTypes.Error;
            _headTypeNotification.Priority = NotificationItem.NotificationPriority.Critical;
            _headTypeNotification.Message = "Machine head type mismatch.";

            ScreenSaverExitCommand = new RelayCommand(ResetScreenSaverTimer);
            _screenSaverTimer = new Timer(TimeSpan.FromMinutes(Settings.ScreenSaverStartDuration).TotalMilliseconds);
        }

        /// <summary>
        /// Called when the application has been started.
        /// </summary>
        public override void OnApplicationStarted()
        {

        }

        public override void OnApplicationReady()
        {
            base.OnApplicationReady();
            MachineProvider.MachineOperator.CartridgeValidationRequestReceived += MachineOperator_CartridgeValidationRequestReceived;
            //MachineProvider.MachineOperator.FirmwareStarted += MachineOperator_FirmwareStarted;
            MachineProvider.MachineOperator.ThreadLoadingStatusChanged += MachineOperator_ThreadLoadingStatusChanged;
            MachineProvider.MachineOperator.ThreadLoadingConfirmationRequired += MachineOperator_ThreadLoadingConfirmationRequired;

            MachineProvider.MachineOperator.PowerUpStarted += MachineOperator_PowerUpStarted;
            MachineProvider.MachineOperator.PowerUpProgress += MachineOperator_PowerUpProgress;
            MachineProvider.MachineOperator.PowerUpEnded += MachineOperator_PowerUpEnded;

            MachineProvider.MachineConnected += MachineProvider_MachineConnected;

            MachineProvider.MachineOperator.WasteReplacementRequired += MachineOperator_WasteReplacementRequired;

            _screenSaverTimer.Elapsed += _screenSaverTimer_Elapsed;
            _screenSaverTimer.Start();
        }

        #region Waste Replacement

        private void MachineOperator_WasteReplacementRequired(object sender, EventArgs e)
        {
            InvokeUI(async () => 
            {
                var vm = await NotificationProvider.ShowDialog<WasteReplacementViewVM>();
                
                if (MachineProvider.IsConnected)
                {
                    await MachineProvider.MachineOperator.CompleteWasteReplacement(vm.DialogResult);
                }
            });
        }

        #endregion

        #region Power Up

        private void MachineOperator_PowerUpEnded(object sender, EventArgs e)
        {
            _started = false;
            _powerUpAppBar?.Close();
            _powerUpAppBar = null;
        }

        private void MachineOperator_PowerUpProgress(object sender, PMR.Power.StartPowerUpResponse status)
        {
            if (_powerUpAppBar != null)
            {
                _powerUpAppBar.Status = status;
            }
        }

        private void MachineOperator_PowerUpStarted(object sender, PMR.Power.StartPowerUpResponse e)
        {
            _started = true;

            InvokeUI(() =>
            {
                if (_powerUpAppBar != null)
                {
                    _powerUpAppBar.Close();
                }

                if (_started)
                {
                    _powerUpAppBar = NotificationProvider.PushAppBarItem<PowerUpAppBarItem>();
                    _powerUpAppBar.Priority = AppBarPriority.Low;
                }
            });
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Handles the Tick event of the _date_timer.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void _date_timer_Tick(object sender, EventArgs e)
        {
            CurrentDateTime = DateTime.Now;
        }

        private void MachineOperator_CartridgeValidationRequestReceived(object sender, CartridgeValidationEventArgs e)
        {
            InvokeUI(async () =>
            {
                var vm = await NotificationProvider.ShowDialog<CartridgeValidationViewVM>(new CartridgeValidationViewVM()
                {
                    IDSPacks = MachineProvider.Machine.Configuration.NoneEmptyIdsPacks.ToList(),
                });

                if (vm.DialogResult)
                {
                    e.Approve(vm.SelectedIDSPack.PackIndex);
                }
                else
                {
                    e.Decline();
                }
            });
        }

        private async void MachineOperator_FirmwareStarted(object sender, EventArgs e)
        {
            if (_isPowerUpDialogShown)
            {
                LogManager.Log("Power up detected but power up dialog is already shown. Skipping...");
                return;
            }

            LogManager.Log("Power up detected, showing power up screen...");

            if (!Settings.DisplayPowerUpScreen)
            {
                LogManager.Log("Power up screen disabled. skipping...");
                return;
            }

            PowerUpViewVM vm;

            try
            {
                LogManager.Log("Loading site rmls...");

                List<Rml> rmls = new List<Rml>();

                using (ObservablesContext db = ObservablesContext.CreateDefault())
                {
                    rmls = (await new RmlsCollectionBuilder(db).SetAll().ForHeadType(MachineProvider.Machine.MachineHeadType).ForSite(MachineProvider.Machine.SiteGuid).BuildListAsync()).OrderBy(x => x.FinalName).ToList();
                }

                var selectedRml = rmls.SingleOrDefault(x => x.Guid == Settings.LoadedRmlGuid);

                vm = new PowerUpViewVM();
                vm.Rmls = rmls;
                vm.SelectedRml = selectedRml != null ? selectedRml : rmls.FirstOrDefault();
                vm.IsSelectedRml = selectedRml != null;
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error initializing power up screen.");
                return;
            }

            InvokeUI(async () =>
            {
                _isPowerUpDialogShown = true;
                await NotificationProvider.ShowDialog<PowerUpViewVM>(vm);
                _isPowerUpDialogShown = false;

                await Task.Factory.StartNew(() =>
                {
                    LogManager.Log("Power up screen closed.");

                    try
                    {
                        using (ObservablesContext db = ObservablesContext.CreateDefault())
                        {
                            List<ProcessParametersTable> processTables = new List<ProcessParametersTable>();

                            if (vm.IsSelectedRml)
                            {
                                LogManager.Log($"Selected rml '{vm.SelectedRml.Name}'...");
                                processTables = new RmlBuilder(db).Set(vm.SelectedRml.Guid).WithActiveParametersGroup().Build().GetActiveProcessGroup().ProcessParametersTables.ToList();
                            }
                            else
                            {
                                LogManager.Log("Selected minimal temperature...");
                                var rmlsToAvg = new RmlsCollectionBuilder(db).SetAll().ForHeadType(MachineProvider.Machine.MachineHeadType).ForSite(MachineProvider.Machine.SiteGuid).WithActiveParametersGroup().Build();
                                processTables = rmlsToAvg.Select(x => x.GetActiveProcessGroup()).SelectMany(x => x.ProcessParametersTables).ToList();
                            }

                            var processToLoad = processTables.OrderBy(x => x.GetAverageTemperature()).First();

                            LogManager.Log($"Selected process parameters:\nRML: {processToLoad.ProcessParametersTablesGroup.Rml.Name}\nGroup: {processToLoad.ProcessParametersTablesGroup.Name}\nProcess Table: {processToLoad.Name}");
                            LogManager.Log("Uploading process parameters...");
                            var r = MachineProvider.MachineOperator.UploadProcessParameters(processToLoad).Result;

                            Settings.LoadedRmlGuid = vm.IsSelectedRml ? vm.SelectedRml.Guid : null;
                            Settings.Save();
                        }
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, "Error occurred while trying to get and upload the proper process parameters after power screen closed.");
                    }
                });
            });
        }

        private void MachineOperator_ThreadLoadingStatusChanged(object sender, PMR.ThreadLoading.StartThreadLoadingResponse e)
        {
            //if (e.State == PMR.ThreadLoading.ThreadLoadingState.Preparing)
            //{
            //    DisplayThreadLoading();
            //}
        }

        private void MachineOperator_ThreadLoadingConfirmationRequired(object sender, ThreadLoadingConfirmationRequiredEventArgs e)
        {
//            DisplayThreadLoading(e);
        }
        #endregion

        #region Head Type Check

        private void MachineProvider_MachineConnected(object sender, EventArgs e)
        {
            ResetScreenSaverTimer();

            NotificationProvider.PopNotification(_headTypeNotification);

            if (MachineProvider.MachineOperator.DeviceInformation != null && !MachineProvider.Machine.IsDemo)
            {
                if (MachineProvider.Machine.HeadType != (int)MachineProvider.MachineOperator.DeviceInformation.HeadType)
                {
                    _headTypeNotification.ExpandedMessage = $"Machine configuration reports head type '{MachineProvider.Machine.MachineHeadType}' while firmware device reports '{MachineProvider.MachineOperator.DeviceInformation.HeadType}'.";
                    NotificationProvider.PushNotification(_headTypeNotification);
                }
            }
        }

        #endregion

        #region Screen Saver

        public void ResetScreenSaverTimer()
        {
            _screenSaverTimer.Stop();
            _screenSaverTimer.Start();
            IsScreenSaverOn = false;
        }

        private void _screenSaverTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            _screenSaverTimer.Interval = TimeSpan.FromMinutes(Settings.ScreenSaverStartDuration).TotalMilliseconds;

            if (Settings.EnableScreenSaver && !MachineProvider.IsConnected)
            {
                IsScreenSaverOn = true;
            }
        }
        
        #endregion
    }
}
href='#n2046'>2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467
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;
using Tango.Integration.Emergency;
using Tango.PMR.MachineStatus;
using Newtonsoft.Json;
using Tango.PMR.Integration;
using System.Globalization;
using Tango.PMR.Power;
using Tango.PMR.ThreadLoading;
using Tango.BL.DTO;
using Tango.PMR.IFS;
using System.Runtime.CompilerServices;

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";

        public const int MAX_DISPENSER_NANOLITER = 130000000;
        public const double MAX_MIDTANK_LITERS = 1.8;
        public const double EMPTY_MIDTANK_LITERS = 0.2;
        public const double LOW_MIDTANK_LITERS = 0.3;
        public const double OVERALL_TEMPERATURE_OK = 35;
        public const double OVERALL_TEMPERATURE_WARNING = 35;
        public const double OVERALL_TEMPERATURE_ERROR = 40;

        private bool _diagnosticsSent;
        private bool _eventsSent;
        private bool _debugSent;
        private bool _machineStatusSent;
        private bool _inkFillingStatusSent;
        private bool _threadLoadingSent;
        private static RunningJobStatus _last_job_status;
        private bool _isPowerDownRequestInProgress;
        private bool _isHeadCleaningInProgress;
        private List<BL.ValueObjects.JobRunLiquidQuantity> _lastJobLiquidQuantities;
        private DateTime _diagnosticsTime;
        private MachineStatus _machineStatusBeforeJobStart;
        private Configuration _machineConfiguration;

        private DateTime _jobStartDate;
        private DateTime? _jobUploadingStartDate;
        private DateTime? _jobHeatingStartDate;
        private DateTime? _jobActualStartDate;
        private List<Event> _emulatedEvents;
        private List<BitResultComposition> _bitResults;
        private JobSpoolType _currentSpoolType;

        public static String EmbeddedLogsFolder { get; private set; }
        public static String EmbeddedLogsTag { get; private set; }
        public static SessionFileLogger SessionLogger { get; set; }
        public static String CachedJobOperationFile { get; set; }

        #region Classes

        private class RequiredLiquid
        {
            public IdsPack IdsPack { get; set; }
            public int Quantity { get; set; }
        }

        #endregion

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

            if (SessionLogger == null)
            {
                SessionLogger = new SessionFileLogger();
                LogManager.Default.RegisterLogger(SessionLogger);
            }


            CachedJobOperationFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Twine", "Tango", "Job Resume", Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.FriendlyName), "CachedJobOperation.cache");
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="MachineOperator"/> class.
        /// </summary>
        public MachineOperator() : base()
        {
            _bitResults = new List<BitResultComposition>();
            _emulatedEvents = new List<Event>();
            ComponentName = $"Machine Operator {_component_counter++}";
            DeviceInformation = new DeviceInformation();
            MachineEventsStateProvider = new DefaultMachineEventsStateProvider();
            JobRunsLogger = new BasicJobRunsLogger(this);
            JobRunsLogger.Start();
            EnableEventsNotification = true;
            EnableMachineStatusUpdates = true;
            EnableInkFillingStatus = true;
            EnableJobResume = true;
            LogEmbeddedDebuggingToFile = true;
            FirmwareUpgradeMode = FirmwareUpgradeModes.DFU | FirmwareUpgradeModes.TFP_PACKAGE;
            GradientGenerationConfiguration = new DefaultGradientGenerationConfiguration();
            EmergencyNotificationProvider = new UsbEmergencyNotificationProvider("COM1");
            EnableJobLiquidQuantityValidation = true;
            FailsWithAdapter = true;
            IsSpoolReplaced = true;
            ContinuousRequestTimeout = TimeSpan.FromSeconds(2);
            ResetInkFllingStatus();
        }

        /// <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 machine embedded device status has changed.
        /// </summary>
        public event EventHandler<MachineStatus> MachineStatusChanged;

        /// <summary>
        /// Occurs when a new cartridge validation request has been received.
        /// </summary>
        public event EventHandler<CartridgeValidationEventArgs> CartridgeValidationRequestReceived;

        /// <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;

        /// <summary>
        /// Occurs when the machine was connected and device has reported IsAfterReset.
        /// </summary>
        public event EventHandler FirmwareStarted;

        /// <summary>
        /// Occurs when power down has started.
        /// </summary>
        public event EventHandler<PowerDownStartedEventArgs> PowerDownStarted;

        /// <summary>
        /// Occurs when the thread loading status has changed.
        /// </summary>
        public event EventHandler<StartThreadLoadingResponse> ThreadLoadingStatusChanged;

        /// <summary>
        /// Occurs when a thread loading confirmation is required.
        /// </summary>
        public event EventHandler<ThreadLoadingConfirmationRequiredEventArgs> ThreadLoadingConfirmationRequired;

        /// <summary>
        /// Occurs when thread loading has completed.
        /// </summary>
        public event EventHandler<StartThreadLoadingResponse> ThreadLoadingCompleted;

        /// <summary>
        /// Occurs when thread loading has failed.
        /// </summary>
        public event EventHandler<StartThreadLoadingResponse> ThreadLoadingFailed;

        /// <summary>
        /// Occurs when the power up sequence has started.
        /// </summary>
        public event EventHandler<StartPowerUpResponse> PowerUpStarted;

        /// <summary>
        /// Occurs when the power up sequence progress has changed.
        /// </summary>
        public event EventHandler<StartPowerUpResponse> PowerUpProgress;

        /// <summary>
        /// Occurs when power up sequence has completed successfully.
        /// </summary>
        public event EventHandler<StartPowerUpResponse> PowerUpCompleted;

        /// <summary>
        /// Occurs when power up sequence has failed.
        /// </summary>
        public event EventHandler<StartPowerUpResponse> PowerUpFailed;

        /// <summary>
        /// Occurs when power up sequence has ended. Could be due to no response to the request!
        /// </summary>
        public event EventHandler PowerUpEnded;

        /// <summary>
        /// Occurs when a head cleaning job has ended.
        /// </summary>
        public event EventHandler<HeadCleaningEndedEventArgs> HeadCleaningEnded;

        /// <summary>
        /// Occurs when the ink filling status has changed.
        /// </summary>
        public event EventHandler<InkFillingStatusChangedEventArgs> InkFillingStatusChanged;

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets a value indicating whether to create a new designated session log file each successful connection.
        /// This log file will contain standard logs that have occurred between the last connection and disconnection states.
        /// </summary>
        public static bool EnableSessionLogFile
        {
            get { return SessionLogger.Enabled; }
            set
            {
                SessionLogger.Enabled = value;
            }
        }

        /// <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; }

        /// <summary>
        /// Gets or sets the job number of units duplication method.
        /// </summary>
        public JobUnitsMethods JobUnitsMethod { get; set; }

        /// <summary>
        /// Gets or sets the way of calculating how much liquid was spent during the job.
        /// </summary>
        public JobLiquidQuantityCalculationMode JobLiquidQuantityCalculationMode { 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();
                    OnStatusChanged(value);
                    RaisePropertyChanged(nameof(IsPrinting));
                    RaisePropertyChanged(nameof(CanPrint));
                    RaisePropertyChanged(nameof(IsConnected));
                }
            }
        }

        /// <summary>
        /// Gets a value indicating whether the machine is connected and status is not disconnected.
        /// </summary>
        public bool IsConnected
        {
            get { return State == TransportComponentState.Connected && Status != MachineStatuses.Disconnected; }
        }

        private MachineStatus _machineStatus;
        /// <summary>
        /// Gets the machine embedded device status.
        /// </summary>
        public MachineStatus MachineStatus
        {
            get { return _machineStatus; }
            private set { _machineStatus = value; RaisePropertyChangedAuto(); }
        }

        private InkFillingStatus _inkFillingStatus;
        /// <summary>
        /// Gets or sets the ink filling status.
        /// </summary>
        public InkFillingStatus InkFillingStatus
        {
            get { return _inkFillingStatus; }
            private set { _inkFillingStatus = value; RaisePropertyChangedAuto(); }
        }

        private StartThreadLoadingResponse _threadLoadingStatus;
        /// <summary>
        /// Gets the current thread loading status.
        /// </summary>
        public StartThreadLoadingResponse ThreadLoadingStatus
        {
            get { return _threadLoadingStatus; }
            private set { _threadLoadingStatus = value; RaisePropertyChangedAuto(); }
        }

        /// <summary>
        /// Gets or sets a value indicating whether to enable liquid quantity validation before starting the job.
        /// The validation is done using the reported <see cref="MachineStatus" />.
        /// </summary>
        public bool EnableJobLiquidQuantityValidation { get; set; }

        /// <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 || Status == MachineStatuses.PowerUp || Status == MachineStatuses.Standby;
            }
        }

        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 _enableMachineStatusUpdates;
        /// <summary>
        /// Gets or sets a value indicating whether to direct the embedded device to update about status changes.
        /// </summary>
        public bool EnableMachineStatusUpdates
        {
            get { return _enableMachineStatusUpdates; }
            set
            {
                if (_enableMachineStatusUpdates != value)
                {
                    _enableMachineStatusUpdates = value;
                    RaisePropertyChangedAuto();
                    OnEnableMachineStatusUpdatesChanged(value);
                }
            }
        }

        private bool _enableInkFillingStatus;
        public bool EnableInkFillingStatus
        {
            get { return _enableInkFillingStatus; }
            set
            {
                if (_enableInkFillingStatus != value)
                {
                    _enableInkFillingStatus = value;
                    RaisePropertyChangedAuto();
                    OnEnableInkFillingStatus(value);
                }
            }
        }

        private bool _enableAutomaticThreadLoading;
        /// <summary>
        /// Gets or sets a value indicating whether to enable automatic thread loading support.
        /// </summary>
        public bool EnableAutomaticThreadLoading
        {
            get { return _enableAutomaticThreadLoading; }
            set
            {
                _enableAutomaticThreadLoading = value;
                RaisePropertyChangedAuto();
                OnEnableAutomaticThreadLoadingChanged(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();
            }
        }

        private bool _enablePowerUpSequence;
        /// <summary>
        /// Gets or sets a value indicating whether to enable the power sequence tracking.
        /// </summary>
        public bool EnablePowerUpSequence
        {
            get { return _enablePowerUpSequence; }
            set { _enablePowerUpSequence = 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(); }
        }

        /// <summary>
        /// Gets or sets the emergency notification provider.
        /// </summary>
        public IEmergencyNotificationProvider EmergencyNotificationProvider { get; set; }

        /// <summary>
        /// Gets or sets the general continuous request timeout.
        /// </summary>
        public TimeSpan ContinuousRequestTimeout { get; set; }

        /// <summary>
        /// Gets a value indicating whether the spool was replaced after the last job.
        /// </summary>
        public bool IsSpoolReplaced { get; private set; }

        #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;

                LogManager.Log($"Sending '{nameof(StartDiagnosticsRequest)}'...");

                SendContinuousRequest<StartDiagnosticsRequest, StartDiagnosticsResponse>(request, new TransportContinuousRequestConfig() { ShouldLog = false }).ObserveOn(new NewThreadScheduler()).Subscribe(
                    (response) =>
                    {
                        if (!responseLogged)
                        {
                            _diagnosticsTime = DateTime.Now;
                            responseLogged = true;
                        }
                        else
                        {
                            _diagnosticsTime = _diagnosticsTime.Add(TimeSpan.FromMilliseconds(response.Message.ElapsedMilli));
                        }

                        response.Message.DateTime = _diagnosticsTime.ToString("MM/dd/yyyy HH:mm:ss.fff");

                        OnDiagnosticsDataAvailable(response);
                    },
                    (ex) =>
                    {
                        _diagnosticsSent = false;
                    },
                    () =>
                    {
                        _diagnosticsSent = false;
                        LogManager.Log("Diagnostics response completed!?", LogCategory.Warning);
                    });
            }
            else if (_diagnosticsSent)
            {
                _diagnosticsSent = false;

                if (State == TransportComponentState.Connected)
                {
                    var req = new StopDiagnosticsRequest();

                    try
                    {
                        var res = await SendRequest<StopDiagnosticsRequest, StopDiagnosticsResponse>(req, new TransportRequestConfig() { ShouldLog = true });
                    }
                    catch { }
                }
            }
        }

        /// <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, new TransportContinuousRequestConfig() { ShouldLog = true }).ObserveOn(new NewThreadScheduler()).Subscribe(
                    (response) =>
                    {
                        OnEventsNotification(response);

                        if (!responseLogged)
                        {
                            responseLogged = true;
                        }
                    },
                    (ex) =>
                    {
                        _eventsSent = false;
                    },
                    () =>
                    {
                        _eventsSent = false;
                        LogManager.Log("Events Notification response completed!?", LogCategory.Warning);
                    });
            }
            else if (_eventsSent)
            {
                _eventsSent = false;

                if (State == TransportComponentState.Connected)
                {
                    var req = new StopEventsNotificationRequest();

                    try
                    {
                        var res = await SendRequest<StopEventsNotificationRequest, StopEventsNotificationResponse>(req, new TransportRequestConfig() { ShouldLog = true });
                    }
                    catch { }
                }
            }
        }

        /// <summary>
        /// Called when the enable embedded debugging has been changed
        /// </summary>
        /// <param name="value">if set to <c>true</c> [value].</param>
        protected virtual async void OnEnableEmbeddedDebuggingChanged(bool value)
        {
            if (value && State == TransportComponentState.Connected && !_debugSent)
            {
                var request = new StartDebugLogRequest();

                bool responseLogged = false;
                _debugSent = true;

                SendContinuousRequest<StartDebugLogRequest, StartDebugLogResponse>(request, new TransportContinuousRequestConfig() { ShouldLog = true }).ObserveOn(new NewThreadScheduler())
                    .Subscribe
                    (
                    (response) =>
                    {
                        if (!responseLogged)
                        {
                            responseLogged = true;
                        }

                        OnDebugLogAvailable(response);
                    },
                    (ex) =>
                    {
                        _debugSent = false;
                    },
                    () =>
                    {
                        _debugSent = false;
                    });
            }
            else if (_debugSent)
            {
                _debugSent = false;

                if (State == TransportComponentState.Connected)
                {
                    var req = new StopDebugLogRequest();

                    try
                    {
                        var res = await SendRequest<StopDebugLogRequest, StopDebugLogResponse>(req, new TransportRequestConfig() { ShouldLog = true });
                    }
                    catch { }
                }
            }
        }

        /// <summary>
        /// Called when the enable machine status updates has been changed.
        /// </summary>
        /// <param name="value">if set to <c>true</c> [value].</param>
        protected virtual async void OnEnableMachineStatusUpdatesChanged(bool value)
        {
            if (value && State == TransportComponentState.Connected && !_machineStatusSent)
            {
                var request = new StartMachineStatusUpdateRequest();

                bool responseLogged = false;
                _machineStatusSent = true;

                SendContinuousRequest<StartMachineStatusUpdateRequest, StartMachineStatusUpdateResponse>(request, new TransportContinuousRequestConfig() { ShouldLog = true }).ObserveOn(new NewThreadScheduler()).Subscribe(
                    (response) =>
                    {
                        OnMachineStatusChanged(response);

                        if (!responseLogged)
                        {
                            responseLogged = true;
                        }
                    },
                    (ex) =>
                    {
                        _machineStatusSent = false;
                    },
                    () =>
                    {
                        _machineStatusSent = false;
                        LogManager.Log("Machine status update response completed!?", LogCategory.Warning);
                    });
            }
            else if (_machineStatusSent)
            {
                _machineStatusSent = false;

                if (State == TransportComponentState.Connected)
                {
                    var req = new StopMachineStatusUpdateRequest();

                    try
                    {
                        var res = await SendRequest<StopMachineStatusUpdateRequest, StopMachineStatusUpdateResponse>(req, new TransportRequestConfig() { ShouldLog = true });
                    }
                    catch { }
                }
            }
        }

        /// <summary>
        /// Called when the enable ink filling status has been changed.
        /// </summary>
        /// <param name="value">if set to <c>true</c> [value].</param>
        protected virtual void OnEnableInkFillingStatus(bool value)
        {
            if (value && State == TransportComponentState.Connected && !_inkFillingStatusSent)
            {
                var request = new StartInkFillingStatusRequest();

                bool responseLogged = false;
                _inkFillingStatusSent = true;

                SendContinuousRequest<StartInkFillingStatusRequest, StartInkFillingStatusResponse>(request, new TransportContinuousRequestConfig() { ShouldLog = true }).ObserveOn(new NewThreadScheduler()).Subscribe(
                    (response) =>
                    {
                        OnInkFillingStatusChanged(response);

                        if (!responseLogged)
                        {
                            responseLogged = true;
                        }
                    },
                    (ex) =>
                    {
                        _inkFillingStatusSent = false;
                    },
                    () =>
                    {
                        _inkFillingStatusSent = false;
                        LogManager.Log("Ink filling status response completed!?", LogCategory.Warning);
                    });
            }
            else if (_inkFillingStatusSent)
            {
                _inkFillingStatusSent = false;
            }
        }

        /// <summary>
        /// Called when the enable automatic thread loading has been changed
        /// </summary>
        /// <param name="value">if set to <c>true</c> [value].</param>
        protected virtual async void OnEnableAutomaticThreadLoadingChanged(bool value)
        {
            if (value && State == TransportComponentState.Connected && !_threadLoadingSent)
            {
                var request = new StartThreadLoadingRequest();

                bool responseLogged = false;
                _threadLoadingSent = true;

                SendContinuousRequest<StartThreadLoadingRequest, StartThreadLoadingResponse>(request, new TransportContinuousRequestConfig() { ShouldLog = true }).ObserveOn(new NewThreadScheduler()).Subscribe(
                    (response) =>
                    {
                        OnThreadLoadingStatusChanged(response);

                        if (!responseLogged)
                        {
                            responseLogged = true;
                        }
                    },
                    (ex) =>
                    {
                        _threadLoadingSent = false;
                    },
                    () =>
                    {
                        _threadLoadingSent = false;
                        LogManager.Log("Thread loading response completed!?", LogCategory.Warning);
                    });
            }
            else if (_threadLoadingSent)
            {
                _threadLoadingSent = false;

                if (State == TransportComponentState.Connected)
                {
                    var req = new StopThreadLoadingRequest();

                    try
                    {
                        var res = await SendRequest<StopThreadLoadingRequest, StopThreadLoadingResponse>(req, new TransportRequestConfig() { ShouldLog = true });
                    }
                    catch { }
                }
            }
        }

        /// <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)
            {
                var events = response.Events;

                foreach (var emulated in _emulatedEvents)
                {
                    if (!events.Any(x => x.Type == emulated.Type))
                    {
                        events.Add(emulated);
                    }
                }

                MachineEventsStateProvider.ApplyEvents(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 (LogEmbeddedDebuggingToFile && EmbeddedLogManager != null)
            {
                EmbeddedLogManager.Log(new EmbeddedLogItem(data));
            }

            DebugLogAvailable?.Invoke(this, data);
        }

        /// <summary>
        /// Called when the machine status has been updated.
        /// </summary>
        /// <param name="response">The response.</param>
        protected virtual void OnMachineStatusChanged(StartMachineStatusUpdateResponse response)
        {
            if (response.Status == null) return;

            bool changed = (MachineStatus == null || response.Status.State != MachineStatus.State);

            MachineStatus = response.Status;
            MachineStatusChanged?.Invoke(this, MachineStatus);

            if (changed)
            {
                OnMachineStateChanged(MachineStatus.State);
            }

            if (MachineStatus.SpoolState == SpoolState.Absent)
            {
                IsSpoolReplaced = true;
            }
        }

        /// <summary>
        /// Called when ink filling status has been changed.
        /// </summary>
        /// <param name="response">The response.</param>
        protected virtual void OnInkFillingStatusChanged(StartInkFillingStatusResponse response)
        {
            if (response.Status == null || response.Status.CartridgesStatuses == null || response.Status.CartridgesStatuses.Count == 0) return;

            int index = -1;
            bool raiseChange = false;

            foreach (var remoteCartridge in response.Status.CartridgesStatuses)
            {
                index++;

                if (remoteCartridge.Cartridge == null)
                {
                    LogManager.Log($"Remote cartridge arrived with null cartridge at position [{index}] and will be ignored.", LogCategory.Error);
                    continue;
                }

                var localCartridge = InkFillingStatus.CartridgesStatuses.SingleOrDefault(x => x.Cartridge.Index == remoteCartridge.Cartridge.Index && x.Cartridge.Slot == remoteCartridge.Cartridge.Slot);

                if (localCartridge != null)
                {
                    if (localCartridge.State != remoteCartridge.State)
                    {
                        localCartridge.State = remoteCartridge.State;
                        LogManager.Log($"{localCartridge.Cartridge.Slot} Cartridge '{localCartridge.Cartridge.Index}' state changed: '{localCartridge.State}' => '{remoteCartridge.State}'.");
                    }

                    if (remoteCartridge.Cartridge.Tag != null)
                    {
                        LogManager.Log($"{localCartridge.Cartridge.Slot} Cartridge '{localCartridge.Cartridge.Index}' Tag arrived:\n{remoteCartridge.Cartridge.Tag.ToJsonString()}");
                    }

                    localCartridge.Message = remoteCartridge.Message;
                    localCartridge.ProgressPercentage = remoteCartridge.ProgressPercentage;

                    raiseChange = true;
                }
                else
                {
                    LogManager.Log($"Could not locate local cartridge with slot '{remoteCartridge.Cartridge.Slot}' and index '{remoteCartridge.Cartridge.Index}'.", LogCategory.Error);
                }
            }

            if (raiseChange)
            {
                RaisePropertyChanged(nameof(InkFillingStatus));
                InkFillingStatusChanged?.Invoke(this, new InkFillingStatusChangedEventArgs() { Status = InkFillingStatus });
            }
        }

        /// <summary>
        /// Called when the machine state has been changed.
        /// </summary>
        /// <param name="state">The state.</param>
        protected async virtual void OnMachineStateChanged(MachineState state)
        {
            LogManager.Log($"Machine State Changed: {state}.");

            if (IsPrinting)
            {
                LogManager.Log($"Machine state change will not affect the machine operator status as it is now in a '{Status}' status.", LogCategory.Warning);
                return;
            }

            switch (state)
            {
                case MachineState.PowerUp:
                    UpdateStatus(MachineStatuses.PowerUp);
                    break;
                //case MachineState.PreparingJob:
                //    Status = MachineStatuses.GettingReady;
                //    break;
                case MachineState.Ready:
                    UpdateStatus(MachineStatuses.ReadyToDye);
                    break;
                case MachineState.Sleep:
                    UpdateStatus(MachineStatuses.Standby);
                    break;
                case MachineState.PowerOff:
                    UpdateStatus(MachineStatuses.ShuttingDown);
                    if (!_isPowerDownRequestInProgress)
                    {
                        try
                        {
                            await PowerDown();
                        }
                        catch { }
                    }
                    break;
                case MachineState.Error:
                    //Status = MachineStatuses.Error;
                    break;
            }
        }

        /// <summary>
        /// Called when the thread loading status has been changed.
        /// </summary>
        /// <param name="response">The response.</param>
        protected virtual void OnThreadLoadingStatusChanged(StartThreadLoadingResponse response)
        {
            bool changed = (ThreadLoadingStatus == null || response.State != ThreadLoadingStatus.State || response.ErrorReason != ThreadLoadingStatus.ErrorReason);

            if (changed)
            {
                ThreadLoadingStatus = response;
                ThreadLoadingStatusChanged?.Invoke(this, response);

                LogManager.Log($"Thread Loading Status Changed: {ThreadLoadingStatus.State}.");

                switch (ThreadLoadingStatus.State)
                {
                    case ThreadLoadingState.ReadyForLoading:

                        LogManager.Log("Thread loading is ready for loading. Invoking confirmation event...");

                        ThreadLoadingConfirmationRequired?.Invoke(this, new ThreadLoadingConfirmationRequiredEventArgs((processTable) =>
                        {
                            //Confirm Action
                            try
                            {
                                var process = processTable.ToProcessParametersPMR();
                                LogManager.Log($"Thread loading confirmation received with process parameters:\n{process.ToJsonString()}");
                                LogManager.Log("Sending continue thread loading request...");
                                var r = SendRequest<ContinueThreadLoadingRequest, ContinueThreadLoadingResponse>(new ContinueThreadLoadingRequest()
                                {
                                    ProcessParameters = process,
                                }, new TransportRequestConfig() { ShouldLog = true }).Result;
                            }
                            catch (Exception ex)
                            {
                                LogManager.Log(ex, "Error confirming thread loading sequence.");
                            }
                        })
                        {
                            Status = ThreadLoadingStatus,
                        });
                        break;
                    case ThreadLoadingState.Completed:
                        ThreadLoadingCompleted?.Invoke(this, ThreadLoadingStatus);
                        break;
                    case ThreadLoadingState.FinalizationError:
                    case ThreadLoadingState.PreparationError:
                        ThreadLoadingFailed?.Invoke(this, ThreadLoadingStatus);
                        break;
                }
            }
        }

        /// <summary>
        /// Called when a new request has been received.
        /// </summary>
        /// <param name="container">The request.</param>
        protected override void OnRequestReceived(RequestReceivedEventArgs e)
        {
            base.OnRequestReceived(e);

            if (e.Handled) return;

            var container = e.Container;

            if (container.Type == MessageType.CartridgeValidationRequest)
            {
                e.Handled = true;
                OnCartridgeValidationRequestReceived(container.Token, MessageFactory.ExtractMessageFromContainer<CartridgeValidationRequest>(container));
            }
            else if (container.Type == MessageType.UpdateStatusRequest)
            {
                e.Handled = true;
                OnUpdateStatusRequestReceived(container.Token, MessageFactory.ExtractMessageFromContainer<UpdateStatusRequest>(container));
            }
        }

        /// <summary>
        /// Called when the machine status has been changed
        /// </summary>
        /// <param name="status">The status.</param>
        protected virtual void OnStatusChanged(MachineStatuses status)
        {
            StatusChanged?.Invoke(this, status);
        }

        /// <summary>
        /// Called when the cartridge validation request has been received.
        /// </summary>
        /// <param name="request">The request.</param>
        protected virtual void OnCartridgeValidationRequestReceived(String token, CartridgeValidationRequest request)
        {
            if (request.Action == CartridgeAction.Inserted)
            {
                CartridgeValidationEventArgs e = new CartridgeValidationEventArgs(request, (index) =>
                {
                    //Approve
                    SendResponse<CartridgeValidationResponse>(new CartridgeValidationResponse()
                    {
                        IsValid = true,
                        Index = index,
                    }, token).Wait();

                }, () =>
                {
                    //Decline
                    SendResponse<CartridgeValidationResponse>(new CartridgeValidationResponse()
                    {

                    }, token).Wait();

                });

                CartridgeValidationRequestReceived?.Invoke(this, e);
            }
        }

        /// <summary>
        /// Called when the update status request has been received.
        /// </summary>
        /// <param name="token">The token.</param>
        /// <param name="request">The update status request.</param>
        protected virtual void OnUpdateStatusRequestReceived(string token, UpdateStatusRequest request)
        {
            try
            {
                UpdateStatus((MachineStatuses)request.Status);
            }
            catch (Exception ex)
            {
                LogManager.Log(ex);
            }

            try
            {
                SendResponse<UpdateStatusResponse>(new UpdateStatusResponse(), token);
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error sending UpdateStatus response.");
            }
        }

        /// <summary>
        /// Called when the printing has been started.
        /// </summary>
        /// <param name="handler">The handler.</param>
        /// <param name="job">The job.</param>
        protected virtual void OnPrintingStarted(JobHandler handler, Job job, bool isResumed = false)
        {
            LogManager.Log("Raising printing started event...");

            PrintingStarted?.Invoke(this, new PrintingEventArgs(handler, job)
            {
                StartDate = _jobStartDate,
                IsResumed = isResumed
            });
        }

        /// <summary>
        /// Called when the printing has been completed.
        /// </summary>
        /// <param name="handler">The handler.</param>
        /// <param name="job">The job.</param>
        protected virtual void OnPrintingCompleted(JobHandler handler, Job job)
        {
            LogManager.Log("Raising printing completed event...");

            PrintingCompleted?.Invoke(this, new PrintingEventArgs(handler, job)
            {
                LiquidQuantities = _lastJobLiquidQuantities.ToList(),
                StartDate = _jobStartDate,
                UploadingStartTime = _jobUploadingStartDate,
                HeatingStartTime = _jobHeatingStartDate,
                ActualStartTime = _jobActualStartDate,
            });

            OnPrintingEnded(handler, job);
        }

        /// <summary>
        /// Called when the printing has been failed.
        /// </summary>
        /// <param name="handler">The handler.</param>
        /// <param name="job">The job.</param>
        /// <param name="exception">The exception.</param>
        protected virtual void OnPrintingFailed(JobHandler handler, Job job, Exception exception)
        {
            LogManager.Log("Raising printing failed event...");

            PrintingFailed?.Invoke(this, new PrintingFailedEventArgs(handler, job, exception)
            {
                LiquidQuantities = _lastJobLiquidQuantities.ToList(),
                StartDate = _jobStartDate,
                UploadingStartTime = _jobUploadingStartDate,
                HeatingStartTime = _jobHeatingStartDate,
                ActualStartTime = _jobActualStartDate,
            });
            OnPrintingEnded(handler, job);
        }

        /// <summary>
        /// Called when the printing has been aborted.
        /// </summary>
        /// <param name="handler">The handler.</param>
        /// <param name="job">The job.</param>
        protected virtual void OnPrintingAborted(JobHandler handler, Job job)
        {
            LogManager.Log("Raising printing aborted event...");

            PrintingAborted?.Invoke(this, new PrintingEventArgs(handler, job)
            {
                LiquidQuantities = _lastJobLiquidQuantities.ToList(),
                StartDate = _jobStartDate,
                UploadingStartTime = _jobUploadingStartDate,
                HeatingStartTime = _jobHeatingStartDate,
                ActualStartTime = _jobActualStartDate,
            });
            OnPrintingEnded(handler, job);
        }

        /// <summary>
        /// Called when the printing has been ended.
        /// </summary>
        /// <param name="handler">The handler.</param>
        /// <param name="job">The job.</param>
        protected virtual void OnPrintingEnded(JobHandler handler, Job job)
        {
            IsSpoolReplaced = false;

            LogManager.Log("Raising printing ended event...");

            PrintingEnded?.Invoke(this, new PrintingEventArgs(handler, job)
            {
                LiquidQuantities = _lastJobLiquidQuantities.ToList(),
                StartDate = _jobStartDate,
                UploadingStartTime = _jobUploadingStartDate,
                HeatingStartTime = _jobHeatingStartDate,
                ActualStartTime = _jobActualStartDate,
            });
        }

        protected virtual void OnHeadCleaningEnded(HeadCleaningHandler handler, JobRunStatus status)
        {
            SaveLastJobLiquidQuantities(null, null, null, null);

            HeadCleaningEnded?.Invoke(this, new HeadCleaningEndedEventArgs()
            {
                StartDate = _jobStartDate,
                Length = handler.Status.Total,
                EndPosition = handler.Status.Progress,
                Status = status,
                LiquidQuantities = _lastJobLiquidQuantities.ToList(),
            });
        }

        #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;
                _eventsSent = false;
                _machineStatusSent = false;

                if (Status != MachineStatuses.Disconnected)
                {
                    UpdateStatus(MachineStatuses.Disconnected);
                    ResetEvents();
                    ResetInkFllingStatus();
                }
            }
        }

        private void ResetEvents()
        {
            if (MachineEventsStateProvider != null)
            {
                LogManager.Log("Resetting active events...");
                _emulatedEvents.Clear();
                MachineEventsStateProvider.Reset();
            }
        }

        /// <summary>
        /// Disconnects the machine operator and the underlying transporter.
        /// </summary>
        /// <returns></returns>
        public async override Task Disconnect()
        {
            if (Status == MachineStatuses.Upgrading) return;

            UpdateStatus(MachineStatuses.Disconnected);

            if (MachineStatus != null)
            {
                MachineStatus.State = MachineState.Ready;
            }

            SessionLogger.EndSession();

            if (State == TransportComponentState.Connected)
            {
                DisconnectRequest request = new DisconnectRequest();

                try
                {
                    var response = await SendRequest<DisconnectRequest, DisconnectResponse>(request, new TransportRequestConfig() { ShouldLog = true });

                    UpdateStatus(MachineStatuses.Disconnected);
                }
                catch { }
            }

            ResetEvents();
            ResetInkFllingStatus();

            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",
                    UnixTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
                    SpoolType = _currentSpoolType
                };

                try
                {
                    var response = await SendRequest<ConnectRequest, ConnectResponse>(request, new TransportRequestConfig() { ShouldLog = true });

                    SessionLogger.CreateSession();

                    _isPowerDownRequestInProgress = false;

                    DeviceInformation = response.Message.DeviceInformation;

                    if (Status != MachineStatuses.Upgrading)
                    {
                        UpdateStatus(MachineStatuses.ReadyToDye);
                    }

                    _diagnosticsSent = false;
                    _eventsSent = false;
                    _debugSent = false;
                    _machineStatusSent = false;

                    _bitResults = null;

                    OnEnableDiagnosticsChanged(EnableDiagnostics);
                    OnEnableEmbeddedDebuggingChanged(EnableEmbeddedDebugging);
                    OnEnableEventsNotification(EnableEventsNotification);
                    OnEnableMachineStatusUpdatesChanged(EnableMachineStatusUpdates);
                    OnEnableAutomaticThreadLoadingChanged(EnableAutomaticThreadLoading);
                    OnEnableInkFillingStatus(EnableInkFillingStatus);

                    if (EnablePowerUpSequence)
                    {
                        TrackPowerUpSequence();
                    }

                    if (EnableJobResume)
                    {
                        ResumeJob();
                    }

                    if (response.Message.IsAfterReset)
                    {
                        FirmwareStarted?.Invoke(this, new EventArgs());
                    }
                }
                catch (Exception ex)
                {
                    SessionLogger.EndSession();
                    await base.Disconnect();
                    throw ex;
                }
                finally
                {
                    UseKeepAlive = keep_alive;
                }
            }
        }

        #endregion

        #region Private Methods

        private void UpdateStatus(MachineStatuses status, [CallerMemberName] string caller = null, [CallerFilePath] string file = null, [CallerLineNumber] int lineNumber = 0)
        {
            if (Status != status)
            {
                Status = status;
                LogManager.Log($"Machine operator status changed: {status}", caller, file, lineNumber);
            }
        }

        private void ResetInkFllingStatus()
        {
            if (InkFillingStatus == null)
            {
                var status = new InkFillingStatus();

                for (int i = 0; i < 8; i++)
                {
                    status.CartridgesStatuses.Add(new CartridgeStatus()
                    {
                        Cartridge = new Cartridge()
                        {
                            Index = i,
                            Slot = CartridgeSlot.Ink,
                        },
                        State = CartridgeState.Absent
                    });
                }

                status.CartridgesStatuses.Add(new CartridgeStatus()
                {
                    Cartridge = new Cartridge() { Index = 0, Slot = CartridgeSlot.WasteMiddle },
                    State = CartridgeState.Absent
                });

                status.CartridgesStatuses.Add(new CartridgeStatus()
                {
                    Cartridge = new Cartridge() { Index = 1, Slot = CartridgeSlot.WasteLower },
                    State = CartridgeState.Absent
                });

                InkFillingStatus = status;
            }
            else
            {
                foreach (var cartridge in InkFillingStatus.CartridgesStatuses)
                {
                    cartridge.ProgressPercentage = 0;
                    cartridge.Message = String.Empty;
                    cartridge.State = CartridgeState.Absent;
                }
            }

            InkFillingStatusChanged?.Invoke(this, new InkFillingStatusChangedEventArgs() { Status = InkFillingStatus });
        }

        private void SaveCachedJobOperation(Job job)
        {
            try
            {
                LogManager.Log("Caching current job operation...");
                CachedJobOperation cache = new CachedJobOperation();
                cache.JobDTO = JobDTO.FromObservable(job);
                cache.MachineStatus = MachineStatus;
                cache.ProcessParametersDTO = ProcessParametersTableDTO.FromObservable(CurrentProcessParameters);
                cache.MachineConfigurationDTO = ConfigurationDTO.FromObservable(job.Machine.Configuration);
                var json = JsonConvert.SerializeObject(cache);
                Directory.CreateDirectory(Path.GetDirectoryName(CachedJobOperationFile));
                File.WriteAllText(CachedJobOperationFile, json);
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error caching job operation for job resume.");
            }
        }

        private CachedJobOperation LoadCachedJobOperation()
        {
            try
            {
                LogManager.Log("Loading last cached job operation...");
                String json = File.ReadAllText(CachedJobOperationFile);
                CachedJobOperation cache = JsonConvert.DeserializeObject<CachedJobOperation>(json);
                return cache;
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error loading cache of last job operation for job resume.");
                return null;
            }
        }

        private void TrackPowerUpSequence()
        {
            LogManager.Log("Starting power up sequence tracking...");

            bool started = false;
            bool completed = false;
            PowerUpState lastState = PowerUpState.None;

            SendContinuousRequest<StartPowerUpRequest, StartPowerUpResponse>(new StartPowerUpRequest(), new TransportContinuousRequestConfig()
            {
                ShouldLog = true,
                Timeout = TimeSpan.FromSeconds(5)
            }).Subscribe((response) =>
            {
                if (!started)
                {
                    started = true;
                    PowerUpStarted?.Invoke(this, response);
                }

                PowerUpProgress?.Invoke(this, response);

                var state = response.Message.State;

                if (state != lastState)
                {
                    LogManager.Log($"Power up sequence state changed to '{state}'...");

                    switch (state)
                    {
                        case PowerUpState.Error:
                            completed = true;
                            LogManager.Log($"Power up sequence failed with state '{state}'. ({response.Message.Message})");
                            PowerUpFailed?.Invoke(this, response);
                            PowerUpEnded?.Invoke(this, new EventArgs());
                            break;
                        case PowerUpState.Cancelled:
                            completed = true;
                            LogManager.Log($"Power up sequence canceled with state '{state}'. ({response.Message.Message})");
                            PowerUpEnded?.Invoke(this, new EventArgs());
                            break;
                        case PowerUpState.MachineReadyToDye:
                            completed = true;
                            LogManager.Log($"Power up sequence completed successfully with state '{state}'. ({response.Message.Message})");
                            PowerUpCompleted?.Invoke(this, response);
                            PowerUpEnded?.Invoke(this, new EventArgs());
                            break;
                    }

                    lastState = state;
                }

            }, (ex) =>
            {
                if (!completed)
                {
                    completed = true;
                    LogManager.Log(ex, "Power up sequence tracking failed.");
                    PowerUpEnded?.Invoke(this, new EventArgs());
                }
            }, () =>
            {
                if (!completed)
                {
                    completed = true;
                    PowerUpEnded?.Invoke(this, new EventArgs());
                }
            });
        }

        private async void ResumeJob()
        {
            LogManager.Log("Checking if a job is in progress...");

            try
            {
                var res = await SendRequest<CurrentJobRequest, CurrentJobResponse>(new CurrentJobRequest(), new TransportRequestConfig() { ShouldLog = true });

                if (res.Message.IsJobInProgress)
                {
                    LogManager.Log("Job is in progress. Trying to resume job...");
                    CachedJobOperation cache = LoadCachedJobOperation();

                    if (cache == null)
                    {
                        LogManager.Log("Cannot resume current job with no cached operation.", LogCategory.Error);
                        return;
                    }

                    Job job = null;
                    Configuration configuration = null;
                    ProcessParametersTable processParameters = null;

                    try
                    {
                        processParameters = cache.ProcessParametersDTO.ToObservable();
                        job = cache.JobDTO.ToObservable();
                        configuration = cache.MachineConfigurationDTO.ToObservable();
                        CurrentProcessParameters = processParameters;
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, "Error deserializing cache job operation. Aborting resume.");
                        return;
                    }

                    JobTicket jobTicket = res.Message.JobTicket;

                    ResumingJobEventArgs args = new ResumingJobEventArgs(() =>
                    {
                        RunningJob = null;
                        RunningJobStatus = null;

                        var request = new ResumeCurrentJobRequest();

                        JobHandler handler = null;

                        handler = new JobHandler(async () =>
                        {
                            try
                            {
                                if (handler.CanCancel)
                                {
                                    handler.CanCancel = false;
                                    handler.IsCanceled = true;
                                    LogManager.Log("Aborting current job...");
                                    var result = await SendRequest<AbortJobRequest, AbortJobResponse>(new AbortJobRequest(), new TransportRequestConfig() { ShouldLog = true });
                                    SaveLastJobLiquidQuantities(job, configuration, processParameters, handler);
                                    OnPrintingAborted(handler, job);
                                    handler.RaiseCanceled();
                                    if (Status != MachineStatuses.Disconnected)
                                    {
                                        UpdateStatus(MachineStatuses.ReadyToDye);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                handler.CanCancel = true;
                                LogManager.Log(ex, "Failed to cancel job.");
                            }
                        }, job, jobTicket, processParameters, JobHandlingMode);

                        handler.StatusChanged += (x, s) =>
                        {
                            RunningJobStatus = s;
                        };

                        if (MachineStatus != null)
                        {
                            _machineStatusBeforeJobStart = MachineStatus.Clone();
                        }
                        else
                        {
                            _machineStatusBeforeJobStart = cache.MachineStatus.Clone();
                        }

                        _jobStartDate = DateTime.UtcNow;
                        _jobUploadingStartDate = _jobStartDate;
                        _jobHeatingStartDate = _jobStartDate;
                        _jobActualStartDate = null;

                        bool responseLogged = false;
                        bool completed = false;

                        Thread.Sleep(500); //Just wait maybe Shlomo is getting this message to fast after restart ?

                        SendContinuousRequest<ResumeCurrentJobRequest, ResumeCurrentJobResponse>(request, new TransportContinuousRequestConfig() { ContinuousTimeout = TimeSpan.FromSeconds(10), ShouldLog = true }).Subscribe((response) =>
                        {
                            if (!completed)
                            {
                                handler.RaiseStatusReceived(response.Message.Status);
                                _last_job_status = handler.Status;

                                if (response.Message.Status.Progress > 0)
                                {
                                    if (_jobActualStartDate == null)
                                    {
                                        _jobActualStartDate = DateTime.UtcNow;
                                    }
                                }

                                if (!responseLogged)
                                {
                                    UpdateStatus(MachineStatuses.GettingReady);
                                    responseLogged = true;
                                    RunningJob = job;
                                    OnPrintingStarted(handler, job, true);
                                }

                                if (JobHandlingMode == JobHandlerModes.SettingUp)
                                {
                                    if (response.Message.Status.Progress > CurrentProcessParameters.DryerBufferLengthMeters)
                                    {
                                        if (!completed)
                                        {
                                            UpdateStatus(MachineStatuses.Printing);
                                        }
                                    }
                                }
                                else
                                {
                                    if (response.Message.Status.Progress > 0)
                                    {
                                        if (!completed)
                                        {
                                            UpdateStatus(MachineStatuses.Printing);
                                        }
                                    }
                                }
                            }
                        }, (ex) =>
                        {
                            if (!completed)
                            {
                                completed = true;

                                if (Status != MachineStatuses.Disconnected)
                                {
                                    UpdateStatus(MachineStatuses.ReadyToDye);
                                }

                                if (!handler.IsCanceled)
                                {
                                    SaveLastJobLiquidQuantities(job, configuration, processParameters, handler);

                                    Exception finalException = ex;

                                    if (ex is ContinuousResponseAbortedException continuousException)
                                    {
                                        finalException = new ContinuousResponseAbortedException($"Job aborted by the embedded device ({continuousException.Container.ErrorMessage}).");
                                    }

                                    OnPrintingFailed(handler, job, finalException);
                                    handler.RaiseFailed(finalException);
                                }
                            }
                        }, () =>
                        {
                            if (!completed)
                            {
                                completed = true;
                                UpdateStatus(MachineStatuses.ReadyToDye);
                                SaveLastJobLiquidQuantities(job, configuration, processParameters, handler);
                                OnPrintingCompleted(handler, job);
                                handler.RaiseCompleted();
                            }
                        });

                        return handler;
                    });

                    args.JobGuid = jobTicket.Guid;
                    ResumingJob?.Invoke(this, args);
                }
            }
            catch (Exception ex)
            {
                LogManager.Log(ex);
            }
        }

        /// <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...");
                try
                {
                    stops = GradientGenerationConfiguration.Generate(segment, job, processParameters, (e) =>
                    {
                        PreparingJobProgress?.Invoke(this, e);
                    });
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException($"Error occurred while trying to generate a gradient.\n{ex.Message}");
                }
                LogManager.Log($"Gradient generated.");

                PreparingJobProgress?.Invoke(this, new PreparingJobProgressEventArgs()
                {
                    Job = job,
                    Total = job.Segments.Sum(x => x.Length),
                    Progress = job.Segments.Sum(x => x.Length),
                });
            }

            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;

            bool responseLogged = false;

            var previous_segments_length = job.Segments.Where(x => x.SegmentIndex < segment.SegmentIndex).Sum(x => x.Length);

            SendContinuousRequest<JobRequest, JobResponse>(request, new TransportContinuousRequestConfig() { ContinuousTimeout = ContinuousRequestTimeout, ShouldLog = true }).Subscribe((response) =>
            {
                response.Message.Status.Progress += previous_segments_length;

                handler.RaiseStatusReceived(response.Message.Status);

                if (!responseLogged && segment == job.OrderedSegments.First())
                {
                    responseLogged = true;
                    UpdateStatus(MachineStatuses.Printing);
                    RunningJob = handler.Job;
                    OnPrintingStarted(handler, handler.Job);
                }

            }, (ex) =>
            {
                if (!(ex is ContinuousResponseAbortedException))
                {
                    UpdateStatus(MachineStatuses.ReadyToDye);

                    if (!handler.IsCanceled)
                    {
                        OnPrintingFailed(handler, handler.Job, ex);
                        handler.RaiseFailed(ex);
                    }
                }
                else
                {
                    UpdateStatus(MachineStatuses.ReadyToDye);
                }
            }, () =>
            {
                if (segment == job.OrderedSegments.Last())
                {
                    UpdateStatus(MachineStatuses.ReadyToDye);
                    OnPrintingCompleted(handler, handler.Job);
                    handler.RaiseCompleted();
                }
                else
                {
                    handler.RaiseSpoolChangeRequired(() =>
                    {
                        ContinueSingleSpoolJob(segment.GetNextSegment(), job, processParameters, handler);
                    }, () =>
                    {
                        OnPrintingAborted(handler, handler.Job);
                        UpdateStatus(MachineStatuses.ReadyToDye);
                        handler.RaiseCanceled();
                    });
                }
            });
        }

        private List<RequiredLiquid> ValidateJobLiquidQuantity(Job job, ProcessParametersTable processParameters, Configuration configuration)
        {
            LogManager.Log("Validating job liquid quantities using integral...");

            Dictionary<int, double> liquidQuantities = new Dictionary<int, double>();
            List<RequiredLiquid> requiredLiquids = new List<RequiredLiquid>();

            foreach (var pack in configuration.NoneEmptyIdsPacks.OrderBy(x => x.PackIndex))
            {
                liquidQuantities.Add(pack.PackIndex, 0);
            }

            int resolution = GradientGenerationConfiguration.ResolutionCM;

            for (int i = 0; i < Math.Max(job.NumberOfUnits, 1); i++)
            {
                for (int segmentIndex = 0; segmentIndex < job.Segments.Count; segmentIndex++)
                {
                    var segment = job.Segments[segmentIndex];
                    var segment_length_cm = segment.Length * 100d;

                    List<BrushStop> orderedBrushCollection = segment.BrushStops.OrderBy(x => x.OffsetMeters).ToList();

                    int solid_gradient_oeff = orderedBrushCollection.Count == 1 ? 1 : 2;
                    double prev_offset_cm = 0;

                    for (int brushIndex = 0; brushIndex < orderedBrushCollection.Count; brushIndex++)
                    {
                        var brush = orderedBrushCollection[brushIndex];
                        double brush_length_centimeters = 0d;
                        double brush_offset_cm = 0;

                        if ((brushIndex + 1) < orderedBrushCollection.Count)
                        {
                            brush_offset_cm = (brush.OffsetMeters * 100d);
                            double next_brush_offset_cm = (orderedBrushCollection[brushIndex + 1].OffsetMeters * 100d);
                            brush_length_centimeters = ((next_brush_offset_cm - brush_offset_cm) + (brush_offset_cm - prev_offset_cm));

                            if (brushIndex == 0)
                            {
                                // add a resolution step for first brush
                                brush_length_centimeters += resolution;
                            }
                        }
                        else//last brush or solid brush
                        {
                            brush_length_centimeters = (segment_length_cm - prev_offset_cm);
                            if (orderedBrushCollection.Count > 1)
                            {
                                // add a resolution for last brush , not solid brush
                                brush_length_centimeters -= resolution;
                            }
                        }

                        prev_offset_cm = brush_offset_cm;

                        foreach (var liquidVolumes in brush.LiquidVolumes)
                        {
                            liquidQuantities[liquidVolumes.IdsPack.PackIndex] += liquidVolumes.NanoliterPerCentimeter * (brush_length_centimeters / solid_gradient_oeff);
                        }
                    }
                }
            }

            if (MachineStatus != null)
            {
                var exception = new InsufficientLiquidQuantityException($"Insufficient liquids level.");

                bool shouldThrow = false;

                foreach (var liquidQuantity in liquidQuantities)
                {
                    int index = liquidQuantity.Key;
                    var packLevel = MachineStatus.IDSPacksLevels.SingleOrDefault(x => x.Index == index);
                    var idsPack = configuration.NoneEmptyIdsPacks.SingleOrDefault(x => x.PackIndex == index);

                    if (packLevel != null)
                    {
                        var idsLevel = new InsufficientLiquidQuantityException.IDSPackLevel()
                        {
                            IdsPack = idsPack,
                            Current = packLevel.DispenserLevel,
                            Required = (int)liquidQuantities[index],
                            Maximum = MAX_DISPENSER_NANOLITER,
                        };

                        requiredLiquids.Add(new RequiredLiquid()
                        {
                            IdsPack = idsPack,
                            Quantity = (int)liquidQuantities[index]
                        });

                        LogManager.Log($"Required {idsLevel.IdsPack.LiquidType.Type}: {idsLevel.Required}, Current: {idsLevel.Current}");

                        if (idsLevel.Required > idsLevel.Current)
                        {
                            shouldThrow = true;
                            string display_value = (((double)(idsLevel.Required - idsLevel.Current) / 1000000)).ToString("N2", CultureInfo.InvariantCulture);
                            idsLevel.Message = $"Missing {display_value} CC to complete the job.";

                            if (idsLevel.Required > idsLevel.Maximum)
                            {
                                display_value = (((double)(idsLevel.Required - idsLevel.Maximum)) / 1000000).ToString("N2", CultureInfo.InvariantCulture);
                                idsLevel.Message = $"Required ink exceeds the maximum capacity of the dispenser by {display_value} CC. Please reduce the segment length.";
                            }
                        }

                        exception.IdsPackLevels.Add(idsLevel);
                    }
                    else
                    {
                        LogManager.Log($"Could not validate required liquid quantity for job. Missing IDS Pack level at index {index}.", LogCategory.Warning);
                    }
                }

                if (shouldThrow)
                {
                    LogManager.Log("Liquid quantity validation failed due to insufficient quantity. Throwing exception...");

                    exception.IdsPackLevels = exception.IdsPackLevels.OrderBy(x => x.IdsPack.PackIndex).ToList();

                    throw LogManager.Log(exception, JsonConvert.SerializeObject(exception.IdsPackLevels.Select(x => new
                    {
                        Liquid = x.IdsPack.LiquidType.Name,
                        x.Required,
                        x.Current
                    }).ToList()));
                }
            }
            else
            {
                LogManager.Log("Could not validate required liquid quantity for job. No machine status received", LogCategory.Warning);
            }

            return requiredLiquids;
        }

        private List<RequiredLiquid> ValidateJobLiquidQuantity(JobTicket ticket, ProcessParametersTable processParameters, Configuration configuration)
        {
            LogManager.Log("Validating job liquid quantity using job ticket...");

            Dictionary<int, double> liquidQuantities = new Dictionary<int, double>();
            List<RequiredLiquid> requiredLiquids = new List<RequiredLiquid>();

            foreach (var pack in configuration.NoneEmptyIdsPacks.OrderBy(x => x.PackIndex))
            {
                liquidQuantities.Add(pack.PackIndex, 0);
            }

            for (int segmentIndex = 0; segmentIndex < ticket.Segments.Count; segmentIndex++)
            {
                var segment = ticket.Segments[segmentIndex];
                var segment_length_cm = segment.Length * 100d;

                var stop_count = segment.BrushStops.Count - (segment.BrushStops.Count == 1 ? 0 : 1);
                var stop_length_centimeters = segment_length_cm / stop_count;

                for (int stopIndex = 0; stopIndex < stop_count; stopIndex++)
                {
                    var stop = segment.BrushStops[stopIndex];

                    foreach (var dispenser in stop.Dispensers)
                    {
                        liquidQuantities[dispenser.Index] += dispenser.NanoliterPerCentimeter * stop_length_centimeters;
                    }
                }
            }

            foreach (var key in liquidQuantities.Select(x => x.Key).ToList())
            {
                liquidQuantities[key] *= Math.Max(ticket.NumberOfUnits, 1);
            }

            if (MachineStatus != null)
            {
                var exception = new InsufficientLiquidQuantityException($"Insufficient liquids level.");

                bool shouldThrow = false;

                foreach (var liquidQuantity in liquidQuantities)
                {
                    int index = liquidQuantity.Key;
                    var packLevel = MachineStatus.IDSPacksLevels.SingleOrDefault(x => x.Index == index);
                    var idsPack = configuration.NoneEmptyIdsPacks.SingleOrDefault(x => x.PackIndex == index);

                    if (packLevel != null)
                    {
                        var idsLevel = new InsufficientLiquidQuantityException.IDSPackLevel()
                        {
                            IdsPack = idsPack,
                            Current = packLevel.DispenserLevel,
                            Required = (int)liquidQuantities[index],
                            Maximum = MAX_DISPENSER_NANOLITER,
                        };

                        requiredLiquids.Add(new RequiredLiquid()
                        {
                            IdsPack = idsPack,
                            Quantity = (int)liquidQuantities[index]
                        });

                        LogManager.Log($"Required {idsLevel.IdsPack.LiquidType.Type}: {idsLevel.Required}, Current: {idsLevel.Current}");

                        if (idsLevel.Required > idsLevel.Current)
                        {
                            shouldThrow = true;

                            string display_value = (((double)(idsLevel.Required - idsLevel.Current) / 1000000)).ToString("N2", CultureInfo.InvariantCulture);
                            idsLevel.Message = $"Missing {display_value} CC to complete the job.";

                            if (idsLevel.Required > idsLevel.Maximum)
                            {
                                display_value = (((double)(idsLevel.Required - idsLevel.Maximum)) / 1000000).ToString("N2", CultureInfo.InvariantCulture);
                                idsLevel.Message = $"Required ink exceeds the maximum capacity of the dispenser by {display_value} CC. Please reduce the segment length.";
                            }
                        }

                        exception.IdsPackLevels.Add(idsLevel);
                    }
                    else
                    {
                        LogManager.Log($"Could not validate required liquid quantity for job. Missing IDS Pack level at index {index}.", LogCategory.Warning);
                    }
                }


                if (shouldThrow)
                {
                    LogManager.Log("Liquid quantity validation failed due to insufficient quantity. Throwing exception...");

                    exception.IdsPackLevels = exception.IdsPackLevels.OrderBy(x => x.IdsPack.PackIndex).ToList();

                    throw LogManager.Log(exception, JsonConvert.SerializeObject(exception.IdsPackLevels.Select(x => new
                    {
                        Liquid = x.IdsPack.LiquidType.Name,
                        x.Required,
                        x.Current
                    }).ToList()));
                }
            }
            else
            {
                LogManager.Log("Could not validate required liquid quantity for job. No machine status received", LogCategory.Warning);
            }

            return requiredLiquids;
        }

        /// <summary>
        /// Assign the liquid quantities spent by the last job using the job and the handler last status.
        /// </summary>
        /// <param name="job">The job.</param>
        /// <param name="configuration">The configuration.</param>
        /// <param name="handler">The handler.</param>
        private void SaveLastJobLiquidQuantities(Job job, Configuration configuration, ProcessParametersTable processParameters, JobHandler handler)
        {
            LogManager.Log($"Calculating job run liquid quantities using '{JobLiquidQuantityCalculationMode}' method...");

            if (configuration == null)
            {
                configuration = _machineConfiguration;
            }

            try
            {
                _lastJobLiquidQuantities = new List<BL.ValueObjects.JobRunLiquidQuantity>();

                if (JobLiquidQuantityCalculationMode == JobLiquidQuantityCalculationMode.MachineStatus)
                {
                    foreach (var pack in configuration.NoneEmptyIdsPacks.ToList())
                    {
                        var packLevelAfter = MachineStatus.IDSPacksLevels.SingleOrDefault(x => x.Index == pack.PackIndex);
                        var packLevelBefore = _machineStatusBeforeJobStart.IDSPacksLevels.SingleOrDefault(x => x.Index == pack.PackIndex);

                        if (packLevelAfter != null && packLevelBefore != null)
                        {
                            if (packLevelAfter.DispenserLevel > packLevelBefore.DispenserLevel)
                            {
                                LogManager.Log($"Invalid '{pack.LiquidType.Name}' dispenser level calculated: {packLevelBefore.DispenserLevel} - {packLevelAfter.DispenserLevel} = {packLevelBefore.DispenserLevel - packLevelAfter.DispenserLevel}. Ignoring...");
                                continue;
                            }

                            _lastJobLiquidQuantities.Add(new BL.ValueObjects.JobRunLiquidQuantity()
                            {
                                LiquidType = pack.LiquidType.Type,
                                Quantity = packLevelBefore.DispenserLevel - packLevelAfter.DispenserLevel,
                            });
                        }
                    }
                }
                else
                {
                    _lastJobLiquidQuantities = CreateJobRunLiquidQuantities(job, configuration, processParameters, handler.Status.Progress, handler.Status.TotalProgress);
                }

                LogManager.Log($"Job run liquid quantities calculation completed:\n{_lastJobLiquidQuantities.ToJsonString()}");
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, LogCategory.Critical, "Error calculating and saving last job run liquid quantities.");
            }
        }

        #endregion

        #region Public Static Methods

        /// <summary>
        /// Creates the job run liquid quantities.
        /// </summary>
        /// <param name="job">The job.</param>
        /// <param name="configuration">The configuration.</param>
        /// <param name="processParameters">The process parameters.</param>
        /// <param name="position">The position.</param>
        /// <param name="length">The length.</param>
        /// <param name="gradientResolution">The gradient resolution.</param>
        /// <returns></returns>
        public static List<BL.ValueObjects.JobRunLiquidQuantity> CreateJobRunLiquidQuantities(Job job, Configuration configuration, ProcessParametersTable processParameters, double position, double length)
        {
            var units = Math.Max(job.NumberOfUnits, 1);

            var effectiveSegments = new List<Segment>();
            for (int i = 0; i < units; i++)
            {
                if (i > 0 && job.EnableInterSegment)
                {
                    effectiveSegments.Add(Job.CreateInterSegment(job.InterSegmentLength));
                }

                foreach (var segment in job.EffectiveSegments)
                {
                    effectiveSegments.Add(segment.Clone(job));
                }
            }

            effectiveSegments.Add(Job.CreateInterSegment(processParameters.DryerBufferLengthMeters));

            double total = length;
            double position_cm = position * 100d;
            double total_length = 0;

            Dictionary<int, double> liquidQuantities = new Dictionary<int, double>();

            foreach (var pack in configuration.NoneEmptyIdsPacks.OrderBy(x => x.PackIndex))
            {
                liquidQuantities.Add(pack.PackIndex, 0);
            }

            bool stop_calc = false;

            for (int segmentIndex = 0; segmentIndex < effectiveSegments.Count && !stop_calc; segmentIndex++)
            {
                var segment = effectiveSegments[segmentIndex];
                var segment_length_cm = segment.Length * 100d;

                List<BrushStop> orderedBrushCollection = segment.BrushStops.OrderBy(x => x.OffsetMeters).ToList();

                int solid_gradient_oeff = orderedBrushCollection.Count == 1 ? 1 : 2;
                double prev_offset_cm = 0;
                double delta_brushLenghtToStopPosition = 0d;

                double position_interval_centimeters = 0d;//interval for calculation where the stop occurred
                for (int brushIndex = 0; brushIndex < orderedBrushCollection.Count && !stop_calc; brushIndex++)
                {
                    var brush = orderedBrushCollection[brushIndex];
                    double brush_length_centimeters = 0d;
                    double brush_offset_cm = 0;

                    if ((brushIndex + 1) < orderedBrushCollection.Count)
                    {
                        brush_offset_cm = (brush.OffsetMeters * 100d);
                        double next_brush_offset_cm = (orderedBrushCollection[brushIndex + 1].OffsetMeters * 100d);
                        brush_length_centimeters = (next_brush_offset_cm - prev_offset_cm);
                        double brush_length_centimeters_before_calc = brush_length_centimeters;

                        if (delta_brushLenghtToStopPosition > 0)//calculate second brush
                        {
                            brush_length_centimeters = ((position_interval_centimeters - delta_brushLenghtToStopPosition) * (position_interval_centimeters - delta_brushLenghtToStopPosition)) / position_interval_centimeters;
                            stop_calc = true;
                        }
                        else if (total_length + prev_offset_cm + brush_length_centimeters > position_cm)//calculate first brush
                        {
                            position_interval_centimeters = brush_length_centimeters;
                            delta_brushLenghtToStopPosition = (total_length + prev_offset_cm + brush_length_centimeters) - position_cm;
                            brush_length_centimeters = brush_length_centimeters - (delta_brushLenghtToStopPosition * delta_brushLenghtToStopPosition / brush_length_centimeters);
                        }
                    }
                    else//last brush or solid brush
                    {
                        brush_length_centimeters = (segment_length_cm - prev_offset_cm);
                        if (delta_brushLenghtToStopPosition > 0)//second  brush
                        {
                            brush_length_centimeters = ((position_interval_centimeters - delta_brushLenghtToStopPosition) * (position_interval_centimeters - delta_brushLenghtToStopPosition)) / position_interval_centimeters;
                            stop_calc = true;
                        }
                        else if (orderedBrushCollection.Count == 1 && (total_length + segment_length_cm) > position_cm)// solid brush
                        {
                            brush_length_centimeters = position_cm - total_length;
                            stop_calc = true;
                        }
                    }

                    prev_offset_cm = brush_offset_cm;

                    if (brush.LiquidVolumes != null)
                    {
                        foreach (var liquidVolumes in brush.LiquidVolumes)
                        {
                            liquidQuantities[liquidVolumes.IdsPack.PackIndex] += liquidVolumes.NanoliterPerCentimeter * (brush_length_centimeters / solid_gradient_oeff);
                        }
                    }
                }
                total_length += segment_length_cm;
            }

            List<BL.ValueObjects.JobRunLiquidQuantity> quantities = new List<BL.ValueObjects.JobRunLiquidQuantity>();

            foreach (var liquidQuantity in liquidQuantities)
            {
                int index = liquidQuantity.Key;
                var idsPack = configuration.NoneEmptyIdsPacks.SingleOrDefault(x => x.PackIndex == index);

                if (idsPack != null)
                {
                    quantities.Add(new BL.ValueObjects.JobRunLiquidQuantity()
                    {
                        LiquidType = idsPack.LiquidType.Type,
                        Quantity = (int)liquidQuantities[index],
                    });
                }
            }

            return quantities;
        }


        #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>
        /// <param name="config">Optional job configuration.</param>
        /// <returns></returns>
        public async Task<JobHandler> Print(Job job, AdditionalJobConfiguration config = null)
        {
            ProcessParametersTable processParameters = null;

            if (config == null) config = new AdditionalJobConfiguration();

            await Task.Factory.StartNew(() =>
            {
                IColorConverter converter = new DefaultColorConverter();

                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);
                }

                try
                {
                    bool useLightInks = config.UseLightInks;
                    if (job.OrderedSegmentsWithGroups.Count > 1 && !job.EnableInterSegment) useLightInks = false;

                    processParameters = converter.GetRecommendedProcessParameters(job, useLightInks);
                }
                catch (Exception ex)
                {
                    throw LogManager.Log(new InvalidOperationException($"An error occurred while trying to resolve the recommended process parameters.\n{ex.Message}"));
                }

                if (processParameters == null)
                {
                    throw new NullReferenceException("Could not locate any process parameters table in group " + processGroup.Name + " for RML " + job.Rml.Name);
                }

                try
                {
                    foreach (var stop in job.OrderedSegmentsWithGroups.SelectMany(x => x.BrushStops).ToList())
                    {
                        stop.SetLiquidVolumes(job.Machine.Configuration, job.Rml, processParameters);
                    }
                }
                catch (Exception ex)
                {
                    throw LogManager.Log(new InvalidOperationException($"An error occurred while trying to apply final liquid volumes.\n{ex.Message}"));
                }
            });

            return await Print(job, processParameters, config);
        }

        /// <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, AdditionalJobConfiguration config = null)
        {
            return Task.Factory.StartNew(() =>
            {
                if (config == null) config = new AdditionalJobConfiguration();

                if (!CanPrint)
                {
                    throw new InvalidOperationException("Could not print while status = " + Status);
                }

                _jobStartDate = DateTime.UtcNow;

                LogManager.Log($"Executing job '{job.Name}'...");

                if (MachineStatus == null)
                {
                    LogManager.Log("Aborting job execution. No machine status received yet.");
                    throw new InvalidOperationException("Cannot execute a job before at least one machine status has been received.");
                }

                _lastJobLiquidQuantities = new List<BL.ValueObjects.JobRunLiquidQuantity>();
                _jobUploadingStartDate = null;
                _jobHeatingStartDate = null;
                _jobActualStartDate = null;

                RunningJob = null;
                RunningJobStatus = null;

                if (job.NumberOfUnits < 1)
                {
                    job.NumberOfUnits = 1;
                }

                var originalJob = job;
                var clonedJob = job.Clone();
                clonedJob.Guid = job.Guid;
                clonedJob.Name = job.Name;

                job = job.Clone();
                job.Guid = originalJob.Guid;
                job.Name = originalJob.Name;

                var jobSegments = job.OrderedSegmentsWithGroups;

                //Color Conversion
                if (config.UseColorConversion)
                {
                    IColorConverter converter = new DefaultColorConverter();

                    bool useLightInks = config.UseLightInks;

                    //Use light inks only if one segment or inter segment is enabled.
                    if (job.OrderedSegmentsWithGroups.Count > 1 && !job.EnableInterSegment) useLightInks = false;

                    foreach (var segment in jobSegments)
                    {
                        foreach (var stop in segment.BrushStops)
                        {
                            try
                            {
                                var output = converter.Convert(stop, false, useLightInks && segment.BrushStops.Count == 1); //Use light inks only if this is a solid segment.
                                output.ApplyOnBrushStopLiquidVolumes(stop, processParameters);
                            }
                            catch (Exception ex)
                            {
                                throw new InvalidOperationException($"Error processing the coordinates of stop '{stop.StopIndex}' of segment '{stop.Segment.SegmentIndex}'.", ex);
                            }
                        }
                    }
                }

                //Lubrication
                if (job.EnableLubrication)
                {
                    if (config.UseLubricantVolume)
                    {
                        LogManager.Log($"Job custom lubrication is enabled. Settings all brush stops to {config.LubricationVolume}% lubricant.");

                        foreach (var stop in jobSegments.SelectMany(x => x.BrushStops).ToList())
                        {
                            var lubricantVolume = stop.LiquidVolumes.SingleOrDefault(x => x.IdsPack != null && x.IdsPack.LiquidType != null && x.LiquidType == LiquidTypes.Lubricant);

                            if (lubricantVolume != null)
                            {
                                lubricantVolume.Volume = config.LubricationVolume;
                            }
                        }
                    }
                    else
                    {
                        LogManager.Log($"Job auto lubrication is enabled. Settings all none Volume brush stops to 100% lubricant.");

                        foreach (var stop in jobSegments.SelectMany(x => x.BrushStops).Where(x => x.BrushColorSpace != ColorSpaces.Volume).ToList())
                        {
                            var lubricantVolume = stop.LiquidVolumes.SingleOrDefault(x => x.IdsPack != null && x.IdsPack.LiquidType != null && x.LiquidType == LiquidTypes.Lubricant);

                            if (lubricantVolume != null)
                            {
                                lubricantVolume.Volume = 100;
                            }
                        }
                    }
                }
                else
                {
                    LogManager.Log("Job lubrication is disabled.");
                }

                //Modify transparent/white brush stops. (Transparent/white stops should be all zeros and 100% TI)
                LogManager.Log("Modifying all 'white' brush stops...");
                foreach (var stop in job.OrderedSegmentsWithGroups.SelectMany(x => x.BrushStops).Where(x => x.IsTransparent || x.IsWhite).ToList())
                {
                    foreach (var liquidVolume in stop.LiquidVolumes.Where(x => x.LiquidType != LiquidTypes.TransparentInk && x.LiquidType != LiquidTypes.Lubricant).ToList())
                    {
                        liquidVolume.Volume = 0;
                    }

                    var tiLiquid = stop.LiquidVolumes.SingleOrDefault(x => x.IdsPack != null && x.IdsPack.LiquidType != null && x.LiquidType == LiquidTypes.TransparentInk);

                    if (tiLiquid != null)
                    {
                        tiLiquid.Volume = 100;
                    }
                }

                var segments = job.OrderedSegmentsWithGroups.ToList();

                List<RequiredLiquid> requiredLiquids = null;

                //Validate liquid quantities
                if (EnableJobLiquidQuantityValidation)
                {
                    if (!originalJob.Rml.UseColorLibGradients) //Validate liquid quantities when ColorLib generate gradient is disabled
                    {
                        requiredLiquids = ValidateJobLiquidQuantity(job, processParameters, job.Machine.Configuration);
                    }
                    else //Validate liquid quantities when ColorLib generate gradient is enabled
                    {
                        JobTicket t = new JobTicket();
                        t.NumberOfUnits = (uint)originalJob.NumberOfUnits;

                        foreach (var segment in segments)
                        {
                            if (segment is Segment simpleSegment)
                            {
                                t.Segments.Add(CreatePMRJobSegment(simpleSegment, originalJob, processParameters));
                            }
                            else if (segment is SegmentsGroup group)
                            {
                                List<JobSegment> groupSegments = new List<JobSegment>();

                                foreach (var innerSegment in group.OrderedSegments)
                                {
                                    groupSegments.Add(CreatePMRJobSegment(innerSegment, originalJob, processParameters));
                                }

                                for (int i = 0; i < group.Repeats; i++)
                                {
                                    t.Segments.AddRange(groupSegments.ToList());
                                }
                            }
                        }

                        requiredLiquids = ValidateJobLiquidQuantity(t, processParameters, job.Machine.Configuration);
                    }
                }
                else
                {
                    LogManager.Log("Liquid quantity validation is disabled. Skipping...");
                }

                CurrentProcessParameters = processParameters;

                JobRequest request = new JobRequest();

                int max = job.OrderedSegmentsWithGroups.Last().SegmentIndex + 1;

                for (int i = 0; i < job.NumberOfUnits - 1; i++)
                {
                    foreach (var s in segments)
                    {
                        var cloned = s.Clone(job);
                        cloned.SegmentIndex = max++;

                        if (cloned is Segment simpleSegment)
                        {
                            job.Segments.Add(simpleSegment);
                        }
                        else if (cloned is SegmentsGroup g)
                        {
                            job.SegmentsGroups.Add(g);
                        }
                    }
                }

                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.UploadStrategy = JobUploadStrategy;

                if (JobUnitsMethod == JobUnitsMethods.Device)
                {
                    ticket.NumberOfUnits = (uint)Math.Max(job.NumberOfUnits, 1);
                }

                //Spool parameters
                ticket.Spool = new JobSpool();
                job.SpoolType.MapPropertiesTo(ticket.Spool);
                ticket.Spool.JobSpoolType = (JobSpoolType)job.SpoolType.Code;

                //Override spool parameters from RML Spool calibration
                var rmlSpool = job.Rml.RmlsSpools.FirstOrDefault(x => x.SpoolType.Guid == job.SpoolType.Guid);
                if (rmlSpool != null)
                {
                    ticket.Spool.RotationsPerPassage = rmlSpool.RotationsPerPassage != null ? rmlSpool.RotationsPerPassage.Value : ticket.Spool.RotationsPerPassage;
                    ticket.Spool.Length = rmlSpool.Length != null ? rmlSpool.Length.Value : ticket.Spool.Length;
                    ticket.Spool.BackingRate = rmlSpool.BackingRate != null ? rmlSpool.BackingRate.Value : ticket.Spool.BackingRate;
                    ticket.Spool.BottomBackingRate = rmlSpool.BottomBackingRate != null ? rmlSpool.BottomBackingRate.Value : ticket.Spool.BottomBackingRate;
                    ticket.Spool.BtsrSpoolTension = rmlSpool.BtsrSpoolTension != null ? rmlSpool.BtsrSpoolTension.Value : ticket.Spool.BtsrSpoolTension;
                }

                //Override spool parameters from Machine Spool calibration
                var machineSpool = job.Machine.Spools.FirstOrDefault(x => x.SpoolType.Guid == job.SpoolType.Guid);
                if (machineSpool != null)
                {
                    ticket.Spool.LimitSwitchStartPointOffset = machineSpool.LimitSwitchStartPointOffset != null ? machineSpool.LimitSwitchStartPointOffset.Value : ticket.Spool.LimitSwitchStartPointOffset;
                }

                //Thread Parameters
                ticket.ThreadParameters = new ThreadParameters();
                job.Rml.MapPrimitivesTo(ticket.ThreadParameters);

                ProcessParameters process = new ProcessParameters();
                processParameters.MapPrimitivesTo(process);
                ticket.ProcessParameters = process;

                //Head Cleaning Parameters
                ticket.HeadCleaningParameters = new HeadCleaningParameters();
                ticket.HeadCleaningParameters.CleanerFlow = job.Rml.CleanerFlow;
                ticket.HeadCleaningParameters.ArcHeadCleaningMotorSpeed = job.Rml.ArcHeadCleaningMotorSpeed;

                //BTSR Parameters
                ticket.BtsrParameters = new PMR.BTSR.BtsrParameters();
                ticket.BtsrParameters.BtsrApplicationType = job.Rml.BtsrApplicationType != null ? (PMR.BTSR.BtsrApplicationType)job.Rml.BtsrApplicationType.Code : PMR.BTSR.BtsrApplicationType.Seamless;
                ticket.BtsrParameters.BtsrYarnType = job.Rml.BtsrYarnType != null ? (PMR.BTSR.BtsrYarnType)job.Rml.BtsrYarnType.Code : PMR.BTSR.BtsrYarnType.AllYarn3;
                ticket.BtsrParameters.TensionError = (float)job.Rml.BtsrTensionError;

                JobHandler handler = null;
                StorageFileHandler fileUploadHandler = null;

                bool requestSent = false;

                handler = new JobHandler(async () =>
                {
                    try
                    {
                        if (handler.CanCancel)
                        {
                            handler.CanCancel = false;
                            handler.IsCanceled = true;
                            LogManager.Log("Aborting current job...");
                            LogManager.Log($"Aborting current gradient generation...");
                            GradientGenerationConfiguration.AbortCurrentGeneration();

                            if (fileUploadHandler != null)
                            {
                                LogManager.Log("Job is currently uploading. Aborting file upload...");
                                await fileUploadHandler.Cancel();
                                fileUploadHandler = null;
                                LogManager.Log("Job upload canceled.");
                                OnPrintingAborted(handler, clonedJob);
                                handler.RaiseCanceled();
                                if (Status != MachineStatuses.Disconnected)
                                {
                                    UpdateStatus(MachineStatuses.ReadyToDye);
                                }
                            }
                            else
                            {
                                if (requestSent)
                                {
                                    var result = await SendRequest<AbortJobRequest, AbortJobResponse>(new AbortJobRequest(), new TransportRequestConfig() { ShouldLog = true });
                                }

                                SaveLastJobLiquidQuantities(clonedJob, originalJob.Machine.Configuration, processParameters, handler);
                                OnPrintingAborted(handler, clonedJob);
                                handler.RaiseCanceled();
                                if (Status != MachineStatuses.Disconnected)
                                {
                                    UpdateStatus(MachineStatuses.ReadyToDye);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        handler.CanCancel = true;
                        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 () =>
                {
                    if (handler.IsCanceled)
                    {
                        UpdateStatus(MachineStatuses.ReadyToDye);
                        return;
                    }

                    UpdateStatus(MachineStatuses.GettingReady);
                    RunningJob = clonedJob;
                    OnPrintingStarted(handler, clonedJob);

                    Thread.Sleep(100);

                    handler.RaiseStatusReceived(new JobStatus()
                    {
                        CurrentSegmentIndex = 0,
                        Progress = 0,
                        Message = "Preparing Job...",
                    });

                    foreach (var segment in segments)
                    {
                        try
                        {
                            if (segment is Segment simpleSegment)
                            {
                                ticket.Segments.Add(CreatePMRJobSegment(simpleSegment, originalJob, processParameters));
                            }
                            else if (segment is SegmentsGroup group)
                            {
                                List<JobSegment> groupSegments = new List<JobSegment>();

                                foreach (var innerSegment in group.OrderedSegments)
                                {
                                    groupSegments.Add(CreatePMRJobSegment(innerSegment, originalJob, processParameters));
                                }

                                for (int i = 0; i < group.Repeats; i++)
                                {
                                    ticket.Segments.AddRange(groupSegments.ToList());
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            handler.RaiseFailed(ex);
                            UpdateStatus(MachineStatuses.ReadyToDye);
                            return;
                        }

                        if (handler.IsCanceled)
                        {
                            UpdateStatus(MachineStatuses.ReadyToDye);
                            return;
                        }
                    }

                    //Log Job Outline (Only first and last brush stops if gradient).
                    var ticketToLog = ticket.Clone();
                    ticketToLog.Segments.Clear();

                    foreach (var seg in ticket.Segments)
                    {
                        JobSegment segmentToLog = new JobSegment();

                        segmentToLog.Length = seg.Length;
                        segmentToLog.BrushStops.Add(seg.BrushStops.First());

                        if (seg.BrushStops.Count > 1)
                        {
                            segmentToLog.BrushStops.Add(seg.BrushStops.Last());
                        }

                        ticketToLog.Segments.Add(segmentToLog);
                    }

                    if (!job.EnableInterSegment)
                    {
                        NormalizeJobTicket(ticketToLog, processParameters);
                    }

                    LogManager.Log($"Job outline for '{job.Name}':\n{ticketToLog.ToJsonString()}");

                    if (handler.IsCanceled)
                    {
                        UpdateStatus(MachineStatuses.ReadyToDye);
                        return;
                    }

                    var segs = new List<JobSegment>();

                    if (JobUnitsMethod == JobUnitsMethods.Operator)
                    {
                        for (int i = 0; i < job.NumberOfUnits; i++)
                        {
                            foreach (var s in ticket.Segments)
                            {
                                var cloned = s.Clone();
                                segs.Add(cloned);
                            }
                        }
                    }
                    else
                    {
                        foreach (var s in ticket.Segments)
                        {
                            var cloned = s.Clone();
                            segs.Add(cloned);
                        }
                    }

                    if (segs.Count > 0)
                    {
                        ticket.Segments.Clear();
                        ticket.Segments.AddRange(segs);
                    }

                    if (!job.EnableInterSegment)
                    {
                        NormalizeJobTicket(ticket, processParameters);
                    }

                    request.JobTicket = ticket.Clone();

                    LogManager.Log($"Job upload method is set to {JobUploadStrategy}...");

                    if (handler.IsCanceled)
                    {
                        UpdateStatus(MachineStatuses.ReadyToDye);
                        return;
                    }

                    var oldKeepAlive = UseKeepAlive;

                    if (requiredLiquids != null)
                    {
                        JobPrepareRequest prepareRequest = new JobPrepareRequest();
                        prepareRequest.ProcessParameters = ticket.ProcessParameters;

                        foreach (var requiredLiquid in requiredLiquids)
                        {
                            JobPrepareDispenser prepareDispenser = new JobPrepareDispenser();
                            prepareDispenser.DispenserLiquidType = (DispenserLiquidType)requiredLiquid.IdsPack.LiquidType.Type;
                            prepareDispenser.Index = requiredLiquid.IdsPack.PackIndex;
                            prepareDispenser.TotalNanoliter = requiredLiquid.Quantity;
                            prepareDispenser.Active = requiredLiquid.Quantity > 0;

                            prepareRequest.Dispensers.Add(prepareDispenser);
                        }

                        try
                        {
                            var response = await SendRequest<JobPrepareRequest, JobPrepareResponse>(prepareRequest, new TransportRequestConfig()
                            {
                                ShouldLog = true,
                                Timeout = TimeSpan.FromSeconds(10)
                            });
                        }
                        catch (ResponseErrorException ex)
                        {
                            LogManager.Log(ex, "Error sending job preparation request. Aborting job...");
                            UseKeepAlive = oldKeepAlive;
                            UpdateStatus(MachineStatuses.ReadyToDye);
                            OnPrintingFailed(handler, clonedJob, ex);
                            handler.RaiseFailed(ex);
                            return;
                        }
                        catch (Exception ex)
                        {
                            LogManager.Log(ex, "Error sending job preparation request.");
                        }
                    }

                    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...",
                            });

                            if (handler.IsCanceled)
                            {
                                UpdateStatus(MachineStatuses.ReadyToDye);
                                return;
                            }

                            LogManager.Log("Creating storage API manager...");
                            var storage = CreateStorageManager();

                            if (handler.IsCanceled)
                            {
                                UpdateStatus(MachineStatuses.ReadyToDye);
                                return;
                            }

                            //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} bytes...");

                            TaskCompletionSource<object> uploadCompletion = new TaskCompletionSource<object>();
                            _jobUploadingStartDate = DateTime.UtcNow;
                            fileUploadHandler = await storage.UploadFile(job_file_path, ms);
                            bool uploadCanceled = false;
                            Exception uploadException = null;
                            fileUploadHandler.Canceled += (_, __) =>
                            {
                                uploadCanceled = true;
                                uploadCompletion.SetResult(true);
                            };
                            fileUploadHandler.Completed += (_, __) =>
                            {
                                uploadCompletion.SetResult(true);
                            };
                            fileUploadHandler.Failed += (_, e) =>
                            {
                                uploadCompletion.SetException(e);
                            };

                            try
                            {
                                await uploadCompletion.Task;
                            }
                            catch (Exception ue)
                            {
                                if (uploadException != null)
                                {
                                    throw uploadException;
                                }
                                else
                                {
                                    throw ue;
                                }
                            }
                            finally
                            {
                                try
                                {
                                    fileUploadHandler = null;
                                    ms.Dispose();
                                }
                                catch { }
                            }

                            if (uploadCanceled)
                            {
                                return;
                            }
                            else
                            {
                                LogManager.Log("Job upload completed successfully.");
                            }

                            request.JobTicket.JobDescriptionFile = job_file_path;
                        }
                        catch (Exception ex)
                        {
                            UseKeepAlive = oldKeepAlive;
                            UpdateStatus(MachineStatuses.ReadyToDye);
                            OnPrintingFailed(handler, clonedJob, ex);
                            handler.RaiseFailed(ex);
                            return;
                        }
                    }
                    else
                    {
                        _jobUploadingStartDate = DateTime.UtcNow;
                    }

                    if (handler.IsCanceled)
                    {
                        UseKeepAlive = oldKeepAlive;
                        UpdateStatus(MachineStatuses.ReadyToDye);
                        return;
                    }

                    _machineStatusBeforeJobStart = MachineStatus.Clone();

                    SaveCachedJobOperation(clonedJob); //Cache job and machine status for job resume!

                    bool responseLogged = false;
                    bool completed = false; //Use this in case Shlomo is sending progress after completion.

                    _jobHeatingStartDate = DateTime.UtcNow;

                    if (handler.IsCanceled)
                    {
                        UseKeepAlive = oldKeepAlive;
                        UpdateStatus(MachineStatuses.ReadyToDye);
                        return;
                    }

                    SendContinuousRequest<JobRequest, JobResponse>(request, new TransportContinuousRequestConfig() { Timeout = TimeSpan.FromSeconds(10), ContinuousTimeout = TimeSpan.FromSeconds(10), ShouldLog = true }).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 (_jobActualStartDate == null)
                                {
                                    _jobActualStartDate = DateTime.UtcNow;
                                }
                            }

                            if (!responseLogged)
                            {
                                requestSent = true;
                                responseLogged = true;
                            }

                            if (JobHandlingMode == JobHandlerModes.SettingUp)
                            {
                                if (response.Message.Status.Progress > processParameters.DryerBufferLengthMeters)
                                {
                                    if (!completed)
                                    {
                                        UpdateStatus(MachineStatuses.Printing);
                                    }
                                }
                            }
                            else
                            {
                                if (response.Message.Status.Progress > 0)
                                {
                                    if (!completed)
                                    {
                                        UpdateStatus(MachineStatuses.Printing);
                                    }
                                }
                            }
                        }

                    }, (ex) =>
                    {
                        if (!completed)
                        {
                            completed = true;

                            UseKeepAlive = oldKeepAlive;

                            if (Status != MachineStatuses.Disconnected)
                            {
                                UpdateStatus(MachineStatuses.ReadyToDye);
                            }

                            if (!handler.IsCanceled)
                            {
                                SaveLastJobLiquidQuantities(originalJob, originalJob.Machine.Configuration, processParameters, handler);

                                Exception finalException = ex;

                                if (ex is ContinuousResponseAbortedException continuousException)
                                {
                                    finalException = new ContinuousResponseAbortedException($"Job aborted by the embedded device ({continuousException.Container.ErrorMessage}).");
                                }

                                OnPrintingFailed(handler, originalJob, finalException);
                                handler.RaiseFailed(finalException);
                            }
                        }
                    }, () =>
                    {
                        if (!completed)
                        {
                            completed = true;

                            UseKeepAlive = oldKeepAlive;

                            UpdateStatus(MachineStatuses.ReadyToDye);
                            SaveLastJobLiquidQuantities(clonedJob, originalJob.Machine.Configuration, processParameters, handler);
                            OnPrintingCompleted(handler, clonedJob);
                            handler.RaiseCompleted();
                        }
                    });
                });

                return handler;

            });
        }

        private void NormalizeJobTicket(JobTicket ticket, ProcessParametersTable processParameters)
        {
            var maxNanoStop = ticket.Segments.SelectMany(x => x.BrushStops).OrderBy(x => x.GetTotalNanoliterPerCentimeter()).Last();
            double maxNanoliter = maxNanoStop.GetTotalNanoliterPerCentimeter();

            LogManager.Log($"Normalizing brush stops TI quantities by {maxNanoliter} nanoliters...");

            foreach (var stop in ticket.Segments.SelectMany(x => x.BrushStops).Where(x => x != maxNanoStop))
            {
                stop.NormalizeStop(maxNanoliter, processParameters.MinInkUptake, processParameters.DyeingSpeed);
            }
        }

        /// <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;
                response = await SendRequest<UploadProcessParametersRequest, UploadProcessParametersResponse>(request, new TransportRequestConfig() { ShouldLog = true });
            }
            catch (Exception 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)
        {
            _machineConfiguration = configuration;

            LogManager.Log("Uploading hardware configuration...");

            try
            {
                hardwareVersion = configuration.GetHardwareConfiguration().Merge(hardwareVersion);
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error merging hardware configuration to hardware version.");
            }

            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
            {
                LogManager.Log("Checking if firmware version < 1.6...");

                if (DeviceInformation != null && DeviceInformation.Version != null)
                {
                    Version firmwareVersion = Version.Parse(DeviceInformation.Version);

                    if (firmwareVersion < new Version("1.6.0.0") && firmwareVersion > new Version("1.0.0.0"))
                    {
                        LogManager.Log("Firmware version is lower than '1.6'. Skipping hardware configuration upload...");
                        return new UploadHardwareConfigurationResponse();
                    }
                }
                else
                {
                    LogManager.Log("No device information found. Continuing...", LogCategory.Warning);
                }
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error occurred while checking for firmware version. Continuing...");
            }

            try
            {
                LogManager.Log($"Sending '{nameof(UploadHardwareConfigurationRequest)}'...");
                LogManager.Log($"{nameof(UploadHardwareConfigurationRequest)} request:\n{request.HardwareConfiguration.ToJsonString()}", LogCategory.Debug);

                CurrentHardwareConfiguration = hardwareConfiguration;
                response = await SendRequest<UploadHardwareConfigurationRequest, UploadHardwareConfigurationResponse>(request, new TransportRequestConfig() { ShouldLog = false });
            }
            catch (Exception 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
            {
                response = await SendRequest<MotorJoggingRequest, MotorJoggingResponse>(request, new TransportRequestConfig() { ShouldLog = true });
            }
            catch (Exception 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)
        {
            return await SendRequest<MotorAbortJoggingRequest, MotorAbortJoggingResponse>(request, new TransportRequestConfig() { ShouldLog = true });
        }

        /// <summary>
        /// Starts homing the specified motor.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public IObservable<MotorHomingResponse> StartMotorHoming(MotorHomingRequest request)
        {
            return SendContinuousRequest<MotorHomingRequest, MotorHomingResponse>(request, new TransportContinuousRequestConfig() { ContinuousTimeout = ContinuousRequestTimeout, ShouldLog = true }).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)
        {
            return await SendRequest<MotorAbortHomingRequest, MotorAbortHomingResponse>(request, new TransportRequestConfig() { ShouldLog = true });
        }

        /// <summary>
        /// Starts jogging the specified dispenser.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public async Task<DispenserJoggingResponse> StartDispenserJogging(DispenserJoggingRequest request)
        {
            return await SendRequest<DispenserJoggingRequest, DispenserJoggingResponse>(request, new TransportRequestConfig() { ShouldLog = true });
        }

        /// <summary>
        /// Stops jogging the specified dispenser.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public async Task<DispenserAbortJoggingResponse> StopDispenserJogging(DispenserAbortJoggingRequest request)
        {
            return await SendRequest<DispenserAbortJoggingRequest, DispenserAbortJoggingResponse>(request, new TransportRequestConfig() { ShouldLog = true });
        }

        /// <summary>
        /// Starts homing the specified dispenser.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public IObservable<DispenserHomingResponse> StartDispenserHoming(DispenserHomingRequest request)
        {
            return SendContinuousRequest<DispenserHomingRequest, DispenserHomingResponse>(request, new TransportContinuousRequestConfig() { ContinuousTimeout = ContinuousRequestTimeout, ShouldLog = true }).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)
        {
            return await SendRequest<DispenserAbortHomingRequest, DispenserAbortHomingResponse>(request, new TransportRequestConfig() { ShouldLog = true });
        }

        /// <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)
        {
            return await SendRequest<SetDigitalOutRequest, SetDigitalOutResponse>(request, new TransportRequestConfig() { ShouldLog = true });
        }

        /// <summary>
        /// Starts jogging the thread motion system.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public async Task<ThreadJoggingResponse> StartThreadJogging(ThreadJoggingRequest request)
        {
            return await SendRequest<ThreadJoggingRequest, ThreadJoggingResponse>(request, new TransportRequestConfig() { ShouldLog = true });
        }

        /// <summary>
        /// Stops jogging the thread motion system.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public async Task<ThreadAbortJoggingResponse> StopThreadJogging(ThreadAbortJoggingRequest request)
        {
            return await SendRequest<ThreadAbortJoggingRequest, ThreadAbortJoggingResponse>(request, new TransportRequestConfig() { ShouldLog = true });
        }

        /// <summary>
        /// Sets the specified component value.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public async Task<SetComponentValueResponse> SetComponentValue(SetComponentValueRequest request)
        {
            return await SendRequest<SetComponentValueRequest, SetComponentValueResponse>(request, new TransportRequestConfig() { ShouldLog = true });
        }

        /// <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
            {
                response = await SendRequest<SetHeaterStateRequest, SetHeaterStateResponse>(request, new TransportRequestConfig() { ShouldLog = true });
            }
            catch (Exception 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
            {
                response = await SendRequest<SetBlowerStateRequest, SetBlowerStateResponse>(request, new TransportRequestConfig() { ShouldLog = true });
            }
            catch (Exception 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
            {
                response = await SendRequest<SetValveStateRequest, SetValveStateResponse>(request, new TransportRequestConfig() { ShouldLog = true });
            }
            catch (Exception 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 };
            return await SendRequest<ResolveEventRequest, ResolveEventResponse>(request, new TransportRequestConfig() { ShouldLog = true });
        }

        /// <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
                };

                response = await SendRequest<StubFpgaWriteRegRequest, StubFpgaWriteRegResponse>(request, new TransportRequestConfig() { ShouldLog = true });
            }
            catch (Exception ex)
            {
                throw ex;
            }

            Thread.Sleep(1000);

            try
            {
                request = new StubFpgaWriteRegRequest()
                {
                    Address = 0x60000800 | 0x3D0,
                    Value = 0x1
                };

                response = await SendRequest<StubFpgaWriteRegRequest, StubFpgaWriteRegResponse>(request, new TransportRequestConfig() { ShouldLog = true });
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return response;
        }

        /// <summary>
        /// Directs the embedded device to switch to stand-by mode.
        /// </summary>
        /// <returns></returns>
        public async Task StandBy()
        {
            LogManager.Log("Switching to stand-by mode...");
            await SendRequest<StandByRequest, StandByResponse>(new StandByRequest(), new TransportRequestConfig() { ShouldLog = true });
        }

        /// <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>
        /// <param name="isEmulated">Specify whether the connected machine is emulated and to skip the actual DFU interface.</param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        public virtual async Task<FirmwareUpgradeHandler> UpgradeFirmware(Stream tfpStream, bool isEmulated = false)
        {
            bool cancel = false;
            ZipFile zip = null;
            Action abortAction = null;

            var upgradeHandler = new FirmwareUpgradeHandler(() =>
            {
                cancel = true;

                abortAction?.Invoke();
            });

            try
            {
                LogManager.Log("Starting firmware upgrade...");
                LogManager.Log($"Firmware upgrade flags: {String.Join(", ", FirmwareUpgradeMode.GetFlags<FirmwareUpgradeModes>().Select(x => x.ToString()))}");

                if (!CanPrint)
                {
                    throw LogManager.Log(new InvalidOperationException($"Could not perform firmware upgrade while operator status is '{Status}'."));
                }

                LogManager.Log("Extracting tfp package...");
                var package_info = await GetFirmwarePackageInfo(tfpStream);
                tfpStream.Position = 0;

                LogManager.Log("Validating TFP package...");
                package_info.Validate();

                LogManager.Log("Reading zip stream...");
                zip = ZipFile.Read(tfpStream);

                double packageUploadTotal = 0;

                try
                {
                    packageUploadTotal = zip.Entries.Sum(x => x.UncompressedSize);
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, "Error calculating total package upload bytes.");
                }

                LogManager.Log("Creating storage manager...");
                var storage = CreateStorageManager();
                LogManager.Log("Getting storage drive information...");
                var drive = await storage.GetStorageDrive();
                LogManager.Log($"Storage drive info:\n{drive.ToJsonString()}");
                LogManager.Log("Getting root folder...");
                var root = await storage.GetRootFolder();
                LogManager.Log($"Root folder: '{root.Path}'");
                var existing_folder = root.Items.SingleOrDefault(x => x.Name == FIRMWARE_UPGRADE_FOLDER_NAME);
                if (existing_folder != null)
                {
                    LogManager.Log("Root folder exists. Deleting...");
                    await storage.DeleteItem(existing_folder);
                }

                String package_folder = Path.Combine(drive.Root, FIRMWARE_UPGRADE_FOLDER_NAME);

                LogManager.Log($"Creating new folder: '{package_folder}'.");
                await storage.CreateFolder(package_folder);

                List<StorageFileHandler> handlers = new List<StorageFileHandler>();
                List<ZipEntry> entries = zip.Entries.ToList();
                List<Stream> streams = new List<Stream>();

                LogManager.Log("Disabling keep alive...");
                var keepAlive = UseKeepAlive;
                UseKeepAlive = false;

                Action upgradeDFU = null;
                Action uploadNext = null;
                Action validate = null;
                Action activate = null;
                Action postActivation = null;

                UpdateStatus(MachineStatuses.Upgrading);

                abortAction = new Action(() =>
                {
                    UpdateStatus(MachineStatuses.ReadyToDye);
                });

                upgradeDFU = new Action(() =>
                {
                    try
                    {
                        if (FirmwareUpgradeMode.HasFlag(FirmwareUpgradeModes.DFU))
                        {
                            if (package_info.ContainsMcu())
                            {
                                LogManager.Log("DFU enabled. Starting upgrade via DFU...");
                                LogManager.Log("Extracting MCU file...");
                                ZipEntry mcuEntry = null;
                                try
                                {
                                    mcuEntry = entries.Single(x => x.FileName == package_info.FileDescriptors.Single(y => y.Destination == VersionFileDestination.Mcu).FileName);
                                    entries.Remove(mcuEntry);
                                }
                                catch (Exception ex)
                                {
                                    LogManager.Log(ex, "Error extracting MCU file from package.");
                                    upgradeHandler.RaiseFailed(new IOException("Error retrieving MCU file from package.", ex));
                                    return;
                                }

                                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.RaiseProgress(FirmwareUpgradeStatus.Upgrading, e.State.ToDescription(), false, e.Total, e.Progress);
                                };

                                LogManager.Log("Disconnecting adapter...");
                                Adapter.Disconnect().Wait();

                                ResetEvents();
                                ResetInkFllingStatus();

                                try
                                {
                                    if (!isEmulated)
                                    {
                                        LogManager.Log("Upgrading...");
                                        upgradeManager.PerformUpgrade(data).Wait();
                                    }
                                    else
                                    {
                                        LogManager.Log("Upgrading (emulated)...");
                                        Thread.Sleep(3000);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    LogManager.Log("Firmware upgrade failed while doing DFU upload. We need to destroy the whole transport layer.", LogCategory.Error);
                                    UpdateStatus(MachineStatuses.Disconnected);
                                    upgradeHandler.RaiseFailed(ex);
                                    OnFailed(ex);
                                    return;
                                }

                                LogManager.Log("Waiting for the device...");
                                upgradeHandler.RaiseProgress(FirmwareUpgradeStatus.Upgrading, "Waiting for the device...");
                                Thread.Sleep(5000);

                                LogManager.Log("Reconnecting adapter...");
                                upgradeHandler.RaiseProgress(FirmwareUpgradeStatus.Upgrading, "Connecting...");
                                Adapter.Connect().Wait();

                                Connect().Wait();

                                LogManager.Log("Connected...");
                                upgradeHandler.RaiseProgress(FirmwareUpgradeStatus.Upgrading, "Connected.");
                                Thread.Sleep(2000);

                                LogManager.Log("Waiting...");
                                upgradeHandler.RaiseProgress(FirmwareUpgradeStatus.Upgrading, "Waiting...");
                                Thread.Sleep(2000);

                                UpdateStatus(MachineStatuses.Upgrading);
                            }
                            else
                            {
                                LogManager.Log("DFU is enabled but no MCU file was found on the package. Skipping...");
                            }
                        }

                        //Upload tfp package only if specified in flag && package info contains more files other than the mcu bin file.
                        if (FirmwareUpgradeMode.HasFlag(FirmwareUpgradeModes.TFP_PACKAGE))
                        {
                            if (package_info.ContainsNoneMcu())
                            {
                                LogManager.Log("TFP package is enabled. Starting upload...");
                                uploadNext();
                            }
                            else
                            {
                                LogManager.Log("TFP package is enabled but no other files other than the MCU file were found on the package. Skipping...");
                                postActivation();
                            }
                        }
                        else
                        {
                            postActivation();
                        }
                    }
                    catch (Exception ex)
                    {
                        UpdateStatus(MachineStatuses.ReadyToDye);
                        upgradeHandler.RaiseFailed(ex);
                        return;
                    }
                });

                uploadNext = new Action(() =>
                {
                    if (entries.Count > 0)
                    {
                        try
                        {
                            var entry = entries.First();
                            entries.Remove(entry);

                            LogManager.Log($"Uploading file '{entry.FileName}'...");

                            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(FirmwareUpgradeStatus.Uploading, $"Uploading '{entry.FileName}'...", false, packageUploadTotal, upgradeHandler.Current + e.Delta);
                            };
                        }
                        catch (Exception ex)
                        {
                            abortAction();
                            upgradeHandler.RaiseFailed(ex);
                        }
                    }
                    else
                    {
                        validate();
                    }
                });

                validate = new Action(() =>
                {
                    try
                    {
                        LogManager.Log("Validating version...");
                        streams.ForEach(x => x.Dispose());
                        upgradeHandler.RaiseProgress(FirmwareUpgradeStatus.Validating, "Validating version...");
                        var validateRequest = new ValidateVersionRequest();
                        validateRequest.Path = package_folder;
                        var validateResponse = SendRequest<ValidateVersionRequest, ValidateVersionResponse>(validateRequest, new TransportRequestConfig() { Timeout = TimeSpan.FromSeconds(10), ShouldLog = true }).Result;
                        activate();
                    }
                    catch (Exception ex)
                    {
                        upgradeHandler.RaiseFailed(ex);
                    }
                });

                activate = new Action(() =>
                {
                    try
                    {
                        TaskCompletionSource<object> activationCompletion = new TaskCompletionSource<object>();

                        bool completed = false;

                        LogManager.Log("Activating version...");

                        upgradeHandler.RaiseProgress(FirmwareUpgradeStatus.Activating, "Activating version...");

                        var activateRequest = new ActivateVersionRequest();
                        activateRequest.Path = package_folder;

                        SendContinuousRequest<ActivateVersionRequest, ActivateVersionResponse>(activateRequest, new TransportContinuousRequestConfig() { Timeout = TimeSpan.FromSeconds(10), ContinuousTimeout = TimeSpan.FromSeconds(10), ShouldLog = true })
                        .Subscribe((response) =>
                        {
                            if (!completed && response.Message.Progress > 0)
                            {
                                upgradeHandler.RaiseProgress(FirmwareUpgradeStatus.Activating, "Activating version...", false, response.Message.Total, response.Message.Progress);
                            }
                        }, (ex) =>
                        {
                            if (!completed)
                            {
                                completed = true;
                                activationCompletion.SetException(ex);
                            }
                        }, () =>
                        {
                            if (!completed)
                            {
                                completed = true;
                                activationCompletion.SetResult(true);
                            }
                        });

                        var result = activationCompletion.Task.GetAwaiter().GetResult();

                        postActivation();
                    }
                    catch (Exception ex)
                    {
                        upgradeHandler.RaiseFailed(ex);
                    }
                });

                postActivation = new Action(() =>
                {
                    LogManager.Log("Firmware upgrade completed.");
                    upgradeHandler.RaiseCompleted();
                    UpdateStatus(MachineStatuses.ReadyToDye);
                    LogManager.Log("Enabling keep alive...");
                    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, new TransportRequestConfig() { Timeout = TimeSpan.FromSeconds(10), ShouldLog = true });
        }

        /// <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, new TransportRequestConfig() { Timeout = TimeSpan.FromSeconds(10), ShouldLog = true });
        }

        /// <summary>
        /// Turns off the machine.
        /// </summary>
        /// <returns></returns>
        public Task<PowerDownHandler> PowerDown()
        {
            if (_isPowerDownRequestInProgress)
            {
                throw new InvalidOperationException("Machine power down is already in progress.");
            }

            _isPowerDownRequestInProgress = true;

            PowerDownHandler handler = new PowerDownHandler(new Task(() =>
            {
                _isPowerDownRequestInProgress = false;
                Thread.Sleep(2000);
                var r = SendRequest<AbortPowerDownRequest, AbortPowerDownResponse>(new AbortPowerDownRequest(), new TransportRequestConfig() { ShouldLog = true }).Result;
            }));

            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(100);

                bool firstResponse = true;

                SendContinuousRequest<StartPowerDownRequest, StartPowerDownResponse>(new StartPowerDownRequest(), new TransportContinuousRequestConfig() { ContinuousTimeout = TimeSpan.FromSeconds(2), ShouldLog = true }).ObserveOn(new NewThreadScheduler()).Subscribe((response) =>
                {
                    if (firstResponse)
                    {
                        firstResponse = false;
                        UpdateStatus(MachineStatuses.ShuttingDown);
                    }

                    handler.RaiseStatusChanged(response);
                }, (ex) =>
                {
                    if (_isPowerDownRequestInProgress)
                    {
                        _isPowerDownRequestInProgress = false;
                        LogManager.Log(ex, "Power down error.");
                        handler.RaiseFailed(ex);
                    }
                }, () =>
                {
                    if (_isPowerDownRequestInProgress)
                    {
                        _isPowerDownRequestInProgress = false;
                        handler.RaiseCompleted();
                    }
                });
            });

            PowerDownStarted?.Invoke(this, new PowerDownStartedEventArgs()
            {
                Handler = handler,
            });

            return Task.FromResult(handler);
        }

        /// <summary>
        /// Turns off the machine.
        /// </summary>
        /// <returns></returns>
        public Task<HeadCleaningHandler> PerformHeadCleaning()
        {
            if (_isHeadCleaningInProgress)
            {
                throw new InvalidOperationException("Head cleaning is already in progress.");
            }

            if (!CanPrint)
            {
                throw new InvalidOperationException($"Cannot perform head cleaning while machine status is '{Status}'.");
            }

            _isHeadCleaningInProgress = true;
            bool _completed = false;

            HeadCleaningHandler handler = null;
            handler = new HeadCleaningHandler(() =>
            {
                _isHeadCleaningInProgress = false;
                Thread.Sleep(1000);

                if (!_completed)
                {
                    _completed = true;
                    OnHeadCleaningEnded(handler, JobRunStatus.Aborted);
                }

                var r = SendRequest<AbortHeadCleaningRequest, AbortHeadCleaningResponse>(new AbortHeadCleaningRequest(), new TransportRequestConfig() { ShouldLog = true }).Result;
            });

            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(100);

                _lastJobLiquidQuantities = new List<BL.ValueObjects.JobRunLiquidQuantity>();
                _machineStatusBeforeJobStart = MachineStatus.Clone();

                bool firstResponse = true;
                _jobStartDate = DateTime.UtcNow;

                SendContinuousRequest<StartHeadCleaningRequest, StartHeadCleaningResponse>(new StartHeadCleaningRequest(), new TransportContinuousRequestConfig() { ContinuousTimeout = TimeSpan.FromSeconds(5), ShouldLog = true }).ObserveOn(new NewThreadScheduler()).Subscribe((response) =>
                {
                    if (firstResponse)
                    {
                        firstResponse = false;
                    }

                    handler.RaiseStatusChanged(response);
                }, (ex) =>
                {
                    if (!(ex is ContinuousResponseAbortedException))
                    {
                        _isHeadCleaningInProgress = false;
                        LogManager.Log(ex, "Head cleaning error.");
                        handler.RaiseFailed(ex);
                    }

                    if (!_completed)
                    {
                        _completed = true;
                        OnHeadCleaningEnded(handler, JobRunStatus.Failed);
                    }
                }, () =>
                {
                    _isHeadCleaningInProgress = false;
                    handler.RaiseCompleted();

                    if (!_completed)
                    {
                        _completed = true;
                        OnHeadCleaningEnded(handler, JobRunStatus.Completed);
                    }
                });
            });

            return Task.FromResult(handler);
        }

        /// <summary>
        /// Starts the automatic thread loading process.
        /// </summary>
        /// <returns></returns>
        public async Task StartThreadLoading()
        {
            var response = await SendRequest<TryThreadLoadingRequest, TryThreadLoadingResponse>(new TryThreadLoadingRequest());
        }

        /// <summary>
        /// Continues the current thread loading.
        /// </summary>
        /// <param name="processParameters">The process parameters.</param>
        /// <returns></returns>
        public async Task ContinueThreadLoading(ProcessParametersTable processParameters)
        {
            var process = processParameters.ToProcessParametersPMR();
            var r = await SendRequest<ContinueThreadLoadingRequest, ContinueThreadLoadingResponse>(new ContinueThreadLoadingRequest()
            {
                ProcessParameters = process,
            }, new TransportRequestConfig() { ShouldLog = true });
        }

        /// <summary>
        /// Attempts to jog the thread in order to check whether there are no thread breaking issues.
        /// </summary>
        /// <returns></returns>
        public async Task AttemptThreadJogging()
        {
            var r = await SendRequest<AttemptThreadJoggingRequest, AttemptThreadJoggingResponse>(new AttemptThreadJoggingRequest()
            {

            }, new TransportRequestConfig() { ShouldLog = true, Timeout = TimeSpan.FromSeconds(20) });
        }

        /// <summary>
        /// Emulates a hardware event that will last for the specified timeout.
        /// </summary>
        /// <param name="ev">Type of the event.</param>
        /// <param name="timeout">The timeout.</param>
        public async void PushEmulatedEvent(Event ev, TimeSpan timeout)
        {
            if (!_emulatedEvents.Exists(x => x.Type == ev.Type))
            {
                _emulatedEvents.Add(ev);
                await Task.Delay(timeout);
                _emulatedEvents.Remove(ev);
            }
        }

        /// <summary>
        /// Gets the last machine built-in test results.
        /// </summary>
        /// <returns></returns>
        public async Task<List<BitResultComposition>> GetBitResults(List<BL.Entities.BitType> bitTypes)
        {
            if (_bitResults == null)
            {
                var response = await SendRequest<BitResultsRequest, BitResultsResponse>(new BitResultsRequest(), new TransportRequestConfig()
                {
                    ShouldLog = true,
                    Timeout = TimeSpan.FromMinutes(5)
                });

                var compositions = new List<BitResultComposition>();

                foreach (var bitType in bitTypes)
                {
                    BitResultComposition composition = new BitResultComposition();
                    composition.BitType = bitType;
                    composition.BitResult = new BitResult() { BitType = (PMR.Diagnostics.BitType)bitType.Code, Description = "Skipped" };
                    compositions.Add(composition);
                }

                foreach (var bitResult in response.Message.Results)
                {
                    var composition = compositions.SingleOrDefault(x => x.BitType.Code == bitResult.BitType.ToInt32());

                    if (composition != null)
                    {
                        composition.BitResult = bitResult;
                    }
                }

                compositions = compositions.OrderBy(x => x.Priority).ToList();

                _bitResults = compositions;
            }

            return _bitResults;
        }

        /// <summary>
        /// Notifies the remote machine about spool type change.
        /// If the machine is not connected the spool type will be added to the connection request.
        /// </summary>
        /// <param name="spoolType">Type of the spool.</param>
        public async Task SetSpoolType(JobSpoolType spoolType)
        {
            _currentSpoolType = spoolType;

            if (IsConnected)
            {
                LogManager.Log($"Changing spool type to: '{spoolType}'.");

                try
                {
                    await SendRequest<SpoolTypeChangedRequest, SpoolTypeChangedResponse>(new SpoolTypeChangedRequest()
                    {
                        SpoolType = spoolType
                    });
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, "Error changing the spool type on the machine.");
                }
            }
        }

        #endregion
    }
}