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