1 // =============================================================================
2 // PROJECT CHRONO - http://projectchrono.org
3 //
4 // Copyright (c) 2014 projectchrono.org
5 // All rights reserved.
6 //
7 // Use of this source code is governed by a BSD-style license that can be found
8 // in the LICENSE file at the top level of the distribution and at
9 // http://projectchrono.org/license-chrono.txt.
10 //
11 // =============================================================================
12 // Authors: Alessandro Tasora
13 // =============================================================================
14 
15 #ifndef CHCOSIMULATION_H
16 #define CHCOSIMULATION_H
17 
18 #include "chrono_cosimulation/ChSocket.h"
19 #include "chrono_cosimulation/ChSocketFramework.h"
20 
21 #include "chrono/core/ChMatrix.h"
22 
23 namespace chrono {
24 namespace cosimul {
25 
26 /// @addtogroup cosimulation_module
27 /// @{
28 
29 /// Class for cosimulation interface.
30 /// Typically, a C::E program can instance an object
31 /// from this class and use it to communicate with a 3rd party
32 /// simulation tool at each time step. The communication is based
33 /// on TCP sockets, where vectors of scalar values are exchanged
34 /// back and forth.
35 /// In this case, C::E will work as a server, waiting for
36 /// a client to talk with.
37 
38 class ChApiCosimulation ChCosimulation {
39   public:
40     /// Create a co-simulation interface.
41     ChCosimulation(ChSocketFramework& mframework,  ///< socket framework
42                    int n_in_values,                ///< number of scalar variables to receive each timestep
43                    int n_out_values                ///< number of scalar variables to send each timestep
44     );
45 
46     ~ChCosimulation();
47 
48     /// Wait for a client to connect to the interface,
49     /// on a given port, and wait until not connected.
50     /// \a aport is a free port number, for example 50009.
51     bool WaitConnection(int aport);
52 
53     /// Exchange data with the client, by sending a
54     /// vector of floating point values over TCP socket
55     /// connection (values are double precision, little endian, 4 bytes each)
56     /// Simulator actual time is also passed as first value.
57     bool SendData(double mtime, ChVectorConstRef mdata);
58 
59     /// Exchange data with the client, by receiving a
60     /// vector of floating point values over TCP socket
61     /// connection (values are double precision, little endian, 4 bytes each)
62     /// External time is also received as first value.
63     bool ReceiveData(double& mtime, ChVectorRef mdata);
64 
65   private:
66     ChSocketTCP* myServer;
67     ChSocketTCP* myClient;
68     int nport;
69 
70     int in_n;
71     int out_n;
72 };
73 
74 /// @} cosimulation_module
75 
76 }  // end namespace cosimul
77 }  // end namespace chrono
78 
79 #endif
80