summaryrefslogtreecommitdiff
path: root/gpsxmple.c
blob: 08ec1dda73ce7f0ad8379ed669c63f0a90377f6b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296

/**************************************************************************
 *
 *  $Id: gpsxmple.c 1.8 2011/04/15 13:04:14 martin REL_M $
 *  $Name: GPSXMPLE_2_3 $
 *
 *  Copyright (c) Meinberg Funkuhren, Bad Pyrmont, Germany
 *
 *  Description:
 *    Sample program demonstrating how to access Meinberg devices
 *    using the binary data protocol.
 *
 *    Depending on the target operating system this program works
 *    either via serial port (the default) or via a network socket
 *    connection.
 *
 *    Other modules needed to build the executable:
 *      mbgextio.c, mbgserio.c, gpsserio.c, gpsutils.c
 *      optionally aes128.c, if network socket I/O is used
 *
 *  Supported target environments:
 *    Windows / VC6 (serial and socket)
 *    Linux / gcc   (serial and socket)
 *    QNX 6.x / gcc (socket only)
 *    DOS / BC3.1   (serial only)
 *
 *  For makefiles and build environment setups check the
 *  corresponding subdirectories.
 *
 *  Please send changes required for other operating systems
 *  or build to <support@meinberg.de>
 *
 * -----------------------------------------------------------------------
 *  $Log: gpsxmple.c $
 *  Revision 1.8  2011/04/15 13:04:14  martin
 *  Optionally poll for user capture events.
 *  Under Unix catch signals to terminate properly.
 *  Revision 1.7  2009/10/02 14:18:08Z  martin
 *  Changes due to renamed library functions.
 *  Optionally force connection.
 *  Read global receiver_info after startup.
 *  Read string type info and port info, if supported.
 *  Fixed a typo for passwd parameter in usage().
 *  Show SVs and DAC.
 *  Optionally loop and wait for automatic messages.
 *  Revision 1.6  2006/10/25 12:31:54Z  martin
 *  Support serial I/O under Windows.
 *  Check return codes of API functions and print associated 
 *  messages in case of error.
 *  Revision 1.5  2006/08/24 13:36:38Z  martin
 *  Conditional support for network socket I/O.
 *  Serial I/O is now also conditional only.
 *  Use unified API calls from mbgextio module.
 *  Account for DAC bias.
 *  Revision 1.4  2006/05/17 10:20:29  martin
 *  Account for renamed structure.
 *  Revision 1.3  2005/09/08 14:28:34  martin
 *  Cleaned up display of synth settings.
 *  Revision 1.2  2005/04/26 11:29:16  martin
 *  Initial revision under RCS.
 *
 **************************************************************************/

#include <mbgextio.h>
#include <gpsutils.h>

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <ctype.h>

#if defined( MBG_TGT_UNIX )
  #include <signal.h>
#endif

#if defined( MBG_TGT_DOS )
  #include <conio.h>
  #define done kbhit()
#else
  static int done;
#endif



// the variables below are required for communication
MBG_MSG_BUFF rbuff;
MBG_MSG_BUFF tbuff;

MBG_MSG_CTL mctl =
{
  { &rbuff, sizeof( rbuff ) },
  { &tbuff, sizeof( tbuff ) }
};


// Define the minimum number of some resource types
// required by the software
#define N_COM_MIN       1    // minimum number of COM ports

// Define the maximum number of some resource types
// supported by the software
#define N_COM_MAX       4    // max. number of COM ports
#define N_STR_TYPE_MAX  20   // max. number of string types
#define N_POUT_MAX      3    // max. number of programmable outputs

#define IDLE_SLEEP_MS   200


#define _log_msg_0( _lvl, _fmt ) \
  printf( _fmt ); printf( "\n" )

#define _log_msg_1( _lvl, _fmt, _v1 ) \
  printf( _fmt, _v1 ); printf( "\n" )

#define _log_msg_2( _lvl, _fmt, _v1, _v2 ) \
  printf( _fmt, _v1, _v2 ); printf( "\n" )

