source: flair-src/trunk/lib/FlairCore/src/FrameworkManager_impl.cpp@ 289

Last change on this file since 289 was 272, checked in by Sanahuja Guillaume, 5 years ago

correct bug og init euler derivative

File size: 27.4 KB
Line 
1// %flair:license{
2// This file is part of the Flair framework distributed under the
3// CECILL-C License, Version 1.0.
4// %flair:license}
5// created: 2011/08/31
6// filename: FrameworkManager.cpp
7//
8// author: Guillaume Sanahuja
9// Copyright Heudiasyc UMR UTC/CNRS 7253
10//
11// version: $Id: $
12//
13// purpose: Classe de base de la librairie
14//
15//
16/*********************************************************************/
17
18#include "FrameworkManager_impl.h"
19#include "FrameworkManager.h"
20#include "Widget_impl.h"
21#include <unistd.h>
22#include "IODevice.h"
23#include "IODevice_impl.h"
24#include "TabWidget.h"
25#include "Layout.h"
26#include "PushButton.h"
27#include "communication.h"
28#include "config.h"
29#include "Watchdog.h"
30#include <errno.h>
31#include <string.h>
32#include <arpa/inet.h>
33#include <sys/mman.h>
34#include <execinfo.h>
35#include <signal.h>
36#include <fcntl.h>
37#ifdef __XENO__
38#include <native/task.h>
39#include <rtdk.h>
40#endif
41
42using namespace std;
43using namespace flair::core;
44using namespace flair::gui;
45
46ui_com *FrameworkManager_impl::com = NULL;
47FrameworkManager_impl *FrameworkManager_impl::_this = NULL;
48
49namespace {
50#ifdef __XENO__
51
52#ifdef SIGDEBUG
53static const char *reason_str[] = {
54 "undefined", "received signal", "invoked syscall", "triggered fault",
55 "affected by priority inversion", "missing mlockall", "runaway thread",
56};
57
58void warn_upon_switch(int sig, siginfo_t *si, void *context) {
59 unsigned int reason = si->si_value.sival_int;
60 void *bt[32];
61 int nentries;
62#ifdef SIGDEBUG_WATCHDOG
63 printf("\nSIGDEBUG received, reason %d: %s\n", reason,
64 reason <= SIGDEBUG_WATCHDOG ? reason_str[reason] : "<unknown>");
65 printf("entering secondary mode\n");
66#endif
67 // Dump a backtrace of the frame which caused the switch to secondary mode:
68 nentries = backtrace(bt, sizeof(bt) / sizeof(bt[0]));
69 backtrace_symbols_fd(bt, nentries, fileno(stdout));
70}
71#else // SIGDEBUG
72void warn_upon_switch(int sig __attribute__((unused))) {
73 void *bt[32];
74 int nentries;
75
76 /* Dump a backtrace of the frame which caused the switch to
77 secondary mode: */
78 nentries = backtrace(bt, sizeof(bt) / sizeof(bt[0]));
79 backtrace_symbols_fd(bt, nentries, fileno(stdout));
80}
81#endif // SIGDEBUG
82#endif //__XENO__
83void seg_fault(int sig __attribute__((unused))) {
84 void *bt[32];
85 int nentries;
86
87 printf("Segmentation fault:\n");
88 /* Dump a backtrace of the frame which caused the segfault: */
89 nentries = backtrace(bt, sizeof(bt) / sizeof(bt[0]));
90 backtrace_symbols_fd(bt, nentries, fileno(stdout));
91
92 exit(1);
93}
94}
95
96FrameworkManager_impl::FrameworkManager_impl(FrameworkManager *self,
97 string name)
98 : Thread(self, "FrameworkManager", FRAMEWORK_TASK_PRIORITY) {
99 this->self = self;
100 is_logging = false;
101 logger_defined = false;
102 disable_errors = false;
103 ui_defined = false;
104 rcv_buf = NULL;
105 gcs_watchdog = NULL;
106 _this = this;
107 tabwidget=NULL;
108
109 // Avoids memory swapping for this program
110 mlockall(MCL_CURRENT | MCL_FUTURE);
111
112 // catch segfault
113 signal(SIGSEGV, seg_fault);
114
115// catch primary->secondary switch
116#ifdef __XENO__
117#ifdef SIGDEBUG
118 struct sigaction sa;
119 sigemptyset(&sa.sa_mask);
120 sa.sa_sigaction = warn_upon_switch;
121 sa.sa_flags = SA_SIGINFO;
122 sigaction(SIGDEBUG, &sa, NULL);
123#else //SIGDEBUG
124 signal(SIGXCPU, warn_upon_switch);
125#endif //SIGDEBUG
126 string task_name = "Framework_" + name;
127
128 // Perform auto-init of rt_print buffers if the task doesn't do so
129 rt_print_auto_init(1);
130 // Initialise the rt_print buffer for this task explicitly
131 rt_print_init(512, task_name.c_str());
132
133 int status = rt_task_shadow(NULL, task_name.c_str(), 10, 0);
134 if (status != 0) {
135 char errorMsg[256];
136 self->Err("rt_task_shadow error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
137 }
138
139#endif //__XENO__
140}
141
142void FrameworkManager_impl::SetConnectionLost(void) {
143 Err("connection lost\n");
144 if(gcs_watchdog!=NULL) gcs_watchdog->SafeStop();
145 connection_lost = true;
146}
147
148FrameworkManager_impl::~FrameworkManager_impl() {
149 // Printf("destruction FrameworkManager_impl\n");
150 int status;
151
152 SafeStop();
153 Join();
154
155 if (rcv_buf != NULL)
156 free(rcv_buf);
157
158 if (logger_defined == true) {
159 continuer = false;
160 (void)pthread_join(log_th, NULL);
161
162 status = DeletePipe(&cmd_pipe);
163 if (status != 0) {
164 char errorMsg[256];
165 Err("Error deleting pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
166 }
167 status = DeletePipe(&data_pipe);
168 if (status != 0) {
169 char errorMsg[256];
170 Err("Error deleting pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
171 }
172
173#ifdef __XENO__
174 status = rt_heap_delete(&log_heap);
175 if (status != 0) {
176 char errorMsg[256];
177 Err("rt_heap_delete error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
178 }
179#endif
180
181 logs.clear();
182 }
183
184 if (file_doc != NULL)
185 xmlFreeDoc(file_doc);
186
187 if (ui_defined)
188 delete top_layout;
189
190 if (com != NULL) {
191 delete com;
192 //avoid waiting on closing if connection is lost
193 if(connection_lost) {
194 bool blocking = false;
195 if (UDT::setsockopt(com_sock, 0, UDT_SNDSYN, &blocking, sizeof(bool)) != 0)
196 Err("UDT::setsockopt error (UDT_SNDSYN)\n");
197 }
198 status = UDT::close(com_sock);
199 if (status != 0)
200 Printf("Error udt::close %s", UDT::getlasterror().getErrorMessage());
201
202 SleepMS(200); // a revoir, sinon UDT::cleanup bloque en RT
203
204 if(connection_lost) {
205 //don't know why?
206 Warn("Cleaning up UDT socket, this can take some time\n");
207 }
208 if (UDT::cleanup() != 0)
209 Err("UDT::cleanup error\n");
210 }
211
212 // Printf("destruction FrameworkManager_impl ok\n");
213}
214
215void FrameworkManager_impl::SetupConnection(string address, uint16_t port,Time watchdogTimeout,
216 size_t rcv_buf_size) {
217 if (com != NULL) {
218 Err("SetupConnection should be called only one time\n");
219 return;
220 }
221 this->address=address;
222 this->port=port;
223
224 UDT::startup2(1024*256,1024*256,1024*256);
225 this->rcv_buf_size = rcv_buf_size;
226
227 // socket file_socket, doit être créé en premier, cf station sol
228 Printf("Connecting to %s:%i\n", address.c_str(), port);
229 //file_sock = GetSocket(address, port);
230 com_sock = GetSocket();
231
232 // receive buffer allocation
233 rcv_buf = (char *)malloc(rcv_buf_size);
234 if (rcv_buf == NULL) {
235 Err("receive buffer malloc error\n");
236 }
237
238 com = new ui_com(this, com_sock);
239
240 Start();
241
242 // watchdog for connection with ground station
243 connection_lost = false;
244 gcs_watchdog = new Watchdog(this, std::bind(&FrameworkManager_impl::SetConnectionLost, this),watchdogTimeout);
245 gcs_watchdog->Start();
246}
247
248void FrameworkManager_impl::SetupUserInterface(string xml_file) {
249 ui_defined = true;
250 this->xml_file = xml_file;
251
252 // top_layout=new Layout(NULL,XML_ROOT_ELEMENT,XML_ROOT_TYPE);
253 top_layout = new Layout(NULL, self->ObjectName(), XML_ROOT_TYPE);
254
255 // xml setup of the main widget
256 if (xml_file != "") {
257 xmlNodePtr *file_node = &(((Widget *)(top_layout))->pimpl_->file_node);
258 file_doc = xmlParseFile(xml_file.c_str());
259 if (file_doc == NULL) {
260 self->Warn("XML document not parsed successfully. Creating a new one.\n");
261 file_doc = xmlNewDoc((xmlChar *)"1.0");
262 *file_node = xmlNewNode(NULL, (xmlChar *)XML_ROOT_TYPE);
263 xmlSetProp(*file_node, (xmlChar *)"name",
264 (xmlChar *)ObjectName().c_str());
265 xmlDocSetRootElement(file_doc, *file_node);
266 // PrintXml();
267 } else {
268 *file_node = xmlDocGetRootElement(file_doc);
269 if (xmlStrcmp((*file_node)->name, (xmlChar *)XML_ROOT_TYPE)) {
270 self->Warn("%s, no match found in xml file\n", XML_ROOT_TYPE);
271 *file_node = xmlNewNode(NULL, (xmlChar *)XML_ROOT_TYPE);
272 xmlSetProp(*file_node, (xmlChar *)"name",
273 (xmlChar *)ObjectName().c_str());
274 xmlDocSetRootElement(file_doc, *file_node);
275 }
276 }
277 } else {
278 self->Err("xml file not defined\n");
279 }
280
281 // gui
282 tabwidget =
283 new TabWidget(top_layout->At(0, 0), XML_MAIN_TABWIDGET, TabWidget::North);
284 save_button =
285 new PushButton(top_layout->At(1, 0),
286 "save config on target (" + self->ObjectName() + ")");
287 // load_button=new PushButton(top_layout->At(1,1),"load config on target (" +
288 // self->ObjectName() + ")");
289}
290
291// in case of RT, this thread switches to secondary mode when calling
292// com->Receive
293// it switches back to RT in ProcessXML when mutex are locked
294void FrameworkManager_impl::Run(void) {
295 while (!ToBeStopped()) {
296 ssize_t bytesRead;
297 bytesRead = com->Receive(rcv_buf, rcv_buf_size);
298 com->CheckConnection();
299//printf("%i\n",bytesRead);
300 if (bytesRead == (ssize_t)rcv_buf_size)
301 Err("FrameworkManager max receive size, augmenter le buffer size!\n");
302
303 if (bytesRead > 0) {
304 //printf("recu %ld, trame %x %lld\n",bytesRead,(uint8_t)rcv_buf[0],GetTime()/(1000000));
305 //rcv_buf[bytesRead-1]=0;//pour affichage
306 //printf("%s\n",rcv_buf);
307
308 switch ((uint8_t)rcv_buf[0]) {
309 case XML_HEADER: {
310 xmlDoc *doc;
311 rcv_buf[bytesRead] = 0;
312 //Printf("%s\n",rcv_buf);
313 doc = xmlReadMemory(rcv_buf, (int)bytesRead, "include.xml",
314 "ISO-8859-1", 0);
315 xmlNode *cur_node = NULL;
316
317 for (cur_node = xmlDocGetRootElement(doc); cur_node;
318 cur_node = cur_node->next) {
319 if (cur_node->type == XML_ELEMENT_NODE) {
320 if (!xmlStrcmp(cur_node->name, (xmlChar *)XML_ROOT_TYPE)) {
321#ifdef __XENO__
322 WarnUponSwitches(
323 true); // ProcessXML should not switch to secondary mode
324#endif
325 top_layout->Widget::pimpl_->ProcessXML(cur_node->children);
326#ifdef __XENO__
327 WarnUponSwitches(false); // other parts of this thread can switch
328 // to secondary mode
329#endif
330 break;
331 }
332 }
333 }
334
335 xmlFreeDoc(doc);
336
337 if (save_button->Clicked())
338 SaveXml();
339
340 SaveXmlChange(rcv_buf);
341
342 break;
343 }
344 case WATCHDOG_HEADER: {
345 if(gcs_watchdog!=NULL) gcs_watchdog->Touch();
346 break;
347 }
348 default:
349 Err("unknown id: %x\n", (uint8_t)rcv_buf[0]);
350 break;
351 }
352 } else {
353 if (com->ConnectionLost())
354 SleepMS(10); // avoid infinite loop in this case
355 }
356 }
357}
358
359void FrameworkManager_impl::SaveXml(void) {
360 if (ui_defined)
361 xmlSaveFormatFile(xml_file.c_str(), file_doc, 1);
362}
363
364void FrameworkManager_impl::SaveXmlChange(char *buf) {
365 if (is_logging == true) {
366 FILE *xml_change;
367 char filename[256];
368 Time time = GetTime();
369
370 sprintf(filename, "%s/changes_at_%lld.xml", log_path.c_str(), time);
371
372 xml_change = fopen(filename, "a");
373 fprintf(xml_change, "%s", buf);
374 fclose(xml_change);
375
376 sprintf(filename, "changes_at_%lld.xml", time);
377 xml_changes.push_back(filename);
378 }
379}
380
381void FrameworkManager_impl::SendFile(UDTSOCKET socket,string path, string name) {
382 char *buf, *more_buf;
383 int size;
384 filebuf *pbuf;
385 ssize_t nb_write;
386 string filename = path + "/" + name;
387
388 // open the file
389 fstream ifs(filename.c_str(), ios::in | ios::binary);
390 ifs.seekg(0, ios::end);
391 size = ifs.tellg();
392 ifs.seekg(0, ios::beg);
393 pbuf = ifs.rdbuf();
394
395 if (size <= 0) {
396 Err("error opening file %s\n", filename.c_str());
397 return;
398 }
399
400 buf = (char *)malloc(sizeof(uint8_t) + sizeof(int) + name.size());
401 if (buf == NULL) {
402 Err("malloc error, not sending file\n");
403 return;
404 }
405
406 if (IsBigEndian()) {
407 buf[0] = FILE_INFO_BIG_ENDIAN;
408 } else {
409 buf[0] = FILE_INFO_LITTLE_ENDIAN;
410 }
411
412 memcpy(buf + 1, &size, sizeof(int));
413 memcpy(buf + 1 + sizeof(int), name.c_str(), name.size());
414 Printf("sending %s, size: %i\n", filename.c_str(), size);
415 // send file information
416 UDT::sendmsg(socket, buf, sizeof(uint8_t) + sizeof(int) + name.size(), -1,true);
417
418 more_buf = (char *)realloc((void *)buf, size);
419 if (more_buf == NULL) {
420 Err("realloc error, not sending file\n");
421 free(buf);
422 return;
423 } else {
424 buf = more_buf;
425 }
426
427 pbuf->sgetn(buf, size);
428 // send the file
429 nb_write = UDT::sendmsg(socket, buf, size, -1, true);
430
431 if (nb_write < 0) {
432 Err("UDT::sendmsg error (%s)\n", UDT::getlasterror().getErrorMessage());
433 } else if (nb_write != size) {
434 Err("UDT::sendmsg error, sent %ld/%i\n", nb_write, size);
435 }
436
437 ifs.close();
438 free(buf);
439}
440
441void FrameworkManager_impl::FinishSending(UDTSOCKET socket) {
442 char rm_cmd[256];
443
444 // send orignal xml
445 SendFile(socket,log_path, "setup.xml");
446 sprintf(rm_cmd, "rm %s/setup.xml", log_path.c_str());
447 system(rm_cmd);
448
449 // send xml changes
450 for (size_t i = 0; i < xml_changes.size(); i++) {
451 // Printf("%s\n",xml_changes.at(i).c_str());
452 SendFile(socket,log_path, xml_changes.at(i).c_str());
453 sprintf(rm_cmd, "rm %s/%s", log_path.c_str(), xml_changes.at(i).c_str());
454 system(rm_cmd);
455 }
456 xml_changes.clear();
457
458 // end notify
459 char buf = END_SENDING_FILES;
460 int nb_write = UDT::sendmsg(socket, &buf, 1, -1, true);
461
462 if (nb_write < 0) {
463 Err("UDT::sendmsg error (%s)\n", UDT::getlasterror().getErrorMessage());
464 } else if (nb_write != 1) {
465 Err("UDT::sendmsg error, sent %i/%i\n", nb_write, 1);
466 }
467
468 //wait end ACK
469 int nb_read = UDT::recvmsg(socket,&buf,1);
470 if(nb_read<0) {
471 Err("UDT::recvmsg error (%s)\n",UDT::getlasterror().getErrorMessage());
472 } else if (nb_read != 1) {
473 Err("UDT::recvmsg error, sent %i/%i\n",nb_read,1);
474 }
475}
476
477UDTSOCKET FrameworkManager_impl::GetSocket(void) {
478 while (1) {
479 UDTSOCKET new_fd;
480 new_fd = UDT::socket(AF_INET, SOCK_DGRAM, 0);
481 if (new_fd == UDT::INVALID_SOCK) {
482 Err("socket error: %s\n", UDT::getlasterror().getErrorMessage());
483 return 0;
484 }
485
486 sockaddr_in serv_addr;
487 serv_addr.sin_family = AF_INET;
488 serv_addr.sin_port = htons(short(port));
489
490 if (inet_pton(AF_INET, address.c_str(), &serv_addr.sin_addr) <= 0) {
491 Err("incorrect network address\n");
492 return 0;
493 }
494
495 memset(&(serv_addr.sin_zero), '\0', 8);
496
497 if (UDT::ERROR ==
498 UDT::connect(new_fd, (sockaddr *)&serv_addr, sizeof(serv_addr))) {
499 // Printf("connect error: %s
500 // %i\n",UDT::getlasterror().getErrorMessage(),UDT::getlasterror().getErrorCode());
501 UDT::close(new_fd);
502 if (UDT::getlasterror().getErrorCode() != 1001 &&
503 UDT::getlasterror().getErrorCode() != 1002) {
504 Err("connect error: %s\n", UDT::getlasterror().getErrorMessage());
505 return 0;
506 }
507 } else {
508 // printf("connected to
509 // %s:%i\n",inet_ntoa(serv_addr.sin_addr),serv_addr.sin_port);
510 return new_fd;
511 }
512 }
513}
514
515#ifdef __XENO__
516int FrameworkManager_impl::CreatePipe(RT_PIPE *fd, string name) {
517 name = self->ObjectName() + "-" + name;
518 // xenomai limitation
519 if (name.size() > 31)
520 self->Err("rt_pipe_create error (%s is too long)\n", name.c_str());
521// start log writter
522#ifdef RT_PIPE_SIZE
523 return rt_pipe_create(fd, name.c_str(), P_MINOR_AUTO, RT_PIPE_SIZE);
524#else
525 return rt_pipe_create(fd, name.c_str(), P_MINOR_AUTO, 0);
526#endif
527}
528#else
529int FrameworkManager_impl::CreatePipe(int (*fd)[2], string name) {
530 // if(pipe2(fd[0],O_NONBLOCK) == -1)
531 if (pipe(fd[0]) == -1) {
532 return errno;
533 } else {
534 int attr = fcntl((*fd)[0], F_GETFL, 0);
535 if (attr == -1) {
536 return errno;
537 }
538 if (fcntl((*fd)[0], F_SETFL, attr | O_NONBLOCK) == -1) {
539 return errno;
540 }
541 attr = fcntl((*fd)[1], F_GETFL, 0);
542 if (attr == -1) {
543 return errno;
544 }
545 if (fcntl((*fd)[1], F_SETFL, attr | O_NONBLOCK) == -1) {
546 return errno;
547 }
548
549 return 0;
550 }
551}
552#endif
553
554#ifdef __XENO__
555int FrameworkManager_impl::DeletePipe(RT_PIPE *fd) {
556 return rt_pipe_delete(fd);
557}
558#else
559int FrameworkManager_impl::DeletePipe(int (*fd)[2]) {
560 int status1 = close((*fd)[0]);
561 int status2 = close((*fd)[1]);
562 if (status1 == 0 && status2 == 0)
563 return 0;
564 if (status1 != 0)
565 return status1;
566 if (status2 != 0)
567 return status2;
568}
569#endif
570
571void FrameworkManager_impl::SetupLogger(string log_path,uint32_t stackSize) {
572
573 if (logger_defined == true) {
574 Warn("SetupLogger() was already called.\n");
575 return;
576 }
577
578 this->log_path = log_path;
579
580 int status = CreatePipe(&cmd_pipe, "log_cmd");
581 if (status != 0) {
582 char errorMsg[256];
583 Err("Error creating pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
584 return;
585 }
586
587 status = CreatePipe(&data_pipe, "log_data");
588 if (status != 0) {
589 char errorMsg[256];
590 Err("Error creating pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
591 return;
592 }
593
594#ifdef __XENO__
595 string tmp_name;
596 tmp_name = self->ObjectName() + "-log_heap";
597 status = rt_heap_create(&log_heap, tmp_name.c_str(), RT_LOG_HEAP, H_FIFO);
598 if (status != 0) {
599 char errorMsg[256];
600 Err("rt_heap_create error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
601 return;
602 }
603#endif //__XENO__
604
605 continuer = true;
606
607 // Initialize thread creation attributes
608 pthread_attr_t attr;
609 status=pthread_attr_init(&attr);
610 if (status != 0) {
611 char errorMsg[256];
612 Err("pthread_attr_init error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
613 return;
614 }
615
616 status=pthread_attr_setstacksize(&attr, stackSize);
617 if (status != 0) {
618 char errorMsg[256];
619 Err("pthread_attr_setstacksize error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
620 return;
621 }
622
623 status=pthread_create(&log_th, &attr, write_log_user, (void *)this);
624 if (status < 0) {
625 char errorMsg[256];
626 Err("pthread_create error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
627 return;
628 }
629
630 status=pthread_attr_destroy(&attr);
631 if (status != 0) {
632 char errorMsg[256];
633 Err("pthread_attr_destroy error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
634 return;
635 }
636
637 logger_defined = true;
638}
639
640void FrameworkManager_impl::AddDeviceToLog(IODevice *device) {
641 if (logger_defined == false) {
642 Warn("SetupLogger() was not called, not adding to log\n");
643 return;
644 }
645
646 if (is_logging == false) {
647 if (!device->pimpl_->IsSetToBeLogged()) {
648 device->pimpl_->SetToBeLogged();
649 log_desc_t tmp;
650 tmp.device = device;
651 logs.push_back(tmp);
652 } else {
653 Warn("not adding it twice\n");
654 }
655 } else {
656 Err("impossible while logging\n");
657 }
658}
659
660bool FrameworkManager_impl::IsDeviceLogged(const IODevice *device) const {
661 return device->pimpl_->IsSetToBeLogged();
662}
663
664void FrameworkManager_impl::StartLog(void) {
665 if (logger_defined == false) {
666 Err("SetupLogger() was not called, not starting log\n");
667 return;
668 }
669
670 ssize_t written;
671 size_t nb_err = 0;
672
673 if (logs.size() == 0) {
674 Warn("Not starting log: nothing to log!\n");
675 return;
676 }
677
678 if (is_logging == false) {
679 for (size_t i = 0; i < logs.size(); i++) {
680
681 logs.at(i).running = true;
682 logs.at(i).dbtFile = NULL;
683 logs.at(i).size = logs.at(i).device->pimpl_->LogSize();
684#ifdef __XENO__
685 written =
686 rt_pipe_write(&cmd_pipe, &logs.at(i), sizeof(log_desc_t), P_NORMAL);
687#else
688 written = write(cmd_pipe[1], &logs.at(i), sizeof(log_desc_t));
689#endif
690
691 if (written < 0) {
692 char errorMsg[256];
693 Err("write pipe error (%s)\n", strerror_r(-written, errorMsg, sizeof(errorMsg)));
694 nb_err++;
695 logs.at(i).running = false;
696 } else if (written != sizeof(log_desc_t)) {
697 Err("write pipe error %ld/%ld\n", written, sizeof(log_desc_t));
698 nb_err++;
699 logs.at(i).running = false;
700 }
701 }
702
703 if (nb_err != logs.size())
704 is_logging = true;
705 } else {
706 Warn("Already logging\n");
707 }
708}
709
710void FrameworkManager_impl::StopLog(void) {
711 ssize_t written;
712
713 if (is_logging == true) {
714 for (size_t i = 0; i < logs.size(); i++) {
715 logs.at(i).running = false;
716 }
717// send only one running false condition, user thread will stop and send all
718#ifdef __XENO__
719 written =
720 rt_pipe_write(&cmd_pipe, &logs.at(0), sizeof(log_desc_t), P_NORMAL);
721#else
722 written = write(cmd_pipe[1], &logs.at(0), sizeof(log_desc_t));
723#endif
724
725 if (written < 0) {
726 char errorMsg[256];
727 Err("write pipe error (%s)\n", strerror_r(-written, errorMsg, sizeof(errorMsg)));
728 return;
729 } else if (written != sizeof(log_desc_t)) {
730 Err("write pipe error %ld/%ld\n", written, sizeof(log_desc_t));
731 return;
732 }
733
734 is_logging = false;
735 } else {
736 Warn("Not logging\n");
737 }
738}
739
740char *FrameworkManager_impl::GetBuffer(size_t sz) {
741// Printf("alloc %i\n",sz);
742#ifdef __XENO__
743 void *ptr;
744 int status = rt_heap_alloc(&log_heap, sz, TM_NONBLOCK, &ptr);
745 if (status != 0) {
746 char errorMsg[256];
747 Err("rt_heap_alloc error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
748 ptr = NULL;
749 }
750 return (char *)ptr;
751#else
752 return (char *)malloc(sz);
753#endif
754}
755
756void FrameworkManager_impl::ReleaseBuffer(char *buf) {
757#ifdef __XENO__
758 int status = rt_heap_free(&log_heap, buf);
759
760 if (status != 0) {
761 char errorMsg[256];
762 Err("rt_heap_free error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
763 }
764#else
765 free(buf);
766#endif
767}
768
769void FrameworkManager_impl::WriteLog(const char *buf, size_t size) {
770 ssize_t written;
771
772#ifdef __XENO__
773 written = rt_pipe_write(&data_pipe, buf, size, P_NORMAL);
774#else
775 written = write(data_pipe[1], buf, size);
776#endif
777
778 if (written < 0) {
779 char errorMsg[256];
780 Err("error write pipe (%s)\n", strerror_r(-written, errorMsg, sizeof(errorMsg)));
781 } else if (written != (ssize_t)size) {
782 Err("error write pipe %ld/%ld\n", written, size);
783 }
784}
785
786void *FrameworkManager_impl::write_log_user(void *arg) {
787 int cmd_pipe = -1;
788 int data_pipe = -1;
789 fd_set set;
790 struct timeval timeout;
791 FrameworkManager_impl *caller = (FrameworkManager_impl *)arg;
792 int rv;
793
794 vector<log_desc_t> logs;
795
796#ifdef __XENO__
797 while (cmd_pipe < 0) {
798 string filename = NRT_PIPE_PATH + caller->self->ObjectName() + "-log_cmd";
799 cmd_pipe = open(filename.c_str(), O_RDWR);
800 if (cmd_pipe < 0 && errno != ENOENT) {
801 char errorMsg[256];
802 caller->self->Err("open rt_pipe error: %s %s\n", filename.c_str(), strerror_r(errno, errorMsg, sizeof(errorMsg)));
803 }
804 usleep(1000);
805 }
806 while (data_pipe < 0) {
807 string filename = NRT_PIPE_PATH + caller->self->ObjectName() + "-log_data";
808 data_pipe = open(filename.c_str(), O_RDWR);
809 if (data_pipe < 0 && errno != ENOENT) {
810 char errorMsg[256];
811 caller->self->Err("open rt_pipe error: %s %s\n", filename.c_str(), strerror_r(errno, errorMsg, sizeof(errorMsg)));
812 }
813 usleep(1000);
814 }
815#else
816 cmd_pipe = caller->cmd_pipe[0];
817 data_pipe = caller->data_pipe[0];
818#endif
819
820 while (caller->continuer == true) {
821 FD_ZERO(&set);
822 FD_SET(cmd_pipe, &set);
823 FD_SET(data_pipe, &set);
824
825 timeout.tv_sec = 0;
826 timeout.tv_usec = SELECT_TIMEOUT_MS * 1000;
827 rv = select(FD_SETSIZE, &set, NULL, NULL, &timeout);
828
829 if (rv == -1) {
830 caller->Err("select error\n"); // an error accured
831 } else if (rv == 0) {
832 // printf("timeout write_log_user %s\n",caller->ObjectName().c_str()); //
833 // a timeout occured
834 } else {
835 if (FD_ISSET(cmd_pipe, &set)) {
836 log_desc_t tmp;
837 read(cmd_pipe, &tmp, sizeof(log_desc_t));
838
839 if (tmp.running == true) {// start logging
840 string filename = caller->log_path + "/" + caller->FileName(tmp.device) + ".dbt";
841 printf("Creating log file %s (log size %i)\n", filename.c_str(), (int)tmp.size);
842 tmp.dbtFile = inithdFile((char *)filename.c_str(), UAV, tmp.size);
843 logs.push_back(tmp);
844
845 if (logs.size() == 1) {
846 filename = caller->log_path + "/setup.xml";
847 xmlSaveFile(filename.c_str(), caller->file_doc);
848 }
849 } else {// stop logging
850 //disable watchdog temporarly
851 //this is necessary because GCS is no longer sending the heartbeat when receiving files...
852 //TODO: add a thread in GCS for receiving file
853 //but be careful that with a xbee modem for exemple, sending files can saturate communication and
854 //avoid the heartbeat to be received... so disabling watchdog is not a so bad option...
855 if(caller->gcs_watchdog!=NULL) {
856 caller->gcs_watchdog->SafeStop();
857 caller->gcs_watchdog->Join();
858 }
859 //create a socket for files
860 UDTSOCKET file_sock = caller->GetSocket();
861 char data=START_SENDING_FILES;
862 ssize_t nb_write = UDT::sendmsg(file_sock, &data, 1, -1, true);
863 if (nb_write < 0) {
864 caller->Err("UDT::sendmsg error (%s)\n", UDT::getlasterror().getErrorMessage());
865 if (UDT::getlasterror().getErrorCode() == CUDTException::ECONNLOST ||
866 UDT::getlasterror().getErrorCode() == CUDTException::EINVSOCK) {
867 }
868 } else if (nb_write != 1) {
869 caller->Err("%s, code %i (%ld/%ld)\n", UDT::getlasterror().getErrorMessage(),
870 UDT::getlasterror().getErrorCode(), nb_write, 1);
871 }
872 for (size_t i = 0; i < logs.size(); i++) {
873 if (logs.at(i).dbtFile != NULL) {
874 close_hdfile(logs.at(i).dbtFile);
875
876 string filename = caller->FileName(logs.at(i).device) + ".dbt";
877 caller->SendFile(file_sock,caller->log_path, filename);
878
879 fstream txt_file;
880 filename = caller->FileName(logs.at(i).device) + ".txt";
881 txt_file.open((caller->log_path + "/" + filename).c_str(),
882 fstream::out);
883 txt_file << "1: time (us)\n2: time (ns)\n";
884 int index = 3;
885 logs.at(i).device->pimpl_->WriteLogsDescriptors(txt_file, &index);
886 txt_file.close();
887
888 caller->SendFile(file_sock,caller->log_path, filename);
889 }
890 }
891 // a revoir celui ci est le xml enregistré et pas forcement l'actuel
892 // if(caller->xml_file!="") caller->SendFile(caller->xml_file);
893 caller->FinishSending(file_sock);
894
895 int status = UDT::close(file_sock);
896 if (status != 0)
897 caller->Err("Error udt::close %s", UDT::getlasterror().getErrorMessage());
898
899 logs.clear();
900 //enable watchdog again
901 if(caller->gcs_watchdog!=NULL) {
902 caller->gcs_watchdog->Start();
903 }
904 }
905 }
906
907 if (FD_ISSET(data_pipe, &set)) {
908 log_header_t header;
909 read(data_pipe, &header, sizeof(log_header_t));
910
911 for (size_t i = 0; i < logs.size(); i++) {
912 if (logs.at(i).device == header.device) {
913 char *buf = (char *)malloc(header.size);
914 read(data_pipe, buf, header.size);
915 // printf("%s \n",header.device->ObjectName().c_str());
916 // for(int i=0;i<header.size;i++) printf("%x ",buf[i]);
917 // printf("\n");
918 if (logs.at(i).size == header.size) {
919 if (logs.at(i).dbtFile != NULL) {
920 write_hdfile(
921 logs.at(i).dbtFile, buf, (road_time_t)(header.time / 1000),
922 (road_timerange_t)(header.time % 1000), header.size);
923 } else {
924 printf("err\n");
925 }
926 } else {
927 caller->self->Err("%s log size is not correct %i/%i\n",
928 header.device->ObjectName().c_str(),
929 header.size, logs.at(i).size);
930 }
931 free(buf);
932 }
933 }
934 }
935 }
936 }
937
938#ifdef __XENO__
939 close(cmd_pipe);
940 close(data_pipe);
941#endif
942
943 pthread_exit(0);
944}
945
946string FrameworkManager_impl::FileName(IODevice *device) {
947 return getFrameworkManager()->ObjectName() + "_" + device->ObjectName();
948}
949
950void FrameworkManager_impl::PrintXml(void) const {
951 xmlChar *xmlbuff;
952 int buffersize;
953 xmlDocDumpFormatMemory(file_doc, &xmlbuff, &buffersize, 1);
954 Printf("xml:\n%s\n", xmlbuff);
955 xmlFree(xmlbuff);
956}
Note: See TracBrowser for help on using the repository browser.