Don't do reinvite if both parties talk diffrent codecs
[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 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
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         if (esc)
168                 ast_log(LOG_DEBUG, "Escaped character '%c'\n", esc);
169         
170         switch(esc) {
171         case 'R': /* Pseudo ring */
172                 time(&now);
173                 if (now > (p->lastring + (RINGT / 1000)))
174                    { /* if stale, treat as new */
175                         p->gotclid = 0;
176                    }
177                 if (p->gotclid)
178                    {
179                         p->fr.frametype = AST_FRAME_CONTROL;
180                         p->fr.subclass = AST_CONTROL_RING;
181                    }
182                 p->ringt = RINGT;
183                 time(&p->lastring);
184                 return &p->fr;
185         case 'X': /* Caller-ID Spill */
186                 if (p->gotclid) return &p->fr;
187                 name[0] = nmbr[0] = 0;
188                 for(;;)
189                    {
190                         char res[1000];
191
192                         if (ast_modem_read_response(p, 5)) break;
193                         strncpy(res, p->response, sizeof(res)-1);
194                         ast_modem_trim(res);
195                         if (!strncmp(res,"\020.",2)) break;
196                         if (!strncmp(res,"NAME",4)) strcpy(name,res + 7);
197                         if (!strncmp(res,"NMBR",4)) strcpy(nmbr,res + 7);
198                    }
199                 p->gotclid = 1;
200                 if ((!strcmp(name,"O")) || (!strcmp(name,"P"))) name[0] = 0;
201                 if ((!strcmp(nmbr,"O")) || (!strcmp(nmbr,"P"))) nmbr[0] = 0;
202                 if ((name[0]) && (nmbr[0])) snprintf(p->cid,sizeof(p->cid),
203                         "\"%s\" <%s>",name,nmbr);
204                 else if (name[0]) snprintf(p->cid,sizeof(p->cid),
205                         "\"%s\"",name);
206                 else if (nmbr[0]) snprintf(p->cid,sizeof(p->cid),
207                         "%s",nmbr);
208                 if (p->owner) p->owner->callerid = strdup(p->cid);
209                 return &p->fr;
210         case '@': /* response from "OK" in command mode */
211                 if (p->owner)
212                         ast_setstate(p->owner, AST_STATE_UP);
213                 if (bestdata_startrec(p)) return NULL;
214                 p->fr.frametype = AST_FRAME_CONTROL;
215                 p->fr.subclass = AST_CONTROL_RING;
216                 return &p->fr;
217         case 'b': /* Busy signal */
218                 p->fr.frametype = AST_FRAME_CONTROL;
219                 p->fr.subclass = AST_CONTROL_BUSY;
220                 return &p->fr;
221         case 'o': /* Overrun */
222                 ast_log(LOG_WARNING, "Overflow on modem, flushing buffers\n");
223                 if (ast_modem_send(p, "\0x10E", 2)) 
224                         ast_log(LOG_WARNING, "Unable to flush buffers\n");
225                 return &p->fr;  
226         case '0':  /* All the DTMF characters */
227         case '1':
228         case '2':
229         case '3':
230         case '4':
231         case '5':
232         case '6':
233         case '7':
234         case '8':
235         case '9':
236         case '*':
237         case '#':
238         case 'A':
239         case 'B':
240         case 'C':
241         case 'D':
242                 p->dtmfrx = esc;  /* save this for when its done */
243                 return &p->fr;  
244         case '/': /* Start of DTMF tone shielding */
245                 p->dtmfrx = ' ';
246                 return &p->fr;  
247         case '~': /* DTMF transition to off */
248                 if (p->dtmfrx > ' ')
249                    {
250                         p->fr.frametype = AST_FRAME_DTMF;
251                         p->fr.subclass = p->dtmfrx;
252                    }
253                 p->dtmfrx = 0;
254                 return &p->fr;  
255         case 'u': /* Underrun */
256                 ast_log(LOG_WARNING, "Data underrun\n");
257                 /* Fall Through */
258         case CHAR_ETX: /* End Transmission */
259         case 'd': /* Dialtone */
260         case 'c': /* Calling Tone */
261         case 'e': /* European version */
262         case 'a': /* Answer Tone */
263         case 'f': /* Bell Answer Tone */
264         case 'T': /* Timing mark */
265         case 't': /* Handset off hook */
266         case 'h': /* Handset hungup */
267         case 0: /* Pseudo signal */
268                 /* Ignore */
269                 return &p->fr;  
270         default:
271                 ast_log(LOG_DEBUG, "Unknown Escaped character '%c' (%d)\n", esc, esc);
272         }
273         return &p->fr;
274 }
275
276 static struct ast_frame *bestdata_read(struct ast_modem_pvt *p)
277 {
278         char result[256];
279         short *b;
280         struct ast_frame *f=NULL;
281         int res;
282         int x;
283
284         if (p->ministate == STATE_COMMAND) {
285                 /* Read the first two bytes, first, in case it's a control message */
286                 fread(result, 1, 2, p->f);
287                 if (result[0] == CHAR_DLE) {
288                         return bestdata_handle_escape(p, result[1]);
289                 } else {
290                         if (p->ringt) /* if ring timeout specified */
291                            {
292                                 x = fileno(p->f);
293                                 res = ast_waitfor_n_fd(&x, 1, &p->ringt, NULL);
294                                 if (res < 0) {
295                                         return NULL;
296                                 }
297                            }
298                         if ((result[0] == '\n') || (result[0] == '\r'))
299                                 return bestdata_handle_escape(p, 0);
300                         /* Read the rest of the line */
301                         fgets(result + 2, sizeof(result) - 2, p->f);
302                         ast_modem_trim(result);
303                         if (!strcasecmp(result, "OK")) {
304                                 /* If we're in immediate mode, reply now */
305                                 if (p->mode == MODEM_MODE_IMMEDIATE)
306                                         return bestdata_handle_escape(p, '@');
307                         } else
308                         if (!strcasecmp(result, "BUSY")) {
309                                 /* Same as a busy signal */
310                                 return bestdata_handle_escape(p, 'b');
311                         } else
312                         if (!strcasecmp(result, "RING")) {
313                                 return bestdata_handle_escape(p, 'R');
314                         } else
315                         if (!strcasecmp(result, "NO DIALTONE")) {
316                                 /* There's no dialtone, so the line isn't working */
317                                 ast_log(LOG_WARNING, "Device '%s' lacking dialtone\n", p->dev);
318                                 return NULL;
319                         }
320                         ast_log(LOG_DEBUG, "Modem said '%s'\n", result);
321                         return bestdata_handle_escape(p, 0);
322                 }
323         } else {
324                   /* if playing, start recording instead */
325                 if (p->ministate == STATE_VOICEPLAY)
326                    {
327                         if (bestdata_startrec(p)) return NULL;
328                    }
329                 /* We have to be more efficient in voice mode */
330                 b = (short *)(p->obuf + p->obuflen);
331                 while (p->obuflen/2 < 240) {
332                         /* Read ahead the full amount */
333                         res = fread(result, 1, 240 - p->obuflen/2, p->f);
334                         if (res < 1) {
335                                 /* If there's nothing there, just continue on */
336                                 if (errno == EAGAIN)
337                                         return bestdata_handle_escape(p, 0);
338                                 ast_log(LOG_WARNING, "Read failed: %s\n", strerror(errno));
339                         }
340                         for (x=0;x<res;x++) {
341                                 /* Process all the bytes that we've read */
342                                 if (result[x] == CHAR_DLE) {
343                                         /* We assume there is no more than one signal frame among our
344                                            data.  */
345                                         if (f) ast_log(LOG_WARNING, "Warning: Dropped a signal frame\n");
346                                           /* if not a DLE in the data */
347                                         if (result[++x] != CHAR_DLE)
348                                            {
349                                                 /* If bestdata_handle_escape says NULL, say it now, doesn't matter
350                                                    what else is there, the connection is dead. */
351                                                 f = bestdata_handle_escape(p, result[x]);
352                                                 if (p->dtmfrx) continue;
353                                                 return(f);
354                                            }
355                                 }
356                                 /* Generate a 16-bit signed linear value from our 
357                                    unsigned 8-bit value */
358                                 *(b++) = (((short)result[x]) - 127) * 0xff;
359                                 p->obuflen += 2;
360                         }
361                         if (f) break;
362                 }
363                 /* If we have a control frame, return it now */
364                 if (f) return f;
365                 /* If we get here, we have a complete voice frame */
366                 p->fr.frametype = AST_FRAME_VOICE;
367                 p->fr.subclass = AST_FORMAT_SLINEAR;
368                 p->fr.samples = 240;
369                 p->fr.data = p->obuf;
370                 p->fr.datalen = p->obuflen;
371                 p->fr.mallocd = 0;
372                 p->fr.offset = AST_FRIENDLY_OFFSET;
373                 p->fr.src = __FUNCTION__;
374                 if (option_debug)
375                         ast_log(LOG_DEBUG, "bestdata_read(voice frame)\n");
376                 p->obuflen = 0;
377                 return &p->fr;
378         }
379         return NULL;
380 }
381
382 static int bestdata_write(struct ast_modem_pvt *p, struct ast_frame *f)
383 {
384 unsigned char   c,buf[32768]; /* I hope we dont have frames larger then 16K */
385 int     i,j;
386 short   *sp;
387 unsigned long u;
388 #define DLE     16
389
390         if (p->owner && (p->owner->_state == AST_STATE_UP) && 
391                 (p->ministate != STATE_VOICEPLAY) && bestdata_startplay(p)) return -1;
392         sp = (short *) f->data;
393           /* stick DLE's in ahead of anything else */
394         for(i = 0,j = 0; i < f->datalen / 2; i++)
395            {
396                 *sp *= 3;
397                 u = *sp++ + 32768;
398                 c = u >> 8;
399                 if (c == DLE) buf[j++] = DLE;
400                 buf[j++] = c;
401            }
402         do i = fwrite(buf,1,j,p->f);
403         while ((i == -1) && (errno == EWOULDBLOCK));
404         if (i != j)
405            {
406                 ast_log(LOG_WARNING,"modem short write!!\n");
407                 return -1;
408            }
409         fflush(p->f);
410         if (option_debug)
411                 ast_log(LOG_DEBUG, "bestdata_write()\n");
412         return 0;
413 }
414
415 static char *bestdata_identify(struct ast_modem_pvt *p)
416 {
417         char identity[256];
418         char mfr[80];
419         char mdl[80];
420         char rev[80];
421         ast_modem_send(p, "AT+FMM", 0);
422         ast_modem_read_response(p, 5);
423         strncpy(mdl, p->response, sizeof(mdl)-1);
424         ast_modem_trim(mdl);
425         ast_modem_expect(p, "OK", 5);
426         ast_modem_send(p, "AT+FMI", 0);
427         ast_modem_read_response(p, 5);
428         strncpy(mfr, p->response, sizeof(mfr)-1);
429         ast_modem_trim(mfr);
430         ast_modem_expect(p, "OK", 5);
431         ast_modem_send(p, "AT+FMR", 0);
432         ast_modem_read_response(p, 5);
433         strncpy(rev, p->response, sizeof(rev)-1);
434         ast_modem_trim(rev);
435         ast_modem_expect(p, "OK", 5);
436         snprintf(identity, sizeof(identity), "%s Model %s Revision %s", mfr, mdl, rev);
437         return strdup(identity);
438 }
439
440 static void bestdata_incusecnt(void)
441 {
442         ast_mutex_lock(&usecnt_lock);
443         usecnt++;
444         ast_mutex_unlock(&usecnt_lock);
445         ast_update_use_count();
446 }
447
448 static void bestdata_decusecnt(void)
449 {
450         ast_mutex_lock(&usecnt_lock);
451         usecnt++;
452         ast_mutex_unlock(&usecnt_lock);
453         ast_update_use_count();
454 }
455
456 static int bestdata_answer(struct ast_modem_pvt *p)
457 {
458         p->ringt = 0;
459         p->lastring = 0;
460         if (ast_modem_send(p, "AT+VLS=1", 0) ||
461              ast_modem_expect(p, "OK", 10)) {
462                 ast_log(LOG_WARNING, "Unable to answer: %s", p->response);
463                 return -1;
464         }
465         return 0;
466 }
467
468 static int bestdata_dialdigit(struct ast_modem_pvt *p, char digit)
469 {
470         char cmd[80];
471
472         if (p->ministate != STATE_COMMAND) bestdata_break(p);
473         snprintf(cmd, sizeof(cmd), "AT+VTS=%c", digit);
474         if (ast_modem_send(p, cmd, 0) ||
475              ast_modem_expect(p, "OK", 10)) {
476                 ast_log(LOG_WARNING, "Unable to answer: %s", p->response);
477                 return -1;
478         }
479         return 0;
480 }
481
482 static int bestdata_dial(struct ast_modem_pvt *p, char *stuff)
483 {
484         char cmd[800],a[20];
485         int i,j;
486
487         if (p->ministate != STATE_COMMAND)
488            {
489                 bestdata_break(p);
490                 strcpy(cmd,"AT+VTS=");
491                 j = strlen(cmd);
492                 for(i = 0; stuff[i]; i++)
493                    {
494                         switch(stuff[i])
495                            {
496                             case '!' :
497                                 a[0] = stuff[i];
498                                 a[1] = 0;
499                                 break;
500                             case ',':
501                                 strcpy(a,"[,,100]");
502                                 break;
503                             default:
504                                 sprintf(a,"{%c,7}",stuff[i]);
505                            }
506                         if (stuff[i + 1]) strcat(a,",");
507                         strcpy(cmd + j,a);
508                         j += strlen(a);
509                    }
510            }
511         else
512            {
513                 snprintf(cmd, sizeof(cmd), "ATD%c %s", p->dialtype,stuff);
514            }
515         if (ast_modem_send(p, cmd, 0)) {
516                 ast_log(LOG_WARNING, "Unable to dial\n");
517                 return -1;
518         }
519         return 0;
520 }
521
522 static int bestdata_hangup(struct ast_modem_pvt *p)
523 {
524         if (bestdata_break(p))
525                 return -1;
526         /* Hangup by switching to data, then back to voice */
527         if (ast_modem_send(p, "ATH", 0) ||
528              ast_modem_expect(p, "OK", 8)) {
529                 ast_log(LOG_WARNING, "Unable to set to data mode\n");
530                 return -1;
531         }
532         if (ast_modem_send(p, "AT+FCLASS=8", 0) ||
533              ast_modem_expect(p, "OK", 5)) {
534                 ast_log(LOG_WARNING, "Unable to set to voice mode\n");
535                 return -1;
536         }
537         p->gotclid = 0;
538         p->ringt = 0;
539         p->lastring = 0;
540         p->dtmfrx = 0;
541         return 0;
542 }
543
544 static struct ast_modem_driver bestdata_driver =
545 {
546         "BestData",
547         bestdata_idents,
548         AST_FORMAT_SLINEAR,
549         0,              /* Not full duplex */
550         bestdata_incusecnt,     /* incusecnt */
551         bestdata_decusecnt,     /* decusecnt */
552         bestdata_identify,      /* identify */
553         bestdata_init,  /* init */
554         NULL,   /* setdev */
555         bestdata_read,
556         bestdata_write,
557         bestdata_dial,  /* dial */
558         bestdata_answer,        /* answer */
559         bestdata_hangup,        /* hangup */
560         bestdata_startrec,      /* start record */
561         NULL,   /* stop record */
562         bestdata_startplay,     /* start playback */
563         NULL,   /* stop playback */
564         NULL,   /* set silence supression */
565         bestdata_dialdigit,     /* dialdigit */
566 };
567
568
569
570 int usecount(void)
571 {
572         int res;
573         ast_mutex_lock(&usecnt_lock);
574         res = usecnt;
575         ast_mutex_unlock(&usecnt_lock);
576         return res;
577 }
578
579 int load_module(void)
580 {
581         return ast_register_modem_driver(&bestdata_driver);
582 }
583
584 int unload_module(void)
585 {
586         return ast_unregister_modem_driver(&bestdata_driver);
587 }
588
589 char *description()
590 {
591         return desc;
592 }
593
594 char *key()
595 {
596         return ASTERISK_GPL_KEY;
597 }