File: libCW.c

package info (click to toggle)
twclock 3.1-1
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 1,108 kB
  • sloc: sh: 3,796; ansic: 2,166; makefile: 19
file content (1161 lines) | stat: -rw-r--r-- 27,571 bytes parent folder | download
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
/* 
 * libCW- 2.0 - Copyright (C) 2006 -> 2011 by Ted Williams - WA0EIR
 * Derived mostly from qrq.c - High speed morse trainer
 * by Fabian Kurz, DJ1YFK, Copyright (C) 2006, and
 * a few bits from unixcw
 * by Simon Baldwin, G0FRD.Copyright (C) 2001-2006
 * 
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */ 

/*
 * include file for libCW.h
 */
#include "libCW.h"

#include <errno.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <fcntl.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/kd.h>
#include <sys/msg.h>
#include <sys/ioctl.h>
#include <linux/rtc.h>

#include <pulse/simple.h>
#include <pulse/error.h>

#define TESTMODE  0
#define MESG      0       /* 0 = no message , 1 =  with message support */
#define DEBUG     0

#define FUDGE     1.066   /* fudge factor for my lousy soundcard */

#define MAX_NAME  20
#define MAX_LETTERS 512
#define MAX_WORD_LENGTH  100L    /* Maximum length of a word */
#define PI 3.1415926             /* Indiana residents, feel free to */
                                 /* change it to 3.2 */
#define DIT '.'
#define DAH '-'
#define DEFAULT_WPM   20.0
#define MIN_WPM        5.0
#define FARNS_OFF  MIN_WPM - 1.0  /* minimum farnsworth speed */
#define RISE 2.0
#define FALL 2.0

#define SAMPLERATE 8000
//#define SAMPLERATE 44100

#define TRUE 1
#define FALSE !TRUE
#define SENT_MSG 7L              /* as defined in common.h */

/*
 * CWirc stuff
*/
#if WITH_CWIRC == 1
#define AUDIOBUF_SIZE 22050   /* Samples */
struct cwirc_extension_api {
   int semid;
   signed short int out_audiobuf[AUDIOBUF_SIZE];
   int out_audiobuf_start;
   int out_audiobuf_end;
   int in_key;
   int pid;
   };
extern struct cwirc_extension_api *cwirc_api_shm;
#endif

#if MESG == 1
extern int qid;
#endif

/* set some variables to their default values */
char serdevice[MAX_NAME] = "/dev/ttyS0";       /* default serial device path */
int  ser_fd = 0;
char pa_name[MAX_NAME];                        /* shows up on pa vol ctrl */
int keyMode = 0;                               /* PA, RTS, or CWIRC */
int doReply = FALSE;                           /* send reply msg when true */

int rts_on = TIOCM_RTS;                        /* for key down */
int rts_off = 0;                               /* for key up */
int initialized = 0;                           /* set to 1 by cw_init */

/* for PA */
static const pa_sample_spec ss =
   {
      .format = PA_SAMPLE_S16LE,
      .rate = SAMPLERATE,
      .channels = 2
   };

   pa_simple *sp = NULL;

int rtc_rate = 4096;                          /* RTC interupt rate */

char *codetable[MAX_LETTERS];

static int freq = 700;                        /* freq value for SC */
static long samplerate = SAMPLERATE;

float wpm = DEFAULT_WPM;                      /* current speed to default */
float farns_wpm = FARNS_OFF;                  /* farnsworth speed to default */

float dit_time = 1200.0 / DEFAULT_WPM;
float dah_time = 1200.0 / DEFAULT_WPM * 3;     /* dah time in milliseconds */
float farns_time;                              /* farns time */

float ic_time = 1200 / DEFAULT_WPM;            /* intra letter time */
float il_time = 3 * 1200 / DEFAULT_WPM;        /* inter letter time */
float iw_time = 7 * 1200 / DEFAULT_WPM;        /* inter word time */

