aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/StubsUtils/Tango.StubsUtils.Service/StubsService.cs
blob: f1b6f9d9c52a701d127acabb34931b85dcf0d665 (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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
using Google.Protobuf;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Tango.Core;
using Tango.Core.DI;
using Tango.Core.ExtensionMethods;
using Tango.FSE.Procedures;
using Tango.Logging;
using Tango.PMR;
using Tango.PMR.Common;
using Tango.Settings;
using Tango.StubsUtils.Shared;
using Tango.Transport;
using Tango.Transport.Adapters;
using Tango.Transport.Transporters;

namespace Tango.StubsUtils.Service
{
    public class StubsService : ExtendedObject
    {
        private static int transporterCount = 1;
        private const string PIPE_NAME = "Tango_Stubs_Server";
        private NamedPipeServerStream _server;
        private StreamReader _reader;
        private StreamWriter _writer;
        private BinaryFormatter _formatter;
        private bool _initialized;
        private List<Type> _stubsTypes;
        private Dictionary<String, StubReflection> _stubsLookup;
        private Thread _communicationThread;

        #region Events

        public event EventHandler CommunicationFailed;

        #endregion

        #region Properties

        private ITransporter _transporter;
        public ITransporter Transporter
        {
            get { return _transporter; }
            private set { _transporter = value; RaisePropertyChangedAuto(); }
        }

        private bool _isStarted;
        public bool IsStarted
        {
            get { return _isStarted; }
            private set { _isStarted = value; RaisePropertyChangedAuto(); }
        }

        private bool _isConnected;
        public bool IsConnected
        {
            get { return _isConnected; }
            set { _isConnected = value; RaisePropertyChangedAuto(); }
        }

        private bool _enableLogs;
        public bool EnableLogs
        {
            get { return _enableLogs; }
            set { _enableLogs = value; RaisePropertyChangedAuto(); }
        }

        #endregion

        #region Constructors

        public StubsService()
        {

        }

        #endregion

        #region Start/Stop

        private void Initialize()
        {
            if (!_initialized)
            {
                _stubsTypes = new List<Type>();
                _stubsLookup = new Dictionary<string, StubReflection>();

                foreach (var type in 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())
                {
                    _stubsTypes.Add(type);
                }

                _server = new NamedPipeServerStream(PIPE_NAME);
                _reader = new StreamReader(_server);
                _writer = new StreamWriter(_server);
                _formatter = new BinaryFormatter();
                _communicationThread = new Thread(CommunicationMethod);
                _communicationThread.IsBackground = true;
                _communicationThread.Start();

                _initialized = true;
            }
        }

        public Task Start()
        {
            return Task.Factory.StartNew(() =>
            {
                if (!IsStarted)
                {
                    try
                    {
                        LogManager.Log("Starting stubs service...");
                        IsStarted = true;
                        Initialize();
                        LogManager.Log("Starting IPC service...");
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, "Error starting stubs service.");
                    }
                }
            });
        }

        public Task Stop()
        {
            return Task.Factory.StartNew(() =>
            {
                if (IsStarted)
                {
                    IsStarted = false;
                }
            });
        }

        #endregion

        #region Connect/Disconnect

        public async Task Connect(String comPort)
        {
            if (!IsStarted) throw new InvalidOperationException("Cannot connect the transporter before the service has started.");

            if (!IsConnected)
            {
                Transporter = new BasicTransporter(new UsbTransportAdapter(comPort));
                Transporter.FailsWithAdapter = true;
                Transporter.ComponentName = $"Transporter {transporterCount++}";
                Transporter.UseKeepAlive = false;
                Transporter.StateChanged += Transporter_StateChanged;
                await Transporter.Connect();
                IsConnected = true;
            }
        }

        public async Task Disconnect()
        {
            if (IsConnected)
            {
                await Transporter.Disconnect();
                IsConnected = false;
            }
        }

        private void Transporter_StateChanged(object sender, TransportComponentState state)
        {
            if (state == TransportComponentState.Failed)
            {
                IsConnected = false;
                CommunicationFailed?.Invoke(this, new EventArgs());
            }
        }

        #endregion

        #region Communication

        private void CommunicationMethod()
        {
            while (IsStarted)
            {
                try
                {
                    _server.WaitForConnection();
                    var request = _reader.ReadLine();

                    if (EnableLogs) LogManager.Log($"Stub package received: '{request}'...");

                    var package = new StubPackageRequestDTO();
                    package.Arguments = request.Split('^');

                    if (package.Arguments.Length == 0)
                    {
                        throw new InvalidOperationException("Zero arguments provided.");
                    }

                    if (package.Arguments[0] == "procedure")
                    {
                        ProcessProcedureProject(package);

                        try
                        {
                            var response = new StubPackageResponseDTO()
                            {
                                Status = StubPackageResponseStatus.OK,
                                Message = $"Completed."
                            };

                            _writer.WriteLine(response.ToString());
                            _writer.Flush();
                        }
                        catch { }
                    }
                    else
                    {
                        var response = ProcessStubPackage(package);

                        _writer.Write(response.ToString());
                        _writer.Flush();
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, "Error processing stub package.");

                    try
                    {
                        var response = new StubPackageResponseDTO()
                        {
                            Status = StubPackageResponseStatus.Error,
                            Message = $"Error: {ex.GetFirstIfAggregate().Message}"
                        };

                        _writer.WriteLine(response.ToString());
                        _writer.Flush();
                    }
                    catch { }
                }
                finally
                {
                    _server.Disconnect();
                }
            }
        }

        #endregion

        #region Process Procedure

        public void ProcessProcedureProject(StubPackageRequestDTO package)
        {
            List<String> arguments = package.Arguments.Skip(1).ToList();
            String projectPath = arguments[0];
            arguments = arguments.Skip(1).ToList();
            String json = File.ReadAllText(projectPath);
            ProcedureProject project = ProcedureProject.FromJson(json);
            var mainScript = project.Scripts.FirstOrDefault(x => x.IsEntryPoint);

            int index = 0;

            foreach (var match in Regex.Matches(mainScript.Code, "public const [S|s]tring.+;").OfType<Match>())
            {
                if (index < arguments.Count)
                {
                    String defLine = match.Value;
                    String replace = Regex.Replace(defLine, "(?<=\").*(?=\")", arguments[index]);
                    mainScript.Code = mainScript.Code.Replace(defLine, replace);
                    index++;
                }
            }

            TangoIOC.Default.ThrowOnRequestedTypeNotFound = false;

            StubsServiceProcedureContext context = new StubsServiceProcedureContext(project, Transporter, new StubsServiceProcedureLogger((message) =>
            {
                _writer.WriteLine(message);
            }));

            var session = project.Run(context).Result;
            var obj = session.WaitForCompletion().Result;

            return;
        }

        #endregion

        #region Process Package

        private StubPackageResponseDTO ProcessStubPackage(StubPackageRequestDTO package)
        {
            StubPackageResponseDTO response = new StubPackageResponseDTO();

            if (Transporter == null || Transporter.State != TransportComponentState.Connected)
            {
                throw new InvalidOperationException("Machine is disconnected");
            }

            if (EnableLogs) LogManager.Log("Processing package...");

            String stubName = package.Arguments[0];
            List<String> arguments = package.Arguments.Skip(1).ToList();

            StubReflection stubReflection = GetStubReflection(stubName);

            MessageContainer requestContainer = new MessageContainer();
            requestContainer.Token = Guid.NewGuid().ToString();
            requestContainer.Type = stubReflection.MessageType;

            IMessage request = Activator.CreateInstance(stubReflection.Type) as IMessage;

            for (int i = 0; i < arguments.Count; i++)
            {
                String argument = arguments[i];

                if (i >= stubReflection.Properties.Count)
                {
                    throw new ArgumentException($"Argument '{argument}' index is out of range for stub '{stubReflection.Type.Name}'.");
                }

                PropertyInfo prop = stubReflection.Properties[i];

                if (prop.PropertyType == typeof(UInt32))
                {
                    prop.SetValue(request, UInt32.Parse(argument));
                }
                else if (prop.PropertyType == typeof(bool))
                {
                    prop.SetValue(request, bool.Parse(argument));
                }
                else if (typeof(IList).IsAssignableFrom(prop.PropertyType))
                {
                    IList arr = prop.GetValue(request) as IList;
                    foreach (var item in argument.Split(','))
                    {
                        object converted = Convert.ChangeType(item, prop.PropertyType.GetGenericArguments()[0]);
                        arr.Add(converted);
                    }
                }
                else
                {
                    object converted = Convert.ChangeType(argument, prop.PropertyType);
                    prop.SetValue(request, converted);
                }
            }

            if (EnableLogs) LogManager.Log($"Request stub constructed:\n{request.ToJsonString()}");

            requestContainer.Data = request.ToByteString();
            var responseContainer = Transporter.SendRequest(requestContainer, new TransportRequestConfig() { ThreadingMode = TransportThreadingMode.ThreadPool }).Result;

            var stubResponseReflection = GetStubReflection(responseContainer.Type.ToOriginalName());
            IMessage stubResponse = stubResponseReflection.Parser.ParseFrom(responseContainer.Data);

            String responseMessage = String.Empty;

            foreach (var prop in stubResponseReflection.Properties)
            {
                responseMessage += $"{prop.Name}: {prop.GetValue(stubResponse).ToStringSafe()}\n";
            }

            if (EnableLogs)
            {
                String responseJson = stubResponse.ToJsonString();
                LogManager.Log($"Stub package response:\n{responseJson}");
            }

            response.Status = StubPackageResponseStatus.OK;
            response.Message = responseMessage;

            return response;
        }

        #endregion

        #region Helper Methods

        private StubReflection GetStubReflection(String stubName)
        {
            if (_stubsLookup.ContainsKey(stubName))
            {
                return _stubsLookup[stubName];
            }

            var stubReflection = StubReflection.FromStubName(stubName, _stubsTypes);
            _stubsLookup[stubName] = stubReflection;
            return stubReflection;
        }

        #endregion
    }
}