aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/StubsUtils/Tango.StubsUtils.Service/StubsServiceProcedureContext.cs
blob: 02eba672e23c4fa8b3da659ca6c5f17626e50adf (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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Google.Protobuf;
using Tango.Core;
using Tango.Core.ExtensionMethods;
using Tango.FSE.Procedures;
using Tango.PMR;
using Tango.Transport;

namespace Tango.StubsUtils.Service
{
    public class StubsServiceProcedureContext : ProcedureContext
    {
        private ITransporter _transporter;

        public StubsServiceProcedureContext(ProcedureProject project, ITransporter transporter, IProcedureLogger logger) : base(project, logger)
        {
            _transporter = transporter;
        }

        public override IMessage Send(IMessage message, int? timeout = null)
        {
            TimeSpan? timespan = null;

            if (timeout != null)
            {
                timespan = TimeSpan.FromMilliseconds(timeout.Value);
            }

            return _transporter.SendRequest(message, new TransportRequestConfig()
            {
                Timeout = timespan,
            }).Result;
        }

        public override void SendContinuous<T>(IMessage message, Action<T> callback, int? timeout = null)
        {
            TaskCompletionSource<object> completion = new TaskCompletionSource<object>();

            TimeSpan? timespan = null;

            if (timeout != null)
            {
                timespan = TimeSpan.FromMilliseconds(timeout.Value);
            }

            _transporter.SendContinuousRequest(message, new TransportContinuousRequestConfig()
            {
                Timeout = timespan,
                ContinuousTimeout = timespan
            }).ObserveOn(new NewThreadScheduler()).Subscribe((msg) =>
            {
                try
                {
                    callback?.Invoke(msg as T);
                }
                catch { }
            }, (ex) =>
            {
                completion.SetException(ex);
            }, () =>
            {
                completion.SetResult(true);
            });

            completion.Task.GetAwaiter().GetResult();
        }
    }
}