#define _log_msg_3( _lvl, _fmt, _v1, _v2, _v3 ) \
  printf( _fmt, _v1, _v2, _v3 ); printf( "\n" )



static const char *target;
static int is_socket;
static int must_force_connection;
static int must_send_auto;
static int must_poll_ucap;
static RECEIVER_INFO receiver_info;
static const char *feature_names[] = DEFAULT_GPS_FEATURE_NAMES;

#if !defined( DEFAULT_DEV_NAME )
  #define DEFAULT_DEV_NAME   NULL
#endif

static const char *default_target = DEFAULT_DEV_NAME;

#if _USE_SERIAL_IO
  static uint32_t default_baudrate = 19200L;
  static const char *default_framing = "8N1";
  static uint32_t baudrate;
  static const char *framing;
#endif

#if _USE_SOCKET_IO
  static const char *password;
#endif


static char ws[256];
static const char *fmt = "%-20s  ";

static const char *dow_str[] =
  { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };



static /*HDR*/
void mbg_sleep_msec( long msec )
{
  #if defined( MBG_TGT_UNIX )
    usleep( msec * 1000 );
  #elif defined( MBG_TGT_WIN32 )
    Sleep( msec );
  #elif defined( MBG_TGT_DOS )
    delay( msec );
  #endif

}  // mbg_sleep_msec



static /*HDR*/
int check_rc( int rc )
{
  const char *cp = NULL;

  if ( done )
    return 0;   // we are going to exit

  switch ( rc )
  {
    case TR_COMPLETE:
      cp = "Data received completely.";
      break;

    case TR_RECEIVING:
      cp = "Received data not complete.";
      break;

    case TR_WAITING:
      cp = "Waiting for data.";
      break;

    case TR_TIMEOUT:
      cp = "Timeout receiving data";
      break;

    case TR_CSUM_HDR:
      cp = "Header checksum error in received data.";
      break;

    case TR_CSUM_DATA:
      cp = "Data checksum error in received data.";
      break;

    case TR_DECRYPTION:
      cp = "Failed to decrypt received data.";
      break;

    case TR_OPEN_ERR:
      cp = "Failed to establish connection.";
      break;

    case TR_IO_ERR:
      cp = "I/O error receiving data";
      break;

    case TR_AUTH_ERR:
      cp = "Authentication error";
      break;

  }  // switch

  if ( cp )
    printf( "%s\n", cp );
  else
    printf( "Unknow error code: %i\n", rc );

  return rc;

}  // check_rc



/*HDR*/
void sprint_tm( char *s, TM_GPS *tm, int print_frac )
{
  int n = 0;
  int year = tm->year & ( DL_AUTO_FLAG - 1 );

  n += sprintf( &s[n], "%02i.%02i.%04i  %02i:%02i:%02i",
           tm->mday,
           tm->month,
           year,
           tm->hour,
           tm->min,
           tm->sec
         );

  if ( tm->year & DL_AUTO_FLAG )
    strncpy( &s[6], "****", 4 );

  if ( print_frac )
    n += sprintf( &s[n], ".%07li", (long) tm->frac );

}  /* sprint_tm */



/*HDR*/
void sprint_lla( char *s, LLA lla )
{
  static const double r2d = 180 / PI;

  sprintf( s, "%c %.4f deg,  %c %.4f deg,  %.0fm",
           ( lla[LAT] < 0 ) ? 'S' : 'N', lla[LAT] * r2d,
           ( lla[LON] < 0 ) ? 'W' : 'E', lla[LON] * r2d,
           lla[ALT]
         );

}  /* sprint_lla */



/*HDR*/
void print_stat_info( STAT_INFO *p )
{
  const char *cp;

  switch ( p->mode )
  {
    case TRACK:     cp = "SINGLE SV MODE";    break;
    case AUTO_166:  cp = "NORMAL OPERATION";  break;
    case WARM_166:  cp = "WARM BOOT";         break;
    case COLD_166:  cp = "COLD BOOT";         break;
    case AUTO_BC:   cp = "REMOTE OPERATION";  break;
    case WARM_BC:   cp = "REMOTE WARM";       break;
    case COLD_BC:   cp = "REMOTE COLD";       break;
    case UPDA_166:  cp = "UPDATE ALMANAC";    break;
    case UPDA_BC:   cp = "REMOTE UPD. ALM.";  break;
    default:        cp = "INVALID MODE";
  };

  printf( "%s, %u/%u SVs, DAC: %+li/%+li\n",
           cp,
           p->good_svs,
           p->svs_in_view,
           (long) p->dac_val - OSC_DAC_BIAS,
           (long) p->dac_cal - OSC_DAC_BIAS
         );

}  /* print_stat_info */



