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

Last change on this file since 133 was 133, checked in by Sanahuja Guillaume, 6 years ago

modif sterror

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