visu_websocket.cc 9.79 KB
Newer Older
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
#ifdef WEBSOCKET

#include <stdio.h> 
#include <sys/socket.h> 
#include <arpa/inet.h> 
#include <unistd.h> 
#include <string.h> 

#include <iostream>
#include <string>
#include <sstream>
#include <chrono>
#include <thread>
#include <sys/time.h>
#include <ctime>

#include "visu_websocket.h"
#include "json.h"
#include <fcntl.h>
#include <poll.h>


int sock = 0;
char buffer[1024] = {0};
bool is_connected = false;
struct pollfd pfds[1]; // More if you want to monitor more
bool pause_sim = false;
struct sockaddr_in serv_addr; 

30
31
32
#define KEYS_LEN 256
uint8_t key_states[KEYS_LEN];

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
#define PORT 65432 
#define START_VIEWPOINT 0 ///< default initial viewpoint
#define FRAMERATE 18.0

using std::chrono::duration_cast;
using std::chrono::milliseconds;
using std::chrono::system_clock;
using std::chrono::high_resolution_clock;

/*! \brief input of the 3D window
 */
typedef struct VisuIn
{
    int nb_models; ///< number of models

    int start_viewpoint; ///< initial viewpoint

    int *nb_q; ///< number of joints for each model

    double **q_vec; ///< initial joint positions

    char **mbs_file; ///< mbs files to load

    char *project_path;
    
    Realtime_visu *visu; ///< pointer to the "visu" structure

} VisuIn;

VisuIn *visu_in;



/*! \brief initialize the communication with the webserver
 */

void init_websocket(Realtime_visu *visu, MbsData *mbs_data, int nb_models, int *nb_q, double **q_vec, char **mbs_file, char *project_path, int start_viewpoint){
	
    
	// safety
    if (nb_models < 1)
    {
        std::cout << "Nb_models for anim should be positive (not " << nb_models << ") !" << std::endl;
        exit(EXIT_FAILURE);
    }
78
79
80
81

    for(int i=0; i<KEYS_LEN; ++i){
        key_states[i] = 0;
    }
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
	
	visu_in = new VisuIn;

    visu_in->nb_models       = nb_models;
    visu_in->start_viewpoint = start_viewpoint;
    visu_in->nb_q            = nb_q;
    visu_in->q_vec           = q_vec;
    visu_in->mbs_file        = mbs_file;
    visu_in->visu            = visu;
    visu_in->project_path    = project_path;


    // Create a socket connection (UDP) to the webserver
    if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) 
    { 
        printf("Socket creation error \n"); 
        exit(EXIT_FAILURE);
    } 

    // Set port and IP:
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);
    serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");

    // Setup polling
    pfds[0].fd = sock;         
    pfds[0].events = POLLIN; // Tell me when ready to read 
    
    is_connected = true;

    // Updade mbs data on the server
    send_mbs_data();
}

/*! \brief update mbs data on the server
 */
void send_mbs_data(){

    JsonNode *node;
    char *msg;

    // Create a JSON message
    node = json_mkobject();

    // Add mbs name and loading path
    json_append_member(node, "mbs_name", json_mkstring(visu_in->mbs_file[0]));
    json_append_member(node, "mbs_path", json_mkstring(visu_in->project_path));
    
    // Encode and send message to the server
    msg = json_encode(node);
    sendto(sock , msg, strlen(msg) , MSG_CONFIRM, (const struct sockaddr *) &serv_addr,  sizeof(serv_addr));
}

/*! \brief update the joint values for visualization
 */
void joints_update(Simu_realtime *realtime, int nb_models, int *nb_q, double **q_vec){
	// variable declaration
    int flag_viewpoint;
    JsonNode *node, *array;
    char *msg;

	// Get all models
    for(int i=0; i<nb_models; i++)
    {
    	// Create a JSON response with the joints updated values
        node = json_mkobject();
        array = json_mkarray();
        for(int j=0; j<nb_q[i]; ++j){
            json_append_element(array, json_mknumber(q_vec[i][j]));
        }
        json_append_member(node, "q_anim", array);
        json_append_member(node, "speed", json_mknumber(realtime->real_simu_speed_factor));
        
        // Encode and send the message to the server
        msg = json_encode(node);
        sendto(sock , msg, strlen(msg) , MSG_CONFIRM, (const struct sockaddr *) &serv_addr,  sizeof(serv_addr) ); 
    }

}

/*! \brief process messages from the realtime server
 */
