aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Utilities/Tango.Stubs.CLI/Program.cs
blob: e7c0f5d52b58a891c81b63817cfdb74629513aac (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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Tango.PMR;
using Tango.PMR.Common;
using Tango.PMR.Stubs;
using Tango.Transport.Adapters;
using Google.Protobuf;
using System.Threading;
using Newtonsoft.Json;
using Google.Protobuf.Collections;
using System.Collections;

namespace Tango.Stubs.CLI
{
    class Program
    {
        static void Main(string[] args)
        {
            Run(args);
        }

        private static void Run(string[] args)
        {
            if (args == null || args.Length < 3 || args[0] == "?")
            {
                PrintHelp();
            }

            String comPort = args[0].ToUpper();
            String baudRate = args[1];
            String stubName = args[2];

            var stubType = GetAvailableRequestResponseStubs().SingleOrDefault(x => x.Name.ToLower() == stubName.ToLower() || x.Name.Replace("Request", "").ToLower() == stubName.ToLower());
            if (stubType == null)
            {
                PrintError("Invalid stub '" + stubName + "'.");
            }

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

            if (stubProps.Length > args.Length - 3)
            {
                PrintError("Not enough arguments for " + stubType.Name + ".");
            }

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

                Object request = Activator.CreateInstance(stubType);

                int argIndex = 3;
                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 if (typeof(IList).IsAssignableFrom(prop.PropertyType))
                    {
                        IList arr = prop.GetValue(request) as IList;
                        foreach (var item in arg.Split(','))
                        {
                            object converted = Convert.ChangeType(item, prop.PropertyType.GetGenericArguments()[0]);
                            arr.Add(converted);
                        }
                    }
                    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();

                UsbSerialBaudRates rate = UsbSerialBaudRates.BR_115200;

                if (!Enum.TryParse<UsbSerialBaudRates>("BR_" + baudRate, out rate))
                {
                    throw new ArgumentException("Invalid baud rate specified.");
                }

                using (UsbTransportAdapter adapter = new UsbTransportAdapter(comPort, rate))
                {
                    Console.WriteLine("Connecting to machine on " + comPort + "...");
                    adapter.Connect().Wait();

                    bool done = false;

                    Task.Factory.StartNew(() =>
                    {
                        Console.WriteLine("Sending " + stubType.Name + "...");
                        adapter.Write(requestData);

                        DateTime startTime = DateTime.Now;

                        MessageContainer responseContainer = null;

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

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

                            if (DateTime.Now > startTime.AddSeconds(5))
                            {
                                PrintError("Response has failed to arrive after 5 seconds.");
                            }
                        }

                        Console.WriteLine("Response Received:");
                        var type = typeof(MessageFactory).Assembly.GetType("Tango.PMR.Stubs." + responseContainer.Type.ToOriginalName());
                        MessageParser parser = type.GetProperty("Parser").GetValue(container) as MessageParser;
                        IMessage message = parser.ParseFrom(responseContainer.Data);
                        Console.WriteLine(JsonConvert.SerializeObject(message, Formatting.Indented));
                        done = true;
                    });

                    while (!done)
                    {
                        Thread.Sleep(10);
                    }
                }
            }
            catch (Exception ex)
            {
                PrintError(ex.FlattenMessage());
            }
        }

        private static void PrintHelp()
        {
            Console.WriteLine("Twine - Tango stubs execution utility v" + typeof(Program).Assembly.GetName().Version.ToString());
            Console.WriteLine();
            Console.WriteLine("Usage:");
            Console.WriteLine(
                String.Format("{0} [Embedded device COM port] [stub name] [param1..] [param2..] [param3..]",
                Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().MainModule.FileName)));

            Console.WriteLine();
            Console.WriteLine("Example:");
            Console.WriteLine();
            Console.WriteLine(
                String.Format("{0} COM4 CalculateRequest 10 5",
                Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().MainModule.FileName)));

            Console.WriteLine();
            Console.WriteLine("Available Stubs:");


            int stubCount = 1;

            foreach (var stub in GetAvailableRequestResponseStubs())
            {
                Console.WriteLine();

                if ((stubCount++) % 2 != 0)
                {
                    Console.WriteLine("-----------------------------------------------------------------------------------");
                }
                Console.WriteLine(stub.Name + ":");

                int paramCount = 1;

                foreach (var prop in stub.GetProperties(BindingFlags.Public | BindingFlags.Instance))
                {
                    Console.WriteLine(String.Format("Param {0}: {1}, {2}", paramCount++, prop.Name, Path.GetExtension(prop.PropertyType.ToString()).Replace(".", "").ToLower()));
                }
            }

            ExitSuccess();
        }

        private static void PrintError(String error)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(error);
            Console.ForegroundColor = ConsoleColor.Gray;
            ExitError();
        }

        private static void ExitError()
        {
            Environment.Exit(-1);
        }

        private static void ExitSuccess()
        {
            Environment.Exit(0);
        }

        private static List<Type> GetAvailableRequestResponseStubs()
        {
            return typeof(MessageFactory).Assembly.GetTypes().Where(x => x.Namespace != null && x.Namespace.Contains("Stubs") && (x.Name.Contains("Request") || x.Name.Contains("Response")) && !x.Name.Contains("Reflection")).ToList();
        }

        public static MessageType ParseMessageType(String text)
        {
            MessageType t;
            if (Enum.TryParse<MessageType>(text, true, out t))
            {
                return t;
            }
            else
            {
                throw new InvalidCastException("Message type " + text + " was not found on PMR MessageType enumeration!");
            }
        }

        /// <summary>
        /// Parses a message container from the specified byte array.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public static MessageContainer ParseContainer(byte[] data)
        {
            MessageContainer container = MessageContainer.Parser.ParseFrom(data);
            return container;
        }
    }
}