float rise = RISE;                      /* risetime in ms */
float fall = FALL;                      /* fall time in ms */
float rt = SAMPLERATE / 1000 * RISE;    /* normalized risetime */
float ft = SAMPLERATE / 1000 * FALL;    /* normalized falltime */

static pthread_t cwthread = 0;                 /* thread for CW output */
static pthread_attr_t cwattr;                  /* thread attributes */

#if WITH_CWIRC == 1
extern struct cwirc_extension_api *cwirc_api_shm;
struct cwirc_extension_api *cwirc_api_shm;
#endif

/* forward declarations internal functions */
int  cw_set_keyMode (int newmode, char *pgmname);
void cleanup ();
void *send_cw (void *p);
void keySC (char *code);
void keyRTS (char *code);
int  open_serial (void);
int  timer (float usec);
int  close_devs(void);
int  tonegen (int freq, float length);

#if WITH_CWIRC == 1
void keyCWIRC (char *code);
#endif


/*
 * cw_init function
 * if name and ser args are present, copy them to local vars.
 * then, set the mode to PA, RTS or CWIRC. PA needs to create a new pa stream.
 * RTS needs to open the serial card.  CWIRC just works. Then init the
 * character table and setup traps.  All need the thread created.
 */
int cw_init (int newmode, char name[], char ser[])
{
   int i, rtn;

   /*join the thread if already initialized */
   if (initialized == 1)
   {
      pthread_join (cwthread, NULL); 
      initialized = 0;
   }

   /* check for a name argument */
   if (name == NULL)
   {
      fprintf (stderr, "cw_init Warning: name argument is NULL\n");
   }
   else
      strncpy (pa_name, name, MAX_NAME - 1);      /* copy name to pa_name */

   /* check for a serial device */
   if (ser == NULL)
   {
      fprintf (stderr, "cw_init Warning: serial device argument is NULL\n");
   }
   else
      strncpy (serdevice, ser, MAX_NAME - 1) ;    /* copy ser to serdevice */

   /* set newmode to PA or RTS */
   switch (newmode)
   {
      case PA:
         #if DEBUG == 1
         fprintf (stderr, "cw_init to PA mode\n");
         #endif
         
         if (cw_set_keyMode (PA, name) != PA)  /* set keyMode to PA */
         {
            return 0;                          /* set keyMode failed */
         }
         break;

      case RTS:
         #if DEBUG == 1
         fprintf (stderr, "cw_init to RTS mode\n");
         #endif

         if ((cw_set_keyMode (RTS, ser)) == RTS)
         {
            strncpy (serdevice, ser, MAX_NAME - 1); 
         }
         break;

      #if WITH_CWIRC == 1
      case CWIRC:
         #if DEBUG == 1
         fprintf (stderr, "USING CWIRC\n");
         #endif
         keyMode = CWIRC;
         break;
      #endif

      default:   /* invalid mode */
         fprintf (stderr, "cw_init error: invalid mode %d\n", newmode);
         exit (1);
   }


  /* Initialize the codetable array */
   for (i = 0; i < MAX_LETTERS; i++)
      codetable[i] = " ";

   /* Pro Signs and Special */        /* Shift/Alt  */
   codetable[1]         = "......";   /* F1 = Error */
   codetable[2]         = ".-.-.";    /* F2 = <AR>  */
   codetable[3]         = "-.--.";    /* F3 = <KN>  */
   codetable[4]         = "...-.-";   /* F4 = <SK>  */
   codetable[5]         = ".-...";    /* F5 = WAIT  */
   codetable[6]         = "-...-.-";  /* F6 = BREAK */

   /* Numbers */
   codetable[(int) '1'] = ".----";
   codetable[(int) '2'] = "..---";
   codetable[(int) '3'] = "...--";
   codetable[(int) '4'] = "....-";
   codetable[(int) '5'] = ".....";
   codetable[(int) '6'] = "-....";
   codetable[(int) '7'] = "--...";
   codetable[(int) '8'] = "---..";
   codetable[(int) '9'] = "----.";
   codetable[(int) '0'] = "-----";
   codetable[216]       = "-----";    /* 216 or 330h is a zero with a slash */

   /* Alphabet */
   codetable[(int) ' '] = " ";
   codetable[(int) 'A'] = ".-";
   codetable[(int) 'B'] = "-...";
   codetable[(int) 'C'] = "-.-.";
   codetable[(int) 'D'] = "-..";
   codetable[(int) 'E'] = ".";
   codetable[(int) 'F'] = "..-.";
   codetable[(int) 'G'] = "--.";
   codetable[(int) 'H'] = "....";
   codetable[(int) 'I'] = "..";
   codetable[(int) 'J'] = ".---";
   codetable[(int) 'K'] = "-.-";
   codetable[(int) 'L'] = ".-..";
   codetable[(int) 'M'] = "--";
   codetable[(int) 'N'] = "-.";
   codetable[(int) 'O'] = "---";
   codetable[(int) 'P'] = ".--.";
   codetable[(int) 'Q'] = "--.-";
   codetable[(int) 'R'] = ".-.";
   codetable[(int) 'S'] = "...";
   codetable[(int) 'T'] = "-";
   codetable[(int) 'U'] = "..-";
   codetable[(int) 'V'] = "...-";
   codetable[(int) 'W'] = ".--";
   codetable[(int) 'X'] = "-..-";
   codetable[(int) 'Y'] = "-.--";
   codetable[(int) 'Z'] = "--..";

   /* Punctuation */
   codetable[(int) '='] = "-...-";
   codetable[(int) '/'] = "-..-.";
   codetable[(int) '?'] = "..--..";
   codetable[(int) ','] = "--..--";
   codetable[(int) '.'] = ".-.-.-";
   codetable[(int) ':'] = "---...";
   codetable[(int) '\''] = ".----.";
   codetable[(int) '"'] = ".-..-.";
   codetable[(int) '_'] = "..--.-";
   codetable[(int) '('] = "-.--.";
   codetable[(int) ')'] = "-.--.-";
   codetable[(int) '#'] = "-.---";
   codetable[(int) '-'] = "-...-";
   codetable[(int) '|'] = "...-..";
   codetable[(int) '\\'] = "-.....";
   codetable[(int) '*'] = "-----.";
   codetable[(int) ';'] = "-.-.-.";
   codetable[(int) '@'] = ".--.-.";
   codetable[(int) '^'] = "....--.-.";
   codetable[(int) '$'] = "...-..-";
   codetable[(int) '!'] = "....-.";
   codetable[(int) '>'] = "....---.";
   codetable[(int) ']'] = "....-....";
   codetable[(int) '['] = "....-..";
   codetable[(int) '<'] = "....-.-..";
   codetable[(int) '&'] = "....--.";
   codetable[(int) '%'] = "....-.--.";
   codetable[(int) '~'] = "....--";
   codetable[(int) '+'] = ".-.-.";
   codetable[(int) '{'] = "....-.--";
   codetable[(int) '}'] = "....--..-";

   /* Initialize the morse thread */
   pthread_attr_init (&cwattr);
   pthread_attr_setdetachstate (&cwattr, PTHREAD_CREATE_JOINABLE);

   /*
    * trap the following signals for the cleanup function
    */
   signal (SIGINT,  (void *)cleanup);
   signal (SIGTERM, (void *)cleanup);
   signal (SIGQUIT, (void *)cleanup);
   signal (SIGSEGV, (void *)cleanup);

   /* create the cwthread and set initialized */
   rtn = pthread_create (&cwthread, NULL, &send_cw, (void *) "");
   if (rtn < 0)
   {
      fprintf (stdout, "cw_init: pthread_create error\n");
      return 0;
   }
   initialized = 1;
   return 1;
}


