f923e478a441a45f72778b12845255c239eb42c3
[asterisk/asterisk.git] / channels / chan_modem_bestdata.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * BestData 56SX-92 Voice Modem Driver (Conexant)
5  * 
6  * Copyright (C) 1999, Mark Spencer and 2001 Jim Dixon
7  *
8  * Mark Spencer <markster@linux-support.net>
9  * Jim Dixon <jim@lambdatel.com>
10  *
11  * This program is free software, distributed under the terms of
12  * the GNU General Public License
13  */
14
15 #include <stdio.h>
16
17 #include <string.h>
18 #include <stdlib.h>
19 #include <errno.h>
20 #include <unistd.h>
21 #include <asterisk/lock.h>
22 #include <asterisk/vmodem.h>
23 #include <asterisk/module.h>
24 #include <asterisk/frame.h>
25 #include <asterisk/logger.h>
26 #include <asterisk/options.h>
27
28 #define STATE_COMMAND   0
29 #define STATE_VOICE     1
30 #define STATE_VOICEPLAY 2
31
32 #define VRA "40"                        /* Number of 100ms of non-ring after a ring cadence after which we consider the lien to be answered */
33 #define VRN "25"                        /* Number of 100ms of non-ring with no cadence after which we assume an answer */
34
35 #define RINGT   7000
36
37 static char *breakcmd = "\020!";
38
39 static char *desc = "BestData (Conexant V.90 Chipset) VoiceModem Driver";
40
41 static int usecnt;
42 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
43
44 static char *bestdata_idents[] = {
45         /* Identify BestData Modem */
46         "ACF3_V1.010-V90_P21_FSH",
47         NULL
48 };
49
50 static int bestdata_startrec(struct ast_modem_pvt *p)
51 {
52 static int bestdata_break(struct ast_modem_pvt *p);
53
54         if (p->ministate != STATE_COMMAND) bestdata_break(p);
55         if (ast_modem_send(p, "AT+VRX", 0) ||
56              ast_modem_expect(p, "CONNECT", 5)) {
57                 ast_log(LOG_WARNING, "Unable to start recording\n");
58                 return -1;
59         }
60         p->ministate = STATE_VOICE;
61         return 0;
62 }
63
64 static int bestdata_startplay(struct ast_modem_pvt *p)
65 {
66 static int bestdata_break(struct ast_modem_pvt *p);
67
68         if (p->ministate != STATE_COMMAND) bestdata_break(p);
69         if (ast_modem_send(p, "AT+VTX", 0) ||
70              ast_modem_expect(p, "CONNECT", 5)) {
71                 ast_log(LOG_WARNING, "Unable to start recording\n");
72                 return -1;
73         }
74         p->ministate = STATE_VOICEPLAY;
75         return 0;
76 }
77
78 static int bestdata_break(struct ast_modem_pvt *p)
79 {
80         if (ast_modem_send(p, breakcmd, 2)) {
81                 ast_log(LOG_WARNING, "Failed to break\n");
82                 return -1;
83         }
84         p->ministate = STATE_COMMAND;
85         usleep(10000);
86         /* Read any outstanding junk */
87         while(!ast_modem_read_response(p, 1));
88         if (ast_modem_send(p, "AT", 0)) {
89                 /* Modem might be stuck in some weird mode, try to get it out */
90                 ast_modem_send(p, "+++", 3);
91                 if (ast_modem_expect(p, "OK", 10)) {
92                         ast_log(LOG_WARNING, "Modem is not responding\n");
93                         return -1;
94                 }
95                 if (ast_modem_send(p, "AT", 0)) {
96                         ast_log(LOG_WARNING, "Modem is not responding\n");
97                         return -1;
98                 }
99         }
100         if (ast_modem_expect(p, "OK", 5)) {
101                 ast_log(LOG_WARNING, "Modem did not respond properly\n");
102                 return -1;
103         }
104         return 0;
105 }
106
107 static int bestdata_init(struct ast_modem_pvt *p)
108 {
109         if (option_debug)
110                 ast_log(LOG_DEBUG, "bestdata_init()\n");
111         if (bestdata_break(p))
112                 return -1;
113         /* Force into command mode */
114         p->ministate = STATE_COMMAND;
115         if (ast_modem_send(p, "AT+FCLASS=8", 0) ||
116              ast_modem_expect(p, "OK", 5)) {
117                 ast_log(LOG_WARNING, "Unable to set to voice mode\n");
118                 return -1;
119         }
120         if (ast_modem_send(p, "AT+VSM=1,8000,0,0", 0) ||
121              ast_modem_expect(p, "OK", 5)) {
122                 ast_log(LOG_WARNING, "Unable to set to 8000 Hz sampling\n");
123                 return -1;
124         }
125         if (ast_modem_send(p, "AT+VLS=0", 0) ||
126              ast_modem_expect(p, "OK", 5)) {
127                 ast_log(LOG_WARNING, "Unable to set to telco interface\n");
128                 return -1;
129         }
130         if (ast_modem_send(p, "AT+VRA=" VRA, 0) ||
131              ast_modem_expect(p, "OK", 5)) {
132                 ast_log(LOG_WARNING, "Unable to set to 'ringback goes away' timer\n");
133                 return -1;
134         }
135         if (ast_modem_send(p, "AT+VRN=" VRN, 0) ||
136              ast_modem_expect(p, "OK", 5)) {
137                 ast_log(LOG_WARNING, "Unable to set to 'ringback never came timer'\n");
138                 return -1;
139         }
140         if (ast_modem_send(p, "AT+VTD=63", 0) ||
141              ast_modem_expect(p, "OK", 5)) {
142                 ast_log(LOG_WARNING, "Unable to set to tone detection\n");
143                 return -1;
144         }
145         if (ast_modem_send(p, "AT+VCID=1", 0) ||
146              ast_modem_expect(p, "OK", 5)) {
147                 ast_log(LOG_WARNING, "Unable to enable Caller*ID\n");
148                 return -1;
149         }
150         return 0;
151 }
152
153 static struct ast_frame *bestdata_handle_escape(struct ast_modem_pvt *p, char esc)
154 {
155         char name[30]="",nmbr[30]="";
156         time_t  now;
157
158         /* Handle escaped characters -- but sometimes we call it directly as 
159            a quick way to cause known responses */
160         p->fr.frametype = AST_FRAME_NULL;
161         p->fr.subclass = 0;
162         p->fr.data = NULL;
163         p->fr.datalen = 0;
164         p->fr.samples = 0;
165         p->fr.offset = 0;
166         p->fr.mallocd = 0;
167         p->fr.delivery.tv_sec = 0;
168         p->fr.delivery.tv_usec = 0;
169         if (esc)
170                 ast_log(LOG_DEBUG, "Escaped character '%c'\n", esc);
171         
172         switch(esc) {
173         case 'R': /* Pseudo ring */
174                 time(&now);
175                 if (now > (p->lastring + (RINGT / 1000)))
176                    { /* if stale, treat as new */
177                         p->gotclid = 0;
178                    }
179                 if (p->gotclid)
180                    {
181                         p->fr.frametype = AST_FRAME_CONTROL;
182                         p->fr.subclass = AST_CONTROL_RING;
183                    }
184                 p->ringt = RINGT;
185                 time(&p->lastring);
186                 return &p->fr;
187         case 'X': /* Caller-ID Spill */
188                 if (p->gotclid) return &p->fr;
189                 name[0] = nmbr[0] = 0;
190                 for(;;)
191                    {
192                         char res[1000]="";
193
194                         if (ast_modem_read_response(p, 5)) break;
195                         strncpy(res, p->response, sizeof(res)-1);
196                         ast_modem_trim(res);
197                         if (!strncmp(res,"\020.",2)) break;
198                         if (!strncmp(res,"NAME",4)) strncpy(name,res + 7, sizeof(name) - 1);
199                         if (!strncmp(res,"NMBR",4)) strncpy(nmbr,res + 7, sizeof(nmbr) - 1);
200                    }
201                 p->gotclid = 1;
202                 if ((!strcmp(name,"O")) || (!strcmp(name,"P"))) name[0] = 0;
203                 if ((!strcmp(nmbr,"O")) || (!strcmp(nmbr,"P"))) nmbr[0] = 0;
204                 if (name[0])
205                         strncpy(p->cid_name, name, sizeof(p->cid_name) - 1);
206                 if (nmbr[0])
207                         strncpy(p->cid_num, nmbr, sizeof(p->cid_num) - 1);
208                 if (p->owner) {
209                         p->owner->cid.cid_num = strdup(p->cid_num);
210                         p->owner->cid.cid_name = strdup(p->cid_name);
211                 }
212                 return &p->fr;
213         case '@': /* response from "OK" in command mode */
214                 if (p->owner)
215                         ast_setstate(p->owner, AST_STATE_UP);
216                 if (bestdata_startrec(p)) return NULL;
217                 p->fr.frametype = AST_FRAME_CONTROL;
218                 p->fr.subclass = AST_CONTROL_RING;
219                 return &p->fr;
220         case 'b': /* Busy signal */
221                 p->fr.frametype = AST_FRAME_CONTROL;
222                 p->fr.subclass = AST_CONTROL_BUSY;
223                 return &p->fr;
224         case 'o': /* Overrun */
225                 ast_log(LOG_WARNING, "Overflow on modem, flushing buffers\n");
226                 if (ast_modem_send(p, "\0x10E", 2)) 
227                         ast_log(LOG_WARNING, "Unable to flush buffers\n");
228                 return &p->fr;  
229         case '0':  /* All the DTMF characters */
230         case '1':
231         case '2':
232         case '3':
233         case '4':
234         case '5':
235         case '6':
236         case '7':
237         case '8':
238         case '9':
239         case '*':
240         case '#':
241         case 'A':
242         case 'B':
243         case 'C':
244         case 'D':
245                 p->dtmfrx = esc;  /* save this for when its done */
246                 return &p->fr;  
247         case '/': /* Start of DTMF tone shielding */
248                 p->dtmfrx = ' ';
249                 return &p->fr;  
250         case '~': /* DTMF transition to off */
251                 if (p->dtmfrx > ' ')
252                    {
253                         p->fr.frametype = AST_FRAME_DTMF;
254                         p->fr.subclass = p->dtmfrx;
255                    }
256                 p->dtmfrx = 0;
257                 return &p->fr;  
258         case 'u': /* Underrun */
259                 ast_log(LOG_WARNING, "Data underrun\n");
260                 /* Fall Through */
261         case CHAR_ETX: /* End Transmission */
262         case 'd': /* Dialtone */
263         case 'c': /* Calling Tone */
264         case 'e': /* European version */
265         case 'a': /* Answer Tone */
266         case 'f': /* Bell Answer Tone */
267         case 'T': /* Timing mark */
268         case 't': /* Handset off hook */
269         case 'h': /* Handset hungup */
270         case 0: /* Pseudo signal */
271                 /* Ignore */
272                 return &p->fr;  
273         default:
274                 ast_log(LOG_DEBUG, "Unknown Escaped character '%c' (%d)\n", esc, esc);
275         }
276         return &p->fr;
277 }
278
279 static struct ast_frame *bestdata_read(struct ast_modem_pvt *p)
280 {
281         char result[256];
282         short *b;
283         struct ast_frame *f=NULL;
284         int res;
285         int x;
286
287         if (p->ministate == STATE_COMMAND) {
288                 /* Read the first two bytes, first, in case it's a control message */
289                 fread(result, 1, 2, p->f);
290                 if (result[0] == CHAR_DLE) {
291                         return bestdata_handle_escape(p, result[1]);
292                 } else {
293                         if (p->ringt) /* if ring timeout specified */
294                            {
295                                 x = fileno(p->f);
296                                 res = ast_waitfor_n_fd(&x, 1, &p->ringt, NULL);
297                                 if (res < 0) {
298                                         return NULL;
299                                 }
300                            }
301                         if ((result[0] == '\n') || (result[0] == '\r'))
302                                 return bestdata_handle_escape(p, 0);
303                         /* Read the rest of the line */
304                         fgets(result + 2, sizeof(result) - 2, p->f);
305                         ast_modem_trim(result);
306                         if (!strcasecmp(result, "OK")) {
307                                 /* If we're in immediate mode, reply now */
308                                 if (p->mode == MODEM_MODE_IMMEDIATE)
309                                         return bestdata_handle_escape(p, '@');
310                         } else
311                         if (!strcasecmp(result, "BUSY")) {
312                                 /* Same as a busy signal */
313                                 return bestdata_handle_escape(p, 'b');
314                         } else
315                         if (!strcasecmp(result, "RING")) {
316                                 return bestdata_handle_escape(p, 'R');
317                         } else
318                         if (!strcasecmp(result, "NO DIALTONE")) {
319                                 /* There's no dialtone, so the line isn't working */
320                                 ast_log(LOG_WARNING, "Device '%s' lacking dialtone\n", p->dev);
321                                 return NULL;
322                         }
323                         ast_log(LOG_DEBUG, "Modem said '%s'\n", result);
324                         return bestdata_handle_escape(p, 0);
325                 }
326         } else {
327                   /* if playing, start recording instead */
328                 if (p->ministate == STATE_VOICEPLAY)
329                    {
330                         if (bestdata_startrec(p)) return NULL;
331                    }
332                 /* We have to be more efficient in voice mode */
333                 b = (short *)(p->obuf + p->obuflen);
334                 while (p->obuflen/2 < 240) {
335                         /* Read ahead the full amount */
336                         res = fread(result, 1, 240 - p->obuflen/2, p->f);
337                         if (res < 1) {
338                                 /* If there's nothing there, just continue on */
339                                 if (errno == EAGAIN)
340                                         return bestdata_handle_escape(p, 0);
341                                 ast_log(LOG_WARNING, "Read failed: %s\n", strerror(errno));
342                         }
343                         for (x=0;x<res;x++) {
344                                 /* Process all the bytes that we've read */
345                                 if (result[x] == CHAR_DLE) {
346                                         /* We assume there is no more than one signal frame among our
347                                            data.  */
348                                         if (f) ast_log(LOG_WARNING, "Warning: Dropped a signal frame\n");
349                                           /* if not a DLE in the data */
350                                         if (result[++x] != CHAR_DLE)
351                                            {
352                                                 /* If bestdata_handle_escape says NULL, say it now, doesn't matter
353                                                    what else is there, the connection is dead. */
354                                                 f = bestdata_handle_escape(p, result[x]);
355                                                 if (p->dtmfrx) continue;
356                                                 return(f);
357                                            }
358                                 }
359                                 /* Generate a 16-bit signed linear value from our 
360                                    unsigned 8-bit value */
361                                 *(b++) = (((short)result[x]) - 127) * 0xff;
362                                 p->obuflen += 2;
363                         }
364                         if (f) break;
365                 }
366                 /* If we have a control frame, return it now */
367                 if (f) return f;
368                 /* If we get here, we have a complete voice frame */
369                 p->fr.frametype = AST_FRAME_VOICE;
370                 p->fr.subclass = AST_FORMAT_SLINEAR;
371                 p->fr.samples = 240;
372                 p->fr.data = p->obuf;
373                 p->fr.datalen = p->obuflen;
374                 p->fr.mallocd = 0;
375                 p->fr.delivery.tv_sec = 0;
376                 p->fr.delivery.tv_usec = 0;
377                 p->fr.offset = AST_FRIENDLY_OFFSET;
378                 p->fr.src = __FUNCTION__;
379                 if (option_debug)
380                         ast_log(LOG_DEBUG, "bestdata_read(voice frame)\n");
381                 p->obuflen = 0;
382                 return &p->fr;
383         }
384         return NULL;
385 }
386
387 static int bestdata_write(struct ast_modem_pvt *p, struct ast_frame *f)
388 {
389 unsigned char   c,buf[32768]; /* I hope we dont have frames larger then 16K */
390 int     i,j;
391 short   *sp;
392 unsigned long u;
393 #define DLE     16
394
395         if (p->owner && (p->owner->_state == AST_STATE_UP) && 
396                 (p->ministate != STATE_VOICEPLAY) && bestdata_startplay(p)) return -1;
397         sp = (short *) f->data;
398           /* stick DLE's in ahead of anything else */
399         for(i = 0,j = 0; i < f->datalen / 2; i++)
400            {
401                 *sp *= 3;
402                 u = *sp++ + 32768;
403                 c = u >> 8;
404                 if (c == DLE) buf[j++] = DLE;
405                 buf[j++] = c;
406            }
407         do i = fwrite(buf,1,j,p->f);
408         while ((i == -1) && (errno == EWOULDBLOCK));
409         if (i != j)
410            {
411                 ast_log(LOG_WARNING,"modem short write!!\n");
412                 return -1;
413            }
414         fflush(p->f);
415         if (option_debug)
416                 ast_log(LOG_DEBUG, "bestdata_write()\n");
417         return 0;
418 }
419
420 static char *bestdata_identify(struct ast_modem_pvt *p)
421 {
422         char identity[256];
423         char mfr[80];
424         char mdl[80];
425         char rev[80];
426         ast_modem_send(p, "AT+FMM", 0);
427         ast_modem_read_response(p, 5);
428         strncpy(mdl, p->response, sizeof(mdl)-1);
429         ast_modem_trim(mdl);
430         ast_modem_expect(p, "OK", 5);
431         ast_modem_send(p, "AT+FMI", 0);
432         ast_modem_read_response(p, 5);
433         strncpy(mfr, p->response, sizeof(mfr)-1);
434         ast_modem_trim(mfr);
435         ast_modem_expect(p, "OK", 5);
436         ast_modem_send(p, "AT+FMR", 0);
437         ast_modem_read_response(p, 5);
438         strncpy(rev, p->response, sizeof(rev)-1);
439         ast_modem_trim(rev);
440         ast_modem_expect(p, "OK", 5);
441         snprintf(identity, sizeof(identity), "%s Model %s Revision %s", mfr, mdl, rev);
442         return strdup(identity);
443 }
444
445 static void bestdata_incusecnt(void)
446 {
447         ast_mutex_lock(&usecnt_lock);
448         usecnt++;
449         ast_mutex_unlock(&usecnt_lock);
450         ast_update_use_count();
451 }
452
453 static void bestdata_decusecnt(void)
454 {
455         ast_mutex_lock(&usecnt_lock);
456         usecnt++;
457         ast_mutex_unlock(&usecnt_lock);
458         ast_update_use_count();
459 }
460
461 static int bestdata_answer(struct ast_modem_pvt *p)
462 {
463         p->ringt = 0;
464         p->lastring = 0;
465         if (ast_modem_send(p, "AT+VLS=1", 0) ||
466              ast_modem_expect(p, "OK", 10)) {
467                 ast_log(LOG_WARNING, "Unable to answer: %s", p->response);
468                 return -1;
469         }
470         return 0;
471 }
472
473 static int bestdata_dialdigit(struct ast_modem_pvt *p, char digit)
474 {
475         char cmd[80];
476
477         if (p->ministate != STATE_COMMAND) bestdata_break(p);
478         snprintf(cmd, sizeof(cmd), "AT+VTS=%c", digit);
479         if (ast_modem_send(p, cmd, 0) ||
480              ast_modem_expect(p, "OK", 10)) {
481                 ast_log(LOG_WARNING, "Unable to answer: %s", p->response);
482                 return -1;
483         }
484         return 0;
485 }
486
487 static int bestdata_dial(struct ast_modem_pvt *p, char *stuff)
488 {
489         char cmd[800] = "",a[20]="";
490         int i,j;
491
492         if (p->ministate != STATE_COMMAND)
493            {
494                 bestdata_break(p);
495                 strncpy(cmd, "AT+VTS=", sizeof(cmd) - 1);
496                 j = strlen(cmd);
497                 for(i = 0; stuff[i]; i++)
498                    {
499                         switch(stuff[i])
500                            {
501                             case '!' :
502                                 a[0] = stuff[i];
503                                 a[1] = 0;
504                                 break;
505                             case ',':
506                                 strncpy(a, "[,,100]", sizeof(a) - 1);
507                                 break;
508                             default:
509                                 snprintf(a, sizeof(a), "{%c,7}", stuff[i]);
510                            }
511                         if (stuff[i + 1]) strncat(a, ",", sizeof(a) - strlen(a) - 1);
512                         strncpy(cmd + j, a, sizeof(cmd) - j - 1);
513                         j += strlen(a);
514                    }
515            }
516         else
517            {
518                 snprintf(cmd, sizeof(cmd), "ATD%c %s", p->dialtype,stuff);
519            }
520         if (ast_modem_send(p, cmd, 0)) {
521                 ast_log(LOG_WARNING, "Unable to dial\n");
522                 return -1;
523         }
524         return 0;
525 }
526
527 static int bestdata_hangup(struct ast_modem_pvt *p)
528 {
529         if (bestdata_break(p))
530                 return -1;
531         /* Hangup by switching to data, then back to voice */
532         if (ast_modem_send(p, "ATH", 0) ||
533              ast_modem_expect(p, "OK", 8)) {
534                 ast_log(LOG_WARNING, "Unable to set to data mode\n");
535                 return -1;
536         }
537         if (ast_modem_send(p, "AT+FCLASS=8", 0) ||
538              ast_modem_expect(p, "OK", 5)) {
539                 ast_log(LOG_WARNING, "Unable to set to voice mode\n");
540                 return -1;
541         }
542         p->gotclid = 0;
543         p->ringt = 0;
544         p->lastring = 0;
545         p->dtmfrx = 0;
546         return 0;
547 }
548
549 static struct ast_modem_driver bestdata_driver =
550 {
551         "BestData",
552         bestdata_idents,
553         AST_FORMAT_SLINEAR,
554         0,              /* Not full duplex */
555         bestdata_incusecnt,     /* incusecnt */
556         bestdata_decusecnt,     /* decusecnt */
557         bestdata_identify,      /* identify */
558         bestdata_init,  /* init */
559         NULL,   /* setdev */
560         bestdata_read,
561         bestdata_write,
562         bestdata_dial,  /* dial */
563         bestdata_answer,        /* answer */
564         bestdata_hangup,        /* hangup */
565         bestdata_startrec,      /* start record */
566         NULL,   /* stop record */
567         bestdata_startplay,     /* start playback */
568         NULL,   /* stop playback */
569         NULL,   /* set silence supression */
570         bestdata_dialdigit,     /* dialdigit */
571 };
572
573
574
575 int usecount(void)
576 {
577         int res;
578         ast_mutex_lock(&usecnt_lock);
579         res = usecnt;
580         ast_mutex_unlock(&usecnt_lock);
581         return res;
582 }
583
584 int load_module(void)
585 {
586         return ast_register_modem_driver(&bestdata_driver);
587 }
588
589 int unload_module(void)
590 {
591         return ast_unregister_modem_driver(&bestdata_driver);
592 }
593
594 char *description()
595 {
596         return desc;
597 }
598
599 char *key()
600 {
601         return ASTERISK_GPL_KEY;
602 }