aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Transport/TransportMessage.cs
blob: 73bf3b1e045747e9871bab95ee1e1a170d9dd51f (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
using Google.Protobuf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading.Tasks;
using Tango.Logging;
using Tango.PMR;
using Tango.PMR.Common;

namespace Tango.Transport
{
    /// <summary>
    /// Represents a generic transport message.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <seealso cref="Tango.Transport.TransportMessageBase" />
    internal class TransportMessage<T> : TransportMessageBase
    {
        private TaskCompletionSource<T> _completionSource;

        public Subject<T> ContinuesResponseSubject { get; set; }

        public bool AtLeastOneResponseReceived { get; set; }

        public DateTime LastResponseTime { get; set; }

        public bool Completed { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="TransportMessage{T}"/> class.
        /// </summary>
        /// <param name="token">The token.</param>
        /// <param name="message">The message.</param>
        /// <param name="direction">The direction.</param>
        /// <param name="toBytes">To bytes.</param>
        /// <param name="completionSource">The completion source.</param>
        public TransportMessage(string token, object message, TransportMessageDirection direction, Func<byte[]> toBytes, TaskCompletionSource<T> completionSource) : base(token, message, direction, toBytes)
        {
            _completionSource = completionSource;
        }

        /// <summary>
        /// Notifies the message observer of the new result.
        /// </summary>
        /// <param name="result">The result.</param>
        public override void SetResult(object result, bool completed)
        {
            Completed = completed;

            Task.Factory.StartNew(() =>
            {
                try
                {
                    if (!IsContinuous)
                    {
                        if (!_completionSource.Task.IsCompleted)
                        {
                            if (_completionSource.GetType() == typeof(TaskCompletionSource<IMessage>))
                            {
                                _completionSource.SetResult((T)result.GetType().GetProperty("Message").GetValue(result));
                            }
                            else if (_completionSource.GetType() == typeof(TaskCompletionSource<MessageContainer>))
                            {
                                _completionSource.SetResult((T)result.GetType().GetProperty("Container").GetValue(result));
                            }
                            else
                            {
                                _completionSource.SetResult((T)result);
                            }
                        }
                    }
                    else
                    {
                        LastResponseTime = DateTime.Now;
                        AtLeastOneResponseReceived = true;

                        if (ContinuesResponseSubject.GetType() == typeof(Subject<IMessage>))
                        {
                            ContinuesResponseSubject.OnNext((T)result.GetType().GetProperty("Message").GetValue(result));
                        }
                        else if (ContinuesResponseSubject.GetType() == typeof(Subject<MessageContainer>))
                        {
                            ContinuesResponseSubject.OnNext((T)result.GetType().GetProperty("Container").GetValue(result));
                        }
                        else
                        {
                            ContinuesResponseSubject.OnNext((T)result);
                        }

                        if (completed)
                        {
                            ContinuesResponseSubject.OnCompleted();
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Log(ex, $"Error while settings result for message.");
                    try
                    {
                        SetException(ex);
                    }
                    catch (Exception e)
                    {
                        LogManager.Log(e, $"Error while settings exception for message.");
                    }
                }
            });
        }

        /// <summary>
        /// Notifies the message observer of an exception.
        /// </summary>
        /// <param name="ex">The ex.</param>
        public override void SetException(Exception ex)
        {
            Completed = true;

            Task.Factory.StartNew(() =>
            {
                if (!IsContinuous)
                {
                    if (!_completionSource.Task.IsCompleted)
                    {
                        _completionSource.SetException(ex);
                    }
                }
                else
                {
                    AtLeastOneResponseReceived = true;
                    ContinuesResponseSubject.OnError(ex);
                }
            });
        }
    }
}