/*
 * cleanup
 * Make sure the sidetone is off and the key is up, then exit
 */
void cleanup (void)
{
   signal (SIGINT,  SIG_IGN);
   signal (SIGTERM, SIG_IGN);
   signal (SIGQUIT, SIG_IGN);
   signal (SIGSEGV, SIG_IGN);
   fprintf(stderr, "libCW terminating\n");

   if (ser_fd != 0)
   {
      if (ioctl (ser_fd, TIOCMSET, &rts_off) == -1)
      {
         perror("cleanup: RTS key up failed");
      }
   }

   pthread_kill (cwthread, 9);
   fprintf (stderr, "Thread killed\n");
   /* close pulseaudio */
   pa_simple_free (sp);
   exit (73);
}


/*
 * close_devs - closes ttyS after making sure the key is up.
 */
int close_devs (void)
{

   if (ser_fd != 0)                      /* if ser_fd is opened */
   {
      /* make sure the key is up */
      if (ioctl (ser_fd, TIOCMSET, &rts_off) < 0)
      {
         perror ("close_devs: RTS key up failed");
         return (0);
      }
      close (ser_fd);                    /* close ser device */
      ser_fd = 0;
   }
   return (1);
}


/*
 * cw_send_str
 * joins the cwthread to send a string of characters
 * called by all other cw_send_* functions.
 */
