1 // generic.cxx -- generic protocol class
3 // Written by Curtis Olson, started November 1999.
5 // Copyright (C) 1999 Curtis L. Olson - http://www.flightgear.org/~curt
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
27 #include <string.h> // strstr()
28 #include <stdlib.h> // strtod(), atoi()
30 #include <simgear/debug/logstream.hxx>
31 #include <simgear/io/iochannel.hxx>
32 #include <simgear/structure/exception.hxx>
33 #include <simgear/misc/sg_path.hxx>
34 #include <simgear/misc/stdint.hxx>
35 #include <simgear/props/props.hxx>
36 #include <simgear/props/props_io.hxx>
37 #include <simgear/math/SGMath.hxx>
39 #include <Main/globals.hxx>
40 #include <Main/fg_props.hxx>
41 #include <Main/fg_os.hxx>
42 #include <Main/util.hxx>
43 #include "generic.hxx"
45 FGGeneric::FGGeneric(vector<string> tokens) : exitOnError(false)
48 if (tokens[1] == "socket") {
50 } else if (tokens[1] == "file") {
56 if (configToken >= tokens.size()) {
57 SG_LOG(SG_NETWORK, SG_ALERT,
58 "Not enough tokens passed for generic protocol");
62 string config = tokens[ configToken ];
63 file_name = config+".xml";
64 direction = tokens[2];
66 if (direction != "in" && direction != "out" && direction != "bi") {
67 SG_LOG(SG_NETWORK, SG_ALERT, "Unsuported protocol direction: "
74 FGGeneric::~FGGeneric() {
87 // generate the message
88 bool FGGeneric::gen_message_binary() {
89 string generic_sentence;
93 for (unsigned int i = 0; i < _out_message.size(); i++) {
95 switch (_out_message[i].type) {
98 val = _out_message[i].offset +
99 _out_message[i].prop->getIntValue() * _out_message[i].factor;
100 int32_t intVal = val;
101 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
102 intVal = (int32_t) sg_bswap_32((uint32_t)intVal);
104 memcpy(&buf[length], &intVal, sizeof(int32_t));
105 length += sizeof(int32_t);
110 buf[length] = (char) (_out_message[i].prop->getBoolValue() ? true : false);
116 val = _out_message[i].offset +
117 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
119 int32_t fixed = (int)(val * 65536.0f);
120 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
121 fixed = (int32_t) sg_bswap_32((uint32_t)fixed);
123 memcpy(&buf[length], &fixed, sizeof(int32_t));
124 length += sizeof(int32_t);
130 val = _out_message[i].offset +
131 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
133 tmpun32.floatVal = static_cast<float>(val);
135 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
136 tmpun32.intVal = sg_bswap_32(tmpun32.intVal);
138 memcpy(&buf[length], &tmpun32.intVal, sizeof(uint32_t));
139 length += sizeof(uint32_t);
145 val = _out_message[i].offset +
146 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
148 tmpun64.doubleVal = val;
150 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
151 tmpun64.longVal = sg_bswap_64(tmpun64.longVal);
153 memcpy(&buf[length], &tmpun64.longVal, sizeof(uint64_t));
154 length += sizeof(uint64_t);
158 default: // SG_STRING
159 const char *strdata = _out_message[i].prop->getStringValue();
160 int32_t strlength = strlen(strdata);
162 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
163 SG_LOG( SG_IO, SG_ALERT, "Generic protocol: "
164 "FG_STRING will be written in host byte order.");
166 /* Format for strings is
167 * [length as int, 4 bytes][ASCII data, length bytes]
169 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
170 strlength = sg_bswap_32(strlength);
172 memcpy(&buf[length], &strlength, sizeof(int32_t));
173 length += sizeof(int32_t);
174 strncpy(&buf[length], strdata, strlength);
176 /* FIXME padding for alignment? Something like:
177 * length += (strlength % 4 > 0 ? sizeof(int32_t) - strlength % 4 : 0;
183 // add the footer to the packet ("line")
184 switch (binary_footer_type) {
186 binary_footer_value = length;
194 if (binary_footer_type != FOOTER_NONE) {
195 int32_t intValue = binary_footer_value;
196 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
197 intValue = sg_bswap_32(binary_footer_value);
199 memcpy(&buf[length], &intValue, sizeof(int32_t));
200 length += sizeof(int32_t);
206 bool FGGeneric::gen_message_ascii() {
207 string generic_sentence;
212 for (unsigned int i = 0; i < _out_message.size(); i++) {
215 generic_sentence += var_separator;
218 switch (_out_message[i].type) {
220 val = _out_message[i].offset +
221 _out_message[i].prop->getIntValue() * _out_message[i].factor;
222 snprintf(tmp, 255, _out_message[i].format.c_str(), (int)val);
226 snprintf(tmp, 255, _out_message[i].format.c_str(),
227 _out_message[i].prop->getBoolValue());
231 val = _out_message[i].offset +
232 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
233 snprintf(tmp, 255, _out_message[i].format.c_str(), (float)val);
237 val = _out_message[i].offset +
238 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
239 snprintf(tmp, 255, _out_message[i].format.c_str(), (float)val);
243 val = _out_message[i].offset +
244 _out_message[i].prop->getDoubleValue() * _out_message[i].factor;
245 snprintf(tmp, 255, _out_message[i].format.c_str(), (double)val);
248 default: // SG_STRING
249 snprintf(tmp, 255, _out_message[i].format.c_str(),
250 _out_message[i].prop->getStringValue());
253 generic_sentence += tmp;
256 /* After each lot of variables has been added, put the line separator
259 generic_sentence += line_separator;
261 length = generic_sentence.length();
262 strncpy( buf, generic_sentence.c_str(), length );
267 bool FGGeneric::gen_message() {
269 return gen_message_binary();
271 return gen_message_ascii();
275 bool FGGeneric::parse_message_binary(int length) {
281 while ((++i < (int)_in_message.size()) && (p1 < p2)) {
283 switch (_in_message[i].type) {
285 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
286 tmp32 = sg_bswap_32(*(int32_t *)p1);
288 tmp32 = *(int32_t *)p1;
290 updateValue(_in_message[i], (int)tmp32);
291 p1 += sizeof(int32_t);
295 updateValue(_in_message[i], p1[0] != 0);
300 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
301 tmp32 = sg_bswap_32(*(int32_t *)p1);
303 tmp32 = *(int32_t *)p1;
305 updateValue(_in_message[i], (float)tmp32 / 65536.0f);
306 p1 += sizeof(int32_t);
311 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
312 tmpun32.intVal = sg_bswap_32(*(uint32_t *)p1);
314 tmpun32.floatVal = *(float *)p1;
316 updateValue(_in_message[i], tmpun32.floatVal);
317 p1 += sizeof(int32_t);
322 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
323 tmpun64.longVal = sg_bswap_64(*(uint64_t *)p1);
325 tmpun64.doubleVal = *(double *)p1;
327 updateValue(_in_message[i], tmpun64.doubleVal);
328 p1 += sizeof(int64_t);
331 default: // SG_STRING
332 SG_LOG( SG_IO, SG_ALERT, "Generic protocol: "
333 "Ignoring unsupported binary input chunk type.");
341 bool FGGeneric::parse_message_ascii(int length) {
344 int chunks = _in_message.size();
345 int line_separator_size = line_separator.size();
347 if (length < line_separator_size ||
348 line_separator.compare(buf + length - line_separator_size) != 0) {
350 SG_LOG(SG_IO, SG_WARN,
351 "Input line does not end with expected line separator." );
353 buf[length - line_separator_size] = 0;
356 while ((++i < chunks) && p1) {
357 p2 = strstr(p1, var_separator.c_str());
360 p2 += var_separator.length();
363 switch (_in_message[i].type) {
365 updateValue(_in_message[i], atoi(p1));
369 updateValue(_in_message[i], atof(p1) != 0.0);
374 updateValue(_in_message[i], (float)strtod(p1, 0));
378 updateValue(_in_message[i], (double)strtod(p1, 0));
381 default: // SG_STRING
382 _in_message[i].prop->setStringValue(p1);
392 bool FGGeneric::parse_message(int length) {
394 return parse_message_binary(length);
396 return parse_message_ascii(length);
401 // open hailing frequencies
402 bool FGGeneric::open() {
403 if ( is_enabled() ) {
404 SG_LOG( SG_IO, SG_ALERT, "This shouldn't happen, but the channel "
405 << "is already in use, ignoring" );
409 SGIOChannel *io = get_io_channel();
411 if ( ! io->open( get_direction() ) ) {
412 SG_LOG( SG_IO, SG_ALERT, "Error opening channel communication layer." );
418 if ( ((get_direction() == SG_IO_OUT )||
419 (get_direction() == SG_IO_BI))
420 && ! preamble.empty() ) {
421 if ( ! io->write( preamble.c_str(), preamble.size() ) ) {
422 SG_LOG( SG_IO, SG_WARN, "Error writing preamble." );
431 // process work for this port
432 bool FGGeneric::process() {
433 SGIOChannel *io = get_io_channel();
435 if ( (get_direction() == SG_IO_OUT) ||
436 (get_direction() == SG_IO_BI) ) {
438 if ( ! io->write( buf, length ) ) {
439 SG_LOG( SG_IO, SG_WARN, "Error writing data." );
444 if (( get_direction() == SG_IO_IN ) ||
445 (get_direction() == SG_IO_BI) ) {
446 if ( io->get_type() == sgFileType ) {
448 length = io->readline( buf, FG_MAX_MSG_SIZE );
450 parse_message( length );
452 SG_LOG( SG_IO, SG_ALERT, "Error reading data." );
456 length = io->read( buf, binary_record_length );
457 if ( length == binary_record_length ) {
458 parse_message( length );
460 SG_LOG( SG_IO, SG_ALERT,
461 "Generic protocol: Received binary "
462 "record of unexpected size, expected: "
463 << binary_record_length << " but received: "
469 while ((length = io->readline( buf, FG_MAX_MSG_SIZE )) > 0 ) {
470 parse_message( length );
473 while ((length = io->read( buf, binary_record_length ))
474 == binary_record_length ) {
475 parse_message( length );
479 SG_LOG( SG_IO, SG_ALERT,
480 "Generic protocol: Received binary "
481 "record of unexpected size, expected: "
482 << binary_record_length << " but received: "
492 return true; // should not get there, but please the compiler
499 bool FGGeneric::close() {
500 SGIOChannel *io = get_io_channel();
502 if ( ((get_direction() == SG_IO_OUT)||
503 (get_direction() == SG_IO_BI))
504 && ! postamble.empty() ) {
505 if ( ! io->write( postamble.c_str(), postamble.size() ) ) {
506 SG_LOG( SG_IO, SG_ALERT, "Error writing postamble." );
511 set_enabled( false );
513 if ( ! io->close() ) {
524 SGPath path( globals->get_fg_root() );
525 path.append("Protocol");
526 path.append(file_name.c_str());
528 SG_LOG(SG_NETWORK, SG_INFO, "Reading communication protocol from "
533 readProperties(path.str(), &root);
534 } catch (const sg_exception & ex) {
535 SG_LOG(SG_NETWORK, SG_ALERT,
536 "Unable to load the protocol configuration file: " << ex.getFormattedMessage() );
540 if (direction == "out") {
541 SGPropertyNode *output = root.getNode("generic/output");
543 _out_message.clear();
544 read_config(output, _out_message);
546 } else if (direction == "in") {
547 SGPropertyNode *input = root.getNode("generic/input");
550 read_config(input, _in_message);
551 if (!binary_mode && (line_separator.size() == 0 ||
552 *line_separator.rbegin() != '\n')) {
554 SG_LOG(SG_IO, SG_WARN,
555 "Warning: Appending newline to line separator in generic input.");
556 line_separator.push_back('\n');
564 FGGeneric::read_config(SGPropertyNode *root, vector<_serial_prot> &msg)
566 binary_mode = root->getBoolValue("binary_mode");
569 /* These variables specified in the $FG_ROOT/data/Protocol/xxx.xml
570 * file for each format
572 * var_sep_string = the string/charachter to place between variables
573 * line_sep_string = the string/charachter to place at the end of each
576 preamble = fgUnescape(root->getStringValue("preamble"));
577 postamble = fgUnescape(root->getStringValue("postamble"));
578 var_sep_string = fgUnescape(root->getStringValue("var_separator"));
579 line_sep_string = fgUnescape(root->getStringValue("line_separator"));
581 if ( var_sep_string == "newline" ) {
582 var_separator = '\n';
583 } else if ( var_sep_string == "tab" ) {
584 var_separator = '\t';
585 } else if ( var_sep_string == "space" ) {
587 } else if ( var_sep_string == "formfeed" ) {
588 var_separator = '\f';
589 } else if ( var_sep_string == "carriagereturn" ) {
590 var_sep_string = '\r';
591 } else if ( var_sep_string == "verticaltab" ) {
592 var_separator = '\v';
594 var_separator = var_sep_string;
597 if ( line_sep_string == "newline" ) {
598 line_separator = '\n';
599 } else if ( line_sep_string == "tab" ) {
600 line_separator = '\t';
601 } else if ( line_sep_string == "space" ) {
602 line_separator = ' ';
603 } else if ( line_sep_string == "formfeed" ) {
604 line_separator = '\f';
605 } else if ( line_sep_string == "carriagereturn" ) {
606 line_separator = '\r';
607 } else if ( line_sep_string == "verticaltab" ) {
608 line_separator = '\v';
610 line_separator = line_sep_string;
613 // default values: no footer and record_length = sizeof(representation)
614 binary_footer_type = FOOTER_NONE;
615 binary_record_length = -1;
617 // default choice is network byte order (big endian)
618 if (sgIsLittleEndian()) {
619 binary_byte_order = BYTE_ORDER_NEEDS_CONVERSION;
621 binary_byte_order = BYTE_ORDER_MATCHES_NETWORK_ORDER;
624 if ( root->hasValue("binary_footer") ) {
625 string footer_type = root->getStringValue("binary_footer");
626 if ( footer_type == "length" ) {
627 binary_footer_type = FOOTER_LENGTH;
628 } else if ( footer_type.substr(0, 5) == "magic" ) {
629 binary_footer_type = FOOTER_MAGIC;
630 binary_footer_value = strtol(footer_type.substr(6,
631 footer_type.length() - 6).c_str(), (char**)0, 0);
632 } else if ( footer_type != "none" ) {
633 SG_LOG(SG_IO, SG_ALERT,
634 "generic protocol: Unknown generic binary protocol "
635 "footer '" << footer_type << "', using no footer.");
639 if ( root->hasValue("record_length") ) {
640 binary_record_length = root->getIntValue("record_length");
643 if ( root->hasValue("byte_order") ) {
644 string byte_order = root->getStringValue("byte_order");
645 if (byte_order == "network" ) {
646 if ( sgIsLittleEndian() ) {
647 binary_byte_order = BYTE_ORDER_NEEDS_CONVERSION;
649 binary_byte_order = BYTE_ORDER_MATCHES_NETWORK_ORDER;
651 } else if ( byte_order == "host" ) {
652 binary_byte_order = BYTE_ORDER_MATCHES_NETWORK_ORDER;
654 SG_LOG(SG_IO, SG_ALERT,
655 "generic protocol: Undefined generic binary protocol"
656 "byte order, using HOST byte order.");
661 int record_length = 0; // Only used for binary protocols.
662 vector<SGPropertyNode_ptr> chunks = root->getChildren("chunk");
663 for (unsigned int i = 0; i < chunks.size(); i++) {
667 // chunk.name = chunks[i]->getStringValue("name");
668 chunk.format = fgUnescape(chunks[i]->getStringValue("format", "%d"));
669 chunk.offset = chunks[i]->getDoubleValue("offset");
670 chunk.factor = chunks[i]->getDoubleValue("factor", 1.0);
671 chunk.min = chunks[i]->getDoubleValue("min");
672 chunk.max = chunks[i]->getDoubleValue("max");
673 chunk.wrap = chunks[i]->getBoolValue("wrap");
674 chunk.rel = chunks[i]->getBoolValue("relative");
676 string node = chunks[i]->getStringValue("node", "/null");
677 chunk.prop = fgGetNode(node.c_str(), true);
679 string type = chunks[i]->getStringValue("type");
681 // Note: officially the type is called 'bool' but for backward
682 // compatibility 'boolean' will also be supported.
683 if (type == "bool" || type == "boolean") {
684 chunk.type = FG_BOOL;
686 } else if (type == "float") {
687 chunk.type = FG_FLOAT;
688 record_length += sizeof(int32_t);
689 } else if (type == "double") {
690 chunk.type = FG_DOUBLE;
691 record_length += sizeof(int64_t);
692 } else if (type == "fixed") {
693 chunk.type = FG_FIXED;
694 record_length += sizeof(int32_t);
695 } else if (type == "string")
696 chunk.type = FG_STRING;
699 record_length += sizeof(int32_t);
701 msg.push_back(chunk);
706 if (binary_record_length == -1) {
707 binary_record_length = record_length;
708 } else if (binary_record_length < record_length) {
709 SG_LOG(SG_IO, SG_ALERT,
710 "generic protocol: Requested binary record length shorter than "
711 " requested record representation.");
712 binary_record_length = record_length;
717 void FGGeneric::updateValue(FGGeneric::_serial_prot& prot, bool val)
721 // value inverted if received true, otherwise leave unchanged
723 setValue(prot.prop, !getValue<bool>(prot.prop));
727 setValue(prot.prop, val);