/*HDR*/
void print_time( TTM *p )
{
  static const char *s[] =
  {
    "(current time)",
    "(capture 0)",
    "(capture 1)"
  };

  sprint_tm( ws, &p->tm, 1 );

  printf( "\rCh: %2i %-14s %s   Status: %04X\n",
          p->channel,
          s[p->channel + 1],
          ws,
          p->tm.status
        );

}  /* print_time */



static /*HDR*/
void check_receiver_info( RECEIVER_INFO *p, int log )
{
  const char *fmt_min = "Number of %s from device (%u) is less than number required (%u)";
  const char *fmt_max = "Number of %s from device (%u) exceeds number supported by the software (%u)";

  // Check if numbers of resources provided by the device 
  // don't exceed numbers of resources supported by the software

  #define _check_min( _n, _min, _info )                      \
  {                                                          \
    if ( (_n) < (_min) )                                     \
    {                                                        \
      if ( log )                                             \
        _log_msg_3( LOG_ERR, fmt_min, _info, _n, _min );     \
    }                                                        \
  }

  #define _check_max( _n, _max, _info )                      \
  {                                                          \
    if ( (_n) > (_max) )                                     \
    {                                                        \
      if ( log )                                             \
        _log_msg_3( LOG_WARNING, fmt_max, _info, _n, _max ); \
                                                             \
      _n = _max;                                             \
    }                                                        \
  }

  if ( p->model_code == GPS_MODEL_UNKNOWN )
  {
    _log_msg_0( LOG_ERR, "Refclock model_code not set: maybe receiver_info "
                         "has not been received correctly" );
  }
  else
    if ( log )
    {
      if ( p->model_code >= N_GPS_MODEL )
      {
        _log_msg_2( LOG_WARNING, "Unsupported refclock model_code %u (name: %s)",
                    p->model_code, p->model_name  );
      }
    }

  _check_min( p->n_com_ports, N_COM_MIN, "COM ports" );
  _check_max( p->n_com_ports, N_COM_MAX, "COM ports" );
  _check_max( p->n_str_type, N_STR_TYPE_MAX, "string types" );
  _check_max( p->n_prg_out, N_POUT_MAX, "progr. outputs" );

}  // check_receiver_info



/*HDR*/
int get_receiver_info( MBG_MSG_CTL *pmctl, RECEIVER_INFO *p )
{
  int rc;
  int i;
  int l;

  printf( fmt, "Receiver info:" );

  rc = mbgextio_get_receiver_info( &mctl, p );

  if ( rc != TR_COMPLETE )
  {
    check_rc( rc );

    if ( rc == TR_TIMEOUT )
    {
      printf( "If you are using a very old GPS model then reading the\n"
              "receiver info structure may not be supported.\n" );
    }

    return rc;
  }

  printf( "%s v%X.%02X",
          p->model_name,
          p->sw_rev.code >> 8,
          p->sw_rev.code & 0xFF
        );

  l = strlen( p->sw_rev.name );

  if ( l )
  {
    // skip trailing spaces
    for ( i = l - 1; i > 0; i-- )
      if ( p->sw_rev.name[i] != ' ' )
        break;

    if ( i != 0 )
      printf( " \"%s\"", p->sw_rev.name );

    #if 0  // hex output for testing
      for ( i= 0; i < l; i++ )
        printf( " %02X", p->sw_rev.name[i] );
    #endif
  }

  printf( ", S/N: %s", p->sernum );
  printf( "\n" );

  // print features
  printf( fmt, "" );
  printf( "Features: 0x%08lX\n", (long) p->features );

  for ( i = 0; i < 8 * sizeof( p->features ); i++ )
  {
    if ( p->features & (1UL << i) )
    {
      printf( fmt, "" );
      printf( " - " );

      if ( i < N_GPS_FEATURE )
        printf( "%s\n", feature_names[i] );
      else
        printf( "Unknown feature flag 0x%08lX\n", (1UL << i) );
    }
  }

  printf( "\n" );

  return rc;

}  // get_receiver_info