int cw_send_str (char *str)
{
   int rtn;
   static char s[MAX_WORD_LENGTH];

   /* cw_init must be called first */
   if (initialized == 0)
   {
      fprintf (stderr, "cw_send_str: cw_init must be called first.\n");
      return 0;
   }

   /* wait for any current string */
   pthread_join (cwthread, NULL);

   strcpy (s, str);                 /* save the string */
   rtn = pthread_create (&cwthread, NULL, &send_cw, (void *) s);
   if (rtn < 0)
   {
      fprintf (stdout, "cw_send_str: pthread_create error\n");
      return 0;
   }
   return 1;
}


/*
 * cw_send_word
 * this does the same as send str, but adds a space to the end
 * to make it compatable for twcw.
 */
int cw_send_word (char *str)
{
   static char new_str[MAX_WORD_LENGTH +1 ];

   strcpy (new_str, str);
   strcat (new_str, " ");
   cw_send_str (new_str);
   return (1);
}


/*
 * cw_send_char - sends one char
 * This method causes a little extra overhead and the timing
 * is off slightly - abt 1 sec longer than it should be over 60 secs. 
 */
int cw_send_char (char ch)
{
   char str[2];

   str[0] = ch;
   str[1] = '\0';
   cw_send_str (str);
   return (1);
}


/*
 * send_cw
 * started as thread by cw_send_str() or cw_send_word()
 */
void *send_cw (void *p)
{
   int i=0;
   char *pt;
   char *code;

   #if MESG == 1
   struct tag1a
   {
      long type;
      union
      {
         char word[MAX_WORD_LENGTH];
         int  val;
      } data;
   } reply;
   #endif

   if (strlen ((char *)p) == 0)     /* nothing to send */
   {
      pthread_exit (0);
   }

   /* open the serial device if needed */
   if (keyMode == RTS)
   {
      ser_fd = open_serial ();
      if (ser_fd < 0)
      {
         fprintf (stderr, "send_cw: open %s failed\n", serdevice);
         pthread_exit (0);
      }
   }

   pt = (char *) p;
   /* now run thru the string, and call keySC, keyTimer or keyCWIRC */
   while (pt[i] != '\0')
   {
      /* get the ./- representation for the character */
      code = codetable[(int)toupper((int)pt[i])];

      /* key devices */
      if ((keyMode & PA) == PA)
      {
         keySC (code);
      }
      if ((keyMode & RTS) == RTS)
      {
         keyRTS(code);
      }

#if WITH_CWIRC == 1
      if (keyMode == CWIRC)
      {
         keyCWIRC(code);
      }
#endif

#if MESG == 1
      /* if doReply is true and MESG is 1, we need to send a reply message */
      if (doReply == TRUE)
      {
         reply.type = SENT_MSG;
         reply.data.word[0] = pt[i];
         reply.data.word[1] = '\0';
         if (msgsnd (qid, (struct msgbuf *)&reply,
                     sizeof(reply.data), 0) == -1)
         {
            perror ("send_cw: msgsnd SENT_MSG failed");
            exit (1);
         }
      }
#endif
      i++;
   }
   close_devs ();
   pthread_exit (0);
}


