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), initOk(false)
48 if (tokens[1] == "socket") {
50 } else if (tokens[1] == "file") {
56 if ((configToken >= tokens.size())||(tokens[ configToken ] == "")) {
57 SG_LOG(SG_NETWORK, SG_ALERT,
58 "Not enough tokens passed for generic '" << tokens[1] << "' 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: "
75 FGGeneric::~FGGeneric() {
88 // generate the message
89 bool FGGeneric::gen_message_binary() {
90 string generic_sentence;
94 for (unsigned int i = 0; i < _out_message.size(); i++) {
96 switch (_out_message[i].type) {
99 val = _out_message[i].offset +
100 _out_message[i].prop->getIntValue() * _out_message[i].factor;
101 int32_t intVal = val;
102 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
103 intVal = (int32_t) sg_bswap_32((uint32_t)intVal);
105 memcpy(&buf[length], &intVal, sizeof(int32_t));
106 length += sizeof(int32_t);
111 buf[length] = (char) (_out_message[i].prop->getBoolValue() ? true : false);
117 val = _out_message[i].offset +
118 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
120 int32_t fixed = (int)(val * 65536.0f);
121 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
122 fixed = (int32_t) sg_bswap_32((uint32_t)fixed);
124 memcpy(&buf[length], &fixed, sizeof(int32_t));
125 length += sizeof(int32_t);
131 val = _out_message[i].offset +
132 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
134 tmpun32.floatVal = static_cast<float>(val);
136 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
137 tmpun32.intVal = sg_bswap_32(tmpun32.intVal);
139 memcpy(&buf[length], &tmpun32.intVal, sizeof(uint32_t));
140 length += sizeof(uint32_t);
146 val = _out_message[i].offset +
147 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
149 tmpun64.doubleVal = val;
151 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
152 tmpun64.longVal = sg_bswap_64(tmpun64.longVal);
154 memcpy(&buf[length], &tmpun64.longVal, sizeof(uint64_t));
155 length += sizeof(uint64_t);
159 default: // SG_STRING
160 const char *strdata = _out_message[i].prop->getStringValue();
161 int32_t strlength = strlen(strdata);
163 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
164 SG_LOG( SG_IO, SG_ALERT, "Generic protocol: "
165 "FG_STRING will be written in host byte order.");
167 /* Format for strings is
168 * [length as int, 4 bytes][ASCII data, length bytes]
170 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
171 strlength = sg_bswap_32(strlength);
173 memcpy(&buf[length], &strlength, sizeof(int32_t));
174 length += sizeof(int32_t);
175 strncpy(&buf[length], strdata, strlength);
177 /* FIXME padding for alignment? Something like:
178 * length += (strlength % 4 > 0 ? sizeof(int32_t) - strlength % 4 : 0;
184 // add the footer to the packet ("line")
185 switch (binary_footer_type) {
187 binary_footer_value = length;
195 if (binary_footer_type != FOOTER_NONE) {
196 int32_t intValue = binary_footer_value;
197 if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
198 intValue = sg_bswap_32(binary_footer_value);
200 memcpy(&buf[length], &intValue, sizeof(int32_t));
201 length += sizeof(int32_t);
207 bool FGGeneric::gen_message_ascii() {
208 string generic_sentence;
213 for (unsigned int i = 0; i < _out_message.size(); i++) {
216 generic_sentence += var_separator;
219 switch (_out_message[i].type) {
221 val = _out_message[i].offset +
222 _out_message[i].prop->getIntValue() * _out_message[i].factor;
223 snprintf(tmp, 255, _out_message[i].format.c_str(), (int)val);
227 snprintf(tmp, 255, _out_message[i].format.c_str(),
228 _out_message[i].prop->getBoolValue());
232 val = _out_message[i].offset +
233 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
234 snprintf(tmp, 255, _out_message[i].format.c_str(), (float)val);
238 val = _out_message[i].offset +
239 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
240 snprintf(tmp, 255, _out_message[i].format.c_str(), (float)val);
244 val = _out_message[i].offset +
245 _out_message[i].prop->getDoubleValue() * _out_message[i].factor;
246 snprintf(tmp, 255, _out_message[i].format.c_str(), (double)val);
249 default: // SG_STRING
250 snprintf(tmp, 255, _out_message[i].format.c_str(),
251 _out_message[i].prop->getStringValue());
254 generic_sentence += tmp;
257 /* After each lot of variables has been added, put the line separator
260 generic_sentence += line_separator;
262 length = generic_sentence.length();
263 strncpy( buf, generic_sentence.c_str(), length );
268 bool FGGeneric::gen_message() {
270 return gen_message_binary();
272 return gen_message_ascii();
276 bool FGGeneric::parse_message_binary(int length) {
282 while ((++i < (int)_in_message.size()) && (p1 < p2)) {
284 switch (_in_message[i].type) {
286 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
287 tmp32 = sg_bswap_32(*(int32_t *)p1);
289 tmp32 = *(int32_t *)p1;
291 updateValue(_in_message[i], (int)tmp32);
292 p1 += sizeof(int32_t);
296 updateValue(_in_message[i], p1[0] != 0);
301 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
302 tmp32 = sg_bswap_32(*(int32_t *)p1);
304 tmp32 = *(int32_t *)p1;
306 updateValue(_in_message[i], (float)tmp32 / 65536.0f);
307 p1 += sizeof(int32_t);
312 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
313 tmpun32.intVal = sg_bswap_32(*(uint32_t *)p1);
315 tmpun32.floatVal = *(float *)p1;
317 updateValue(_in_message[i], tmpun32.floatVal);
318 p1 += sizeof(int32_t);
323 if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
324 tmpun64.longVal = sg_bswap_64(*(uint64_t *)p1);
326 tmpun64.doubleVal = *(double *)p1;
328 updateValue(_in_message[i], tmpun64.doubleVal);
329 p1 += sizeof(int64_t);
332 default: // SG_STRING
333 SG_LOG( SG_IO, SG_ALERT, "Generic protocol: "
334 "Ignoring unsupported binary input chunk type.");
342 bool FGGeneric::parse_message_ascii(int length) {
345 int chunks = _in_message.size();
346 int line_separator_size = line_separator.size();
348 if (length < line_separator_size ||
349 line_separator.compare(buf + length - line_separator_size) != 0) {
351 SG_LOG(SG_IO, SG_WARN,
352 "Input line does not end with expected line separator." );
354 buf[length - line_separator_size] = 0;
357 size_t varsep_len = var_separator.length();
358 while ((++i < chunks) && p1) {
363 p2 = strstr(p1, var_separator.c_str());
370 switch (_in_message[i].type) {
372 updateValue(_in_message[i], atoi(p1));
376 updateValue(_in_message[i], atof(p1) != 0.0);
381 updateValue(_in_message[i], (float)strtod(p1, 0));
385 updateValue(_in_message[i], (double)strtod(p1, 0));
388 default: // SG_STRING
389 _in_message[i].prop->setStringValue(p1);
399 bool FGGeneric::parse_message_len(int length) {
401 return parse_message_binary(length);
403 return parse_message_ascii(length);
408 // open hailing frequencies
409 bool FGGeneric::open() {
410 if ( is_enabled() ) {
411 SG_LOG( SG_IO, SG_ALERT, "This shouldn't happen, but the channel "
412 << "is already in use, ignoring" );
416 SGIOChannel *io = get_io_channel();
418 if ( ! io->open( get_direction() ) ) {
419 SG_LOG( SG_IO, SG_ALERT, "Error opening channel communication layer." );
425 if ( ((get_direction() == SG_IO_OUT )||
426 (get_direction() == SG_IO_BI))
427 && ! preamble.empty() ) {
428 if ( ! io->write( preamble.c_str(), preamble.size() ) ) {
429 SG_LOG( SG_IO, SG_WARN, "Error writing preamble." );
438 // process work for this port
439 bool FGGeneric::process() {
440 SGIOChannel *io = get_io_channel();
442 if ( (get_direction() == SG_IO_OUT) ||
443 (get_direction() == SG_IO_BI) ) {
445 if ( ! io->write( buf, length ) ) {
446 SG_LOG( SG_IO, SG_WARN, "Error writing data." );
451 if (( get_direction() == SG_IO_IN ) ||
452 (get_direction() == SG_IO_BI) ) {
453 if ( io->get_type() == sgFileType ) {
455 length = io->readline( buf, FG_MAX_MSG_SIZE );
457 parse_message_len( length );
459 SG_LOG( SG_IO, SG_ALERT, "Error reading data." );
463 length = io->read( buf, binary_record_length );
464 if ( length == binary_record_length ) {
465 parse_message_len( length );
467 SG_LOG( SG_IO, SG_ALERT,
468 "Generic protocol: Received binary "
469 "record of unexpected size, expected: "
470 << binary_record_length << " but received: "
476 while ((length = io->readline( buf, FG_MAX_MSG_SIZE )) > 0 ) {
477 parse_message_len( length );
480 while ((length = io->read( buf, binary_record_length ))
481 == binary_record_length ) {
482 parse_message_len( length );
486 SG_LOG( SG_IO, SG_ALERT,
487 "Generic protocol: Received binary "
488 "record of unexpected size, expected: "
489 << binary_record_length << " but received: "
499 return true; // should not get there, but please the compiler
506 bool FGGeneric::close() {
507 SGIOChannel *io = get_io_channel();
509 if ( ((get_direction() == SG_IO_OUT)||
510 (get_direction() == SG_IO_BI))
511 && ! postamble.empty() ) {
512 if ( ! io->write( postamble.c_str(), postamble.size() ) ) {
513 SG_LOG( SG_IO, SG_ALERT, "Error writing postamble." );
518 set_enabled( false );
520 if ( ! io->close() ) {
531 SGPath path( globals->get_fg_root() );
532 path.append("Protocol");
533 path.append(file_name.c_str());
535 SG_LOG(SG_NETWORK, SG_INFO, "Reading communication protocol from "
540 readProperties(path.str(), &root);
541 } catch (const sg_exception & ex) {
542 SG_LOG(SG_NETWORK, SG_ALERT,
543 "Unable to load the protocol configuration file: " << ex.getFormattedMessage() );
547 if (direction == "out") {
548 SGPropertyNode *output = root.getNode("generic/output");
550 _out_message.clear();
551 if (!read_config(output, _out_message))
557 } else if (direction == "in") {
558 SGPropertyNode *input = root.getNode("generic/input");
561 if (!read_config(input, _in_message))
566 if (!binary_mode && (line_separator.size() == 0 ||
567 *line_separator.rbegin() != '\n')) {
569 SG_LOG(SG_IO, SG_WARN,
570 "Warning: Appending newline to line separator in generic input.");
571 line_separator.push_back('\n');
581 FGGeneric::read_config(SGPropertyNode *root, vector<_serial_prot> &msg)
583 binary_mode = root->getBoolValue("binary_mode");
586 /* These variables specified in the $FG_ROOT/data/Protocol/xxx.xml
587 * file for each format
589 * var_sep_string = the string/charachter to place between variables
590 * line_sep_string = the string/charachter to place at the end of each
593 preamble = fgUnescape(root->getStringValue("preamble"));
594 postamble = fgUnescape(root->getStringValue("postamble"));
595 var_sep_string = fgUnescape(root->getStringValue("var_separator"));
596 line_sep_string = fgUnescape(root->getStringValue("line_separator"));
598 if ( var_sep_string == "newline" ) {
599 var_separator = '\n';
600 } else if ( var_sep_string == "tab" ) {
601 var_separator = '\t';
602 } else if ( var_sep_string == "space" ) {
604 } else if ( var_sep_string == "formfeed" ) {
605 var_separator = '\f';
606 } else if ( var_sep_string == "carriagereturn" ) {
607 var_sep_string = '\r';
608 } else if ( var_sep_string == "verticaltab" ) {
609 var_separator = '\v';
611 var_separator = var_sep_string;
614 if ( line_sep_string == "newline" ) {
615 line_separator = '\n';
616 } else if ( line_sep_string == "tab" ) {
617 line_separator = '\t';
618 } else if ( line_sep_string == "space" ) {
619 line_separator = ' ';
620 } else if ( line_sep_string == "formfeed" ) {
621 line_separator = '\f';
622 } else if ( line_sep_string == "carriagereturn" ) {
623 line_separator = '\r';
624 } else if ( line_sep_string == "verticaltab" ) {
625 line_separator = '\v';
627 line_separator = line_sep_string;
630 // default values: no footer and record_length = sizeof(representation)
631 binary_footer_type = FOOTER_NONE;
632 binary_record_length = -1;
634 // default choice is network byte order (big endian)
635 if (sgIsLittleEndian()) {
636 binary_byte_order = BYTE_ORDER_NEEDS_CONVERSION;
638 binary_byte_order = BYTE_ORDER_MATCHES_NETWORK_ORDER;
641 if ( root->hasValue("binary_footer") ) {
642 string footer_type = root->getStringValue("binary_footer");
643 if ( footer_type == "length" ) {
644 binary_footer_type = FOOTER_LENGTH;
645 } else if ( footer_type.substr(0, 5) == "magic" ) {
646 binary_footer_type = FOOTER_MAGIC;
647 binary_footer_value = strtol(footer_type.substr(6,
648 footer_type.length() - 6).c_str(), (char**)0, 0);
649 } else if ( footer_type != "none" ) {
650 SG_LOG(SG_IO, SG_ALERT,
651 "generic protocol: Unknown generic binary protocol "
652 "footer '" << footer_type << "', using no footer.");
656 if ( root->hasValue("record_length") ) {
657 binary_record_length = root->getIntValue("record_length");
660 if ( root->hasValue("byte_order") ) {
661 string byte_order = root->getStringValue("byte_order");
662 if (byte_order == "network" ) {
663 if ( sgIsLittleEndian() ) {
664 binary_byte_order = BYTE_ORDER_NEEDS_CONVERSION;
666 binary_byte_order = BYTE_ORDER_MATCHES_NETWORK_ORDER;
668 } else if ( byte_order == "host" ) {
669 binary_byte_order = BYTE_ORDER_MATCHES_NETWORK_ORDER;
671 SG_LOG(SG_IO, SG_ALERT,
672 "generic protocol: Undefined generic binary protocol"
673 "byte order, using HOST byte order.");
678 int record_length = 0; // Only used for binary protocols.
679 vector<SGPropertyNode_ptr> chunks = root->getChildren("chunk");
681 for (unsigned int i = 0; i < chunks.size(); i++) {
685 // chunk.name = chunks[i]->getStringValue("name");
686 chunk.format = fgUnescape(chunks[i]->getStringValue("format", "%d"));
687 chunk.offset = chunks[i]->getDoubleValue("offset");
688 chunk.factor = chunks[i]->getDoubleValue("factor", 1.0);
689 chunk.min = chunks[i]->getDoubleValue("min");
690 chunk.max = chunks[i]->getDoubleValue("max");
691 chunk.wrap = chunks[i]->getBoolValue("wrap");
692 chunk.rel = chunks[i]->getBoolValue("relative");
694 string node = chunks[i]->getStringValue("node", "/null");
695 chunk.prop = fgGetNode(node.c_str(), true);
697 string type = chunks[i]->getStringValue("type");
699 // Note: officially the type is called 'bool' but for backward
700 // compatibility 'boolean' will also be supported.
701 if (type == "bool" || type == "boolean") {
702 chunk.type = FG_BOOL;
704 } else if (type == "float") {
705 chunk.type = FG_FLOAT;
706 record_length += sizeof(int32_t);
707 } else if (type == "double") {
708 chunk.type = FG_DOUBLE;
709 record_length += sizeof(int64_t);
710 } else if (type == "fixed") {
711 chunk.type = FG_FIXED;
712 record_length += sizeof(int32_t);
713 } else if (type == "string")
714 chunk.type = FG_STRING;
717 record_length += sizeof(int32_t);
719 msg.push_back(chunk);
725 if ((chunks.size() > 1)&&(var_sep_string.length() == 0))
727 // ASCII protocols really need a separator when there is more than one chunk per line
728 SG_LOG(SG_IO, SG_ALERT,
729 "generic protocol: Invalid configuration. "
730 "'var_separator' must not be empty for protocols which have more than one chunk per line.");
736 if (binary_record_length == -1) {
737 binary_record_length = record_length;
738 } else if (binary_record_length < record_length) {
739 SG_LOG(SG_IO, SG_ALERT,
740 "generic protocol: Requested binary record length shorter than "
741 " requested record representation.");
742 binary_record_length = record_length;
749 void FGGeneric::updateValue(FGGeneric::_serial_prot& prot, bool val)
753 // value inverted if received true, otherwise leave unchanged
755 setValue(prot.prop, !getValue<bool>(prot.prop));
759 setValue(prot.prop, val);