Fix ADSI 'B' issue (bug #3833)
[asterisk/asterisk.git] / res / res_adsi.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * ADSI support 
5  * 
6  * Copyright (C) 2001, Linux Support Services, Inc.
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License.
12  *
13  * Includes code and algorithms from the Zapata library.
14  *
15  */
16
17 #include <time.h>
18 #include <string.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <math.h>
23 #include <errno.h>
24 #include <asterisk/ulaw.h>
25 #include <asterisk/alaw.h>
26 #include <asterisk/callerid.h>
27 #include <asterisk/logger.h>
28 #include <asterisk/fskmodem.h>
29 #include <asterisk/channel.h>
30 #include <asterisk/adsi.h>
31 #include <asterisk/module.h>
32 #include <asterisk/config.h>
33 #include <asterisk/file.h>
34
35 #define DEFAULT_ADSI_MAX_RETRIES 3
36
37 #define ADSI_MAX_INTRO 20
38 #define ADSI_MAX_SPEED_DIAL 6
39
40 #define ADSI_FLAG_DATAMODE      (1 << 8)
41
42 static int maxretries = DEFAULT_ADSI_MAX_RETRIES;
43
44 /* Asterisk ADSI button definitions */
45 #define ADSI_SPEED_DIAL         10      /* 10-15 are reserved for speed dial */
46
47 static char intro[ADSI_MAX_INTRO][20];
48 static int aligns[ADSI_MAX_INTRO];
49
50 static char speeddial[ADSI_MAX_SPEED_DIAL][3][20];
51
52 static int alignment = 0;
53
54 static int adsi_generate(unsigned char *buf, int msgtype, char *msg, int msglen, int msgnum, int last, int codec)
55 {
56         int sum;
57         int x;  
58         int bytes=0;
59         /* Initial carrier (imaginary) */
60         float cr = 1.0;
61         float ci = 0.0;
62         float scont = 0.0;
63
64         if (msglen > 255)
65                 msglen = 255;
66
67         /* If first message, Send 150ms of MARK's */
68         if (msgnum == 1) {
69                 for (x=0;x<150;x++)     /* was 150 */
70                         PUT_CLID_MARKMS;
71         }
72         /* Put message type */
73         PUT_CLID(msgtype);
74         sum = msgtype;
75
76         /* Put message length (plus one  for the message number) */
77         PUT_CLID(msglen + 1);
78         sum += msglen + 1;
79
80         /* Put message number */
81         PUT_CLID(msgnum);
82         sum += msgnum;
83
84         /* Put actual message */
85         for (x=0;x<msglen;x++) {
86                 PUT_CLID(msg[x]);
87                 sum += msg[x];
88         }
89
90         /* Put 2's compliment of sum */
91         PUT_CLID(256-(sum & 0xff));
92
93 #if 0
94         if (last) {
95                 /* Put trailing marks */
96                 for (x=0;x<50;x++)
97                         PUT_CLID_MARKMS;
98         }
99 #endif
100         return bytes;
101
102 }
103
104 static int adsi_careful_send(struct ast_channel *chan, unsigned char *buf, int len, int *remainder)
105 {
106         /* Sends carefully on a full duplex channel by using reading for
107            timing */
108         struct ast_frame *inf, outf;
109         int amt;
110
111         /* Zero out our outgoing frame */
112         memset(&outf, 0, sizeof(outf));
113
114         if (remainder && *remainder) {
115                 amt = len;
116
117                 /* Send remainder if provided */
118                 if (amt > *remainder)
119                         amt = *remainder;
120                 else
121                         *remainder = *remainder - amt;
122                 outf.frametype = AST_FRAME_VOICE;
123                 outf.subclass = AST_FORMAT_ULAW;
124                 outf.data = buf;
125                 outf.datalen = amt;
126                 outf.samples = amt;
127                 if (ast_write(chan, &outf)) {
128                         ast_log(LOG_WARNING, "Failed to carefully write frame\n");
129                         return -1;
130                 }
131                 /* Update pointers and lengths */
132                 buf += amt;
133                 len -= amt;
134         }
135
136         while(len) {
137                 amt = len;
138                 /* If we don't get anything at all back in a second, forget
139                    about it */
140                 if (ast_waitfor(chan, 1000) < 1)
141                         return -1;
142                 inf = ast_read(chan);
143                 /* Detect hangup */
144                 if (!inf)
145                         return -1;
146                 if (inf->frametype == AST_FRAME_VOICE) {
147                         /* Read a voice frame */
148                         if (inf->subclass != AST_FORMAT_ULAW) {
149                                 ast_log(LOG_WARNING, "Channel not in ulaw?\n");
150                                 return -1;
151                         }
152                         /* Send no more than they sent us */
153                         if (amt > inf->datalen)
154                                 amt = inf->datalen;
155                         else if (remainder)
156                                 *remainder = inf->datalen - amt;
157                         outf.frametype = AST_FRAME_VOICE;
158                         outf.subclass = AST_FORMAT_ULAW;
159                         outf.data = buf;
160                         outf.datalen = amt;
161                         outf.samples = amt;
162                         if (ast_write(chan, &outf)) {
163                                 ast_log(LOG_WARNING, "Failed to carefully write frame\n");
164                                 return -1;
165                         }
166                         /* Update pointers and lengths */
167                         buf += amt;
168                         len -= amt;
169                 }
170                 ast_frfree(inf);
171         }
172         return 0;
173 }
174
175 static int __adsi_transmit_messages(struct ast_channel *chan, unsigned char **msg, int *msglen, int *msgtype)
176 {
177         /* msglen must be no more than 256 bits, each */
178         unsigned char buf[24000 * 5];
179         int pos = 0, res;
180         int x;
181         int start=0;
182         int retries = 0;
183
184         char ack[3];
185
186         /* Wait up to 500 ms for initial ACK */
187         int waittime;
188         struct ast_frame *f;
189         int rem = 0;
190         int def;
191
192         if (chan->adsicpe == AST_ADSI_UNAVAILABLE) {
193                 /* Don't bother if we know they don't support ADSI */
194                 errno = ENOSYS;
195                 return -1;
196         }
197
198         while(retries < maxretries) {
199                 if (!(chan->adsicpe & ADSI_FLAG_DATAMODE)) {
200                         /* Generate CAS (no SAS) */
201                         ast_gen_cas(buf, 0, 680, AST_FORMAT_ULAW);
202                 
203                         /* Send CAS */
204                         if (adsi_careful_send(chan, buf, 680, NULL)) {
205                                 ast_log(LOG_WARNING, "Unable to send CAS\n");
206                         }
207                         /* Wait For DTMF result */
208                         waittime = 500;
209                         for(;;) {
210                                 if (((res = ast_waitfor(chan, waittime)) < 1)) {
211                                         /* Didn't get back DTMF A in time */
212                                         ast_log(LOG_DEBUG, "No ADSI CPE detected (%d)\n", res);
213                                         if (!chan->adsicpe)
214                                                 chan->adsicpe = AST_ADSI_UNAVAILABLE;
215                                         errno = ENOSYS;
216                                         return -1;
217                                 }
218                                 waittime = res;
219                                 f = ast_read(chan);
220                                 if (!f) {
221                                         ast_log(LOG_DEBUG, "Hangup in ADSI\n");
222                                         return -1;
223                                 }
224                                 if (f->frametype == AST_FRAME_DTMF) {
225                                         if (f->subclass == 'A') {
226                                                 /* Okay, this is an ADSI CPE.  Note this for future reference, too */
227                                                 if (!chan->adsicpe)
228                                                         chan->adsicpe = AST_ADSI_AVAILABLE;
229                                                 break;
230                                         } else {
231                                                 if (f->subclass == 'D')  {
232                                                         ast_log(LOG_DEBUG, "Off-hook capable CPE only, not ADSI\n");
233                                                 } else
234                                                         ast_log(LOG_WARNING, "Unknown ADSI response '%c'\n", f->subclass);
235                                                 if (!chan->adsicpe)
236                                                         chan->adsicpe = AST_ADSI_UNAVAILABLE;
237                                                 errno = ENOSYS;
238                                                 return -1;
239                                         }
240                                 }
241                                 ast_frfree(f);
242                         }
243
244                         ast_log(LOG_DEBUG, "ADSI Compatible CPE Detected\n");
245                 } else
246                         ast_log(LOG_DEBUG, "Already in data mode\n");
247
248                 x = 0;
249                 pos = 0;
250 #if 1
251                 def= ast_channel_defer_dtmf(chan);
252 #endif
253                 while((x < 6) && msg[x]) {
254                         res = adsi_generate(buf + pos, msgtype[x], msg[x], msglen[x], x+1 - start, (x == 5) || !msg[x+1], AST_FORMAT_ULAW);
255                         if (res < 0) {
256                                 ast_log(LOG_WARNING, "Failed to generate ADSI message %d on channel %s\n", x + 1, chan->name);
257                                 return -1;
258                         }
259                         ast_log(LOG_DEBUG, "Message %d, of %d input bytes, %d output bytes\n", 
260                                         x + 1, msglen[x], res);
261                         pos += res; 
262                         x++;
263                 }
264
265
266                 rem = 0;
267                 res = adsi_careful_send(chan, buf, pos, &rem); 
268                 if (!def)
269                         ast_channel_undefer_dtmf(chan);
270                 if (res)
271                         return -1;
272
273                 ast_log(LOG_DEBUG, "Sent total spill of %d bytes\n", pos);
274
275                 memset(ack, 0, sizeof(ack));
276                 /* Get real result */
277                 res = ast_readstring(chan, ack, 2, 1000, 1000, "");
278                 /* Check for hangup */
279                 if (res < 0)
280                         return -1;
281                 if (ack[0] == 'D') {
282                         ast_log(LOG_DEBUG, "Acked up to message %d\n", atoi(ack + 1));
283                         start += atoi(ack + 1);
284                         if (start >= x)
285                                 break;
286                         else {
287                                 retries++;
288                                 ast_log(LOG_DEBUG, "Retransmitting (%d), from %d\n", retries, start + 1);
289                         }
290                 } else {
291                         retries++;
292                         ast_log(LOG_WARNING, "Unexpected response to ack: %s (retry %d)\n", ack, retries);
293                 } 
294         }
295         if (retries >= maxretries) {
296                 ast_log(LOG_WARNING, "Maximum ADSI Retries (%d) exceeded\n", maxretries);
297                 errno = ETIMEDOUT;
298                 return -1;
299         }
300         return 0;
301         
302 }
303
304 int adsi_begin_download(struct ast_channel *chan, char *service, char *fdn, char *sec, int version)
305 {
306         int bytes;
307         unsigned char buf[256];
308         char ack[2];
309         bytes = 0;
310         /* Setup the resident soft key stuff, a piece at a time */
311         /* Upload what scripts we can for voicemail ahead of time */
312         bytes += adsi_download_connect(buf + bytes, service, fdn, sec, version);
313         if (adsi_transmit_message_full(chan, buf, bytes, ADSI_MSG_DOWNLOAD, 0))
314                 return -1;
315         if (ast_readstring(chan, ack, 1, 10000, 10000, ""))
316                 return -1;
317         if (ack[0] == 'B')
318                 return 0;
319         ast_log(LOG_DEBUG, "Download was denied by CPE\n");
320         return -1;
321 }
322
323 int adsi_end_download(struct ast_channel *chan)
324 {
325         int bytes;
326         unsigned char buf[256];
327         bytes = 0;
328         /* Setup the resident soft key stuff, a piece at a time */
329         /* Upload what scripts we can for voicemail ahead of time */
330         bytes += adsi_download_disconnect(buf + bytes);
331         if (adsi_transmit_message_full(chan, buf, bytes, ADSI_MSG_DOWNLOAD, 0))
332                 return -1;
333         return 0;
334 }
335
336 int adsi_transmit_message_full(struct ast_channel *chan, unsigned char *msg, int msglen, int msgtype, int dowait)
337 {
338         unsigned char *msgs[5] = { NULL, NULL, NULL, NULL, NULL };
339         int msglens[5];
340         int msgtypes[5];
341         int newdatamode;
342         int res;
343         int x;
344         int writeformat, readformat;
345         int waitforswitch = 0;
346
347         writeformat = chan->writeformat;
348         readformat = chan->readformat;
349
350         newdatamode = chan->adsicpe & ADSI_FLAG_DATAMODE;
351
352         for (x=0;x<msglen;x+=(msg[x+1]+2)) {
353                 if (msg[x] == ADSI_SWITCH_TO_DATA) {
354                         ast_log(LOG_DEBUG, "Switch to data is sent!\n");
355                         waitforswitch++;
356                         newdatamode = ADSI_FLAG_DATAMODE;
357                 }
358                 
359                 if (msg[x] == ADSI_SWITCH_TO_VOICE) {
360                         ast_log(LOG_DEBUG, "Switch to voice is sent!\n");
361                         waitforswitch++;
362                         newdatamode = 0;
363                 }
364         }
365         msgs[0] = msg;
366
367         msglens[0] = msglen;
368         msgtypes[0] = msgtype;
369
370         if (msglen > 253) {
371                 ast_log(LOG_WARNING, "Can't send ADSI message of %d bytes, too large\n", msglen);
372                 return -1;
373         }
374
375         ast_stopstream(chan);
376
377         if (ast_set_write_format(chan, AST_FORMAT_ULAW)) {
378                 ast_log(LOG_WARNING, "Unable to set write format to ULAW\n");
379                 return -1;
380         }
381
382         if (ast_set_read_format(chan, AST_FORMAT_ULAW)) {
383                 ast_log(LOG_WARNING, "Unable to set read format to ULAW\n");
384                 if (writeformat) {
385                         if (ast_set_write_format(chan, writeformat)) 
386                                 ast_log(LOG_WARNING, "Unable to restore write format to %d\n", writeformat);
387                 }
388                 return -1;
389         }
390         res = __adsi_transmit_messages(chan, msgs, msglens, msgtypes);
391
392         if (dowait) {
393                 ast_log(LOG_DEBUG, "Wait for switch is '%d'\n", waitforswitch);
394                 while(waitforswitch-- && ((res = ast_waitfordigit(chan, 1000)) > 0)) { res = 0; ast_log(LOG_DEBUG, "Waiting for 'B'...\n"); }
395         }
396         
397         if (!res)
398                 chan->adsicpe = (chan->adsicpe & ~ADSI_FLAG_DATAMODE) | newdatamode;
399
400         if (writeformat)
401                 ast_set_write_format(chan, writeformat);
402         if (readformat)
403                 ast_set_read_format(chan, readformat);
404
405         if (!res)
406                 res = ast_safe_sleep(chan, 100 );
407         return res;
408 }
409
410 int adsi_transmit_message(struct ast_channel *chan, unsigned char *msg, int msglen, int msgtype)
411 {
412         return adsi_transmit_message_full(chan, msg, msglen, msgtype, 1);
413 }
414
415 static inline int ccopy(unsigned char *dst, unsigned char *src, int max)
416 {
417         int x=0;
418         /* Carefully copy the requested data */
419         while ((x < max) && src[x] && (src[x] != 0xff)) {
420                 dst[x] = src[x];
421                 x++;
422         }
423         return x;
424 }
425
426 int adsi_load_soft_key(unsigned char *buf, int key, unsigned char *llabel, unsigned char *slabel, unsigned char *ret, int data)
427 {
428         int bytes=0;
429
430         /* Abort if invalid key specified */
431         if ((key < 2) || (key > 33))
432                 return -1;
433         buf[bytes++] = ADSI_LOAD_SOFTKEY;
434         /* Reserve for length */
435         bytes++;
436         /* Which key */
437         buf[bytes++] = key;
438
439         /* Carefully copy long label */
440         bytes += ccopy(buf + bytes, llabel, 18);
441
442         /* Place delimiter */
443         buf[bytes++] = 0xff;
444
445         /* Short label */
446         bytes += ccopy(buf + bytes, slabel, 7);
447
448
449         /* If specified, copy return string */
450         if (ret) {
451                 /* Place delimiter */
452                 buf[bytes++] = 0xff;
453                 if (data)
454                         buf[bytes++] = ADSI_SWITCH_TO_DATA2;
455                 /* Carefully copy return string */
456                 bytes += ccopy(buf + bytes, ret, 20);
457
458         }
459         /* Replace parameter length */
460         buf[1] = bytes - 2;
461         return bytes;
462         
463 }
464
465 int adsi_connect_session(unsigned char *buf, unsigned char *fdn, int ver)
466 {
467         int bytes=0;
468         int x;
469
470         /* Message type */
471         buf[bytes++] = ADSI_CONNECT_SESSION;
472
473         /* Reserve space for length */
474         bytes++;
475
476         if (fdn) {
477                 for (x=0;x<4;x++)
478                         buf[bytes++] = fdn[x];
479                 if (ver > -1)
480                         buf[bytes++] = ver & 0xff;
481         }
482
483         buf[1] = bytes - 2;
484         return bytes;
485
486 }
487
488 int adsi_download_connect(unsigned char *buf, unsigned char *service,  unsigned char *fdn, unsigned char *sec, int ver)
489 {
490         int bytes=0;
491         int x;
492
493         /* Message type */
494         buf[bytes++] = ADSI_DOWNLOAD_CONNECT;
495
496         /* Reserve space for length */
497         bytes++;
498
499         /* Primary column */
500         bytes+= ccopy(buf + bytes, service, 18);
501
502         /* Delimiter */
503         buf[bytes++] = 0xff;
504         
505         for (x=0;x<4;x++) {
506                 buf[bytes++] = fdn[x];
507         }
508         for (x=0;x<4;x++)
509                 buf[bytes++] = sec[x];
510         buf[bytes++] = ver & 0xff;
511
512         buf[1] = bytes - 2;
513
514         return bytes;
515
516 }
517
518 int adsi_disconnect_session(unsigned char *buf)
519 {
520         int bytes=0;
521
522         /* Message type */
523         buf[bytes++] = ADSI_DISC_SESSION;
524
525         /* Reserve space for length */
526         bytes++;
527
528         buf[1] = bytes - 2;
529         return bytes;
530
531 }
532
533 int adsi_query_cpeid(unsigned char *buf)
534 {
535         int bytes = 0;
536         buf[bytes++] = ADSI_QUERY_CPEID;
537         /* Reserve space for length */
538         bytes++;
539         buf[1] = bytes - 2;
540         return bytes;
541 }
542
543 int adsi_query_cpeinfo(unsigned char *buf)
544 {
545         int bytes = 0;
546         buf[bytes++] = ADSI_QUERY_CONFIG;
547         /* Reserve space for length */
548         bytes++;
549         buf[1] = bytes - 2;
550         return bytes;
551 }
552
553 int adsi_read_encoded_dtmf(struct ast_channel *chan, unsigned char *buf, int maxlen)
554 {
555         int bytes = 0;
556         int res;
557         unsigned char current = 0;
558         int gotstar = 0;
559         int pos = 0;
560         memset(buf, 0, sizeof(buf));
561         while(bytes <= maxlen) {
562                 /* Wait up to a second for a digit */
563                 res = ast_waitfordigit(chan, 1000);
564                 if (!res)
565                         break;
566                 if (res == '*') {
567                         gotstar = 1;    
568                         continue;
569                 }
570                 /* Ignore anything other than a digit */
571                 if ((res < '0') || (res > '9'))
572                         continue;
573                 res -= '0';
574                 if (gotstar)
575                         res += 9;
576                 if (pos)  {
577                         pos = 0;
578                         buf[bytes++] = (res << 4) | current;
579                 } else {
580                         pos = 1;
581                         current = res;
582                 }
583                 gotstar = 0;
584         }
585         return bytes;
586 }
587
588 int adsi_get_cpeid(struct ast_channel *chan, unsigned char *cpeid, int voice)
589 {
590         char buf[256];
591         int bytes = 0;
592         int res;
593         bytes += adsi_data_mode(buf);
594         adsi_transmit_message_full(chan, buf, bytes, ADSI_MSG_DISPLAY, 0);
595
596         bytes = 0;
597         bytes += adsi_query_cpeid(buf);
598         adsi_transmit_message_full(chan, buf, bytes, ADSI_MSG_DISPLAY, 0);
599
600         /* Get response */
601         memset(buf, 0, sizeof(buf));
602         res = adsi_read_encoded_dtmf(chan, cpeid, 4);
603         if (res != 4) {
604                 ast_log(LOG_WARNING, "Got %d bytes back of encoded DTMF, expecting 4\n", res);
605                 res = 0;
606         } else {
607                 res = 1;
608         }
609
610         if (voice) {
611                 bytes = 0;
612                 bytes += adsi_voice_mode(buf, 0);
613                 adsi_transmit_message_full(chan, buf, bytes, ADSI_MSG_DISPLAY, 0);
614                 /* Ignore the resulting DTMF B announcing it's in voice mode */
615                 ast_waitfordigit(chan, 1000);
616         }
617         return res;
618 }
619
620 int adsi_get_cpeinfo(struct ast_channel *chan, int *width, int *height, int *buttons, int voice)
621 {
622         char buf[256];
623         int bytes = 0;
624         int res;
625         bytes += adsi_data_mode(buf);
626         adsi_transmit_message_full(chan, buf, bytes, ADSI_MSG_DISPLAY, 0);
627
628         bytes = 0;
629         bytes += adsi_query_cpeinfo(buf);
630         adsi_transmit_message_full(chan, buf, bytes, ADSI_MSG_DISPLAY, 0);
631
632         /* Get width */
633         memset(buf, 0, sizeof(buf));
634         res = ast_readstring(chan, buf, 2, 1000, 500, "");
635         if (res < 0)
636                 return res;
637         if (strlen(buf) != 2) {
638                 ast_log(LOG_WARNING, "Got %d bytes of width, expecting 2\n", res);
639                 res = 0;
640         } else {
641                 res = 1;
642         }
643         if (width)
644                 *width = atoi(buf);
645         /* Get height */
646         memset(buf, 0, sizeof(buf));
647         if (res) {
648                 res = ast_readstring(chan, buf, 2, 1000, 500, "");
649                 if (res < 0)
650                         return res;
651                 if (strlen(buf) != 2) {
652                         ast_log(LOG_WARNING, "Got %d bytes of height, expecting 2\n", res);
653                         res = 0;
654                 } else {
655                         res = 1;
656                 }       
657                 if (height)
658                         *height= atoi(buf);
659         }
660         /* Get buttons */
661         memset(buf, 0, sizeof(buf));
662         if (res) {
663                 res = ast_readstring(chan, buf, 1, 1000, 500, "");
664                 if (res < 0)
665                         return res;
666                 if (strlen(buf) != 1) {
667                         ast_log(LOG_WARNING, "Got %d bytes of buttons, expecting 1\n", res);
668                         res = 0;
669                 } else {
670                         res = 1;
671                 }       
672                 if (buttons)
673                         *buttons = atoi(buf);
674         }
675         if (voice) {
676                 bytes = 0;
677                 bytes += adsi_voice_mode(buf, 0);
678                 adsi_transmit_message_full(chan, buf, bytes, ADSI_MSG_DISPLAY, 0);
679                 /* Ignore the resulting DTMF B announcing it's in voice mode */
680                 ast_waitfordigit(chan, 1000);
681         }
682         return res;
683 }
684
685 int adsi_data_mode(unsigned char *buf)
686 {
687         int bytes=0;
688
689         /* Message type */
690         buf[bytes++] = ADSI_SWITCH_TO_DATA;
691
692         /* Reserve space for length */
693         bytes++;
694
695         buf[1] = bytes - 2;
696         return bytes;
697
698 }
699
700 int adsi_clear_soft_keys(unsigned char *buf)
701 {
702         int bytes=0;
703
704         /* Message type */
705         buf[bytes++] = ADSI_CLEAR_SOFTKEY;
706
707         /* Reserve space for length */
708         bytes++;
709
710         buf[1] = bytes - 2;
711         return bytes;
712
713 }
714
715 int adsi_clear_screen(unsigned char *buf)
716 {
717         int bytes=0;
718
719         /* Message type */
720         buf[bytes++] = ADSI_CLEAR_SCREEN;
721
722         /* Reserve space for length */
723         bytes++;
724
725         buf[1] = bytes - 2;
726         return bytes;
727
728 }
729
730 int adsi_voice_mode(unsigned char *buf, int when)
731 {
732         int bytes=0;
733
734         /* Message type */
735         buf[bytes++] = ADSI_SWITCH_TO_VOICE;
736
737         /* Reserve space for length */
738         bytes++;
739
740         buf[bytes++] = when & 0x7f;
741
742         buf[1] = bytes - 2;
743         return bytes;
744
745 }
746
747 int adsi_available(struct ast_channel *chan)
748 {
749         int cpe = chan->adsicpe & 0xff;
750         if ((cpe == AST_ADSI_AVAILABLE) ||
751             (cpe == AST_ADSI_UNKNOWN))
752                 return 1;
753         return 0;
754 }
755
756 int adsi_download_disconnect(unsigned char *buf)
757 {
758         int bytes=0;
759
760         /* Message type */
761         buf[bytes++] = ADSI_DOWNLOAD_DISC;
762
763         /* Reserve space for length */
764         bytes++;
765
766         buf[1] = bytes - 2;
767         return bytes;
768
769 }
770
771 int adsi_display(unsigned char *buf, int page, int line, int just, int wrap, 
772                  unsigned char *col1, unsigned char *col2)
773 {
774         int bytes=0;
775
776         /* Sanity check line number */
777
778         if (page) {
779                 if (line > 4) return -1;
780         } else {
781                 if (line > 33) return -1;
782         }
783
784         if (line < 1)
785                 return -1;
786         /* Parameter type */
787         buf[bytes++] = ADSI_LOAD_VIRTUAL_DISP;
788         
789         /* Reserve space for size */
790         bytes++;
791
792         /* Page and wrap indicator */
793         buf[bytes++] = ((page & 0x1) << 7) | ((wrap & 0x1) << 6) | (line & 0x3f);
794
795         /* Justification */
796         buf[bytes++] = (just & 0x3) << 5;
797
798         /* Omit highlight mode definition */
799         buf[bytes++] = 0xff;
800
801         /* Primary column */
802         bytes+= ccopy(buf + bytes, col1, 20);
803
804         /* Delimiter */
805         buf[bytes++] = 0xff;
806         
807         /* Secondary column */
808         bytes += ccopy(buf + bytes, col2, 20);
809
810         /* Update length */
811         buf[1] = bytes - 2;
812         
813         return bytes;
814
815 }
816
817 int adsi_input_control(unsigned char *buf, int page, int line, int display, int format, int just)
818 {
819         int bytes=0;
820
821         if (page) {
822                 if (line > 4) return -1;
823         } else {
824                 if (line > 33) return -1;
825         }
826
827         if (line < 1)
828                 return -1;
829
830         buf[bytes++] = ADSI_INPUT_CONTROL;
831         bytes++;
832         buf[bytes++] = ((page & 1) << 7) | (line & 0x3f);
833         buf[bytes++] = ((display & 1) << 7) | ((just & 0x3) << 4) | (format & 0x7);
834         
835         buf[1] = bytes - 2;
836         return bytes;
837
838 }
839
840 int adsi_input_format(unsigned char *buf, int num, int dir, int wrap, unsigned char *format1, unsigned char *format2)
841 {
842         int bytes = 0;
843
844         if (!strlen(format1))
845                 return -1;
846
847         buf[bytes++] = ADSI_INPUT_FORMAT;
848         bytes++;
849         buf[bytes++] = ((dir & 1) << 7) | ((wrap & 1) << 6) | (num & 0x7);
850         bytes += ccopy(buf + bytes, format1, 20);
851         buf[bytes++] = 0xff;
852         if (format2 && strlen(format2)) {
853                 bytes += ccopy(buf + bytes, format2, 20);
854         }
855         buf[1] = bytes - 2;
856         return bytes;
857 }
858
859 int adsi_set_keys(unsigned char *buf, unsigned char *keys)
860 {
861         int bytes=0;
862         int x;
863         /* Message type */
864         buf[bytes++] = ADSI_INIT_SOFTKEY_LINE;
865         /* Space for size */
866         bytes++;
867         /* Key definitions */
868         for (x=0;x<6;x++)
869                 buf[bytes++] = (keys[x] & 0x3f) ? keys[x] : (keys[x] | 0x1);
870         buf[1] = bytes - 2;
871         return bytes;
872 }
873
874 int adsi_set_line(unsigned char *buf, int page, int line)
875 {
876         int bytes=0;
877
878         /* Sanity check line number */
879
880         if (page) {
881                 if (line > 4) return -1;
882         } else {
883                 if (line > 33) return -1;
884         }
885
886         if (line < 1)
887                 return -1;
888         /* Parameter type */
889         buf[bytes++] = ADSI_LINE_CONTROL;
890         
891         /* Reserve space for size */
892         bytes++;
893
894         /* Page and line */
895         buf[bytes++] = ((page & 0x1) << 7) | (line & 0x3f);
896
897         buf[1] = bytes - 2;
898         return bytes;
899
900 };
901
902 static int total = 0;
903 static int speeds = 0;
904
905 int adsi_channel_restore(struct ast_channel *chan)
906 {
907         char dsp[256];
908         int bytes;
909         int x;
910         unsigned char keyd[6];
911
912         memset(dsp, 0, sizeof(dsp));
913
914         /* Start with initial display setup */
915         bytes = 0;
916         bytes += adsi_set_line(dsp + bytes, ADSI_INFO_PAGE, 1);
917
918         /* Prepare key setup messages */
919
920         if (speeds) {
921                 memset(keyd, 0, sizeof(keyd));
922                 for (x=0;x<speeds;x++) {
923                         keyd[x] = ADSI_SPEED_DIAL + x;
924                 }
925                 bytes += adsi_set_keys(dsp + bytes, keyd);
926         }
927         adsi_transmit_message_full(chan, dsp, bytes, ADSI_MSG_DISPLAY, 0);
928         return 0;
929
930 }
931
932 int adsi_print(struct ast_channel *chan, char **lines, int *aligns, int voice)
933 {
934         char buf[4096];
935         int bytes=0;
936         int res;
937         int x;
938         for(x=0;lines[x];x++) 
939                 bytes += adsi_display(buf + bytes, ADSI_INFO_PAGE, x+1, aligns[x],0, lines[x], "");
940         bytes += adsi_set_line(buf + bytes, ADSI_INFO_PAGE, 1);
941         if (voice) {
942                 bytes += adsi_voice_mode(buf + bytes, 0);
943         }
944         res = adsi_transmit_message_full(chan, buf, bytes, ADSI_MSG_DISPLAY, 0);
945         if (voice) {
946                 /* Ignore the resulting DTMF B announcing it's in voice mode */
947                 ast_waitfordigit(chan, 1000);
948         }
949         return res;
950 }
951
952 int adsi_load_session(struct ast_channel *chan, unsigned char *app, int ver, int data)
953 {
954         char dsp[256];
955         int bytes;
956         int res;
957         char resp[2];
958
959         memset(dsp, 0, sizeof(dsp));
960
961         /* Connect to session */
962         bytes = 0;
963         bytes += adsi_connect_session(dsp + bytes, app,ver);
964
965         if (data)
966                 bytes += adsi_data_mode(dsp + bytes);
967
968         /* Prepare key setup messages */
969         if (adsi_transmit_message_full(chan, dsp, bytes, ADSI_MSG_DISPLAY, 0))
970                 return -1;
971         if (app) {
972                 res = ast_readstring(chan, resp, 1, 1200, 1200, "");
973                 if (res < 0)
974                         return -1;
975                 if (res) {
976                         ast_log(LOG_DEBUG, "No response from CPE about version.  Assuming not there.\n");
977                         return 0;
978                 }
979                 if (!strcmp(resp, "B")) {
980                         ast_log(LOG_DEBUG, "CPE has script '%s' version %d already loaded\n", app, ver);
981                         return 1;
982                 } else if (!strcmp(resp, "A")) {
983                         ast_log(LOG_DEBUG, "CPE hasn't script '%s' version %d already loaded\n", app, ver);
984                 } else {
985                         ast_log(LOG_WARNING, "Unexpected CPE response to script query: %s\n", resp);
986                 }
987         } else
988                 return 1;
989         return 0;
990
991 }
992
993 int adsi_unload_session(struct ast_channel *chan)
994 {
995         char dsp[256];
996         int bytes;
997
998         memset(dsp, 0, sizeof(dsp));
999
1000         /* Connect to session */
1001         bytes = 0;
1002         bytes += adsi_disconnect_session(dsp + bytes);
1003         bytes += adsi_voice_mode(dsp + bytes, 0);
1004
1005         /* Prepare key setup messages */
1006         if (adsi_transmit_message_full(chan, dsp, bytes, ADSI_MSG_DISPLAY, 0))
1007                 return -1;
1008         return 0;
1009 }
1010
1011 static int str2align(char *s)
1012 {
1013         if (!strncasecmp(s, "l", 1))
1014                 return ADSI_JUST_LEFT;
1015         else if (!strncasecmp(s, "r", 1))
1016                 return ADSI_JUST_RIGHT;
1017         else if (!strncasecmp(s, "i", 1))
1018                 return ADSI_JUST_IND;
1019         else
1020                 return ADSI_JUST_CENT;
1021 }
1022
1023 static void init_state(void)
1024 {
1025         int x;
1026
1027         for (x=0;x<ADSI_MAX_INTRO;x++)
1028                 aligns[x] = ADSI_JUST_CENT;
1029         strncpy(intro[0], "Welcome to the", sizeof(intro[0]) - 1);
1030         strncpy(intro[1], "Asterisk", sizeof(intro[1]) - 1);
1031         strncpy(intro[2], "Open Source PBX", sizeof(intro[2]) - 1);
1032         total = 3;
1033         speeds = 0;
1034         for (x=3;x<ADSI_MAX_INTRO;x++)
1035                 intro[x][0] = '\0';
1036         memset(speeddial, 0, sizeof(speeddial));
1037         alignment = ADSI_JUST_CENT;
1038 }
1039
1040 static void adsi_load(void)
1041 {
1042         int x;
1043         struct ast_config *conf;
1044         struct ast_variable *v;
1045         char *name, *sname;
1046         init_state();
1047         conf = ast_config_load("adsi.conf");
1048         if (conf) {
1049                 x=0;
1050                 v = ast_variable_browse(conf, "intro");
1051                 while(v) {
1052                         if (!strcasecmp(v->name, "alignment"))
1053                                 alignment = str2align(v->value);
1054                         else if (!strcasecmp(v->name, "greeting")) {
1055                                 if (x < ADSI_MAX_INTRO) {
1056                                         aligns[x] = alignment;
1057                                         strncpy(intro[x], v->value, sizeof(intro[x]) - 1);
1058                                         intro[x][sizeof(intro[x]) - 1] = '\0';
1059                                         x++;
1060                                 }
1061                         } else if (!strcasecmp(v->name, "maxretries")) {
1062                                 if (atoi(v->value) > 0)
1063                                         maxretries = atoi(v->value);
1064                         }
1065                         v = v->next;
1066                 }
1067                 v = ast_variable_browse(conf, "speeddial");
1068                 if (x)
1069                         total = x;
1070                 x = 0;
1071                 while(v) {
1072                         char *stringp=NULL;
1073                         stringp=v->value;
1074                         name = strsep(&stringp, ",");
1075                         sname = strsep(&stringp, ",");
1076                         if (!sname) 
1077                                 sname = name;
1078                         if (x < ADSI_MAX_SPEED_DIAL) {
1079                                 /* Up to 20 digits */
1080                                 strncpy(speeddial[x][0], v->name, sizeof(speeddial[x][0]) - 1);
1081                                 strncpy(speeddial[x][1], name, 18);
1082                                 strncpy(speeddial[x][2], sname, 7);
1083                                 x++;
1084                         }
1085                         v = v->next;
1086                                 
1087                 }
1088                 if (x)
1089                         speeds = x;
1090                 ast_config_destroy(conf);
1091         }
1092 }
1093
1094 int reload(void)
1095 {
1096         adsi_load();
1097         return 0;
1098 }
1099
1100 int load_module(void)
1101 {
1102         adsi_load();
1103         return 0;
1104 }
1105
1106 int unload_module(void)
1107 {
1108         /* Can't unload this once we're loaded */
1109         return -1;
1110 }
1111
1112 char *description(void)
1113 {
1114         return "ADSI Resource";
1115 }
1116
1117 int usecount(void)
1118 {
1119         /* We should never be unloaded */
1120         return 1;
1121 }
1122
1123 char *key()
1124 {
1125         return ASTERISK_GPL_KEY;
1126 }