/*
 * keySC (char *code)
 * uses the morse representation to key the SC
 */
void keySC (char *code)
{ 
   int i = 0;
   float t;

   while (code[i] != '\0')
   {   
      if (code[i] == ' ')                /* do a space or non-valid char */
      {                                  /* this assumes that the */
         tonegen (0, iw_time - il_time); /* previous character has */
         return;                         /* done the il_time already */
      }

      if (code[i] == DIT)
      {
         t = dit_time;
      }
      else if (code[i] == DAH)
      {
         t = dah_time;
      }
      else
      {
         fprintf (stderr, "keySC: Program error - not a DIT or DAH\n");
         exit (1);
      }

      tonegen (freq, t);                 /* and send the dit/dah */

      /* do ic_time if there are more elements in this letter */
      i++;
      if (code[i] != '\0')               /* if more ./- to do */
      {                                  /* for this character */ 
         tonegen (0, ic_time);           /* add intra character time */
      }
   }
   tonegen (0, il_time);                 /* do inter letter time */
   return;
}


/*
 * keyRTS (char code)
 * uses the morse representation to key the RTS
 */
void keyRTS (char *code)
{ 
   int i = 0;
   float t;

   if (ser_fd == 0)  /* if no serial device */
   {
      return;
   }

   while (code[i] != '\0')
   {   
      if (code[i] == ' ')                      /* do a space or non-valid ch */
      {
         timer (iw_time - il_time);
         return;
      }

      if (code[i] == DIT)
      {
         t = dit_time;
      }
      else
      {
         t = dah_time;
      }

      if (ioctl (ser_fd, TIOCMSET, &rts_on) < 0)    /* key down */
      {
         perror("keyRTS: RTS key down failed");
      }

      timer (t);

      if (ioctl (ser_fd, TIOCMSET, &rts_off) < 0)   /* RTS key up */
      {
         perror ("keyRTS: RTS key up failed");
      }
      i++;
      if (strlen (code) > i)                   /* if more ./- to do */
      {                                        /* for this character */ 
         timer (ic_time);
      }
   }
   timer (il_time);
}


/*
 * keyCWIRC
 * toggles cwirc_api_shm->in_key to key cwirc
 */
#if WITH_CWIRC == 1
void keyCWIRC (char *code)
{
   int i = 0;
   float t;

   while (code[i] != '\0')
   {   
      if (code[i] == ' ')                /* do a space or non-valid ch */
      {
         timer (iw_time - il_time);
         return;
      }

      if (code[i] == DIT)
         t = dit_time;
      else
         t = dah_time;

      /* key cwirc */
      cwirc_api_shm->in_key = 1;
      timer (t);
      cwirc_api_shm->in_key = 0;

      i++;
      if (strlen (code) > i)             /* if more ./- to do */
      {                                  /* for this character */ 
         timer (ic_time);
      }
   }
   timer (il_time);
   return;
}
#endif


/*
 * tonegen
 * This function was mostly taken from qrq.
 * Copyright (C) 2006  Fabian Kurz, DJ1YFK.  Thanks, Fabian.
 * Generates a sinus tone of frequency 'freq' and length 'len'
 * based on 'samplerate', 'rt' (rise time), 'ft' (fall time)
 */