/*HDR*/
void show_sw_rev( MBG_MSG_CTL *pmctl )
{
  SW_REV sw_rev;
  int rc;

  printf( fmt, "Software Revision:" );

  rc = mbgextio_get_sw_rev( pmctl, &sw_rev );

  if ( rc != TR_COMPLETE )
  {
    check_rc( rc );
    return;
  }

  printf( "%X.%02X  %s\n",
          sw_rev.code >> 8,
          sw_rev.code & 0xFF,
          sw_rev.name
        );

}  /* show_sw_rev */



/*HDR*/
void show_bvar_stat( MBG_MSG_CTL *pmctl )
{
  BVAR_STAT bvar_stat;
  int rc;

  printf( fmt, "BVAR status:" );

  rc = mbgextio_get_bvar_stat( pmctl, &bvar_stat );

  if ( rc != TR_COMPLETE )
  {
    check_rc( rc );
    return;
  }

  printf( "%04X\n", bvar_stat );

}  /* show_bvar_stat */



/*HDR*/
void show_stat_info( MBG_MSG_CTL *pmctl )
{
  STAT_INFO stat_info;
  int rc;

  printf( fmt, "Receiver status:" );

  rc = mbgextio_get_stat_info( pmctl, &stat_info );

  if ( rc != TR_COMPLETE )
  {
    check_rc( rc );
    return;
  }

  print_stat_info( &stat_info );

}  /* show_stat_info */



/*HDR*/
void show_pos( MBG_MSG_CTL *pmctl )
{
  LLA lla;  // Position as logitude, latitude, altitude
  int rc;

  printf( fmt, "Receiver Position:" );

  rc = mbgextio_get_pos_lla( pmctl, lla );

  if ( rc != TR_COMPLETE )
  {
    check_rc( rc );
    return;
  }

  sprint_lla( ws, lla );
  printf( "%s\n", ws );

}  /* show_pos */



/*HDR*/
void show_tzdl( MBG_MSG_CTL *pmctl )
{
  TZDL tzdl;
  int rc;

  printf( fmt, "Time Zone:" );

  rc = mbgextio_get_tzdl( pmctl, &tzdl );

  if ( rc != TR_COMPLETE )
  {
    check_rc( rc );
    return;
  }

  printf( "%-5s = UTC%+lisec\n",
          tzdl.name[0],
          (long) tzdl.offs
        );

  printf( fmt, " " );
  printf( "%-5s = UTC%+lisec\n",
          tzdl.name[1],
          (long) tzdl.offs + tzdl.offs_dl
        );

  printf( fmt, "Daylight Saving" );
  printf( "starts: " );
  if ( tzdl.tm_on.year & DL_AUTO_FLAG )
  {
    printf( "%s after ",
            dow_str[(int) tzdl.tm_on.wday]
          );
  }
  sprint_tm( ws, &tzdl.tm_on, 0 );
  printf( "%sh\n", ws );

  printf( fmt, " " );
  printf( "ends:   " );
  if ( tzdl.tm_off.year & DL_AUTO_FLAG )
  {
    printf( "%s after ",
            dow_str[(int) tzdl.tm_off.wday]
          );
  }
  sprint_tm( ws, &tzdl.tm_off, 0 );
  printf( "%sh\n", ws );

}  /* show_tzdl */



