app_alarmreceiver.c 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 2004 - 2005 Steve Rodgers
  5. *
  6. * Steve Rodgers <hwstar@rodgers.sdcoxmail.com>
  7. *
  8. * See http://www.asterisk.org for more information about
  9. * the Asterisk project. Please do not directly contact
  10. * any of the maintainers of this project for assistance;
  11. * the project provides a web site, mailing lists and IRC
  12. * channels for your use.
  13. *
  14. * This program is free software, distributed under the terms of
  15. * the GNU General Public License Version 2. See the LICENSE file
  16. * at the top of the source tree.
  17. */
  18. /*! \file
  19. *
  20. * \brief Central Station Alarm receiver for Ademco Contact ID
  21. * \author Steve Rodgers <hwstar@rodgers.sdcoxmail.com>
  22. *
  23. * *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING ***
  24. *
  25. * Use at your own risk. Please consult the GNU GPL license document included with Asterisk. *
  26. *
  27. * *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING *** WARNING ***
  28. *
  29. * \ingroup applications
  30. */
  31. /*! \li \ref app_alarmreceiver.c uses the configuration file \ref alarmreceiver.conf
  32. * \addtogroup configuration_file Configuration Files
  33. */
  34. /*!
  35. * \page alarmreceiver.conf alarmreceiver.conf
  36. * \verbinclude alarmreceiver.conf.sample
  37. */
  38. /*** MODULEINFO
  39. <support_level>extended</support_level>
  40. ***/
  41. #include "asterisk.h"
  42. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  43. #include <math.h>
  44. #include <sys/wait.h>
  45. #include <sys/time.h>
  46. #include "asterisk/lock.h"
  47. #include "asterisk/file.h"
  48. #include "asterisk/channel.h"
  49. #include "asterisk/pbx.h"
  50. #include "asterisk/module.h"
  51. #include "asterisk/translate.h"
  52. #include "asterisk/app.h"
  53. #include "asterisk/dsp.h"
  54. #include "asterisk/config.h"
  55. #include "asterisk/localtime.h"
  56. #include "asterisk/callerid.h"
  57. #include "asterisk/astdb.h"
  58. #include "asterisk/utils.h"
  59. #include "asterisk/indications.h"
  60. #include "asterisk/format_cache.h"
  61. #define ALMRCV_CONFIG "alarmreceiver.conf"
  62. #define UNKNOWN_FORMAT "UNKNOWN_FORMAT"
  63. #define ADEMCO_CONTACT_ID "ADEMCO_CONTACT_ID"
  64. /*
  65. AAAA _ID_ P CCC XX ZZZ S
  66. where AAAA is the account number, _ID_ is 18 or 98, P is the pin status (alarm or restore), CCC
  67. is the alarm code which is pre-defined by Ademco (but you may be able to reprogram it in the panel), XX
  68. is the dialer group, partition or area number, ZZZ is the zone or user number and S is the checksum
  69. */
  70. #define ADEMCO_EXPRESS_4_1 "ADEMCO_EXPRESS_4_1"
  71. /*
  72. AAAA _ID_ C S
  73. where AAAA is the account number, _ID_ is 17, C is the alarm code and S is the checksum.
  74. */
  75. #define ADEMCO_EXPRESS_4_2 "ADEMCO_EXPRESS_4_2"
  76. /*
  77. AAAA _ID_ C Z S
  78. where AAAA is the account number, _ID_ is 27, C is the alarm code, Z is the zone or user number and S is the checksum.
  79. */
  80. #define ADEMCO_HIGH_SPEED "ADEMCO_HIGH_SPEED"
  81. /*
  82. AAAA _ID_ PPPP PPPP X S
  83. where AAAA is the account number, _ID_ is 55, PPPP PPPP is the status of each zone, X
  84. is a special digit which describes the type of information in the PPPP PPPP fields and S is checksum.
  85. Each P field contains one of the following values:
  86. 1 new alarm 3 new restore 5 normal
  87. 2 new opening 4 new closing 6 outstanding
  88. The X field contains one of the following values:
  89. 0 AlarmNet messages
  90. 1 ambush or duress
  91. 2 opening by user (the first P field contains the user number)
  92. 3 bypass (the P fields indicate which zones are bypassed)
  93. 4 closing by user (the first P field contain the user number)
  94. 5 trouble (the P fields contain which zones are in trouble)
  95. 6 system trouble
  96. 7 normal message (the P fields indicate zone status)
  97. 8 low battery (the P fields indicate zone status)
  98. 9 test (the P fields indicate zone status)
  99. */
  100. #define ADEMCO_SUPER_FAST "ADEMCO_SUPER_FAST"
  101. /*
  102. AAAA _ID_ PPPP PPPP X
  103. where AAA is the account number, _ID_ is 56
  104. */
  105. #define ADEMCO_MSG_TYPE_1 "18"
  106. #define ADEMCO_MSG_TYPE_2 "98"
  107. #define ADEMCO_MSG_TYPE_3 "17"
  108. #define ADEMCO_MSG_TYPE_4 "27"
  109. #define ADEMCO_MSG_TYPE_5 "55"
  110. #define ADEMCO_MSG_TYPE_6 "56"
  111. #define ADEMCO_AUDIO_CALL_NEXT "606"
  112. struct {
  113. char digit;
  114. char weight;
  115. } digits_mapping[] = { {'0', 10}, {'1', 1} , {'2', 2}, {'3', 3}, {'4', 4}, {'5', 5},
  116. {'6', 6}, {'7', 7}, {'8', 8}, {'9', 9}, {'*', 11}, {'#', 12},
  117. {'A', 13}, {'B', 14}, {'C', 15} };
  118. struct event_node{
  119. char data[17];
  120. struct event_node *next;
  121. };
  122. typedef struct event_node event_node_t;
  123. struct timeval call_start_time;
  124. static const char app[] = "AlarmReceiver";
  125. /*** DOCUMENTATION
  126. <application name="AlarmReceiver" language="en_US">
  127. <synopsis>
  128. Provide support for receiving alarm reports from a burglar or fire alarm panel.
  129. </synopsis>
  130. <syntax />
  131. <description>
  132. <para>This application should be called whenever there is an alarm panel calling in to dump its events.
  133. The application will handshake with the alarm panel, and receive events, validate them, handshake them,
  134. and store them until the panel hangs up. Once the panel hangs up, the application will run the system
  135. command specified by the eventcmd setting in <filename>alarmreceiver.conf</filename> and pipe the
  136. events to the standard input of the application.
  137. The configuration file also contains settings for DTMF timing, and for the loudness of the
  138. acknowledgement tones.</para>
  139. <note><para>Few Ademco DTMF signalling formats are detected automaticaly: Contact ID, Express 4+1,
  140. Express 4+2, High Speed and Super Fast.</para></note>
  141. <para>The application is affected by the following variables:</para>
  142. <variablelist>
  143. <variable name="ALARMRECEIVER_CALL_LIMIT">
  144. <para>Maximum call time, in milliseconds.</para>
  145. <para>If set, this variable causes application to exit after the specified time.</para>
  146. </variable>
  147. <variable name="ALARMRECEIVER_RETRIES_LIMIT">
  148. <para>Maximum number of retries per call.</para>
  149. <para>If set, this variable causes application to exit after the specified number of messages.</para>
  150. </variable>
  151. </variablelist>
  152. </description>
  153. <see-also>
  154. <ref type="filename">alarmreceiver.conf</ref>
  155. </see-also>
  156. </application>
  157. ***/
  158. /* Config Variables */
  159. static int fdtimeout = 2000;
  160. static int sdtimeout = 200;
  161. static int answait = 1250;
  162. static int toneloudness = 4096;
  163. static int log_individual_events = 0;
  164. static int no_group_meta = 0;
  165. static char event_spool_dir[128] = {'\0'};
  166. static char event_app[128] = {'\0'};
  167. static char db_family[128] = {'\0'};
  168. static char time_stamp_format[128] = {"%a %b %d, %Y @ %H:%M:%S %Z"};
  169. /* Misc variables */
  170. static char event_file[14] = "/event-XXXXXX";
  171. /*!
  172. * \brief Attempt to access a database variable and increment it
  173. *
  174. * \note Only if the user defined db-family in alarmreceiver.conf
  175. *
  176. * The alarmreceiver app will write statistics to a few variables
  177. * in this family if it is defined. If the new key doesn't exist in the
  178. * family, then create it and set its value to 1.
  179. *
  180. * \param key A database key to increment
  181. * \return Nothing
  182. */
  183. static void database_increment(char *key)
  184. {
  185. unsigned v;
  186. char value[16];
  187. if (ast_strlen_zero(db_family)) {
  188. return; /* If not defined, don't do anything */
  189. }
  190. if (ast_db_get(db_family, key, value, sizeof(value) - 1)) {
  191. ast_verb(4, "AlarmReceiver: Creating database entry %s and setting to 1\n", key);
  192. /* Guess we have to create it */
  193. ast_db_put(db_family, key, "1");
  194. return;
  195. }
  196. sscanf(value, "%30u", &v);
  197. v++;
  198. ast_verb(4, "AlarmReceiver: New value for %s: %u\n", key, v);
  199. snprintf(value, sizeof(value), "%u", v);
  200. if (ast_db_put(db_family, key, value)) {
  201. ast_verb(4, "AlarmReceiver: database_increment write error\n");
  202. }
  203. return;
  204. }
  205. /*!
  206. * \brief Receive a fixed length DTMF string.
  207. *
  208. * \note Doesn't give preferential treatment to any digit,
  209. * \note allow different timeout values for the first and all subsequent digits
  210. *
  211. * \param chan Asterisk Channel
  212. * \param digit_string Digits String
  213. * \param buf_size The size of the Digits String buffer
  214. * \param expected Digits expected for this message type
  215. * \param received Pointer to number of digits received so far
  216. *
  217. * \retval 0 if all digits were successfully received
  218. * \retval 1 if a timeout occurred
  219. * \retval -1 if the caller hung up or on channel errors
  220. */
  221. static int receive_dtmf_digits(struct ast_channel *chan, char *digit_string, int buf_size, int expected, int *received)
  222. {
  223. int rtn = 0;
  224. int r;
  225. struct ast_frame *f;
  226. struct timeval lastdigittime;
  227. lastdigittime = ast_tvnow();
  228. while (*received < expected && *received < buf_size - 1) {
  229. /* If timed out, leave */
  230. if (ast_tvdiff_ms(ast_tvnow(), lastdigittime) > ((*received > 0) ? sdtimeout : fdtimeout)) {
  231. ast_verb(4, "AlarmReceiver: DTMF Digit Timeout on %s\n", ast_channel_name(chan));
  232. ast_debug(1, "AlarmReceiver: DTMF timeout on chan %s\n", ast_channel_name(chan));
  233. rtn = 1;
  234. break;
  235. }
  236. if ((r = ast_waitfor(chan, -1)) < 0) {
  237. ast_debug(1, "Waitfor returned %d\n", r);
  238. continue;
  239. }
  240. if ((f = ast_read(chan)) == NULL) {
  241. rtn = -1;
  242. break;
  243. }
  244. /* If they hung up, leave */
  245. if ((f->frametype == AST_FRAME_CONTROL)
  246. && (f->subclass.integer == AST_CONTROL_HANGUP)) {
  247. if (f->data.uint32) {
  248. ast_channel_hangupcause_set(chan, f->data.uint32);
  249. }
  250. ast_frfree(f);
  251. rtn = -1;
  252. break;
  253. }
  254. /* If not DTMF, just do it again */
  255. if (f->frametype != AST_FRAME_DTMF) {
  256. ast_frfree(f);
  257. continue;
  258. }
  259. /* Save digit */
  260. digit_string[(*received)++] = f->subclass.integer;
  261. ast_frfree(f);
  262. lastdigittime = ast_tvnow();
  263. }
  264. /* Null terminate the end of the digit_string */
  265. digit_string[*received] = '\0';
  266. return rtn;
  267. }
  268. /*!
  269. * \brief Write metadata to log file
  270. *
  271. * \param logfile Log File Pointer
  272. * \param signalling_type Signaling Type
  273. * \param chan Asterisk Channel
  274. * \param no_checksum Expecting messages without checksum
  275. *
  276. * \retval 0 success
  277. * \retval -1 failure
  278. */
  279. static int write_metadata(FILE *logfile, char *signalling_type, struct ast_channel *chan, int no_checksum)
  280. {
  281. struct timeval t;
  282. struct ast_tm now;
  283. char *cl;
  284. char *cn;
  285. char workstring[80];
  286. char timestamp[80];
  287. /* Extract the caller ID location */
  288. ast_copy_string(workstring,
  289. S_COR(ast_channel_caller(chan)->id.number.valid,
  290. ast_channel_caller(chan)->id.number.str, ""), sizeof(workstring));
  291. ast_shrink_phone_number(workstring);
  292. if (ast_strlen_zero(workstring)) {
  293. cl = "<unknown>";
  294. } else {
  295. cl = workstring;
  296. }
  297. cn = S_COR(ast_channel_caller(chan)->id.name.valid,
  298. ast_channel_caller(chan)->id.name.str, "<unknown>");
  299. /* Get the current time */
  300. t = ast_tvnow();
  301. ast_localtime(&t, &now, NULL);
  302. /* Format the time */
  303. ast_strftime(timestamp, sizeof(timestamp), time_stamp_format, &now);
  304. if (no_group_meta && fprintf(logfile, "PROTOCOL=%s\n"
  305. "CHECKSUM=%s\n"
  306. "CALLINGFROM=%s\n"
  307. "CALLERNAME=%s\n"
  308. "TIMESTAMP=%s\n\n",
  309. signalling_type, (!no_checksum) ? "yes" : "no", cl, cn, timestamp) > -1) {
  310. return 0;
  311. } else if (fprintf(logfile, "\n\n[metadata]\n\n"
  312. "PROTOCOL=%s\n"
  313. "CHECKSUM=%s\n"
  314. "CALLINGFROM=%s\n"
  315. "CALLERNAME=%s\n"
  316. "TIMESTAMP=%s\n\n"
  317. "[events]\n\n",
  318. signalling_type, (!no_checksum) ? "yes" : "no", cl, cn, timestamp) > -1) {
  319. return 0;
  320. }
  321. ast_verb(3, "AlarmReceiver: can't write metadata\n");
  322. ast_debug(1, "AlarmReceiver: can't write metadata\n");
  323. return -1;
  324. }
  325. /*!
  326. * \brief Log a single event
  327. *
  328. * \param logfile Log File Pointer
  329. * \param event Event Structure
  330. *
  331. * \retval 0 success
  332. * \retval -1 failure
  333. */
  334. static int write_event(FILE *logfile, event_node_t *event)
  335. {
  336. if (fprintf(logfile, "%s%s\n", no_group_meta ? "event=" : "", event->data) < 0) {
  337. return -1;
  338. }
  339. return 0;
  340. }
  341. /*!
  342. * \brief Log events if configuration key logindividualevents is enabled or on exit
  343. *
  344. * \param chan Asterisk Channel
  345. * \param signalling_type Signaling Type
  346. * \param event Event Structure
  347. * \param no_checksum Expecting messages without checksum
  348. *
  349. * \retval 0 success
  350. * \retval -1 failure
  351. */
  352. static int log_events(struct ast_channel *chan, char *signalling_type, event_node_t *event, int no_checksum)
  353. {
  354. char workstring[sizeof(event_spool_dir) + sizeof(event_file)] = "";
  355. int fd;
  356. FILE *logfile;
  357. event_node_t *elp = event;
  358. if (!ast_strlen_zero(event_spool_dir)) {
  359. /* Make a template */
  360. ast_copy_string(workstring, event_spool_dir, sizeof(workstring));
  361. strncat(workstring, event_file, sizeof(workstring) - strlen(workstring) - 1);
  362. /* Make the temporary file */
  363. fd = mkstemp(workstring);
  364. if (fd == -1) {
  365. ast_verb(3, "AlarmReceiver: can't make temporary file\n");
  366. ast_debug(1, "AlarmReceiver: can't make temporary file\n");
  367. return -1;
  368. }
  369. if ((logfile = fdopen(fd, "w")) == NULL) {
  370. return -1;
  371. }
  372. /* Write the file */
  373. if (write_metadata(logfile, signalling_type, chan, no_checksum)) {
  374. fflush(logfile);
  375. fclose(logfile);
  376. return -1;
  377. }
  378. while ((elp != NULL) && (write_event(logfile, elp) == 0)) {
  379. elp = elp->next;
  380. }
  381. fflush(logfile);
  382. fclose(logfile);
  383. }
  384. return 0;
  385. }
  386. /*!
  387. * \brief Verify Ademco checksum
  388. * \since 11.0
  389. *
  390. * \param event Received DTMF String
  391. * \param expected Number of Digits expected
  392. *
  393. * \retval 0 success
  394. * \retval -1 failure
  395. */
  396. static int ademco_verify_checksum(char *event, int expected)
  397. {
  398. int checksum = 0;
  399. int i, j;
  400. for (j = 0; j < expected; j++) {
  401. for (i = 0; i < ARRAY_LEN(digits_mapping); i++) {
  402. if (digits_mapping[i].digit == event[j]) {
  403. break;
  404. }
  405. }
  406. if (i >= ARRAY_LEN(digits_mapping)) {
  407. ast_verb(2, "AlarmReceiver: Bad DTMF character %c, trying again\n", event[j]);
  408. return -1;
  409. }
  410. checksum += digits_mapping[i].weight;
  411. }
  412. /* Checksum is mod(15) of the total */
  413. if (!(checksum % 15)) {
  414. return 0;
  415. }
  416. return -1;
  417. }
  418. /*!
  419. * \brief Send a single tone burst for a specified duration and frequency.
  420. * \since 11.0
  421. *
  422. * \param chan Asterisk Channel
  423. * \param tone_freq Frequency of the tone to send
  424. * \param tone_duration Tone duration in ms
  425. * \param delay Delay before sending the tone
  426. *
  427. * \retval 0 success
  428. * \retval -1 failure
  429. */
  430. static int send_tone_burst(struct ast_channel *chan, const char *tone_freq, int tone_duration, int delay)
  431. {
  432. if (delay && ast_safe_sleep(chan, delay)) {
  433. return -1;
  434. }
  435. if (ast_playtones_start(chan, toneloudness, tone_freq, 0)) {
  436. return -1;
  437. }
  438. if (ast_safe_sleep(chan, tone_duration)) {
  439. return -1;
  440. }
  441. ast_playtones_stop(chan);
  442. return 0;
  443. }
  444. /*!
  445. * \brief Check if the message is in known and valid Ademco format
  446. *
  447. * \param signalling_type Expected signalling type for the message
  448. * \param event event received
  449. *
  450. * \retval 0 The event is valid
  451. * \retval -1 The event is not valid
  452. */
  453. static int ademco_check_valid(char *signalling_type, char *event)
  454. {
  455. if (!strcmp(signalling_type, UNKNOWN_FORMAT)) {
  456. return 1;
  457. }
  458. if (!strcmp(signalling_type, ADEMCO_CONTACT_ID)
  459. && strncmp(event + 4, ADEMCO_MSG_TYPE_1, 2)
  460. && strncmp(event + 4, ADEMCO_MSG_TYPE_2, 2)) {
  461. return -1;
  462. }
  463. if (!strcmp(signalling_type, ADEMCO_EXPRESS_4_1) && strncmp(event + 4, ADEMCO_MSG_TYPE_3, 2)) {
  464. return -1;
  465. }
  466. if (!strcmp(signalling_type, ADEMCO_EXPRESS_4_2) && strncmp(event + 4, ADEMCO_MSG_TYPE_4, 2)) {
  467. return -1;
  468. }
  469. if (!strcmp(signalling_type, ADEMCO_HIGH_SPEED) && strncmp(event + 4, ADEMCO_MSG_TYPE_5, 2)) {
  470. return -1;
  471. }
  472. if (!strcmp(signalling_type, ADEMCO_SUPER_FAST) && strncmp(event + 4, ADEMCO_MSG_TYPE_6, 2)) {
  473. return -1;
  474. }
  475. return 0;
  476. }
  477. /*!
  478. * \brief Detect the message format of an event
  479. *
  480. * \param signalling_type Expected signalling type for the message
  481. * \param event event received
  482. * \param no_checksum Should we calculate checksum for the message
  483. *
  484. * \returns The expected digits for the detected event type
  485. */
  486. static int ademco_detect_format(char *signalling_type, char *event, int *no_checksum)
  487. {
  488. int res = 16;
  489. if (!strncmp(event + 4, ADEMCO_MSG_TYPE_1, 2)
  490. || !strncmp(event + 4, ADEMCO_MSG_TYPE_2, 2)) {
  491. sprintf(signalling_type, "%s", ADEMCO_CONTACT_ID);
  492. }
  493. if (!strncmp(event + 4, ADEMCO_MSG_TYPE_3, 2)) {
  494. sprintf(signalling_type, "%s", ADEMCO_EXPRESS_4_1);
  495. res = 8;
  496. }
  497. if (!strncmp(event + 4, ADEMCO_MSG_TYPE_4, 2)) {
  498. sprintf(signalling_type, "%s", ADEMCO_EXPRESS_4_2);
  499. res = 9;
  500. }
  501. if (!strncmp(event + 4, ADEMCO_MSG_TYPE_5, 2)) {
  502. sprintf(signalling_type, "%s", ADEMCO_HIGH_SPEED);
  503. }
  504. if (!strncmp(event + 4, ADEMCO_MSG_TYPE_6, 2)) {
  505. sprintf(signalling_type, "%s", ADEMCO_SUPER_FAST);
  506. *no_checksum = 1;
  507. res = 15;
  508. }
  509. if (strcmp(signalling_type, UNKNOWN_FORMAT)) {
  510. ast_verb(4, "AlarmMonitoring: Detected format %s.\n", signalling_type);
  511. ast_debug(1, "AlarmMonitoring: Autodetected format %s.\n", signalling_type);
  512. }
  513. return res;
  514. }
  515. /*!
  516. * \brief Receive Ademco ContactID or other format Data String
  517. *
  518. * \param chan Asterisk Channel
  519. * \param ehead Pointer to events list
  520. * \param signalling_type Expected signalling type for the message
  521. * \param no_checksum Should we calculate checksum for the message
  522. *
  523. * \retval 0 success
  524. * \retval -1 failure
  525. */
  526. static int receive_ademco_event(struct ast_channel *chan, event_node_t **ehead, char *signalling_type, int *no_checksum)
  527. {
  528. int res = 0;
  529. const char *limit;
  530. char event[17];
  531. event_node_t *enew, *elp;
  532. int got_some_digits = 0;
  533. int events_received = 0;
  534. int ack_retries = 0;
  535. int limit_retries = 0;
  536. int expected_length = sizeof(event) - 1;
  537. database_increment("calls-received");
  538. /* Wait for first event */
  539. ast_verb(4, "AlarmReceiver: Waiting for first event from panel...\n");
  540. while (res >= 0) {
  541. int digits_received = 0;
  542. res = 0;
  543. if (log_individual_events) {
  544. sprintf(signalling_type, "%s", UNKNOWN_FORMAT);
  545. expected_length = 16;
  546. *no_checksum = 0;
  547. }
  548. if (got_some_digits == 0) {
  549. /* Send ACK tone sequence */
  550. ast_verb(4, "AlarmReceiver: Sending 1400Hz 100ms burst (ACK)\n");
  551. res = send_tone_burst(chan, "1400", 100, 0);
  552. if (!res) {
  553. ast_verb(4, "AlarmReceiver: Sending 2300Hz 100ms burst (ACK)\n");
  554. res = send_tone_burst(chan, "2300", 100, 100);
  555. }
  556. }
  557. if (res) {
  558. return -1;
  559. }
  560. res = receive_dtmf_digits(chan, event, sizeof(event), expected_length, &digits_received);
  561. if (res < 0) {
  562. if (events_received == 0) {
  563. /* Hangup with no events received should be logged in the DB */
  564. database_increment("no-events-received");
  565. ast_verb(4, "AlarmReceiver: No events received!\n");
  566. } else {
  567. if (ack_retries) {
  568. database_increment("ack-retries");
  569. ast_verb(4, "AlarmReceiver: ACK retries during this call: %d\n", ack_retries);
  570. }
  571. }
  572. ast_verb(4, "AlarmReceiver: App exiting...\n");
  573. break;
  574. }
  575. if (!strcmp(signalling_type, UNKNOWN_FORMAT) && digits_received > 5) {
  576. expected_length = ademco_detect_format(signalling_type, event, no_checksum);
  577. if (res > 0) {
  578. if (digits_received == expected_length) {
  579. res = limit_retries = 0;
  580. } else if (digits_received == expected_length - 1
  581. && (!strcmp(signalling_type, ADEMCO_EXPRESS_4_2)
  582. || !strcmp(signalling_type, ADEMCO_EXPRESS_4_1))) {
  583. /* ADEMCO EXPRESS without checksum */
  584. res = limit_retries = 0;
  585. expected_length--;
  586. *no_checksum = 1;
  587. ast_verb(4, "AlarmMonitoring: Skipping checksum for format %s.\n", signalling_type);
  588. ast_debug(1, "AlarmMonitoring: Skipping checksum for format %s.\n", signalling_type);
  589. }
  590. }
  591. }
  592. ast_channel_lock(chan);
  593. limit = pbx_builtin_getvar_helper(chan, "ALARMRECEIVER_CALL_LIMIT");
  594. if (!ast_strlen_zero(limit)) {
  595. if (ast_tvdiff_ms(ast_tvnow(), call_start_time) > atoi(limit)) {
  596. ast_channel_unlock(chan);
  597. return -1;
  598. }
  599. }
  600. limit = pbx_builtin_getvar_helper(chan, "ALARMRECEIVER_RETRIES_LIMIT");
  601. ast_channel_unlock(chan);
  602. if (!ast_strlen_zero(limit)) {
  603. if (limit_retries + 1 >= atoi(limit)) {
  604. return -1;
  605. }
  606. }
  607. if (res) {
  608. /* Didn't get all of the digits */
  609. ast_verb(2, "AlarmReceiver: Incomplete string: %s, trying again...\n", event);
  610. limit_retries++;
  611. if (!events_received && strcmp(signalling_type, UNKNOWN_FORMAT))
  612. {
  613. sprintf(signalling_type, "%s", UNKNOWN_FORMAT);
  614. expected_length = sizeof(event) - 1;
  615. }
  616. if (!got_some_digits) {
  617. got_some_digits = (!ast_strlen_zero(event)) ? 1 : 0;
  618. ack_retries++;
  619. }
  620. continue;
  621. }
  622. got_some_digits = 1;
  623. ast_verb(2, "AlarmReceiver: Received Event %s\n", event);
  624. ast_debug(1, "AlarmReceiver: Received event: %s\n", event);
  625. /* Calculate checksum */
  626. if (!(*no_checksum) && ademco_verify_checksum(event, expected_length)) {
  627. database_increment("checksum-errors");
  628. ast_verb(2, "AlarmReceiver: Nonzero checksum\n");
  629. ast_debug(1, "AlarmReceiver: Nonzero checksum\n");
  630. continue;
  631. }
  632. /* Check the message type for correctness */
  633. if (ademco_check_valid(signalling_type, event)) {
  634. database_increment("format-errors");
  635. ast_verb(2, "AlarmReceiver: Wrong message type\n");
  636. ast_debug(1, "AlarmReceiver: Wrong message type\n");
  637. continue;
  638. }
  639. events_received++;
  640. /* Queue the Event */
  641. if (!(enew = ast_calloc(1, sizeof(*enew)))) {
  642. return -1;
  643. }
  644. enew->next = NULL;
  645. ast_copy_string(enew->data, event, sizeof(enew->data));
  646. /* Insert event onto end of list */
  647. if (*ehead == NULL) {
  648. *ehead = enew;
  649. } else {
  650. for (elp = *ehead; elp->next != NULL; elp = elp->next) {
  651. ;
  652. }
  653. elp->next = enew;
  654. }
  655. /* Let the user have the option of logging the single event before sending the kissoff tone */
  656. if (log_individual_events && log_events(chan, signalling_type, enew, *no_checksum)) {
  657. return -1;
  658. }
  659. /* Send the kissoff tone (1400 Hz, 900 ms, after 200ms delay) */
  660. if (send_tone_burst(chan, "1400", 900, 200)) {
  661. return -1;
  662. }
  663. /* If audio call follows, exit alarm receiver app */
  664. if (!strcmp(signalling_type, ADEMCO_CONTACT_ID)
  665. && !strncmp(event + 7, ADEMCO_AUDIO_CALL_NEXT, 3)) {
  666. ast_verb(4, "AlarmReceiver: App exiting... Audio call next!\n");
  667. return 0;
  668. }
  669. }
  670. return res;
  671. }
  672. /*!
  673. * \brief This is the main function called by Asterisk Core whenever the App is invoked in the extension logic.
  674. *
  675. * \param chan Asterisk Channel
  676. * \param data Application data
  677. *
  678. * \retval 0 success
  679. * \retval -1 failure
  680. */
  681. static int alarmreceiver_exec(struct ast_channel *chan, const char *data)
  682. {
  683. int res = 0;
  684. int no_checksum = 0;
  685. event_node_t *elp, *efree;
  686. char signalling_type[64] = "";
  687. event_node_t *event_head = NULL;
  688. if ((ast_format_cmp(ast_channel_writeformat(chan), ast_format_ulaw) == AST_FORMAT_CMP_NOT_EQUAL) &&
  689. (ast_format_cmp(ast_channel_writeformat(chan), ast_format_alaw) == AST_FORMAT_CMP_NOT_EQUAL)) {
  690. ast_verb(4, "AlarmReceiver: Setting write format to Mu-law\n");
  691. if (ast_set_write_format(chan, ast_format_ulaw)) {
  692. ast_log(LOG_WARNING, "AlarmReceiver: Unable to set write format to Mu-law on %s\n",ast_channel_name(chan));
  693. return -1;
  694. }
  695. }
  696. if ((ast_format_cmp(ast_channel_readformat(chan), ast_format_ulaw) == AST_FORMAT_CMP_NOT_EQUAL) &&
  697. (ast_format_cmp(ast_channel_readformat(chan), ast_format_alaw) == AST_FORMAT_CMP_NOT_EQUAL)) {
  698. ast_verb(4, "AlarmReceiver: Setting read format to Mu-law\n");
  699. if (ast_set_read_format(chan, ast_format_ulaw)) {
  700. ast_log(LOG_WARNING, "AlarmReceiver: Unable to set read format to Mu-law on %s\n",ast_channel_name(chan));
  701. return -1;
  702. }
  703. }
  704. /* Set default values for this invocation of the application */
  705. ast_copy_string(signalling_type, UNKNOWN_FORMAT, sizeof(signalling_type));
  706. call_start_time = ast_tvnow();
  707. /* Answer the channel if it is not already */
  708. if (ast_channel_state(chan) != AST_STATE_UP) {
  709. ast_verb(4, "AlarmReceiver: Answering channel\n");
  710. if (ast_answer(chan)) {
  711. return -1;
  712. }
  713. }
  714. /* Wait for the connection to settle post-answer */
  715. ast_verb(4, "AlarmReceiver: Waiting for connection to stabilize\n");
  716. if (ast_safe_sleep(chan, answait)) {
  717. return -1;
  718. }
  719. /* Attempt to receive the events */
  720. receive_ademco_event(chan, &event_head, signalling_type, &no_checksum);
  721. /* Events queued by receiver, write them all out here if so configured */
  722. if (!log_individual_events) {
  723. res = log_events(chan, signalling_type, event_head, no_checksum);
  724. }
  725. /* Do we exec a command line at the end? */
  726. if ((!res) && (!ast_strlen_zero(event_app)) && (event_head)) {
  727. ast_debug(1,"Alarmreceiver: executing: %s\n", event_app);
  728. ast_safe_system(event_app);
  729. }
  730. /* Free up the data allocated in our linked list */
  731. for (elp = event_head; (elp != NULL);) {
  732. efree = elp;
  733. elp = elp->next;
  734. ast_free(efree);
  735. }
  736. return 0;
  737. }
  738. /*!
  739. * \brief Load the configuration from the configuration file
  740. *
  741. * \param reload True on reload
  742. *
  743. * \retval 1 success
  744. * \retval 0 failure
  745. */
  746. static int load_config(int reload)
  747. {
  748. struct ast_config *cfg;
  749. const char *value;
  750. struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  751. /* Read in the config file */
  752. cfg = ast_config_load(ALMRCV_CONFIG, config_flags);
  753. if (!cfg) {
  754. ast_verb(4, "AlarmReceiver: No config file\n");
  755. return 0;
  756. } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
  757. return 1;
  758. } else if (cfg == CONFIG_STATUS_FILEINVALID) {
  759. ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n",
  760. ALMRCV_CONFIG);
  761. return 0;
  762. }
  763. if ((value = ast_variable_retrieve(cfg, "general", "eventcmd")) != NULL) {
  764. ast_copy_string(event_app, value, sizeof(event_app));
  765. }
  766. if ((value = ast_variable_retrieve(cfg, "general", "loudness")) != NULL) {
  767. toneloudness = atoi(value);
  768. if (toneloudness < 100) {
  769. toneloudness = 100;
  770. } else if (toneloudness > 8192) {
  771. toneloudness = 8192;
  772. }
  773. }
  774. if ((value = ast_variable_retrieve(cfg, "general", "fdtimeout")) != NULL) {
  775. fdtimeout = atoi(value);
  776. if (fdtimeout < 1000) {
  777. fdtimeout = 1000;
  778. } else if (fdtimeout > 10000) {
  779. fdtimeout = 10000;
  780. }
  781. }
  782. if ((value = ast_variable_retrieve(cfg, "general", "sdtimeout")) != NULL) {
  783. sdtimeout = atoi(value);
  784. if (sdtimeout < 110) {
  785. sdtimeout = 110;
  786. } else if (sdtimeout > 4000) {
  787. sdtimeout = 4000;
  788. }
  789. }
  790. if ((value = ast_variable_retrieve(cfg, "general", "answait")) != NULL) {
  791. answait = atoi(value);
  792. if (answait < 500) {
  793. answait = 500;
  794. } else if (answait > 10000) {
  795. answait = 10000;
  796. }
  797. }
  798. if ((value = ast_variable_retrieve(cfg, "general", "no_group_meta")) != NULL) {
  799. no_group_meta = ast_true(value);
  800. }
  801. if ((value = ast_variable_retrieve(cfg, "general", "logindividualevents")) != NULL) {
  802. log_individual_events = ast_true(value);
  803. }
  804. if ((value = ast_variable_retrieve(cfg, "general", "eventspooldir")) != NULL) {
  805. ast_copy_string(event_spool_dir, value, sizeof(event_spool_dir));
  806. }
  807. if ((value = ast_variable_retrieve(cfg, "general", "timestampformat")) != NULL) {
  808. ast_copy_string(time_stamp_format, value, sizeof(time_stamp_format));
  809. }
  810. if ((value = ast_variable_retrieve(cfg, "general", "db-family")) != NULL) {
  811. ast_copy_string(db_family, value, sizeof(db_family));
  812. }
  813. ast_config_destroy(cfg);
  814. return 1;
  815. }
  816. /*!
  817. * \brief Unregister Alarm Receiver App
  818. *
  819. * \retval 0 success
  820. * \retval -1 failure
  821. */
  822. static int unload_module(void)
  823. {
  824. return ast_unregister_application(app);
  825. }
  826. /*!
  827. * \brief Load the module
  828. *
  829. * Module loading including tests for configuration or dependencies.
  830. * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
  831. * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
  832. * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
  833. * configuration file or other non-critical problem return
  834. * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
  835. */
  836. static int load_module(void)
  837. {
  838. if (load_config(0)) {
  839. if (ast_register_application_xml(app, alarmreceiver_exec)) {
  840. return AST_MODULE_LOAD_FAILURE;
  841. }
  842. return AST_MODULE_LOAD_SUCCESS;
  843. }
  844. return AST_MODULE_LOAD_DECLINE;
  845. }
  846. static int reload(void)
  847. {
  848. if (load_config(1)) {
  849. return AST_MODULE_LOAD_SUCCESS;
  850. }
  851. return AST_MODULE_LOAD_DECLINE;
  852. }
  853. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Alarm Receiver for Asterisk",
  854. .support_level = AST_MODULE_SUPPORT_EXTENDED,
  855. .load = load_module,
  856. .unload = unload_module,
  857. .reload = reload,
  858. );