void process_msg(Simu_realtime *realtime){
    // variable declaration
    int bytes_read;
    socklen_t server_struct_length = sizeof(serv_addr);
    char buf[4096] = {""};
    int key, state, speed;

    Realtime_visu *visu;
    MbsData* mbs_data;

    // get fields
    visu     = realtime->ext->visu;
    mbs_data = realtime->ext->mbs_data;

    // Check if data is available
    if(poll(pfds, 1, 0)>0){

        // Read the data
        bytes_read = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr *) &serv_addr, &server_struct_length);
        if (bytes_read > 0) {

            // Decode the JSON message from the server
            JsonNode *node, *object, *subobject;
            node = json_decode(buf);

            if (node == NULL) {
                printf("Incorrect JSON message \n");
            }

            // Check if message is of type keyEvent
            object = json_find_member(node, "keyEvent");

            if (object != NULL) {

                // Get the key code and key state
                subobject = json_find_member(object, "keyCode");
                key = (int) subobject->number_;

                subobject = json_find_member(object, "keyState");
                state = (int) subobject->number_;

                // Apply the key press actions
206
207
                key_states[key] = state;
                user_keyboard(mbs_data, realtime, 0, key_states);
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
            }

            // Check if message is of type speedControl
            object = json_find_member(node, "speedControl");

            if (object != NULL) {

                // Get the pause/play and speed change requests
                subobject = json_find_member(object, "pause");
                pause_sim = (bool) subobject->bool_;


                subobject = json_find_member(object, "speed_ctrl");
                speed = (int) subobject->number_;

                // Increase/decrease the simulation speed
                if(speed>0){
                    realtime->simu_speed_flag++;
                }else if(speed<0){
                    realtime->simu_speed_flag--;
                }
            }

        }
    }
}

void pause_routine(Simu_realtime *realtime){

     // variables declaration
    int start_break_t_usec;
    int delta_break_u_sec;
    int init_t_sec, init_t_usec;

    init_t_sec  = realtime->init_t_sec;
    init_t_usec = realtime->init_t_usec;

    // start of the break instant
    // start_break_t_usec = t_usec(init_t_sec, init_t_usec);
    auto start_break = high_resolution_clock::now();

     // Block the simulation thread if a pause is requested
    while(pause_sim){
        std::this_thread::sleep_for(std::chrono::milliseconds(100));

        // Still process incoming messages
        process_msg(realtime);
    }

    auto end_break = high_resolution_clock::now();

    auto delta_us = duration_cast<std::chrono::microseconds>(start_break - end_break);
    
    // update variables after the break
    realtime->speed_last_t_usec += delta_us.count();
    update_realtime_constraints_break(realtime, delta_break_u_sec);
}

/*! \brief main update loop for the visualization
 */
double t_last_update = 0;

void update_websocket(Simu_realtime *realtime){
	// variables declaration
    Realtime_visu *visu;
    MbsData* mbs_data;
    // auto t;


    // get fields
    visu     = realtime->ext->visu;
    mbs_data = realtime->ext->mbs_data;

    auto t = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();


    // Update the visualisation at the specified framerate (indpendently of the simulation time)
    if(t - t_last_update > 1000.0/FRAMERATE){

        // update joint positions
        user_realtime_visu(mbs_data, visu->nb_models, visu->nb_q, visu->cur_q);

        // if socket is connection -> send the updated joint positions
    	if(is_connected){
    	   joints_update(realtime, visu->nb_models, visu->nb_q, visu->cur_q);
    	}

        t_last_update = t;



    }

    // Process incoming messages from the server
    process_msg(realtime);

    if(pause_sim){
        pause_routine(realtime);
    }


    
	
}

/*! \brief update the realtime plot data
 */

double t_last_plot = 0;

void update_plot_vectors(Simu_realtime *realtime, double tsim){
    
    JsonNode *node, *parent, *q_array, *l_array, *dnode;
    char *msg;
    double *y_curves;
    char **label_curves;
    int nb_curves;

    AutoPlot *auto_plot;

    auto_plot  = realtime->ext->auto_plot;
    y_curves   = auto_plot->y_curves;
    label_curves   = auto_plot->label_curves;

    nb_curves = auto_plot->nb;

    auto t = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();

    // Update the plot at a specified framerate
    if(t - t_last_plot > 1000.0/FRAMERATE){

        if (!nb_curves)
        {
            return;
        }

        // Create a JSON message
        parent = json_mkobject();
        node = json_mkobject();

        // Fill a JSON array with the plot data
        q_array = json_mkarray();
        for(int j=0; j<nb_curves; ++j){
            dnode = json_mkobject();
            json_append_member(dnode, "label", json_mkstring(label_curves[j]));
            json_append_member(dnode, "value", json_mknumber(y_curves[j]));
            json_append_element(q_array, dnode);
        }
        json_append_member(node, "datasets", q_array);
        json_append_member(node, "t", json_mknumber(realtime->ext->mbs_data->tsim));

        json_append_member(parent, "plot_data", node);

        // Encode and send the data to the server
        msg = json_encode(parent);
        sendto(sock , msg, strlen(msg) , MSG_CONFIRM, (const struct sockaddr *) &serv_addr,  sizeof(serv_addr) ); 
        

        t_last_plot = t;
    }

}

/*! \brief close the socket connection
 * 
 * \param[in] visu data
 */
void free_websocket(void *visu_class){

    // Close de socket connection
	close(sock);
}

#endif