/*HDR*/
void show_synth( MBG_MSG_CTL *pmctl )
{
  SYNTH synth;
  double f;
  int rc;

  printf( fmt, "Synthesizer:" );

  rc = mbgextio_get_synth( pmctl, &synth );

  if ( rc != TR_COMPLETE )
  {
    check_rc( rc );
    return;
  }

  if ( synth.freq == 0 )
  {
    printf( "disabled\n" );
    return;
  }


  if ( synth.range == 0 )
  {
    // freq field is in 0.1 Hz units, so if 
    // the range is 0 we must divide by 10
    // to yield the correct result
    f = (double) synth.freq / 10.0;
  }
  else
  {
    ulong scale = 1;
    int i;

    for ( i = 1; i < synth.range; i++ )
      scale *= 10L;

    f = synth.freq * (double) scale;
  }

  printf( "%.1f Hz, Phase: %+.1f deg",
          (double) f,
          (double) synth.phase / 10.0
        );

  printf( ( f < SYNTH_PHASE_SYNC_LIMIT ) ? "\n" : " (phase ignored)\n" );

}  /* show_synth */



/*HDR*/
void set_synth( void )
{
  SYNTH synth = { 0 };
  int rc;

  if ( !( receiver_info.features & GPS_HAS_SYNTH ) )
  {
    printf( "The device doesn't provide a synthesizer.\n" );
    return;
  }

  // In this example we set the synthesizer frequency to
  // 1 kHz, and the phase to 180 degrees.
  // The effective frequency is: (freq/10)*(10^^range)

  synth.freq = 1000;   // base frequency value in 1/10 Hz Units
  synth.range = 1;     // multiplier 10^^range 
  synth.phase = 1800;  // phase in 1/10 degrees

  rc = mbgextio_set_synth( &mctl, &synth );

  if ( rc < 0 )
    printf( "Failed to set synthesizer output, code: %i\n", rc );
  else
    printf( "Synthesizer has been modified.\n" );

}  // set_synth



// set programmable output mode

/*HDR*/
void set_pout_mode( void )
{
  POUT_INFO_IDX pout_info_idx;
  POUT_SETTINGS pout_settings = { 0 };  // new settings, init'd to 0
  uint16_t pout_idx = 0;  // index of the programmable output
  int rc;

  if ( receiver_info.n_prg_out == 0 )
  {
    printf( "The device doesn't support programmable outputs.\n" );
    return;
  }

  // valid pout_idx numbers include 0..receiver_info.n_prg_out-1

  if ( pout_idx >= receiver_info.n_prg_out )
  {
    printf( "Programmable output index %u out of range (%u..%u)\n",
      pout_idx, 0, receiver_info.n_prg_out - 1 );
    return;
  }

  // OK, now get the current settings, and see which modes are 
  // supported by the selected programmable pulse output.

  rc = mbgextio_get_pout_info_idx( &mctl, &pout_info_idx, pout_idx );

  if ( rc != TR_COMPLETE )
  {
    check_rc( rc );
    return;
  }


  // As an example we want to set POUT_CYCLIC_PULSE mode.

  // First see if that mode is supported for that output.
  if ( !( pout_info_idx.pout_info.supp_modes & MSK_POUT_CYCLIC_PULSE ) )
  {
    printf( "The selected mode is not supported by the selected output.\n" );
    return;
  }

  // Generate a pulse every pout_settings.tm[0].on.t interval.
  // In this example we want an interval of 20 minutes, and a pulse length
  // of 300 milliseconds
  pout_settings.mode = POUT_CYCLIC_PULSE;
  pout_settings.tm[0].on.t.hour = 0;
  pout_settings.tm[0].on.t.min = 20;
  pout_settings.tm[0].on.t.sec = 0;
  pout_settings.pulse_len = 30;  // 10 millisecond units

  rc = mbgextio_set_pout_settings_idx( &mctl, &pout_settings, pout_idx );

  if ( rc < 0 )
    printf( "Failed to set programmable pulse output mode, code: %i\n", rc );
  else
    printf( "Programmable output mode has been changed.\n" );

}  // set_pout_mode



