aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/MachineStudio/Tango.MachineStudio.UI/ViewModels/FirmwareUpgradeViewVM.cs
blob: e45c29f73c73c2fc24ea069c434bd79c02f1da72 (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
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Tango.Core.Commands;
using Tango.Integration.Operation;
using Tango.Integration.Upgrade;
using Tango.MachineStudio.Common.Notifications;
using Tango.SharedUI;
using Tango.SharedUI.Helpers;

namespace Tango.MachineStudio.UI.ViewModels
{
    public class FirmwareUpgradeViewVM : DialogViewVM
    {
        private IMachineOperator _operator;
        private INotificationProvider _notification;
        private FileStream _stream;

        private FirmwareUpgradeHandler _handler;
        public FirmwareUpgradeHandler Handler
        {
            get { return _handler; }
            set { _handler = value; RaisePropertyChangedAuto(); }
        }

        private String _selectedFile;
        public String SelectedFile
        {
            get { return _selectedFile; }
            set { _selectedFile = value; RaisePropertyChangedAuto(); }
        }

        private int _currentPage;
        public int CurrentPage
        {
            get { return _currentPage; }
            set { _currentPage = value; RaisePropertyChangedAuto(); }
        }

        private String upgradeError;
        public String UpgradeError
        {
            get { return upgradeError; }
            set { upgradeError = value; RaisePropertyChangedAuto(); }
        }

        private bool _dfu;
        public bool DFU
        {
            get { return _dfu; }
            set
            {
                _dfu = value; RaisePropertyChangedAuto();

                if (_dfu)
                {
                    UploadTFP = false;
                    DFUAndTFP = false;
                }
            }
        }

        private bool _uploadTFP;
        public bool UploadTFP
        {
            get { return _uploadTFP; }
            set
            {
                _uploadTFP = value; RaisePropertyChangedAuto();

                if (_uploadTFP)
                {
                    DFU = false;
                    DFUAndTFP = false;
                }
            }
        }

        private bool _dfuAndTFP;

        public bool DFUAndTFP
        {
            get { return _dfuAndTFP; }
            set
            {
                _dfuAndTFP = value; RaisePropertyChangedAuto();

                if (_dfuAndTFP)
                {
                    DFU = false;
                    UploadTFP = false;
                }
            }
        }


        public RelayCommand SelectCommand { get; set; }

        public RelayCommand UpgradeCommand { get; set; }

        public RelayCommand AbortCommand { get; set; }

        public FirmwareUpgradeViewVM(IMachineOperator machineOperator, INotificationProvider notificationProvider) : base()
        {
            DFU = true;
            _notification = notificationProvider;
            _operator = machineOperator;
            SelectCommand = new RelayCommand(BrowseForFile);
            UpgradeCommand = new RelayCommand(StartUpgrade, () => SelectedFile != null);
            AbortCommand = new RelayCommand(AbortUpgrade, () => Handler != null && Handler.Status != FirmwareUpgradeStatus.Validating && Handler.Status != FirmwareUpgradeStatus.Activating);
        }

        private async void BrowseForFile()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "Select tango firmware package file";
            dlg.Filter = "Tango Firmware Package|*.tfp";
            if (dlg.ShowDialog().Value)
            {
                try
                {
                    using (FileStream fs = new FileStream(dlg.FileName, FileMode.Open))
                    {
                        var info = await _operator.GetFirmwarePackageInfo(fs);
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex);
                    _notification.ShowError("The selected package seems to be invalid.");
                    return;
                }

                SelectedFile = dlg.FileName;
                InvalidateRelayCommands();
            }
        }

        private async void StartUpgrade()
        {
            CanClose = false;
            CurrentPage = 1;

            try
            {
                IsFree = false;

                if (DFU)
                {
                    _operator.FirmwareUpgradeMode = FirmwareUpgradeModes.DFU;
                }
                else if (UploadTFP)
                {
                    _operator.FirmwareUpgradeMode = FirmwareUpgradeModes.TFP_PACKAGE;
                }
                else if (DFUAndTFP)
                {
                    _operator.FirmwareUpgradeMode = FirmwareUpgradeModes.DFU | FirmwareUpgradeModes.TFP_PACKAGE;
                }

                _stream = new FileStream(SelectedFile, FileMode.Open);
                Handler = await _operator.UpgradeFirmware(_stream);
                Handler.Progress += (_, e) =>
                {
                    InvokeUI(() =>
                    {
                        AbortCommand.RaiseCanExecuteChanged();
                    });

                    UIHelper.DoEvents();
                };
                Handler.Completed += (_, __) =>
                {
                    CanClose = true;
                    _stream.Dispose();
                    CurrentPage = 2;
                    IsFree = true;
                };
                Handler.Canceled += (_, __) =>
                {
                    CanClose = true;
                    _stream.Dispose();
                    CurrentPage = 0;
                    IsFree = true;
                };
                Handler.Failed += (_, ex) =>
                {
                    UpgradeError = ex.FlattenMessage();
                    CanClose = true;
                    _stream.Dispose();
                    CurrentPage = 3;
                    IsFree = true;
                };
            }
            catch (Exception ex)
            {
                IsFree = true;
                CanClose = true;
                UpgradeError = ex.FlattenMessage();
                CurrentPage = 3;
            }
        }

        private async void AbortUpgrade()
        {
            CanClose = true;
            await Handler.Cancel();
            CurrentPage = 0;
        }
    }
}
"> } } } #endif #if SILVERLIGHT /// <summary> /// Gets the Pixels array /// </summary> internal int[] Pixels { get { return _writeableBitmap.Pixels; } } /// <summary> /// Gets the length of the Pixels array /// </summary> internal int Length { get { return _writeableBitmap.Pixels.Length; } } /// <summary> /// Performs a Copy operation from source BitmapContext to destination BitmapContext /// </summary> /// <remarks>Equivalent to calling Buffer.BlockCopy in Silverlight, or native memcpy in WPF</remarks> internal static void BlockCopy(BitmapContext src, int srcOffset, BitmapContext dest, int destOffset, int count) { Buffer.BlockCopy(src.Pixels, srcOffset, dest.Pixels, destOffset, count); } /// <summary> /// Performs a Copy operation from source Array to destination BitmapContext /// </summary> /// <remarks>Equivalent to calling Buffer.BlockCopy in Silverlight, or native memcpy in WPF</remarks> internal static void BlockCopy(Array src, int srcOffset, BitmapContext dest, int destOffset, int count) { Buffer.BlockCopy(src, srcOffset, dest.Pixels, destOffset, count); } /// <summary> /// Performs a Copy operation from source BitmapContext to destination Array /// </summary> /// <remarks>Equivalent to calling Buffer.BlockCopy in Silverlight, or native memcpy in WPF</remarks> internal static void BlockCopy(BitmapContext src, int srcOffset, Array dest, int destOffset, int count) { Buffer.BlockCopy(src.Pixels, srcOffset, dest, destOffset, count); } /// <summary> /// Clears the BitmapContext, filling the underlying bitmap with zeros /// </summary> internal void Clear() { var pixels = _writeableBitmap.Pixels; Array.Clear(pixels, 0, pixels.Length); } /// <summary> /// Disposes this instance if the underlying platform needs that. /// </summary> internal void Dispose() { // For silverlight, do nothing except redraw _writeableBitmap.Invalidate(); } #elif NETFX_CORE /// <summary> /// Gets the Pixels array /// </summary> internal int[] Pixels { get { return pixels; } } /// <summary> /// Gets the length of the Pixels array /// </summary> internal int Length { get { return length; } } /// <summary> /// Performs a Copy operation from source BitmapContext to destination BitmapContext /// </summary> /// <remarks>Equivalent to calling Buffer.BlockCopy in Silverlight, or native memcpy in WPF</remarks> internal static void BlockCopy(BitmapContext src, int srcOffset, BitmapContext dest, int destOffset, int count) { Buffer.BlockCopy(src.Pixels, srcOffset, dest.Pixels, destOffset, count); } /// <summary> /// Performs a Copy operation from source Array to destination BitmapContext /// </summary> /// <remarks>Equivalent to calling Buffer.BlockCopy in Silverlight, or native memcpy in WPF</remarks> internal static void BlockCopy(Array src, int srcOffset, BitmapContext dest, int destOffset, int count) { Buffer.BlockCopy(src, srcOffset, dest.Pixels, destOffset, count); } /// <summary> /// Performs a Copy operation from source BitmapContext to destination Array /// </summary> /// <remarks>Equivalent to calling Buffer.BlockCopy in Silverlight, or native memcpy in WPF</remarks> internal static void BlockCopy(BitmapContext src, int srcOffset, Array dest, int destOffset, int count) { Buffer.BlockCopy(src.Pixels, srcOffset, dest, destOffset, count); } /// <summary> /// Clears the BitmapContext, filling the underlying bitmap with zeros /// </summary> internal void Clear() { var pixels = Pixels; Array.Clear(pixels, 0, pixels.Length); } /// <summary> /// Disposes this instance if the underlying platform needs that. /// </summary> internal unsafe void Dispose() { // Decrement the update count. If it hits zero if (DecrementRefCount(_writeableBitmap) == 0) { // Remove this bitmap from the update map UpdateCountByBmp.Remove(_writeableBitmap); PixelCacheByBmp.Remove(_writeableBitmap); // Copy data back if (_mode == ReadWriteMode.ReadWrite) { using (var stream = _writeableBitmap.PixelBuffer.AsStream()) { var buffer = new byte[length * 4]; fixed (int* srcPtr = pixels) { var b = 0; for (var i = 0; i < length; i++, b += 4) { var p = srcPtr[i]; buffer[b + 3] = (byte)((p >> 24) & 0xff); buffer[b + 2] = (byte)((p >> 16) & 0xff); buffer[b + 1] = (byte)((p >> 8) & 0xff); buffer[b + 0] = (byte)(p & 0xff); } stream.Write(buffer, 0, length * 4); } } _writeableBitmap.Invalidate(); } } } #elif WPF /// <summary> /// The pixels as ARGB integer values, where each channel is 8 bit. /// </summary> internal unsafe int* Pixels { [System.Runtime.TargetedPatchingOptOut("Candidate for inlining across NGen boundaries for performance reasons")] get { return _backBuffer; } } /// <summary> /// The pixel format /// </summary> internal PixelFormat Format { [System.Runtime.TargetedPatchingOptOut("Candidate for inlining across NGen boundaries for performance reasons")] get { return _writeableBitmap.Format; } } /// <summary> /// The number of pixels. /// </summary> internal int Length { [System.Runtime.TargetedPatchingOptOut("Candidate for inlining across NGen boundaries for performance reasons")] get { return _length; } } /// <summary> /// Performs a Copy operation from source to destination BitmapContext /// </summary> /// <remarks>Equivalent to calling Buffer.BlockCopy in Silverlight, or native memcpy in WPF</remarks> [System.Runtime.TargetedPatchingOptOut("Candidate for inlining across NGen boundaries for performance reasons")] internal static unsafe void BlockCopy(BitmapContext src, int srcOffset, BitmapContext dest, int destOffset, int count) { NativeMethods.CopyUnmanagedMemory((byte*)src.Pixels, srcOffset, (byte*)dest.Pixels, destOffset, count); } /// <summary> /// Performs a Copy operation from source Array to destination BitmapContext /// </summary> /// <remarks>Equivalent to calling Buffer.BlockCopy in Silverlight, or native memcpy in WPF</remarks> [System.Runtime.TargetedPatchingOptOut("Candidate for inlining across NGen boundaries for performance reasons")] internal static unsafe void BlockCopy(int[] src, int srcOffset, BitmapContext dest, int destOffset, int count) { fixed (int* srcPtr = src) { NativeMethods.CopyUnmanagedMemory((byte*)srcPtr, srcOffset, (byte*)dest.Pixels, destOffset, count); } } /// <summary> /// Performs a Copy operation from source Array to destination BitmapContext /// </summary> /// <remarks>Equivalent to calling Buffer.BlockCopy in Silverlight, or native memcpy in WPF</remarks> [System.Runtime.TargetedPatchingOptOut("Candidate for inlining across NGen boundaries for performance reasons")] internal static unsafe void BlockCopy(byte[] src, int srcOffset, BitmapContext dest, int destOffset, int count) { fixed (byte* srcPtr = src) { NativeMethods.CopyUnmanagedMemory(srcPtr, srcOffset, (byte*)dest.Pixels, destOffset, count); } } /// <summary> /// Performs a Copy operation from source BitmapContext to destination Array /// </summary> /// <remarks>Equivalent to calling Buffer.BlockCopy in Silverlight, or native memcpy in WPF</remarks> [System.Runtime.TargetedPatchingOptOut("Candidate for inlining across NGen boundaries for performance reasons")] internal static unsafe void BlockCopy(BitmapContext src, int srcOffset, byte[] dest, int destOffset, int count) { fixed (byte* destPtr = dest) { NativeMethods.CopyUnmanagedMemory((byte*)src.Pixels, srcOffset, destPtr, destOffset, count); } } /// <summary> /// Performs a Copy operation from source BitmapContext to destination Array /// </summary> /// <remarks>Equivalent to calling Buffer.BlockCopy in Silverlight, or native memcpy in WPF</remarks> [System.Runtime.TargetedPatchingOptOut("Candidate for inlining across NGen boundaries for performance reasons")] internal static unsafe void BlockCopy(BitmapContext src, int srcOffset, int[] dest, int destOffset, int count) { fixed (int* destPtr = dest) { NativeMethods.CopyUnmanagedMemory((byte*)src.Pixels, srcOffset, (byte*)destPtr, destOffset, count); } } /// <summary> /// Clears the BitmapContext, filling the underlying bitmap with zeros /// </summary> [System.Runtime.TargetedPatchingOptOut("Candidate for inlining across NGen boundaries for performance reasons")] internal void Clear() { NativeMethods.SetUnmanagedMemory(_writeableBitmap.BackBuffer, 0, _writeableBitmap.BackBufferStride * _writeableBitmap.PixelHeight); } /// <summary> /// Disposes the BitmapContext, unlocking it and invalidating if WPF /// </summary> public void Dispose() { // Decrement the update count. If it hits zero if (DecrementRefCount(_writeableBitmap) == 0) { // Remove this bitmap from the update map UpdateCountByBmp.Remove(_writeableBitmap); // Invalidate the bitmap if ReadWrite _mode if (_mode == ReadWriteMode.ReadWrite) { _writeableBitmap.AddDirtyRect(new Int32Rect(0, 0, _writeableBitmap.PixelWidth, _writeableBitmap.PixelHeight)); } // Unlock the bitmap _writeableBitmap.Unlock(); } } #endif #if WPF || NETFX_CORE private static void IncrementRefCount(WriteableBitmap target) { UpdateCountByBmp[target]++; } private static int DecrementRefCount(WriteableBitmap target) { int current; if (!UpdateCountByBmp.TryGetValue(target, out current)) { return -1; } current--; UpdateCountByBmp[target] = current; return current; } #endif } }