aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Transport/TransporterBase.cs
blob: 5a56754b9f3808fc2c2e29a6fe29b56632f6c12f (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
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
/* Generated by the protocol buffer compiler.  DO NOT EDIT! */
/* Generated from: ConnectResponse.proto */

#ifndef PROTOBUF_C_ConnectResponse_2eproto__INCLUDED
#define PROTOBUF_C_ConnectResponse_2eproto__INCLUDED

#include <protobuf-c/protobuf-c.h>

PROTOBUF_C__BEGIN_DECLS

#if PROTOBUF_C_VERSION_NUMBER < 1003000
# error This file was generated by a newer version of protoc-c which is incompatible with your libprotobuf-c headers. Please update your headers.
#elif 1003000 < PROTOBUF_C_MIN_COMPILER_VERSION
# error This file was generated by an older version of protoc-c which is incompatible with your libprotobuf-c headers. Please regenerate this file with a newer version of protoc-c.
#endif

#include "DeviceInformation.pb-c.h"

typedef struct _ConnectResponse ConnectResponse;


/* --- enums --- */


/* --- messages --- */

struct  _ConnectResponse
{
  ProtobufCMessage base;
  DeviceInformation *deviceinformation;
};
#define CONNECT_RESPONSE__INIT \
 { PROTOBUF_C_MESSAGE_INIT (&connect_response__descriptor) \
    , NULL }


/* ConnectResponse methods */
void   connect_response__init
                     (ConnectResponse         *message);
size_t connect_response__get_packed_size
                     (const ConnectResponse   *message);
size_t connect_response__pack
                     (const ConnectResponse   *message,
                      uint8_t             *out);
size_t connect_response__pack_to_buffer
                     (const ConnectResponse   *message,
                      ProtobufCBuffer     *buffer);
ConnectResponse *
       connect_response__unpack
                     (ProtobufCAllocator  *allocator,
                      size_t               len,
                      const uint8_t       *data);
void   connect_response__free_unpacked
                     (ConnectResponse *message,
                      ProtobufCAllocator *allocator);
/* --- per-message closures --- */

typedef void (*ConnectResponse_Closure)
                 (const ConnectResponse *message,
                  void *closure_data);

/* --- services --- */


/* --- descriptors --- */

extern const ProtobufCMessageDescriptor connect_response__descriptor;

PROTOBUF_C__END_DECLS


#endif  /* PROTOBUF_C_ConnectResponse_2eproto__INCLUDED */
id='n459' href='#n459'>459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
using Google.Protobuf;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Tango.Core;
using Tango.Logging;
using Tango.PMR;
using Tango.PMR.Common;
using System.Reactive.Linq;
using System.ServiceModel;
using Tango.Transport.Encoders;
using Tango.PMR.Connection;
using Tango.Core.Threading;
using System.IO;
using Tango.Core.ExtensionMethods;
using Tango.PMR.Integration;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Reactive.Concurrency;

namespace Tango.Transport
{
    /// <summary>
    /// Represents an <see cref="ITransporter"/> base class.
    /// </summary>
    /// <seealso cref="Tango.Transport.ITransporter" />
    public abstract class TransporterBase : ExtendedObject, ITransporter
    {
        protected static long _component_counter = 1;

        private class RequestHandler
        {
            public Type RequestType { get; set; }
            public Action<ITransporter, Object, String> Callback { get; set; }
            public object RegisteredCallback { get; set; }
        }

        private const int MESSAGE_TOKEN_LENGTH = 36;
        private PriorityProducerConsumerQueue<TransportMessageBase> _sendingQueue;
        private ConcurrentList<TransportMessageBase> _pendingRequests;
        private ProducerConsumerQueue<byte[]> _arrivedResponses;
        private Thread _pushThread;
        private Thread _pullThread;
        private Thread _keepAliveThread;
        private ITransportAdapter _adapter;
        private Dictionary<String, PendingResponse> _pendingResponses;
        private DateTime _lastKeepAliveTime;
        private List<RequestHandler> _requestHandlers;
        private static JsonSerializerSettings _genericMessageSettings = new JsonSerializerSettings()
        {
            TypeNameHandling = TypeNameHandling.All,
        };

        #region Events

        /// <summary>
        /// Occurs when a new request message has been received.
        /// </summary>
        public event EventHandler<RequestReceivedEventArgs> RequestReceived;

        /// <summary>
        /// Occurs when a new response message has been received.
        /// </summary>
        public event EventHandler<MessageContainer> PendingResponseReceived;

        /// <summary>
        /// Occurs when component state changes.
        /// </summary>
        public event EventHandler<TransportComponentState> StateChanged;

        /// <summary>
        /// Occurs when a request has been sent.
        /// </summary>
        public event EventHandler<IMessage> RequestSent;

        /// <summary>
        /// Occurs when a request response has been received.
        /// </summary>
        public event EventHandler<IMessage> ResponseReceived;

        /// <summary>
        /// Occurs when a request has failed.
        /// </summary>
        public event EventHandler<RequestFailedEventArgs> RequestFailed;

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the name of the transport component.
        /// </summary>
        public String ComponentName { get; set; }

        /// <summary>
        /// Gets or sets the <see cref="ITransportAdapter" /> used to read and write raw data.
        /// </summary>
        public ITransportAdapter Adapter
        {
            get { return _adapter; }
            set
            {
                var previous = _adapter;
                _adapter = value;
                OnAdapterChanged(previous, value);
                RaisePropertyChangedAuto();
            }
        }

        /// <summary>
        /// Gets or sets the transport encoder used to encode and decode tango messages.
        /// </summary>
        public ITransportEncoder Encoder { get; set; }

        private TransportComponentState _state;
        /// <summary>
        /// Gets the component state.
        /// </summary>
        public TransportComponentState State
        {
            get { return _state; }
            protected set
            {
                if (_state != value)
                {
                    _state = value;
                    OnStateChanged(_state);
                }
            }
        }

        /// <summary>
        /// Gets or sets the request timeout.
        /// </summary>
        public TimeSpan RequestTimeout { get; set; }

        private bool _useKeepAlive;
        /// <summary>
        /// Gets or sets a value indicating whether to use a keep alive mechanism.
        /// </summary>
        public bool UseKeepAlive
        {
            get { return _useKeepAlive; }
            set
            {
                _useKeepAlive = value;
                RaisePropertyChangedAuto();

                if (_useKeepAlive)
                {
                    LogManager.Log($"{GetExtendedComponentName()}: KeepAlive is activated...");
                }
                else
                {
                    LogManager.Log($"{GetExtendedComponentName()}: KeepAlive is deactivated.");
                }
            }
        }

        /// <summary>
        /// Gets or sets the keep alive timeout.
        /// </summary>
        public TimeSpan KeepAliveTimeout { get; set; }

        /// <summary>
        /// Gets or sets the keep alive retries.
        /// </summary>
        public int KeepAliveRetries { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether to auto respond to keep alive requests.
        /// </summary>
        public bool EnableKeepAliveAutoResponse { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether the transporter will get in to a failed state if any adapter has failed.
        /// </summary>
        public bool FailsWithAdapter { get; set; }

        /// <summary>
        /// Gets the last failed state exception/reason.
        /// </summary>
        public Exception FailedStateException { get; private set; }

        private GenericMessageProtocol _genericProtocol;
        /// <summary>
        /// Gets or sets the generic protocol used to serialize/deserialize generic messages.
        /// </summary>
        public GenericMessageProtocol GenericProtocol
        {
            get { return _genericProtocol; }
            set { _genericProtocol = value; RaisePropertyChangedAuto(); }
        }

        #endregion

        #region Virtual Methods

        /// <summary>
        /// Called when the <see cref="Adapter"/> has changed.
        /// </summary>
        /// <param name="newAdapter">The adapter.</param>
        protected async virtual void OnAdapterChanged(ITransportAdapter oldAdapter, ITransportAdapter newAdapter)
        {
            if (oldAdapter != newAdapter)
            {
                _pendingRequests.Clear();
                _pendingResponses.Clear();
                _arrivedResponses = new ProducerConsumerQueue<byte[]>();
                _sendingQueue = new PriorityProducerConsumerQueue<TransportMessageBase>();
            }

            if (oldAdapter != null)
            {
                oldAdapter.StateChanged -= OnAdapterStateChanged;
                oldAdapter.DataAvailable -= OnAdapterDataAvailable;
            }

            if (newAdapter != null)
            {
                LogManager.Log($"{GetExtendedComponentName()}: Adapter Changed: Type = {newAdapter.GetType().Name}, Address = {newAdapter.Address}, State = {newAdapter.State}");

                newAdapter.StateChanged -= OnAdapterStateChanged;
                newAdapter.DataAvailable -= OnAdapterDataAvailable;
                newAdapter.StateChanged += OnAdapterStateChanged;
                newAdapter.DataAvailable += OnAdapterDataAvailable;

                if (State == TransportComponentState.Connected && newAdapter.State == TransportComponentState.Disconnected)
                {
                    await newAdapter.Connect();
                }
            }
            else
            {
                LogManager.Log($"{GetExtendedComponentName()}: Adapter Changed: null");
            }
        }

        /// <summary>
        /// Called when the current adapter state has changed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        protected virtual void OnAdapterStateChanged(object sender, TransportComponentState e)
        {
            if (e == TransportComponentState.Failed && FailsWithAdapter)
            {
                OnFailed(new CommunicationException($"The adapter has failed with exception '{Adapter.FailedStateException.Message}' and the transporter is configured to fail with the adapter."));
            }
        }

        /// <summary>
        /// Called when there is data available from the adapter.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="data">The data.</param>
        protected virtual void OnAdapterDataAvailable(object sender, byte[] data)
        {
            _lastKeepAliveTime = DateTime.Now;
            EnqueueMessageIn(data);
        }

        /// <summary>
        /// Called when the component has failed.
        /// </summary>
        /// <param name="ex">The ex.</param>
        protected virtual async void OnFailed(Exception ex)
        {
            if (State != TransportComponentState.Failed)
            {
                FailedStateException = ex;
                LogManager.Log(ex, $"{GetExtendedComponentName()}: Transporter failed.");
                State = TransportComponentState.Failed;

                await OnPostDisconnection();
            }
            else
            {
                LogManager.Log(ex, LogCategory.Warning, $"{GetExtendedComponentName()}: OnFailed called while state is already failed!");
            }
        }

        protected virtual async Task OnPostDisconnection()
        {
            try
            {
                if (_pullThread != null)
                {
                    _pullThread.Abort();
                    _pushThread.Abort();
                    _keepAliveThread.Abort();
                }
            }
            catch { }

            if (Adapter != null)
            {
                await Adapter.Disconnect();
            }

            NotifyContinuousRequestMessagesDisconnection();
        }

        /// <summary>
        /// Called when a new request has been received.
        /// </summary>
        /// <param name="container">The request.</param>
        protected virtual void OnRequestReceived(RequestReceivedEventArgs e)
        {
            var container = e.Container;

            if (_requestHandlers.Count > 0)
            {
                if (container.Type != MessageType.GenericRequest)
                {
                    var handlers = _requestHandlers.Where(x => x.RequestType.Name == container.Type.ToOriginalName()).ToList();

                    if (handlers.Count > 0) //Handle
                    {
                        e.Handled = true;

                        var request = MessageFactory.ExtractMessageFromContainer(container);

                        foreach (var handler in handlers)
                        {
                            try
                            {
                                handler.Callback.Invoke(this, request, container.Token);
                            }
                            catch
                            {
                                //Ignore any exception on the client side.
                            }
                        }
                    }
                }
                else
                {
                    var genericRequest = MessageFactory.ExtractMessageFromContainer<GenericRequest>(container);

                    var handlers = _requestHandlers.Where(x => x.RequestType.AssemblyQualifiedName == genericRequest.Type).ToList();

                    if (handlers.Count > 0)
                    {
                        e.Handled = true;

                        var innerRequest = GenericMessageSerializer.DeserializeFromByteString(handlers[0].RequestType, genericRequest.Data, GenericProtocol);

                        foreach (var handler in handlers)
                        {
                            try
                            {
                                handler.Callback.Invoke(this, innerRequest, container.Token);
                            }
                            catch
                            {
                                //Ignore any exception on the client side.
                            }
                        }
                    }
                }
            }

            RequestReceived?.Invoke(this, e);
        }

        /// <summary>
        /// Called when a new response has been received.
        /// </summary>
        /// <param name="container">The request.</param>
        protected virtual void OnResponseReceived(MessageContainer container)
        {
            PendingResponseReceived?.Invoke(this, container);
        }

        /// <summary>
        /// Called when the component state has changed.
        /// </summary>
        /// <param name="state">The state.</param>
        protected virtual void OnStateChanged(TransportComponentState state)
        {
            StateChanged?.Invoke(this, state);
        }

        /// <summary>
        /// Returns a string representing the component name. If an adapter is attached it will be part of the string.
        /// </summary>
        /// <returns></returns>
        protected virtual String GetExtendedComponentName()
        {
            return Adapter != null ? $"{ComponentName} ({Adapter.Address})" : ComponentName;
        }

        /// <summary>
        /// Notifies all the continuous request messages about disconnection.
        /// </summary>
        protected virtual void NotifyContinuousRequestMessagesDisconnection()
        {
            LogManager.Log("Notifying all continuous request messages about disconnection...");
            foreach (var request in _pendingRequests.ToList().Where(x => x.Direction == TransportMessageDirection.Request && x.IsContinuous))
            {
                try
                {
                    _pendingRequests.Remove(request);
                    LogManager.Log($"Notifying continuous request '{(request.Message as ITangoMessage).Type}'...");
                    OnRequestFailed(request, new TransporterDisconnectedException("Transporter disconnected."));
                    request.SetException(new TransporterDisconnectedException("Transporter disconnected."));
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e.ToString());
                }
            }
        }

        /// <summary>
        /// Called when the request has been sent
        /// </summary>
        /// <param name="response">The request.</param>
        private void OnRequestSent(TransportMessageBase request)
        {
            if (request.ShouldLog)
            {
                IMessage message = request.GetActualMessage() as IMessage;

                if (message != null)
                {
                    RequestSent?.Invoke(this, message);
                }
            }
        }

        /// <summary>
        /// Called when the response has been received
        /// </summary>
        /// <param name="response">The response.</param>
        private void OnResponseReceived(IMessage response)
        {
            if (response != null)
            {
                ResponseReceived?.Invoke(this, response);
            }
        }

        /// <summary>
        /// Called when the request has been failed
        /// </summary>
        /// <param name="request">The request.</param>
        private void OnRequestFailed(TransportMessageBase request, Exception exception)
        {
            IMessage message = request.GetActualMessage() as IMessage;

            if (message != null)
            {
                RequestFailed?.Invoke(this, new RequestFailedEventArgs(message, exception));
            }
        }

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="TransporterBase"/> class.
        /// </summary>
        public TransporterBase()
        {
            ComponentName = "Not Set";
            Encoder = new ProtoEncoder();
            _pendingResponses = new Dictionary<string, PendingResponse>();
            _sendingQueue = new PriorityProducerConsumerQueue<TransportMessageBase>();
            _pendingRequests = new ConcurrentList<TransportMessageBase>();
            _arrivedResponses = new ProducerConsumerQueue<byte[]>();
            _requestHandlers = new List<RequestHandler>();
            RequestTimeout = TimeSpan.FromSeconds(5);
            EnableKeepAliveAutoResponse = true;
            KeepAliveTimeout = TimeSpan.FromSeconds(2);
            KeepAliveRetries = 1;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="TransporterBase"/> class.
        /// </summary>
        /// <param name="adapter">The transport adapter.</param>
        public TransporterBase(ITransportAdapter adapter) : this()
        {
            Adapter = adapter;
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Clears all message queues.
        /// </summary>
        public void ClearQueues()
        {
            _sendingQueue = new PriorityProducerConsumerQueue<TransportMessageBase>();
            _pendingRequests = new ConcurrentList<TransportMessageBase>();
            _arrivedResponses = new ProducerConsumerQueue<byte[]>();
        }

        /// <summary>
        /// Connects the transport component.
        /// </summary>
        /// <returns></returns>
        public virtual async Task Connect()
        {
            if (Adapter != null)
            {
                await Adapter.Connect();
            }

            State = TransportComponentState.Connected;
            StartThreads();

            LogManager.Log($"{GetExtendedComponentName()}: Transporter Connected...");
        }

        /// <summary>
        /// Disconnects the transport component.
        /// </summary>
        /// <returns></returns>
        public virtual async Task Disconnect()
        {
            if (State == TransportComponentState.Connected)
            {
                State = TransportComponentState.Disconnected;

                await OnPostDisconnection();

                LogManager.Log($"{GetExtendedComponentName()}: Transporter Disconnected...");
            }
        }

        #endregion

        #region Public Request Methods

        /// <summary>
        /// Sends a request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="config">Request configuration.</param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        public Task<IMessage> SendRequest(IMessage request, TransportRequestConfig config = null)
        {
            MessageContainer container = new MessageContainer();
            container.Token = Guid.NewGuid().ToString();
            container.Data = request.ToByteString();
            container.Timeout = config.Timeout.HasValue ? (UInt32)config.Timeout.Value.TotalMilliseconds : (UInt32)RequestTimeout.TotalMilliseconds;
            container.Type = MessageFactory.ParseMessageType(request.GetType().Name);

            return SendRequestInternal<IMessage>(container.Token, container, config).Task;
        }

        /// <summary>
        /// Sends the request.
        /// </summary>
        /// <param name="container"></param>
        /// <param name="config">Request configuration.</param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        public Task<MessageContainer> SendRequest(MessageContainer container, TransportRequestConfig config = null)
        {
            return SendRequestInternal<MessageContainer>(container.Token, container, config).Task;
        }

        /// <summary>
        /// Sends a request.
        /// </summary>
        /// <typeparam name="Request">The type of the request.</typeparam>
        /// <typeparam name="Response">The type of the response.</typeparam>
        /// <param name="request">The request.</param>
        /// <param name="config">Request configuration.</param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        public Task<TangoMessage<Response>> SendRequest<Request, Response>(TangoMessage<Request> request, TransportRequestConfig config = null) where Request : IMessage<Request> where Response : IMessage<Response>
        {
            return SendRequestInternal<TangoMessage<Response>>(request.Container.Token, request, config).Task;
        }

        private TaskCompletionSource<T> SendRequestInternal<T>(String token, Object request, TransportRequestConfig config = null)
        {
            config = config ?? new TransportRequestConfig();

            TaskCompletionSource<T> source = new TaskCompletionSource<T>();

            String requestName = TransportMessageBase.GetActualMessageTypeName(request);

            Func<byte[]> toBytes = null;

            if (request is ITangoMessage tangoMessage)
            {
                toBytes = () => Encoder.Encode(tangoMessage);
            }
            else if (request is IMessage protoMessage)
            {
                toBytes = () => protoMessage.ToByteArray();
            }

            TransportMessage<T> message = new TransportMessage<T>(token, request, TransportMessageDirection.Request, toBytes, source);
            message.ShouldLog = config.ShouldLog;
            message.Immidiate = config.Immediate;
            message.Priority = config.Priority;
            message.TransportComponentName = GetExtendedComponentName();
            message.ThreadingMode = config.ThreadingMode;

            TimeSpan? timeout = config.Timeout;

            if (request is MessageContainer container)
            {
                timeout = GetContainerTimeoutOrDefault(container);
            }

            if (timeout == null)
            {
                timeout = RequestTimeout;
            }

            if (request is ITangoMessage tanMessage)
            {
                tanMessage.Container.Timeout = (uint)timeout.Value.TotalMilliseconds;
            }

            String responseName = requestName.Replace("Request", "Response");

            LogManager.Log($"{GetExtendedComponentName()}: Queuing request message: {requestName} Token: {token}", LogCategory.Debug);
            LogManager.Log($"{GetExtendedComponentName()}: Expected response: {responseName}", LogCategory.Debug);

            if (State != TransportComponentState.Connected)
            {
                throw LogManager.Log(new InvalidOperationException($"{GetExtendedComponentName()}: Could not send the request while transporter state is {State}."));
            }


            Action timeoutAction = () => 
            {
                if (!source.Task.IsCompleted)
                {
                    TimeoutException ex = new TimeoutException($"{GetExtendedComponentName()}: Request message '{requestName}' had timed out after {timeout.Value.TotalSeconds} seconds.");
                    OnRequestFailed(message, ex);
                    message.SetException(ex);
                }
            };

            if (config.ThreadingMode == TransportThreadingMode.NewThread)
            {
                message.ActivateTimeout = () =>
                {
                    TimeoutTask.StartNew(() =>
                    {
                        timeoutAction();
                    }, timeout.Value);
                };
            }
            else
            {
                message.ActivateTimeout = () =>
                {
                    Task.Delay(timeout.Value).ContinueWith((x) =>
                    {
                        timeoutAction();
                    });
                };
            }

            EnqueueMessageOut(message);

            return source;
        }

        /// <summary>
        /// Sends a request and expecting multiple response messages.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="config">Request configuration.</param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        public IObservable<IMessage> SendContinuousRequest(IMessage request, TransportContinuousRequestConfig config = null)
        {
            MessageContainer container = new MessageContainer();
            container.Token = Guid.NewGuid().ToString();
            container.Data = request.ToByteString();
            container.Type = MessageFactory.ParseMessageType(request.GetType().Name);

            //We need to assign this timeout because when the internal method detects a MessageContainer it will bypass the container continuous timeout assignment.
            container.ContinuousTimeout = config.ContinuousTimeout != null ? (UInt32)config.ContinuousTimeout.Value.TotalMilliseconds : 0;

            container.Continuous = true;

            return SendContinuousRequestInternal<IMessage>(container.Token, container, config);
        }

        /// <summary>
        /// Sends a request and expecting multiple response messages.
        /// </summary>
        /// <typeparam name="Request">The type of the request.</typeparam>
        /// <typeparam name="Response">The type of the response.</typeparam>
        /// <param name="request"></param>
        /// <param name="config">Request configuration.</param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        public IObservable<TangoMessage<Response>> SendContinuousRequest<Request, Response>(TangoMessage<Request> request, TransportContinuousRequestConfig config = null) where Request : IMessage<Request> where Response : IMessage<Response>
        {
            request.Container.Continuous = true;
            request.Container.Completed = false;
            return SendContinuousRequestInternal<TangoMessage<Response>>(request.Container.Token, request, config);
        }

        /// <summary>
        /// Sends a continuous request.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <param name="config">Request configuration.</param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException"></exception>
        public IObservable<MessageContainer> SendContinuousRequest(MessageContainer container, TransportContinuousRequestConfig config = null)
        {
            return SendContinuousRequestInternal<MessageContainer>(container.Token, container, config);
        }

        private IObservable<T> SendContinuousRequestInternal<T>(String token, Object request, TransportContinuousRequestConfig config = null)
        {
            config = config ?? new TransportContinuousRequestConfig();

            String requestName = TransportMessageBase.GetActualMessageTypeName(request);

            Func<byte[]> toBytes = null;

            if (request is ITangoMessage tangoMessage)
            {
                toBytes = () => Encoder.Encode(tangoMessage);
            }
            else if (request is IMessage protoMessage)
            {
                toBytes = () => protoMessage.ToByteArray();
            }

            Subject<T> subject = new Subject<T>();

            TransportMessage<T> message = new TransportMessage<T>(token, request, TransportMessageDirection.Request, toBytes, null);
            message.ShouldLog = config.ShouldLog;
            message.Immidiate = config.Immediate;
            message.Priority = config.Priority;
            message.TransportComponentName = GetExtendedComponentName();
            message.IsContinuous = true;
            message.ContinuesResponseSubject = subject;

            TimeSpan? timeout = config.Timeout;
            TimeSpan? continuousTimeout = config.ContinuousTimeout;

            if (request is MessageContainer container)
            {
                timeout = GetContainerTimeoutOrDefault(container);

                if (timeout == null)
                {
                    timeout = config.Timeout != null ? config.Timeout.Value : RequestTimeout;
                    container.Timeout = (uint)timeout.Value.TotalMilliseconds;
                }

                continuousTimeout = GetContainerContinuousTimeoutOrDefault(container);
            }

            if (timeout == null)
            {
                timeout = RequestTimeout;
            }

            if (request is ITangoMessage tanMessage)
            {
                tanMessage.Container.Continuous = true;
                tanMessage.Container.Completed = false;
                tanMessage.Container.Timeout = (uint)timeout.Value.TotalMilliseconds;
                tanMessage.Container.ContinuousTimeout = continuousTimeout != null ? (UInt32)continuousTimeout.Value.TotalMilliseconds : 0;
            }

            String responseName = requestName.Replace("Request", "Response");

            LogManager.Log($"{GetExtendedComponentName()}: Queuing continuous request message: {requestName} Token: {token}", LogCategory.Debug);
            LogManager.Log($"{GetExtendedComponentName()}: Expected response: {responseName}", LogCategory.Debug);

            if (State != TransportComponentState.Connected)
            {
                throw LogManager.Log(new InvalidOperationException($"{GetExtendedComponentName()}: Could not send the request while transporter state is {State}."));
            }

            Action timeoutAction = () => 
            {
                if (!message.AtLeastOneResponseReceived)
                {
                    TimeoutException ex = new TimeoutException($"{GetExtendedComponentName()}: Request message '{requestName}' had timed out after {timeout.Value.TotalSeconds} seconds.");
                    OnRequestFailed(message, ex);
                    message.SetException(ex);
                }

                if (continuousTimeout != null)
                {
                    Task.Factory.StartNew(async () =>
                    {
                        while (!message.Completed)
                        {
                            await Task.Delay(continuousTimeout.Value).ContinueWith((y) =>
                            {
                                if (!message.Completed)
                                {
                                    if (DateTime.Now - message.LastResponseTime > continuousTimeout.Value)
                                    {
                                        TimeoutException ex = new TimeoutException($"{GetExtendedComponentName()}: Continuous request message '{requestName}' had failed to provide a response for a period of {continuousTimeout.Value.TotalSeconds} seconds and has timed out.");
                                        OnRequestFailed(message, ex);
                                        message.SetException(ex);
                                        return;
                                    }
                                }
                            });
                        }
                    });
                }
            };

            if (config.ThreadingMode == TransportThreadingMode.NewThread)
            {
                message.ActivateTimeout = () =>
                {
                    TimeoutTask.StartNew(() =>
                    {
                        timeoutAction();
                    }, timeout.Value);
                };
            }
            else
            {
                message.ActivateTimeout = () =>
                {
                    Task.Delay(timeout.Value).ContinueWith((x) =>
                    {
                        timeoutAction();
                    });
                };
            }

            EnqueueMessageOut(message);

            return subject.AsObservable();
        }

        /// <summary>
        /// Sends a generic request of any type.
        /// </summary>
        /// <typeparam name="Request">The type of the request.</typeparam>
        /// <typeparam name="Response">The type of the response.</typeparam>
        /// <param name="request">The request.</param>
        /// <param name="config">The configuration.</param>
        /// <returns></returns>
        public async Task<Response> SendGenericRequest<Request, Response>(Request request, TransportRequestConfig config = null) where Request : class where Response : class
        {
            GenericRequest genericRequest = new GenericRequest();
            genericRequest.Type = request.GetType().AssemblyQualifiedName;
            genericRequest.Data = GenericMessageSerializer.SerializeToByteString<Request>(request, GenericProtocol);

            var response = await SendRequest<GenericRequest, GenericResponse>(genericRequest, config);
            var responseObject = GenericMessageSerializer.DeserializeFromByteString<Response>(response.Message.Data, GenericProtocol);
            return responseObject;
        }

        /// <summary>
        /// Sends a generic request and expecting multiple generic response messages.
        /// </summary>
        /// <typeparam name="Request">The type of the request.</typeparam>
        /// <typeparam name="Response">The type of the response.</typeparam>
        /// <param name="config">Request configuration.</param>
        /// <returns></returns>
        public IObservable<Response> SendGenericContinuousRequest<Request, Response>(Request request, TransportContinuousRequestConfig config = null) where Request : class where Response : class
        {
            GenericRequest genericRequest = new GenericRequest();
            genericRequest.Type = request.GetType().AssemblyQualifiedName;

            genericRequest.Data = GenericMessageSerializer.SerializeToByteString<Request>(request, GenericProtocol);

            Subject<Response> subject = new Subject<Response>();

            SendContinuousRequest<GenericRequest, GenericResponse>(genericRequest, config).Subscribe((response) =>
            {

                try
                {
                    var responseObject = GenericMessageSerializer.DeserializeFromByteString<Response>(response.Message.Data, GenericProtocol);
                    subject.OnNext(responseObject);
                }
                catch (Exception ex)
                {
                    Debugger.Break();
                    System.Diagnostics.Debug.WriteLine($"Exception thrown by the generic request continuous handler.\n{ex.ToString()}");
                    //Ignore exception at the client side.
                }

            }, (ex) =>
            {

                try
                {
                    subject.OnError(ex);
                }
                catch (Exception xx)
                {
                    Debugger.Break();
                    System.Diagnostics.Debug.WriteLine($"Exception thrown by the generic request error handler.\n{xx.ToString()}");
                    //Ignore exception at the client side.
                }

            }, () =>
            {
                try
                {
                    subject.OnCompleted();
                }
                catch (Exception ex)
                {
                    Debugger.Break();
                    System.Diagnostics.Debug.WriteLine($"Exception thrown by the generic request completed handler.\n{ex.ToString()}");
                    //Ignore exception at the client side.
                }
            });

            return subject.AsObservable();
        }

        #endregion

        #region Public Response Methods

        /// <summary>
        /// Sends a response.
        /// </summary>
        /// <typeparam name="Response">The type of the response.</typeparam>
        /// <param name="response">The response.</param>
        /// <returns></returns>
        public Task SendResponse<Response>(TangoMessage<Response> response) where Response : IMessage<Response>
        {
            return SendResponse<Response>(response, response.Container.Token);
        }

        /// <summary>
        /// Sends the response.
        /// </summary>
        /// <param name="response"></param>
        /// <param name="token">Request token.</param>
        /// <param name="config">Response configuration.</param>
        /// <returns></returns>
        public Task SendResponse(IMessage response, String token, TransportResponseConfig config = null)
        {
            config = config ?? new TransportResponseConfig();

            String responseName = response.GetType().Name;

            MessageContainer container = new MessageContainer();
            container.Token = token;
            container.Data = response.ToByteString();
            container.Type = MessageFactory.ParseMessageType(responseName);

            if (config.ErrorCode.HasValue)
            {
                container.Error = config.ErrorCode.Value;
            }

            if (config.ErrorMessage != null)
            {
                container.ErrorMessage = config.ErrorMessage;
            }

            container.Completed = config.Completed;

            return SendResponse(container);
        }

        /// <summary>
        /// Sends the response.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException">
        /// </exception>
        public Task SendResponse(MessageContainer container, TransportResponseConfig config = null)
        {
            config = config ?? new TransportResponseConfig();

            if (_pushThread == null || _pushThread.ThreadState == System.Threading.ThreadState.Aborted)
            {
                throw new InvalidOperationException("Transporter push thread is not in a running state.");
            }

            String token = container.Token;

            LogManager.Log($"{GetExtendedComponentName()}: Queuing response message: " + container.Type, LogCategory.Debug);

            PendingResponse pendingResponse = null;

            if (State != TransportComponentState.Connected)
            {
                throw LogManager.Log(new InvalidOperationException($"{GetExtendedComponentName()}: Could not send the response while transporter state is {State}."));
            }

            LogManager.Log($"{GetExtendedComponentName()}: Searching for matching request token: " + token, LogCategory.Debug);

            if (_pendingResponses.TryGetValue(token, out pendingResponse))
            {
                LogManager.Log($"{GetExtendedComponentName()}: Found matching request token: " + token, LogCategory.Debug);

                if (!pendingResponse.IsContinuous)
                {
                    LogManager.Log($"{GetExtendedComponentName()}: Removing matching request token.", LogCategory.Debug);
                    _pendingResponses.Remove(token);
                }
                else if (container.Completed)
                {
                    LogManager.Log($"{GetExtendedComponentName()}: Response completed. Removing matching request token.", LogCategory.Debug);
                    _pendingResponses.Remove(token);
                }
            }
            else
            {
                //This should never happen.
                throw LogManager.Log(new InvalidOperationException($"{GetExtendedComponentName()}: Matching request token was not found!"), LogCategory.Critical);
            }

            TaskCompletionSource<object> source = new TaskCompletionSource<object>();
            TransportMessage<object> message = new TransportMessage<object>(token, container, TransportMessageDirection.Response, () => container.ToByteArray(), source);
            message.ShouldLog = config.ShouldLog;
            message.Immidiate = config.Immediate;
            message.Priority = config.Priority;
            EnqueueMessageOut(message);
            return source.Task;
        }

        /// <summary>
        /// Sends a response.
        /// </summary>
        /// <typeparam name="Response">The type of the response.</typeparam>
        /// <param name="response">The response.</param>
        /// <param name="token">Request token.</param>
        /// <param name="config">Response configuration.</param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException">
        /// Transporter push thread is not in a running state.
        /// </exception>
        public Task SendResponse<Response>(TangoMessage<Response> response, String token, TransportResponseConfig config = null) where Response : IMessage<Response>
        {
            config = config ?? new TransportResponseConfig();

            if (_pushThread == null || _pushThread.ThreadState == System.Threading.ThreadState.Aborted)
            {
                throw new InvalidOperationException("Transporter push thread is not in a running state.");
            }

            response.Container.Token = token;

            response.Container.Completed = config.Completed;

            if (config.ErrorCode.HasValue)
            {
                response.Container.Error = config.ErrorCode.Value;
            }

            if (!String.IsNullOrEmpty(config.ErrorMessage))
            {
                response.Container.ErrorMessage = config.ErrorMessage;
            }

            LogManager.Log($"{GetExtendedComponentName()}: Queuing response message: " + typeof(Response).Name, LogCategory.Debug);

            if (State != TransportComponentState.Connected)
            {
                throw LogManager.Log(new InvalidOperationException($"{GetExtendedComponentName()}: Could not send the response while transporter state is {State}."));
            }

            PendingResponse pendingResponse = null;

            LogManager.Log($"{GetExtendedComponentName()}: Searching for matching request token: " + token, LogCategory.Debug);

            if (_pendingResponses.TryGetValue(token, out pendingResponse))
            {
                LogManager.Log($"{GetExtendedComponentName()}: Found matching request token: " + token, LogCategory.Debug);

                if (!pendingResponse.IsContinuous)
                {
                    LogManager.Log($"{GetExtendedComponentName()}: Removing matching request token.", LogCategory.Debug);
                    _pendingResponses.Remove(token);
                }
                else if (response.Container.Completed)
                {
                    LogManager.Log($"{GetExtendedComponentName()}: Response completed. Removing matching request token.", LogCategory.Debug);
                    _pendingResponses.Remove(token);
                }
            }
            else
            {
                //This should never happen.
                throw LogManager.Log(new InvalidOperationException($"{GetExtendedComponentName()}: Matching request token was not found!"), LogCategory.Critical);
            }

            TaskCompletionSource<object> source = new TaskCompletionSource<object>();
            TransportMessage<object> message = new TransportMessage<object>(token, response, TransportMessageDirection.Response, () => Encoder.Encode(response), source);
            message.ShouldLog = config.ShouldLog;
            message.Immidiate = config.Immediate;
            message.Priority = config.Priority;
            EnqueueMessageOut(message);
            return source.Task;
        }

        /// <summary>
        /// Sends a generic response.
        /// </summary>
        /// <typeparam name="Response">The type of the response.</typeparam>
        /// <param name="response">The response.</param>
        /// <param name="token">The request token.</param>
        /// <param name="config">The response configuration.</param>
        /// <returns></returns>
        public async Task SendGenericResponse<Response>(Response response, String token, TransportResponseConfig config = null) where Response : class
        {
            GenericResponse genericResponse = new GenericResponse();

            genericResponse.Type = response.GetType().AssemblyQualifiedName;
            genericResponse.Data = GenericMessageSerializer.SerializeToByteString<Response>(response, GenericProtocol);
            await SendResponse<GenericResponse>(genericResponse, token, config);
        }

        /// <summary>
        /// Sends a general error response agnostic to the type of request.
        /// </summary>
        /// <param name="exception">The exception.</param>
        /// <param name="config">Response configuration.</param>
        /// <returns></returns>
        public Task SendErrorResponse(Exception exception, String token)
        {
            return SendResponse<ErrorResponse>(new ErrorResponse() { }, token, new TransportResponseConfig()
            {
                ErrorCode = ErrorCode.GeneralError,
                Completed = true,
                ErrorMessage = exception.FlattenMessage()
            });
        }

        #endregion

        #region Request Handlers

        /// <summary>
        /// Registers a custom request handler.
        /// </summary>
        /// <typeparam name="Request">The type of the request.</typeparam>
        /// <param name="callback">The callback.</param>
        public void RegisterRequestHandler<Request>(RequestHandlerCallbackDelegate<Request> callback) where Request : class
        {
            RequestHandler handler = new RequestHandler();
            handler.RequestType = typeof(Request);
            handler.RegisteredCallback = callback;
            handler.Callback = (transporter, obj, token) =>
            {
                callback?.Invoke(transporter, obj as Request, token);
            };

            _requestHandlers.Add(handler);
        }

        /// <summary>
        /// Unregisters a custom request handler.
        /// </summary>
        /// <typeparam name="Request">The type of the request.</typeparam>
        /// <param name="callback">The callback.</param>
        public void UnregisterRequestHandler<Request>(RequestHandlerCallbackDelegate<Request> callback) where Request : class
        {
            var handler = _requestHandlers.FirstOrDefault(x => (x.RegisteredCallback as RequestHandlerCallbackDelegate<Request>) == callback);
            if (handler != null)
            {
                _requestHandlers.Remove(handler);
            }
        }

        /// <summary>
        /// Copies this instance request handlers to the specified instance.
        /// </summary>
        /// <param name="transporter">The transporter to copy the handlers to.</param>
        public void CopyRequestHandlers(ITransporter transporter)
        {
            foreach (var handler in _requestHandlers.ToList())
            {
                (transporter as TransporterBase)._requestHandlers.Add(handler);
                _requestHandlers.Remove(handler);
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Starts the pull and push threads.
        /// </summary>
        protected void StartThreads()
        {
            try
            {
                _pullThread = new Thread(PullThreadMethod);
                _pullThread.Name = $"{GetExtendedComponentName()} Pull Thread";
                _pullThread.IsBackground = true;
                _pullThread.Start();

                _pushThread = new Thread(PushThreadMethod);
                _pushThread.Name = $"{GetExtendedComponentName()} Push Thread";
                _pushThread.IsBackground = true;
                _pushThread.Start();

                _keepAliveThread = new Thread(KeepAliveThreadMethod);
                _keepAliveThread.Name = $"{GetExtendedComponentName()} KeepAlive Thread";
                _keepAliveThread.IsBackground = true;
                _keepAliveThread.Start();
            }
            catch (Exception ex)
            {
                LogManager.Log(ex, "Error starting transporter threads.");
            }
        }

        /// <summary>
        /// Gets the container timeout or default.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <returns></returns>
        private TimeSpan? GetContainerTimeoutOrDefault(MessageContainer container)
        {
            return container.Timeout > 0 ? TimeSpan.FromMilliseconds(container.Timeout) : default(TimeSpan?);
        }

        /// <summary>
        /// Gets the container timeout or default.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <returns></returns>
        private TimeSpan? GetContainerContinuousTimeoutOrDefault(MessageContainer container)
        {
            return container.ContinuousTimeout > 0 ? TimeSpan.FromMilliseconds(container.ContinuousTimeout) : default(TimeSpan?);
        }

        /// <summary>
        /// Enqueues the message and releases the push wait handle.
        /// </summary>
        /// <param name="message">The message.</param>
        private void EnqueueMessageOut(TransportMessageBase message)
        {
            _sendingQueue.BlockEnqueue(message, message.Priority);
        }

        /// <summary>
        /// Enqueues the message and releases the pull wait handle.
        /// </summary>
        /// <param name="data">The data.</param>
        private void EnqueueMessageIn(byte[] data)
        {
            _arrivedResponses.BlockEnqueue(data);
        }

        #endregion

        #region Push Thread

        /// <summary>
        /// Push thread loop.
        /// </summary>
        private void PushThreadMethod()
        {
            try
            {
                while (State == TransportComponentState.Connected)
                {
                    TransportMessageBase message = _sendingQueue.BlockDequeue();

                    try
                    {
                        if (Adapter.State == TransportComponentState.Connected)
                        {
                            if (message.Token.Length != MESSAGE_TOKEN_LENGTH)
                            {
                                var ex = LogManager.Log(new InvalidOperationException($"{GetExtendedComponentName()}: Invalid message token length: " + message.Token));
                                OnRequestFailed(message, ex);
                                message.SetException(ex);
                                continue;
                            }

                            if (message.Direction == TransportMessageDirection.Request)
                            {
                                if (message.ShouldLog)
                                {
                                    LogManager.Log($"{GetExtendedComponentName()}: Sending request '{message.GetActualMessageTypeName()}'...\n{message.GetActualMessage().ToJsonString()}", LogCategory.Info);
                                    OnRequestSent(message);
                                }

                                lock (_pendingRequests)
                                {
                                    _pendingRequests.Add(message);
                                }
                            }
                            else
                            {
                                if (message.ShouldLog)
                                {
                                    LogManager.Log($"{GetExtendedComponentName()}: Sending response '{message.GetActualMessageTypeName()}'...\n{message.GetActualMessage().ToJsonString()}", LogCategory.Info);
                                }
                            }

                            Adapter.Write(message.Serialize(), message.Immidiate);

                            message.ActivateTimeout?.Invoke();

                            LogManager.Log($"{GetExtendedComponentName()}: Message sent...", LogCategory.Debug, message.Message);
                        }
                        else
                        {
                            if (message.Direction == TransportMessageDirection.Request)
                            {
                                var ex = new InvalidOperationException($"{GetExtendedComponentName()}: Could not send message " + message.GetActualMessageTypeName() + ". Adapter is disconnected.");
                                OnRequestFailed(message, ex);
                                message.SetException(ex);
                            }
                        }

                        if (message.Direction == TransportMessageDirection.Response)
                        {
                            message.SetResult(true, true);
                        }
                    }
                    catch (ThreadAbortException)
                    {
                        Exception requestException = FailedStateException != null ? FailedStateException : new TransporterDisconnectedException("The transporter push thread has been aborted.");
                        OnRequestFailed(message, requestException);
                        message.SetException(requestException);
                    }
                    catch (Exception ex)
                    {
                        OnRequestFailed(message, ex);
                        message.SetException(ex);
                    }
                }
            }
            catch (ThreadAbortException)
            {
                LogManager.Log($"{GetExtendedComponentName()}: Push thread has been aborted.");
            }
            catch (Exception ex)
            {
                OnFailed(ex);
            }
        }

        #endregion

        #region Pull Thread

        /// <summary>
        /// Pull thread loop.
        /// </summary>
        private void PullThreadMethod()
        {
            try
            {
                while (State == TransportComponentState.Connected)
                {
                    byte[] data = _arrivedResponses.BlockDequeue();

                    LogManager.Log($"{GetExtendedComponentName()}: Message received...", LogCategory.Debug);

                    LogManager.Log($"{GetExtendedComponentName()}: Parsing message container...", LogCategory.Debug);

                    MessageContainer container = null;

                    try
                    {
                        container = Encoder.DecodeContainer(data);
                    }
                    catch (Exception ex)
                    {
                        LogManager.Log(ex, $"{GetExtendedComponentName()}: Error parsing message container. Skipping incoming message...");
                        continue;
                    }

                    LogManager.Log($"{GetExtendedComponentName()}: Message was identified as " + container.Type + ".", LogCategory.Debug);

                    if (container.Token.Length != MESSAGE_TOKEN_LENGTH)
                    {
                        LogManager.Log($"{GetExtendedComponentName()}: Invalid message token length received: " + container.Token, LogCategory.Error);
                        continue;
                    }

                    LogManager.Log($"{GetExtendedComponentName()}: Searching for pending request token: " + container.Token, LogCategory.Debug);

                    TransportMessageBase request = null;
                    lock (_pendingRequests)
                    {
                        try
                        {
                            var requests = _pendingRequests.ToList().Where(x => x.Token == container.Token).ToList();

                            try
                            {
                                if (requests.Count > 1)
                                {
                                    LogManager.Log($"{GetExtendedComponentName()}: {requests.Count} requests with the same token were detected - {requests.First().GetActualMessageTypeName()}.", LogCategory.Warning);
                                }
                            }
                            catch (Exception ex)
                            {
                                LogManager.Log(ex, LogCategory.Warning, "Something bad happened please investigate.");
                            }

                            request = requests.LastOrDefault();
                        }
                        catch (Exception ex)
                        {
                            LogManager.Log(ex, LogCategory.Warning, "Something bad happened please investigate.");
                        }
                    }

                    if (request != null)
                    {
                        LogManager.Log($"{GetExtendedComponentName()}: Found pending request: " + request.GetActualMessageTypeName(), LogCategory.Debug);

                        if (!request.IsContinuous)
                        {
                            LogManager.Log($"{GetExtendedComponentName()}: Pending request was identified as 'single response'. Removing pending request.", LogCategory.Debug);

                            _pendingRequests.Remove(request);

                            try
                            {
                                if (container.Error == ErrorCode.None)
                                {
                                    var message = Encoder.Decode(data);

                                    if (request.ShouldLog)
                                    {
                                        try
                                        {
                                            String responseType = message.Type.ToString();
                                            var messageContent = message.GetType().GetProperty("Message").GetValue(message);

                                            try
                                            {
                                                if (messageContent.GetType() == typeof(GenericResponse))
                                                {
                                                    Type genericType = Type.GetType((messageContent as GenericResponse).Type);
                                                    responseType = genericType.Name;
                                                    messageContent = GenericMessageSerializer.DeserializeFromByteString(genericType, (messageContent as GenericResponse).Data, GenericProtocol);
                                                }
                                            }
                                            catch { }

                                            LogManager.Log($"{GetExtendedComponentName()}: Response received '{responseType}'...\n{messageContent.ToJsonString()}", LogCategory.Info);
                                            OnResponseReceived(messageContent as IMessage);
                                        }
                                        catch
                                        {
                                            LogManager.Log("Error logging response received.", LogCategory.Warning);
                                        }
                                    }

                                    LogManager.Log($"{GetExtendedComponentName()}: Parsing inner response message and setting pending request task result...", LogCategory.Debug, message);
                                    request.SetResult(message, true);
                                    LogManager.Log($"{GetExtendedComponentName()}: Message enquirer released...", LogCategory.Debug);
                                }
                                else
                                {
                                    var ex = new ResponseErrorException(container, request.GetActualMessageTypeName());
                                    OnRequestFailed(request, ex);
                                    request.SetException(ex);
                                }
                            }
                            catch (Exception ex)
                            {
                                OnRequestFailed(request, ex);
                                request.SetException(LogManager.Log(ex, $"{GetExtendedComponentName()}: Error parsing response message."));
                            }
                        }
                        else
                        {
                            LogManager.Log($"{GetExtendedComponentName()}: Pending request was identified as 'continuous response'. keeping pending request.", LogCategory.Debug);

                            try
                            {
                                if (container.Error == ErrorCode.None)
                                {
                                    var message = Encoder.Decode(data);

                                    if (request.ShouldLog && !request.AtLeastOneResponseReceived)
                                    {
                                        try
                                        {
                                            var messageContent = message.GetType().GetProperty("Message").GetValue(message);
                                            LogManager.Log($"{GetExtendedComponentName()}: Response received '{message.Type}'...\n{messageContent.ToJsonString()}", LogCategory.Info);
                                            OnResponseReceived(messageContent as IMessage);
                                        }
                                        catch
                                        {
                                            LogManager.Log("Error logging response received.", LogCategory.Warning);
                                        }
                                    }

                                    LogManager.Log($"{GetExtendedComponentName()}: Parsing inner response message and invoking continuous response callback...", LogCategory.Debug, message);

                                    if (container.Completed)
                                    {
                                        LogManager.Log($"{GetExtendedComponentName()}: Continuous sequence completed.", LogCategory.Debug);
                                        _pendingRequests.Remove(request);
                                    }
                                    request.SetResult(message, container.Completed);
                                }
                                else if (container.Error == ErrorCode.ContinuousResponseAborted)
                                {
                                    String m = $"{GetExtendedComponentName()}: Continuous response " + container.Type + " has been aborted: " + container.Error.ToString();
                                    LogManager.Log(m, LogCategory.Info);
                                    _pendingRequests.Remove(request);
                                    OnRequestFailed(request, new ContinuousResponseAbortedException(container, m));
                                    request.SetException(new ContinuousResponseAbortedException(container, m));
                                }
                                else
                                {
                                    LogManager.Log($"{GetExtendedComponentName()}: Continuous response has returned with error: " + container.Error.ToString(), LogCategory.Warning);
                                    _pendingRequests.Remove(request);

                                    var exx = new ResponseErrorException(container, request.GetActualMessageTypeName());
                                    OnRequestFailed(request, exx);
                                    request.SetException(exx);
                                }
                            }
                            catch (Exception ex)
                            {
                                LogManager.Log(ex, $"{GetExtendedComponentName()}: Error parsing response message.");
                            }
                        }

                        try
                        {
                            Task.Factory.StartNew(() => OnResponseReceived(container));
                        }
                        catch
                        {
                            //Ignore any exceptions that may raise on the client side..
                        }
                    }
                    else
                    {
                        if (container.Type.ToString().EndsWith("Response"))
                        {
                            LogManager.Log($"{GetExtendedComponentName()}: A response message with no awaiting request was identified. {container.Type}, Token: {container.Token}. Message ignored.", LogCategory.Warning);
                            continue;
                        }

                        LogManager.Log($"{GetExtendedComponentName()}: Message was identified as a new request message: " + container.Type.ToString(), LogCategory.Debug);

                        try
                        {
                            LogManager.Log($"{GetExtendedComponentName()}: Saving request token: " + container.Token, LogCategory.Debug);
                            _pendingResponses.Add(container.Token, new PendingResponse(container.Continuous));

                            if (container.Type == MessageType.KeepAliveRequest && EnableKeepAliveAutoResponse)
                            {
                                LogManager.Log($"{GetExtendedComponentName()}: Submitting keep alive response...", LogCategory.Debug);
                                try
                                {
                                    SendResponse<KeepAliveResponse>(new KeepAliveResponse(), container.Token, new TransportResponseConfig()
                                    {
                                        Priority = QueuePriority.High
                                    });
                                }
                                catch { }
                            }
                            else
                            {
                                LogManager.Log($"{GetExtendedComponentName()}: Invoking RequestReceived event...", LogCategory.Debug, container);

                                try
                                {
                                    Task.Factory.StartNew(() => OnRequestReceived(new RequestReceivedEventArgs(container)));
                                }
                                catch
                                {
                                    //Ignore any exceptions that may raise on the client side..
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            LogManager.Log(ex);
                        }
                    }
                }
            }
            catch (ThreadAbortException)
            {
                LogManager.Log($"{GetExtendedComponentName()}: Pull thread has been aborted.");
            }
            catch (Exception ex)
            {
                OnFailed(ex);
            }
        }

        #endregion

        #region Keep Alive Thread

        /// <summary>
        /// Responsible for sending keep alive messages.
        /// </summary>
        private void KeepAliveThreadMethod()
        {
            bool aborted = false;

            int retryCounter = KeepAliveRetries;

            try
            {
                Thread.Sleep(2000);

                while (State == TransportComponentState.Connected)
                {
                    try
                    {
                        Thread.Sleep(2000);

                        if (UseKeepAlive)
                        {
                            if (_arrivedResponses.Count == 0)
                            {
                                retryCounter--;

                                if (State == TransportComponentState.Connected)
                                {
                                    var response = SendRequest<KeepAliveRequest, KeepAliveResponse>(new KeepAliveRequest(), new TransportRequestConfig()
                                    {
                                        Timeout = KeepAliveTimeout,
                                        Priority = QueuePriority.High
                                    }).Result;
                                    retryCounter = KeepAliveRetries;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                LogManager.Log($"{GetExtendedComponentName()}: Keep alive request was skipped due to busy response queue.", LogCategory.Debug);
                            }
                        }
                    }
                    catch (Exception ex) when (ex is TimeoutException || ex is AggregateException)
                    {
                        if (State != TransportComponentState.Connected || aborted || (Adapter.State == TransportComponentState.Failed && FailsWithAdapter)) return;

                        if (UseKeepAlive)
                        {
                            if (DateTime.Now - _lastKeepAliveTime > KeepAliveTimeout)
                            {
                                if (retryCounter <= 0)
                                {
                                    OnFailed(new KeepAliveException("The transporter has not received a KeepAlive response within the given time."));
                                    return;
                                }
                                else
                                {
                                    LogManager.Log($"The transporter has not received a KeepAlive response within the given time. Retrying ({retryCounter}/{KeepAliveRetries})...", LogCategory.Warning);
                                }
                            }
                            else
                            {
                                retryCounter = KeepAliveRetries;
                                LogManager.Log($"{GetExtendedComponentName()}: The transporter has not received a KeepAlive response within the given time, but was rescued due to other message received within the given time.", LogCategory.Warning);
                            }
                        }
                    }
                    catch (ThreadAbortException)
                    {
                        aborted = true;
                        LogManager.Log($"{GetExtendedComponentName()}: KeepAlive thread has been aborted.");
                        return;
                    }
                    catch (Exception ex)
                    {
                        if (State != TransportComponentState.Connected || aborted) return;

                        if (UseKeepAlive)
                        {
                            OnFailed(ex);
                            return;
                        }
                    }
                }
            }
            catch (ThreadAbortException)
            {
                LogManager.Log($"{GetExtendedComponentName()}: KeepAlive thread has been aborted.");
            }
        }

        #endregion

        #region Override Methods

        /// <summary>
        /// Returns a <see cref="System.String" /> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String" /> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return this.GetType().Name + ", Adapter: " + (Adapter != null ? Adapter.ToString() : "Null") + ", Encoder: " + (Encoder != null ? Encoder.ToString() : "Null");
        }

        #endregion

        #region Dispose

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            Disconnect().Wait();
            State = TransportComponentState.Disposed;
        }

        #endregion
    }
}