/*HDR*/
void show_port_parm( MBG_MSG_CTL *pmctl )
{
  PORT_PARM port_parm;
  int rc;
  int i;


  rc = mbgextio_get_port_parm( pmctl, &port_parm );

  if ( rc != TR_COMPLETE )
  {
    check_rc( rc );
    return;
  }


  for ( i = 0; ; )
  {
    printf( "COM%i:  %5lu Baud, %s, ",
            i,
            (ulong) port_parm.com[i].baud_rate,
            port_parm.com[i].framing
          );

    switch ( port_parm.mode[i] )
    {
      case 0:   printf( "Time string on request only\n" ); break;
      case 1:   printf( "Time string once per second\n" ); break;
      case 2:   printf( "Time string once per minute\n" ); break;
      case 3:   printf( "Capture Events\n" ); break;
      default:  printf( "Unknown mode\n" );
    }

    if ( ++i >= 2 )
      break;

    printf( fmt, "" );
  }

}  /* show_port_parm */



/*HDR*/
void show_port_settings( MBG_MSG_CTL *pmctl )
{
  const char *mode_names[N_STR_MODE] = DEFAULT_ENG_MODE_NAMES;
  STR_TYPE_INFO sti[N_STR_TYPE_MAX];
  STR_TYPE_INFO_IDX stii;
  PORT_INFO_IDX pii;
  PORT_SETTINGS *p;
  int rc;
  int i;

  printf( fmt, "Serial ports:" );

  if ( receiver_info.model_code == GPS_MODEL_UNKNOWN )
  {
    // This may be an old GPS model which does not provide 
    // a receiver info structure.
    show_port_parm( pmctl );
    return;
  }

  // The number of serial ports and time string formats supported
  // by this device is specified in the receiver info structure.

  // Read time string information

  for ( i = 0; i < receiver_info.n_str_type; i++ )
  {
    rc = mbgextio_get_str_type_info_idx( pmctl, &stii, (uint16_t) i );

    if ( rc != TR_COMPLETE )
    {
      check_rc( rc );
      return;
    }

    if ( stii.idx != i )
    {
      printf( "** Info for string type %i requested, but for %i received.\n",
              stii.idx, i );
      return;
    }

    sti[i] = stii.str_type_info;
  }


  // Read and print port settings

  for ( i = 0; ; )
  {
    rc = mbgextio_get_port_info_idx( pmctl, &pii, (uint16_t) i );

    if ( rc != TR_COMPLETE )
    {
      check_rc( rc );
      return;
    }

    if ( pii.idx != i )
    {
      printf( "** Info for port %i requested, but for %i received.\n",
              pii.idx, i );
      return;
    }

    p = &pii.port_info.port_settings;

    printf( "COM%i:  %5lu Baud, %s",
            i,
            (ulong) p->parm.baud_rate,
            p->parm.framing
          );

    // Make sure indices received from the device do not exceed
    // maximum numbers supported by this program.

    if ( p->str_type >= N_STR_TYPE_MAX )
      printf( " (string type exceeds max)" );
    else
      if ( p->mode >= N_STR_MODE )
        printf( " (string mode exceeds max)" );
      else
        printf( ", \"%s\" string %s", sti[p->str_type].long_name, mode_names[p->mode] );

    printf( "\n" );

    if ( ++i >= receiver_info.n_com_ports )
      break;

    printf( fmt, "" );
  }

}  /* show_port_settings */



/*HDR*/ static
int check_ucap_poll( void )
{
  int rc;


  printf( "Polling for user capture events:\n" );

  do
  {
    TTM ttm;
    memset( &ttm, 0, sizeof( ttm ) );
    rc = mbgextio_get_ucap( &mctl, &ttm );

    if ( _ttm_time_is_avail( &ttm ) )
    {
      printf( "CAP%i: %04u-%02u-%02u %02u:%02u:%02u.%07u",
              ttm.channel, ttm.tm.year, ttm.tm.month, ttm.tm.mday,
              ttm.tm.hour,ttm.tm.min, ttm.tm.sec, ttm.tm.frac );
      printf( ", Status: %04X (hex)", ttm.tm.status );
      printf( "\n" );
    }
    else
    {
      // No capture event available. We wait some time
      // and then retry.
      mbg_sleep_msec( IDLE_SLEEP_MS );
    }

  } while ( !done );

  return 0;

}  // check_ucap_poll



