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

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

maj thread

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