aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Utilities/Tango.Stubs.UI/StubManager.cs
blob: 6249b357727541b709dd8feafb9cfc2d6c6bc544 (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
using Google.Protobuf;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using Tango.PMR;
using Tango.PMR.Common;
using Tango.Transport.Adapters;

namespace Tango.Stubs.UI
{
    /// <summary>
    /// Represents a manager capable of executing stub scripts asynchronously.
    /// </summary>
    public class StubManager
    {
        private UsbTransportAdapter _adapter; //Holds the USB transport adapter.
        private Action<String> _writeLine;
        private Action<String> _write;
        private Action _clear;

        /// <summary>
        /// Occurs when the stub has failed to execute.
        /// </summary>
        public event EventHandler<Exception> Failed;

        /// <summary>
        /// Occurs when the stub has completed successfully.
        /// </summary>
        public event EventHandler<String> Completed;

        /// <summary>
        /// Occurs when the stub has been initialized and executed.
        /// </summary>
        public event EventHandler<String> Executed;

        /// <summary>
        /// Gets a value indicating whether this <see cref="StubManager"/> is aborted.
        /// </summary>
        internal bool Aborted { get; private set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="StubManager"/> class.
        /// </summary>
        /// <param name="adapter">The adapter.</param>
        public StubManager(UsbTransportAdapter adapter, Action<String> writeLine, Action<String> write, Action clear)
        {
            _writeLine = writeLine;
            _write = write;
            _clear = clear;

            _adapter = adapter;
        }

        /// <summary>
        /// Aborts the current script.
        /// </summary>
        internal void Abort()
        {
            Aborted = true;
        }

        /// <summary>
        /// Runs the specified stub name.
        /// </summary>
        /// <param name="stubName">Name of the stub.</param>
        /// <param name="args">The arguments.</param>
        public IMessage Run(String stubName, params Object[] args)
        {
            if (Aborted) return null;

            var stubType = StubBase.GetAvailableRequestStubs().SingleOrDefault(x => x.Name.ToLower() == stubName.ToLower() || x.Name.Replace("Request", "").ToLower() == stubName.ToLower());
            if (stubType == null)
            {
                OnFailed(new ArgumentException("Invalid stub '" + stubName + "'."));
                return null;
            }

            var stubProps = stubType.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            if (stubProps.Length > args.Length)
            {
                OnFailed(new ArgumentOutOfRangeException("Not enough arguments for " + stubType.Name + "."));
                return null;
            }

            Executed?.Invoke(this, stubType.Name);

            try
            {
                MessageContainer container = new MessageContainer();
                container.Token = Guid.NewGuid().ToString();
                container.Type = MessageFactory.ParseMessageType(stubType.Name);

                Object request = Activator.CreateInstance(stubType);

                int argIndex = 0;
                foreach (var prop in stubProps)
                {
                    String arg = args[argIndex++].ToString();

                    if (prop.PropertyType == typeof(UInt32))
                    {
                        prop.SetValue(request, UInt32.Parse(arg));
                    }
                    else if (prop.PropertyType == typeof(bool))
                    {
                        prop.SetValue(request, bool.Parse(arg));
                    }
                    else
                    {
                        object converted = Convert.ChangeType(arg, prop.PropertyType);
                        prop.SetValue(request, converted);
                    }
                }

                container.Data = typeof(IMessage).GetExtensionMethod(typeof(ByteString).Assembly, "ToByteString").Invoke(request, new object[] { request }) as ByteString;

                byte[] requestData = container.ToByteArray();

                bool done = false;

                IMessage message = null;

                Task.Factory.StartNew(() =>
                {
                    _adapter.Write(requestData);

                    DateTime startTime = DateTime.Now;

                    MessageContainer responseContainer = null;

                    _adapter.DataAvailable += (sender, data) =>
                    {
                        responseContainer = MessageFactory.ParseContainer(data);
                    };

                    while (responseContainer == null)
                    {
                        Thread.Sleep(2);

                        if (DateTime.Now > startTime.AddSeconds(2))
                        {
                            done = true;
                            OnFailed(new TimeoutException("Response has failed to arrive after 2 seconds."));
                            return;
                        }
                    }

                    message = MessageFactory.ExtractMessageFromContainer(responseContainer);
                    OnCompleted(JsonConvert.SerializeObject(message, Formatting.Indented));
                    done = true;
                });

                while (!done)
                {
                    Thread.Sleep(2);
                }

                return message;
            }
            catch (Exception ex)
            {
                OnFailed(ex);
            }

            return null;
        }

        public T Run<T>(String stubName, params Object[] args) where T : class, IMessage
        {
            return Run(stubName, args) as T;
        }

        public void WriteLine(Object obj)
        {
            _writeLine(obj.ToString());
        }

        public void Write(Object obj)
        {
            _write(obj.ToString());
        }

        public void WriteLineHex(Object number, int digits)
        {
            _writeLine("#" + Convert.ToInt32(number).ToString("X" + digits.ToString()));
        }

        public void WriteHex(Object number, int digits)
        {
            _write("#" + Convert.ToInt32(number).ToString("X" + digits.ToString()));
        }

        public void Clear()
        {
            _clear();
        }

        /// <summary>
        /// Raises the <see cref="Failed"/> event.
        /// </summary>
        /// <param name="ex">The exception.</param>
        protected virtual void OnFailed(Exception ex)
        {
            Failed?.Invoke(this, ex);
        }

        /// <summary>
        /// Raises the <see cref="Completed"/> event.
        /// </summary>
        /// <param name="response">The response.</param>
        protected virtual void OnCompleted(String response)
        {
            Completed?.Invoke(this, response);
        }
    }
}