]> git.mxchange.org Git - flightgear.git/blob - src/Network/generic.cxx
Remove unneeded function and add bool relative changes
[flightgear.git] / src / Network / generic.cxx
1 // generic.cxx -- generic protocal class
2 //
3 // Written by Curtis Olson, started November 1999.
4 //
5 // Copyright (C) 1999  Curtis L. Olson - http://www.flightgear.org/~curt
6 //
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.
11 //
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.
16 //
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.
20 //
21 // $Id$
22
23 #ifdef HAVE_CONFIG_H
24 #  include "config.h"
25 #endif
26
27 #include <string.h>                // strstr()
28 #include <stdlib.h>                // strtod(), atoi()
29
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
38 #include <Main/globals.hxx>
39 #include <Main/fg_props.hxx>
40 #include <Main/fg_os.hxx>
41 #include <Main/util.hxx>
42 #include "generic.hxx"
43
44 FGGeneric::FGGeneric(vector<string> tokens) : exitOnError(false)
45 {
46     size_t configToken;
47     if (tokens[1] == "socket") {
48         configToken = 7;
49     } else if (tokens[1] == "file") {
50         configToken = 5;
51     } else {
52         configToken = 6; 
53     }
54
55     if (configToken >= tokens.size()) {
56        SG_LOG(SG_NETWORK, SG_ALERT,
57               "Not enough tokens passed for generic protocol");
58        return;
59     }
60
61     string config = tokens[ configToken ];
62     file_name = config+".xml";
63     direction = tokens[2];
64
65     if (direction != "in" && direction != "out" && direction != "bi") {
66         SG_LOG(SG_NETWORK, SG_ALERT, "Unsuported protocol direction: "
67                << direction);
68     }
69
70     reinit();
71 }
72
73 FGGeneric::~FGGeneric() {
74 }
75
76 union u32 {
77     uint32_t intVal;
78     float floatVal;
79 };
80
81 union u64 {
82     uint64_t longVal;
83     double doubleVal;
84 };
85
86 // generate the message
87 bool FGGeneric::gen_message_binary() {
88     string generic_sentence;
89     length = 0;
90
91     double val;
92     for (unsigned int i = 0; i < _out_message.size(); i++) {
93
94         switch (_out_message[i].type) {
95         case FG_INT:
96         {
97             val = _out_message[i].offset +
98                   _out_message[i].prop->getIntValue() * _out_message[i].factor;
99             int32_t intVal = val;
100             if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
101                 intVal = (int32_t) sg_bswap_32((uint32_t)intVal);
102             }
103             memcpy(&buf[length], &intVal, sizeof(int32_t));
104             length += sizeof(int32_t);
105             break;
106         }
107
108         case FG_BOOL:
109             buf[length] = (char) (_out_message[i].prop->getBoolValue() ? true : false);
110             length += 1;
111             break;
112
113         case FG_FIXED:
114         {
115             val = _out_message[i].offset +
116                  _out_message[i].prop->getFloatValue() * _out_message[i].factor;
117
118             int32_t fixed = (int)(val * 65536.0f);
119             if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
120                 fixed = (int32_t) sg_bswap_32((uint32_t)fixed);
121             } 
122             memcpy(&buf[length], &fixed, sizeof(int32_t));
123             length += sizeof(int32_t);
124             break;
125         }
126
127         case FG_FLOAT:
128         {
129             val = _out_message[i].offset +
130                  _out_message[i].prop->getFloatValue() * _out_message[i].factor;
131             u32 tmpun32;
132             tmpun32.floatVal = static_cast<float>(val);
133
134             if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
135                 tmpun32.intVal = sg_bswap_32(tmpun32.intVal);
136             }
137             memcpy(&buf[length], &tmpun32.intVal, sizeof(uint32_t));
138             length += sizeof(uint32_t);
139             break;
140         }
141
142         case FG_DOUBLE:
143         {
144             val = _out_message[i].offset +
145                  _out_message[i].prop->getFloatValue() * _out_message[i].factor;
146             u64 tmpun64;
147             tmpun64.doubleVal = val;
148
149             if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
150                 tmpun64.longVal = sg_bswap_64(tmpun64.longVal);
151             }
152             memcpy(&buf[length], &tmpun64.longVal, sizeof(uint64_t));
153             length += sizeof(uint64_t);
154             break;
155         }
156
157         default: // SG_STRING
158             const char *strdata = _out_message[i].prop->getStringValue();
159             int32_t strlength = strlen(strdata);
160
161             if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
162                 SG_LOG( SG_IO, SG_ALERT, "Generic protocol: "
163                         "FG_STRING will be written in host byte order.");
164             }
165             /* Format for strings is 
166              * [length as int, 4 bytes][ASCII data, length bytes]
167              */
168             if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
169                 strlength = sg_bswap_32(strlength);
170             }
171             memcpy(&buf[length], &strlength, sizeof(int32_t));
172             length += sizeof(int32_t);
173             strncpy(&buf[length], strdata, strlength);
174             length += strlength; 
175             /* FIXME padding for alignment? Something like: 
176              * length += (strlength % 4 > 0 ? sizeof(int32_t) - strlength % 4 : 0;
177              */
178         }
179     }
180
181     // add the footer to the packet ("line")
182     switch (binary_footer_type) {
183         case FOOTER_LENGTH:
184             binary_footer_value = length;
185             break;
186
187         case FOOTER_MAGIC:
188         case FOOTER_NONE:
189             break;
190     }
191
192     if (binary_footer_type != FOOTER_NONE) {
193         int32_t intValue = binary_footer_value;
194         if (binary_byte_order != BYTE_ORDER_MATCHES_NETWORK_ORDER) {
195             intValue = sg_bswap_32(binary_footer_value);
196         }
197         memcpy(&buf[length], &intValue, sizeof(int32_t));
198         length += sizeof(int32_t);
199     }
200
201     return true;
202 }
203
204 bool FGGeneric::gen_message_ascii() {
205     string generic_sentence;
206     char tmp[255];
207     length = 0;
208
209     double val;
210     for (unsigned int i = 0; i < _out_message.size(); i++) {
211
212         if (i > 0) {
213             generic_sentence += var_separator;
214         }
215
216         switch (_out_message[i].type) {
217         case FG_INT:
218             val = _out_message[i].offset +
219                   _out_message[i].prop->getIntValue() * _out_message[i].factor;
220             snprintf(tmp, 255, _out_message[i].format.c_str(), (int)val);
221             break;
222
223         case FG_BOOL:
224             snprintf(tmp, 255, _out_message[i].format.c_str(),
225                                _out_message[i].prop->getBoolValue());
226             break;
227
228         case FG_FIXED:
229             val = _out_message[i].offset +
230                 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
231             snprintf(tmp, 255, _out_message[i].format.c_str(), (float)val);
232             break;
233
234         case FG_FLOAT:
235             val = _out_message[i].offset +
236                 _out_message[i].prop->getFloatValue() * _out_message[i].factor;
237             snprintf(tmp, 255, _out_message[i].format.c_str(), (float)val);
238             break;
239
240         case FG_DOUBLE:
241             val = _out_message[i].offset +
242                 _out_message[i].prop->getDoubleValue() * _out_message[i].factor;
243             snprintf(tmp, 255, _out_message[i].format.c_str(), (double)val);
244             break;
245
246         default: // SG_STRING
247             snprintf(tmp, 255, _out_message[i].format.c_str(),
248                                    _out_message[i].prop->getStringValue());
249         }
250
251         generic_sentence += tmp;
252     }
253
254     /* After each lot of variables has been added, put the line separator
255      * char/string
256      */
257     generic_sentence += line_separator;
258
259     length =  generic_sentence.length();
260     strncpy( buf, generic_sentence.c_str(), length );
261
262     return true;
263 }
264
265 bool FGGeneric::gen_message() {
266     if (binary_mode) {
267         return gen_message_binary();
268     } else {
269         return gen_message_ascii();
270     }
271 }
272
273 bool FGGeneric::parse_message_binary(int length) {
274     char *p2, *p1 = buf;
275     int32_t tmp32;
276     int i = -1;
277
278     p2 = p1 + length;
279     while ((++i < (int)_in_message.size()) && (p1  < p2)) {
280
281         switch (_in_message[i].type) {
282         case FG_INT:
283             if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
284                 tmp32 = sg_bswap_32(*(int32_t *)p1);
285             } else {
286                 tmp32 = *(int32_t *)p1;
287             }
288             updateValue(_in_message[i], (int)tmp32);
289             p1 += sizeof(int32_t);
290             break;
291
292         case FG_BOOL:
293             updateValue(_in_message[i], p1[0] != 0);
294             p1 += 1;
295             break;
296
297         case FG_FIXED:
298             if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
299                 tmp32 = sg_bswap_32(*(int32_t *)p1);
300             } else {
301                 tmp32 = *(int32_t *)p1;
302             }
303             updateValue(_in_message[i], (float)tmp32 / 65536.0f);
304             p1 += sizeof(int32_t);
305             break;
306
307         case FG_FLOAT:
308             u32 tmpun32;
309             if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
310                 tmpun32.intVal = sg_bswap_32(*(uint32_t *)p1);
311             } else {
312                 tmpun32.floatVal = *(float *)p1;
313             }
314             updateValue(_in_message[i], tmpun32.floatVal);
315             p1 += sizeof(int32_t);
316             break;
317
318         case FG_DOUBLE:
319             u64 tmpun64;
320             if (binary_byte_order == BYTE_ORDER_NEEDS_CONVERSION) {
321                 tmpun64.longVal = sg_bswap_64(*(uint64_t *)p1);
322             } else {
323                 tmpun64.doubleVal = *(double *)p1;
324             }
325             updateValue(_in_message[i], tmpun64.doubleVal);
326             p1 += sizeof(int64_t);
327             break;
328
329         default: // SG_STRING
330             SG_LOG( SG_IO, SG_ALERT, "Generic protocol: "
331                     "Ignoring unsupported binary input chunk type.");
332         }
333     }
334     
335     return true;
336 }
337
338 bool FGGeneric::parse_message_ascii(int length) {
339     char *p2, *p1 = buf;
340     int i = -1;
341     int chunks = _in_message.size();
342     int line_separator_size = line_separator.size();
343
344     if (length < line_separator_size ||
345         line_separator.compare(buf + length - line_separator_size) != 0) {
346
347         SG_LOG(SG_IO, SG_WARN,
348                "Input line does not end with expected line separator." );
349     } else {
350         buf[length - line_separator_size] = 0;
351     }
352
353     while ((++i < chunks) && p1) {
354         p2 = strstr(p1, var_separator.c_str());
355         if (p2) {
356             *p2 = 0;
357             p2 += var_separator.length();
358         }
359
360         switch (_in_message[i].type) {
361         case FG_INT:
362             updateValue(_in_message[i], atoi(p1));
363             break;
364
365         case FG_BOOL:
366             updateValue(_in_message[i], atof(p1) != 0.0);
367             break;
368
369         case FG_FIXED:
370         case FG_FLOAT:
371             updateValue(_in_message[i], (float)strtod(p1, 0));
372             break;
373
374         case FG_DOUBLE:
375             updateValue(_in_message[i], (double)strtod(p1, 0));
376             break;
377
378         default: // SG_STRING
379             _in_message[i].prop->setStringValue(p1);
380         }
381
382         p1 = p2;
383     }
384
385     return true;
386 }
387
388 bool FGGeneric::parse_message(int length) {
389     if (binary_mode) {
390         return parse_message_binary(length);
391     } else {
392         return parse_message_ascii(length);
393     }
394 }
395
396
397 // open hailing frequencies
398 bool FGGeneric::open() {
399     if ( is_enabled() ) {
400         SG_LOG( SG_IO, SG_ALERT, "This shouldn't happen, but the channel " 
401                 << "is already in use, ignoring" );
402         return false;
403     }
404
405     SGIOChannel *io = get_io_channel();
406
407     if ( ! io->open( get_direction() ) ) {
408         SG_LOG( SG_IO, SG_ALERT, "Error opening channel communication layer." );
409         return false;
410     }
411
412     set_enabled( true );
413
414     if ( ((get_direction() == SG_IO_OUT )||
415           (get_direction() == SG_IO_BI))
416           && ! preamble.empty() ) {
417         if ( ! io->write( preamble.c_str(), preamble.size() ) ) {
418             SG_LOG( SG_IO, SG_WARN, "Error writing preamble." );
419             return false;
420         }
421     }
422
423     return true;
424 }
425
426
427 // process work for this port
428 bool FGGeneric::process() {
429     SGIOChannel *io = get_io_channel();
430
431     if ( (get_direction() == SG_IO_OUT) ||
432          (get_direction() == SG_IO_BI) ) {
433         gen_message();
434         if ( ! io->write( buf, length ) ) {
435             SG_LOG( SG_IO, SG_WARN, "Error writing data." );
436             goto error_out;
437         }
438     }
439
440     if (( get_direction() == SG_IO_IN ) ||
441         (get_direction() == SG_IO_BI) ) {
442         if ( io->get_type() == sgFileType ) {
443             if (!binary_mode) {
444                 length = io->readline( buf, FG_MAX_MSG_SIZE );
445                 if ( length > 0 ) {
446                     parse_message( length );
447                 } else {
448                     SG_LOG( SG_IO, SG_ALERT, "Error reading data." );
449                     return false;
450                 }
451             } else {
452                 length = io->read( buf, binary_record_length );
453                 if ( length == binary_record_length ) {
454                     parse_message( length );
455                 } else {
456                     SG_LOG( SG_IO, SG_ALERT,
457                             "Generic protocol: Received binary "
458                             "record of unexpected size, expected: "
459                             << binary_record_length << " but received: "
460                             << length);
461                 }
462             }
463         } else {
464             if (!binary_mode) {
465                 while ((length = io->readline( buf, FG_MAX_MSG_SIZE )) > 0 ) {
466                     parse_message( length );
467                 }
468             } else {
469                 while ((length = io->read( buf, binary_record_length )) 
470                           == binary_record_length ) {
471                     parse_message( length );
472                 }
473
474                 if ( length > 0 ) {
475                     SG_LOG( SG_IO, SG_ALERT,
476                         "Generic protocol: Received binary "
477                         "record of unexpected size, expected: "
478                         << binary_record_length << " but received: "
479                         << length);
480                 }
481             }
482         }
483     }
484     return true;
485 error_out:
486     if (exitOnError) {
487         fgOSExit(1);
488         return true; // should not get there, but please the compiler
489     } else
490         return false;
491 }
492
493
494 // close the channel
495 bool FGGeneric::close() {
496     SGIOChannel *io = get_io_channel();
497
498     if ( ((get_direction() == SG_IO_OUT)||
499           (get_direction() == SG_IO_BI))
500           && ! postamble.empty() ) {
501         if ( ! io->write( postamble.c_str(), postamble.size() ) ) {
502             SG_LOG( SG_IO, SG_ALERT, "Error writing postamble." );
503             return false;
504         }
505     }
506
507     set_enabled( false );
508
509     if ( ! io->close() ) {
510         return false;
511     }
512
513     return true;
514 }
515
516
517 void
518 FGGeneric::reinit()
519 {
520     SGPath path( globals->get_fg_root() );
521     path.append("Protocol");
522     path.append(file_name.c_str());
523
524     SG_LOG(SG_NETWORK, SG_INFO, "Reading communication protocol from "
525                                 << path.str());
526
527     SGPropertyNode root;
528     try {
529         readProperties(path.str(), &root);
530     } catch (const sg_exception & ex) {
531         SG_LOG(SG_NETWORK, SG_ALERT,
532          "Unable to load the protocol configuration file: " << ex.getFormattedMessage() );
533          return;
534     }
535
536     if (direction == "out") {
537         SGPropertyNode *output = root.getNode("generic/output");
538         if (output) {
539             _out_message.clear();
540             read_config(output, _out_message);
541         }
542     } else if (direction == "in") {
543         SGPropertyNode *input = root.getNode("generic/input");
544         if (input) {
545             _in_message.clear();
546             read_config(input, _in_message);
547             if (!binary_mode && (line_separator.size() == 0 ||
548                 *line_separator.rbegin() != '\n')) {
549
550                 SG_LOG(SG_IO, SG_WARN,
551                     "Warning: Appending newline to line separator in generic input.");
552                 line_separator.push_back('\n');
553             }
554         }
555     }
556 }
557
558
559 void
560 FGGeneric::read_config(SGPropertyNode *root, vector<_serial_prot> &msg)
561 {
562     binary_mode = root->getBoolValue("binary_mode");
563
564     if (!binary_mode) {
565         /* These variables specified in the $FG_ROOT/data/Protocol/xxx.xml
566          * file for each format
567          *
568          * var_sep_string  = the string/charachter to place between variables
569          * line_sep_string = the string/charachter to place at the end of each
570          *                   lot of variables
571          */
572         preamble = fgUnescape(root->getStringValue("preamble"));
573         postamble = fgUnescape(root->getStringValue("postamble"));
574         var_sep_string = fgUnescape(root->getStringValue("var_separator"));
575         line_sep_string = fgUnescape(root->getStringValue("line_separator"));
576
577         if ( var_sep_string == "newline" ) {
578             var_separator = '\n';
579         } else if ( var_sep_string == "tab" ) {
580             var_separator = '\t';
581         } else if ( var_sep_string == "space" ) {
582             var_separator = ' ';
583         } else if ( var_sep_string == "formfeed" ) {
584             var_separator = '\f';
585         } else if ( var_sep_string == "carriagereturn" ) {
586             var_sep_string = '\r';
587         } else if ( var_sep_string == "verticaltab" ) {
588             var_separator = '\v';
589         } else {
590             var_separator = var_sep_string;
591         }
592
593         if ( line_sep_string == "newline" ) {
594             line_separator = '\n';
595         } else if ( line_sep_string == "tab" ) {
596             line_separator = '\t';
597         } else if ( line_sep_string == "space" ) {
598             line_separator = ' ';
599         } else if ( line_sep_string == "formfeed" ) {
600             line_separator = '\f';
601         } else if ( line_sep_string == "carriagereturn" ) {
602             line_separator = '\r';
603         } else if ( line_sep_string == "verticaltab" ) {
604             line_separator = '\v';
605         } else {
606             line_separator = line_sep_string;
607         }
608     } else {
609         // default values: no footer and record_length = sizeof(representation)
610         binary_footer_type = FOOTER_NONE;
611         binary_record_length = -1;
612
613         // default choice is network byte order (big endian)
614         if (sgIsLittleEndian()) {
615            binary_byte_order = BYTE_ORDER_NEEDS_CONVERSION;
616         } else {
617            binary_byte_order = BYTE_ORDER_MATCHES_NETWORK_ORDER;
618         }
619
620         if ( root->hasValue("binary_footer") ) {
621             string footer_type = root->getStringValue("binary_footer");
622             if ( footer_type == "length" ) {
623                 binary_footer_type = FOOTER_LENGTH;
624             } else if ( footer_type.substr(0, 5) == "magic" ) {
625                 binary_footer_type = FOOTER_MAGIC;
626                 binary_footer_value = strtol(footer_type.substr(6, 
627                             footer_type.length() - 6).c_str(), (char**)0, 0);
628             } else if ( footer_type != "none" ) {
629                 SG_LOG(SG_IO, SG_ALERT,
630                        "generic protocol: Unknown generic binary protocol "
631                        "footer '" << footer_type << "', using no footer.");
632             }
633         }
634
635         if ( root->hasValue("record_length") ) {
636             binary_record_length = root->getIntValue("record_length");
637         }
638
639         if ( root->hasValue("byte_order") ) {
640             string byte_order = root->getStringValue("byte_order");
641             if (byte_order == "network" ) {
642                 if ( sgIsLittleEndian() ) {
643                     binary_byte_order = BYTE_ORDER_NEEDS_CONVERSION;
644                 } else {
645                     binary_byte_order = BYTE_ORDER_MATCHES_NETWORK_ORDER;
646                 }
647             } else if ( byte_order == "host" ) {
648                 binary_byte_order = BYTE_ORDER_MATCHES_NETWORK_ORDER;
649             } else {
650                 SG_LOG(SG_IO, SG_ALERT,
651                        "generic protocol: Undefined generic binary protocol"
652                        "byte order, using HOST byte order.");
653             }
654         }
655     }
656
657     int record_length = 0; // Only used for binary protocols.
658     vector<SGPropertyNode_ptr> chunks = root->getChildren("chunk");
659     for (unsigned int i = 0; i < chunks.size(); i++) {
660
661         _serial_prot chunk;
662
663         // chunk.name = chunks[i]->getStringValue("name");
664         chunk.format = fgUnescape(chunks[i]->getStringValue("format", "%d"));
665         chunk.offset = chunks[i]->getDoubleValue("offset");
666         chunk.factor = chunks[i]->getDoubleValue("factor", 1.0);
667         chunk.min = chunks[i]->getDoubleValue("min");
668         chunk.max = chunks[i]->getDoubleValue("max");
669         chunk.wrap = chunks[i]->getBoolValue("wrap");
670         chunk.rel = chunks[i]->getBoolValue("relative");
671
672         string node = chunks[i]->getStringValue("node", "/null");
673         chunk.prop = fgGetNode(node.c_str(), true);
674
675         string type = chunks[i]->getStringValue("type");
676
677         // Note: officially the type is called 'bool' but for backward
678         //       compatibility 'boolean' will also be supported.
679         if (type == "bool" || type == "boolean") {
680             chunk.type = FG_BOOL;
681             record_length += 1;
682         } else if (type == "float") {
683             chunk.type = FG_FLOAT;
684             record_length += sizeof(int32_t);
685         } else if (type == "double") {
686             chunk.type = FG_DOUBLE;
687             record_length += sizeof(int64_t);
688         } else if (type == "fixed") {
689             chunk.type = FG_FIXED;
690             record_length += sizeof(int32_t);
691         } else if (type == "string")
692             chunk.type = FG_STRING;
693         else {
694             chunk.type = FG_INT;
695             record_length += sizeof(int32_t);
696         }
697         msg.push_back(chunk);
698
699     }
700
701     if( binary_mode ) {
702         if (binary_record_length == -1) {
703             binary_record_length = record_length;
704         } else if (binary_record_length < record_length) {
705             SG_LOG(SG_IO, SG_ALERT,
706                    "generic protocol: Requested binary record length shorter than "
707                    " requested record representation.");
708             binary_record_length = record_length;
709         }
710     }
711 }
712
713 void FGGeneric::updateValue(FGGeneric::_serial_prot& prot, bool val)
714 {
715   if( prot.rel )
716   {
717     // value inverted if received true, otherwise leave unchanged
718     if( val )
719       setValue(prot.prop, !getValue<bool>(prot.prop));
720   }
721   else
722   {
723     setValue(prot.prop, val);
724   }
725 }