/*HDR*/ static
void exit_close_connection( void )
{
  mbgextio_close_connection( &mctl );

  printf( "Connection closed.\n" );
  printf( "\n" );

} /* exit_close_connection */



/*HDR*/ static
void exit_auto_off( void )
{
  mbgextio_xmt_cmd( &mctl, GPS_AUTO_OFF );

  #if defined( DEBUG )
    printf( "AUTO mode turned off.\n" );
  #endif

} /* exit_auto_off */



/*HDR*/ static
void set_auto_mode( void )
{
  mbgextio_xmt_cmd( &mctl, GPS_AUTO_ON );

  #if defined( DEBUG )
    printf( "AUTO mode turned on.\n" );
  #endif

  atexit( exit_auto_off );

}  // set_auto_mode



#if defined( MBG_TGT_UNIX )

static /*HDR*/
void sighandler( int sig )
{
  #if defined( DEBUG )
    printf( "Caught signal %i, exiting.\n", sig );
  #endif

  done = 1;

}  // sighandler

#endif



// Do a very simple processing of command line parameters:

static /*HDR*/
int check_command_line( int argc, char *argv[] )
{
  int must_print_usage = 0;
  int i;

  for ( i = 1; i < argc; i++ )
  {
    if ( strcmp( argv[i], "-a" ) == 0 ) 
    {
      must_send_auto = 1;
      continue;
    }

    if ( strcmp( argv[i], "-u" ) == 0 ) 
    {
      must_poll_ucap = 1;
      continue;
    }

    if ( strcmp( argv[i], "-?" ) == 0 ) 
    {
      must_print_usage = 1;
      continue;
    }

    if ( strcmp( argv[i], "-h" ) == 0 ) 
    {
      must_print_usage = 1;
      continue;
    }

    #if _USE_SOCKET_IO
      if ( strcmp( argv[i], "-n" ) == 0 ) 
      {
        is_socket = 1;
        continue;
      }
    #endif

    #if _USE_SOCKET_IO
      if ( strcmp( argv[i], "-p" ) == 0 )
      { 
        if ( ++i < argc )
          password = argv[i];
        else
          must_print_usage = 1;

        continue;
      }
    #endif

    #if _USE_SERIAL_IO
      if ( strcmp( argv[i], "-b" ) == 0 )
      { 
        if ( ++i < argc )
          baudrate = strtoul( argv[i], NULL, 10 );
        else
          must_print_usage = 1;

        continue;
      }
    #endif

    #if _USE_SERIAL_IO
      if ( strcmp( argv[i], "-f" ) == 0 )
      { 
        if ( ++i < argc )
          framing = argv[i];
        else
          must_print_usage = 1;

        continue;
      }
    #endif

    #if _USE_SERIAL_IO
      if ( strcmp( argv[i], "-F" ) == 0 )
      {
        must_force_connection = 1;
        continue;
      }
    #endif

    if ( argv[i][0] != '-' )
      target = argv[i];
    else
      must_print_usage = 1;
  }

  if ( target == NULL )
  {
    if ( is_socket )
      must_print_usage = 1;
    else
      target = default_target;
  }

  if ( must_print_usage )
  {
    printf( "Usage: %s [options] target\n"
      "\n"
      #if _USE_SERIAL_IO
        "  target can specify a serial port\n"
      #endif
      #if _USE_SOCKET_IO
        "  target can specify a network host name or IP address\n"
      #endif
      "\n"
      "Options\n"
      "  -? or -h     Print this usage\n"
      "  -a           Set auto mode\n"
      "  -u           Poll user capture events\n"
      #if _USE_SOCKET_IO
        "  -n           Connect to network target, not serial port\n"
        "  -p passwd    Use specified password to connect\n"
      #endif
      #if _USE_SERIAL_IO
        "  -b speed     Serial port baud rate, default: %lu\n"
        "  -f xxx       Serial port framing, default: %s\n"
        "  -F           Force serial connection to %lu/%s\n"
      #endif
      "\n"
      "Example:\n"
      #if _USE_SERIAL_IO
        "  %s                           Connect to serial port %s using %lu/%s\n"
      #endif
      #if _USE_SOCKET_IO
        "  %s -n -p secret 172.16.1.1   Connect to the specified network host\n"
      #endif
      "\n",
      argv[0]
      #if _USE_SERIAL_IO
      , (long) default_baudrate
      , framing
      , (long) default_baudrate
      , framing
      , argv[0]
      , default_target
      , (long) default_baudrate
      , framing
      #endif
      #if _USE_SOCKET_IO
      , argv[0]
      #endif
    );

    return -1;
  }

  return 0;

}  // check_command_line