int tonegen (int freq, float len)
{
   int x, rtn;
   int buf[20000];   //plenty big for a 8wpm dah
   float val;
   int error;

   /* convert len from milliseconds to samples, determine rise/fall time */
   len = samplerate * len / 1000.0;

   for (x=0; x < len-1; x++)
   {
      val = 1 + sin(2*PI*freq*x/samplerate);
      if (x < rt)
      {
         val *= sin(PI*x/(2.0*rt));                 /* rising edge */
      }

      if (x > (len-ft))
      {
         val *= sin(2*PI*(x-(len-ft)+ft)/(4*ft));   /* falling edge */
      }
      buf[x] = val*8000;
      buf[x] = buf[x] + (buf[x]<<16);           /* add second channel */
   }

   /* now write the buffer */
   rtn = pa_simple_write (sp, buf, 4*x, &error); 
   if (rtn == -1)
   {
      fprintf (stderr, "pa_simple_write failed - error=%d: %s\n",
               error, pa_strerror(error));
      return -1;
   }
   return 0;
}


/*
 * timer - use the real time clock for accurate timing
 */
int timer (float msec)
{
   unsigned long rtc_data;
   int fd;
   int i;
   int cnt;

   cnt = msec * rtc_rate / 1000.0;
   /* open rtc */
   if ((fd = open ("/dev/rtc", O_RDONLY)) < 0)
   {
      perror ("timer: open /dev/rtc failed");
      return -1;
   }

   /* configure rtc for periodic interupts */
   if (ioctl (fd, RTC_IRQP_SET, rtc_rate) < 0)
   {
      perror ("timer: RTC_IRQP_SET");
      return -1;
   }

   if (ioctl (fd, RTC_PIE_ON, 0) < 0)
   {
      perror ("timer: PIE_ON");
      return -1;
   }

   i = 0;
   while (cnt - i > 0)
   {
      if (read (fd, &rtc_data, sizeof(rtc_data)) < 0)
      {
         perror ("timer: RTC read");
         exit (1);
      }
      i = i + (rtc_data >> 8);
   }

   if (ioctl (fd, RTC_PIE_OFF, 0) < 0)
   {
      perror ("timer: PIE_OFF");
      exit (1);
   }
   close (fd);
   return 0;
}


/*
 * cw_set_doReply - sets/clears reply mode 
 * set doReply to TRUE/FALSE
//TJW join thread?
 */
int  cw_set_doReply (int new_doReply)
{
   doReply = new_doReply;
   return (doReply);
}


/*
 * get doReply - returns current reply mode
//TJW join thread
 */
int  cw_get_doReply (void)
{
   return (doReply);
}


/*
 *cw_get_serdev - returns the current key mode
//TJW join str?
 */
char *cw_get_serdev (void)
{
   if (serdevice != NULL)
   {
      return (serdevice);
   }
   else
   {
      return (NULL);
   }
}


/*
 * cw_get_keyMode
//TJW join thread
 */
int cw_get_keyMode (void)
{
   return (keyMode);
}


/*
 * cw_set_keyMode (int newmode, char *name)
 * Use PA, RTS, or IRC for newmode.  Returns keyMode, if it works
 */
int cw_set_keyMode (int newmode, char *name)
{  
   int fd, error;

#if WITH_CWIRC == 1
   /* if current mode is CWIRC, you're stuck there. just return */
   if (newmode == CWIRC)
   {
      return keyMode;
   }
#endif

   /* if keyMode is already correct, just return */
   if (newmode == keyMode)
   {
      return keyMode;
   }

   /* if initialized, wait for the current thread */
   if (initialized == 1)
   {
      //pthread_join (cwthread, NULL);
   }

   /* setup the mode */
   switch (newmode)
   {
      case PA:
         /* check for a soundcard pointer */
         if (sp == NULL)          /* don't create a sp if we have one */
         {
            sp = pa_simple_new (NULL, pa_name, PA_STREAM_PLAYBACK, NULL,
                                name, &ss, NULL, NULL, &error);
            if (sp == NULL)       /* if NULL now, we have an error */
            {
               perror ("cw_set_keymode: pa_simple_new failed");
               return 0;
            }
         }
         break;

      case RTS:
         /* open rtc and find the highest interupt rate */
         rtc_rate = 4096;
         if ((fd = open ("/dev/rtc", O_RDONLY)) < 0)
         {
            perror ("cw_init: open /dev/rtc failed");
            exit (1);
         }
         /* find the highest interupt rate */
         /* if 64 is the system default rate, that's kinda slow */
         while (ioctl(fd, RTC_IRQP_SET, rtc_rate) < 0)
         {
            fprintf (stderr, "cw_init RTC_IRQP_SET %d failed\n", rtc_rate);
            rtc_rate = rtc_rate/2;
         }
         fprintf (stderr, "RTC rate = %d\n", rtc_rate);
         close (fd);   /* close the rtc */
         break;

      default:
         fprintf (stderr, "cw_set_keyMode: invalid mode %d\n", newmode);
         return 0;       /* oops!  invalid mode */
   }
   keyMode = newmode;
   return keyMode;
}


