aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.Stubs/StubManager.cs
blob: 8e0eafa3a706cf854b9d33415929a462e8a0b4db (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
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 Tango.PMR;
using Tango.PMR.Common;
using Tango.Stubs;
using Tango.Transport;
using Tango.Transport.Adapters;

namespace Tango.MachineStudio.Stubs
{
    /// <summary>
    /// Represents a manager capable of executing stub scripts asynchronously.
    /// </summary>
    public class StubManager
    {
        private ITransportAdapter _adapter; //Holds the USB transport adapter.

        /// <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(ITransportAdapter adapter)
        {
            _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 void Run(String stubName, params Object[] args)
        {
            if (Aborted) return;

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

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

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

            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;

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

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

                while (!done)
                {
                    Thread.Sleep(2);
                }
            }
            catch (Exception ex)
            {
                OnFailed(ex);
            }
        }

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