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