/* 
 * cw_get_wpm - returns current wpm
//TJW join thread?
 */
int cw_get_wpm (void)
{
   return (wpm);
}


/*
 * cw_set_wpm
 * set wpm.  Calculate the times for all character, including the
 * iw_time and ic_time for farnsworths, if required. Also figure the
 * rise/fall times
 */
int cw_set_wpm (int new_wpm)
{
   float wpm_time;

   /* cw_init must be called first */
//TJW is this true?
   if (initialized == 0)
   {
      fprintf (stderr, "cw_set_wpm: cw_init must be called first.\n");
      return -1;
   }
   /*
    * we don't want to change speed while sending somethingm
    * so wait for the thread
    */
   pthread_join (cwthread, NULL);
   /*
    * save the new wpm value if it is >= 5
    */
   if (new_wpm >= 5)
   {
      wpm = new_wpm;
   }
   /*
    * speed is in wpm so we have to calculate the dot-length in
    * milliseconds using the well-known formula -> dotlength= 1200 / wpm
    */
   dit_time = 1200 / wpm;
   dah_time = 3 * dit_time;

   /* fudge it for a lousy soundcard */
   if (keyMode == PA)
   {
      dit_time = dit_time * FUDGE;
      dah_time = dah_time * FUDGE;
   }

   ic_time  = dit_time;

   if ((farns_wpm <= wpm) && (farns_wpm > FARNS_OFF))
   { /* do farnsworth timing */
      farns_time = 1200 / farns_wpm * 50.0; /* time to send a "word" @ fwpm */ 
      wpm_time = 31 * dit_time;             /* PARIS minus iw_time @ wpm */
      il_time = 3/19.0 * (farns_time - wpm_time);
      iw_time = 7/19.0 * (farns_time - wpm_time);
   }
   else
   { /* use standard timing */
      il_time = 3 * dit_time;
      iw_time = 7 * dit_time;
   }
   /* rc and ft are the rise and fall times in milliseconds */
   rt = (samplerate / 1000.0) * rise;
   ft = (samplerate / 1000.0) * fall;

   #if DEBUG == 1
   fprintf (stderr, "libCW dit=%4.1f dah=%4.1f il=%4.1f iw=%4.1f rt/ft=%4.1f\n",
           dit_time, dah_time, il_time, iw_time, rt);
   #endif
   return wpm;
}


/*
 * cw_set_freq - sets the frequency of the audio out
//TJW join thread
 */
int cw_set_freq (int new_freq)
{
   freq = new_freq;
   return freq;
}
   

/*
 * cw_get_freq - gets the frequency of the audio out
//TJW join thread
 */
int cw_get_freq (void)
{
   return freq;
}


/* 
 * cw_get_fwpm - returns current farnsworth wpm
//TJW join thread
 */
int cw_get_fwpm (void)
{
   return (farns_wpm);
}


/*
 * cw_set_fwpm
 * set farns_wpm.  Calculate the farnsworth times for il_time and
 * iw_time for farnsworth.
 */