int main( int argc, char *argv[] )
{
  int rc;

  printf( "\n\n\nExample Program Accessing a Meinberg Device via Binary Protocol\n" );

  baudrate = default_baudrate;
  framing = default_framing;

  if ( check_command_line( argc, argv ) < 0 )
    return 1;

  #if defined( MBG_TGT_UNIX )
    signal( SIGTERM, sighandler );
    signal( SIGINT, sighandler );
  #endif

  #if _USE_SOCKET_IO
    if ( is_socket )
    {
      rc = mbgextio_open_socket( &mctl, target, password );

      if ( rc < 0 )
      {
        if ( rc == TR_OPEN_ERR )
          perror( "Error connecting" );
        else
          fprintf( stderr, "mbgextio_open_socket returned %i", rc );

        exit( 1 );
      }

      goto doit;
    }
  #endif

  #if _USE_SERIAL_IO
    if ( must_force_connection )
    {
      printf( "Trying to force connection to 19200/8N1 ..." );
      mbgextio_force_connection( target );
      printf( "\n" );

      baudrate = default_baudrate;
      framing = default_framing;
    }

    rc = mbgextio_open_serial( &mctl, target, baudrate, framing );

    if ( rc < 0 )
    {
      printf( "Error using port %s.\n", target );
      return -1;      // Error ...
    }

    printf( "      (Using %s with %li baud, %s)\n\n",
            target, (long) baudrate, framing );

    goto doit;
  #endif

  #if !_USE_SOCKET_IO && !_USE_SERIAL_IO
    return 1;
  #endif



doit:
  atexit( exit_close_connection );

  // now start communication with whichever device has been opened above:

  get_receiver_info( &mctl, &receiver_info );
  check_receiver_info( &receiver_info, 1 );

  /* display system specific values */
  show_sw_rev( &mctl );
  show_bvar_stat( &mctl );
  show_stat_info( &mctl );
  show_pos( &mctl );
  show_tzdl( &mctl );
  show_port_settings( &mctl );
  show_synth( &mctl );

//  set_synth();
//  set_pout_mode();

  if ( must_poll_ucap )
    return check_ucap_poll();

  if ( !must_send_auto )
    return 0;


  printf( "\n" );

  // We will start to wait for automatically transmitted messages
  // which require a longer timeout than we have used by default
  // to wait for replies to dedicated request messages.
  mbgextio_set_char_rcv_timeout( &mctl, 2000 );   // [msec]
  mbgextio_set_msg_rcv_timeout( &mctl, 2000 );    // [msec]

  set_auto_mode();

  do
  {
    MBG_MSG_BUFF *pmb;
    MSG_DATA *p;


    rc = mbgextio_rcv_msg( &mctl, -1 );

    if ( rc != TR_COMPLETE )
    {
      check_rc( rc );
      break;
    }

    mbgextio_xmt_cmd( &mctl, GPS_AUTO_ON );

    pmb = mctl.rcv.pmb;
    p = &pmb->u.msg_data;

    switch ( pmb->hdr.cmd )
    {
      case GPS_TIME:
        print_time( &p->ttm );

        if ( p->ttm.channel == -1 )
        {
          mbgextio_xmt_cmd( &mctl, GPS_AUTO_ON );
          mbgextio_xmt_cmd( &mctl, GPS_STAT_INFO );
          mbgextio_xmt_cmd( &mctl, GPS_UCAP );
        }
        break;

      case GPS_STAT_INFO:
        print_stat_info( &p->stat_info );
        break;

    }  /* switch */

  } while ( !done );

  return 0;

}  /* main */