int cw_set_fwpm (int new_fwpm)
{
   float wpm_time;

   if (initialized == 0)
   {
      fprintf (stderr, "cw_set_fwpm: cw_init must be called first.\n");
      return -1;
   }

   /*
    * we don't want to change speed while sending something
    * so wait for the thread if it is running.
    */
   pthread_join (cwthread, NULL);

   if ((new_fwpm < wpm) && (new_fwpm > FARNS_OFF))
   { /* do farnsworth timing */
      farns_wpm = new_fwpm;
      farns_time = 1200 / farns_wpm * 50.0; /* time to send a "word" @ fwpm */ 
      wpm_time = 31 * dit_time;             /* PARIS minus iw_time @ wpm */
      
      il_time = 3.0/19.0 * (farns_time - wpm_time);
      iw_time = 7.0/19.0 * (farns_time - wpm_time);
   }
   else
   {
      il_time = 3 * dit_time;
      iw_time = 7 * dit_time;
   }
   rt = (samplerate / 1000.0) * rise;
   ft = (samplerate / 1000.0) * fall;

   #if DEBUG == 1
   fprintf (stderr, "FARNS dit=%4.1f dah=%4.1f il=%4.1f iw=%4.1f\n",
            dit_time, dit_time*3, il_time, iw_time);
   fprintf (stderr, "SAMPLERATE = %ld\n", samplerate);
   #endif
   return farns_wpm;
}


/*
 * open_serial
 * open the serial device and return fd. 
 */
int open_serial ()
{
   int fd = 0;

   if (ser_fd != 0)         /* already open ?*/
   {
      /* yes, so just make sure the key is up and return ser_fd */
      ioctl (fd, TIOCMSET, &rts_off);
      return (ser_fd);
   }

   if ((fd = open(serdevice, O_RDWR, 0)) < 0)
   {
      perror("open_serial: can't open the serial device");
   }
   else
   {
      /* make sure the key is up */
      if (fd > 0)
      {
         ioctl (fd, TIOCMSET, &rts_off);
      }
   }
   return fd;   /* return fd or error */
}


#if TESTMODE == 1
/*
 * main function for testing standalone
 */
int main (int argc, char *argv[])
{
   int i;
   char d;
   char pgmName[] = "test mode";
   char newdev[] = "/dev/ttyS0";

   /* pick a key mode */
   //int mode = RTS;
   int mode = PA;
   //int mode = CWIRC;

   /* initialize libCW */
   cw_init (mode, pgmName, newdev);
   //cw_init (mode, pgmName, NULL);

   /* set some other setup functions */
   cw_set_doReply (FALSE);
   cw_set_wpm (20);                      /* set wpm */
   cw_set_fwpm (20);                     /* set fwpm */

   printf ("Enter to start: ");          /* hit rtn when ready */
   d = getchar ();

#if 1
   /* send paris as 20 strings */
   for (i=0; i<10; i++)
   {
      cw_send_str ("paris ");            /* send "paris" */

      #if 0
      if (i % 2 == 0)                    /* altername between PA and RTS */
      {       /* odd ones */
         cw_set_fwpm (10);
      }
      else
      {       /* even ones */
         cw_set_fwpm (FARNS_OFF);
      }
      #endif
   }
#endif

#if 0
   /* send paris as 20 words */
   for (i=0; i<20; i++)
   {
      cw_send_word ("paris");
   }
#endif

#if 0
   /* send paris as chars - twcw method */
   for (i=0; i<4; i++)
   {
      cw_send_char ('p');
      cw_send_char ('a');
      cw_send_char ('r');
      // cw_set_keyMode(RTS, pgmName);
      cw_send_char ('i');
      cw_send_char ('s');
      cw_send_char (' ');
      //cw_set_fwpm (i+5);
   }
#endif

   /* beep with an 'e' when all done */
   cw_send_str ("e");
   pthread_join (cwthread, NULL);       /* wait for it before we terminate */
   return 0;
}
#endif   /* END TESTMODE */