devicestate.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2008, Digium, Inc.
  5. *
  6. * Mark Spencer <markster@digium.com>
  7. * Russell Bryant <russell@digium.com>
  8. *
  9. * See http://www.asterisk.org for more information about
  10. * the Asterisk project. Please do not directly contact
  11. * any of the maintainers of this project for assistance;
  12. * the project provides a web site, mailing lists and IRC
  13. * channels for your use.
  14. *
  15. * This program is free software, distributed under the terms of
  16. * the GNU General Public License Version 2. See the LICENSE file
  17. * at the top of the source tree.
  18. */
  19. /*! \file
  20. *
  21. * \brief Device state management
  22. *
  23. * \author Mark Spencer <markster@digium.com>
  24. * \author Russell Bryant <russell@digium.com>
  25. *
  26. * \arg \ref AstExtState
  27. */
  28. /*! \page AstExtState Extension and device states in Asterisk
  29. *
  30. * (Note that these descriptions of device states and extension
  31. * states have not been updated to the way things work
  32. * in Asterisk 1.6.)
  33. *
  34. * Asterisk has an internal system that reports states
  35. * for an extension. By using the dialplan priority -1,
  36. * also called a \b hint, a connection can be made from an
  37. * extension to one or many devices. The state of the extension
  38. * now depends on the combined state of the devices.
  39. *
  40. * The device state is basically based on the current calls.
  41. * If the devicestate engine can find a call from or to the
  42. * device, it's in use.
  43. *
  44. * Some channel drivers implement a callback function for
  45. * a better level of reporting device states. The SIP channel
  46. * has a complicated system for this, which is improved
  47. * by adding call limits to the configuration.
  48. *
  49. * Functions that want to check the status of an extension
  50. * register themself as a \b watcher.
  51. * Watchers in this system can subscribe either to all extensions
  52. * or just a specific extensions.
  53. *
  54. * For non-device related states, there's an API called
  55. * devicestate providers. This is an extendible system for
  56. * delivering state information from outside sources or
  57. * functions within Asterisk. Currently we have providers
  58. * for app_meetme.c - the conference bridge - and call
  59. * parking (metermaids).
  60. *
  61. * There are manly three subscribers to extension states
  62. * within Asterisk:
  63. * - AMI, the manager interface
  64. * - app_queue.c - the Queue dialplan application
  65. * - SIP subscriptions, a.k.a. "blinking lamps" or
  66. * "buddy lists"
  67. *
  68. * The CLI command "show hints" show last known state
  69. *
  70. * \note None of these handle user states, like an IM presence
  71. * system. res_xmpp.c can subscribe and watch such states
  72. * in jabber/xmpp based systems.
  73. *
  74. * \section AstDevStateArch Architecture for devicestates
  75. *
  76. * When a channel driver or asterisk app changes state for
  77. * a watched object, it alerts the core. The core queues
  78. * a change. When the change is processed, there's a query
  79. * sent to the channel driver/provider if there's a function
  80. * to handle that, otherwise a channel walk is issued to find
  81. * a channel that involves the object.
  82. *
  83. * The changes are queued and processed by a separate thread.
  84. * This thread calls the watchers subscribing to status
  85. * changes for the object. For manager, this results
  86. * in events. For SIP, NOTIFY requests.
  87. *
  88. * - Device states
  89. * \arg \ref devicestate.c
  90. * \arg \ref devicestate.h
  91. *
  92. * \section AstExtStateArch Architecture for extension states
  93. *
  94. * Hints are connected to extension. If an extension changes state
  95. * it checks the hint devices. If there is a hint, the callbacks into
  96. * device states are checked. The aggregated state is set for the hint
  97. * and reported back.
  98. *
  99. * - Extension states
  100. * \arg \ref ast_extension_states "AstENUM"
  101. * \arg \ref pbx.c
  102. * \arg \ref pbx.h
  103. * - Structures
  104. * - \ref ast_state_cb struct. Callbacks for watchers
  105. * - Callback ast_state_cb_type
  106. * - \ref ast_hint struct.
  107. * - Functions
  108. * - ast_extension_state_add()
  109. * - ast_extension_state_del()
  110. * - ast_get_hint()
  111. *
  112. */
  113. /*** MODULEINFO
  114. <support_level>core</support_level>
  115. ***/
  116. /*** DOCUMENTATION
  117. <managerEvent language="en_US" name="DeviceStateChange">
  118. <managerEventInstance class="EVENT_FLAG_CALL">
  119. <synopsis>Raised when a device state changes</synopsis>
  120. <syntax>
  121. <parameter name="Device">
  122. <para>The device whose state has changed</para>
  123. </parameter>
  124. <parameter name="State">
  125. <para>The new state of the device</para>
  126. </parameter>
  127. </syntax>
  128. <description>
  129. <para>This differs from the <literal>ExtensionStatus</literal>
  130. event because this event is raised for all device state changes,
  131. not only for changes that affect dialplan hints.</para>
  132. </description>
  133. <see-also>
  134. <ref type="managerEvent">ExtensionStatus</ref>
  135. </see-also>
  136. </managerEventInstance>
  137. </managerEvent>
  138. ***/
  139. #include "asterisk.h"
  140. #include "asterisk/_private.h"
  141. #include "asterisk/channel.h"
  142. #include "asterisk/utils.h"
  143. #include "asterisk/lock.h"
  144. #include "asterisk/linkedlists.h"
  145. #include "asterisk/devicestate.h"
  146. #include "asterisk/pbx.h"
  147. #include "asterisk/app.h"
  148. #include "asterisk/astobj2.h"
  149. #include "asterisk/stasis.h"
  150. #include "asterisk/devicestate.h"
  151. #define DEVSTATE_TOPIC_BUCKETS 57
  152. /*! \brief Device state strings for printing */
  153. static const char * const devstatestring[][2] = {
  154. { /* 0 AST_DEVICE_UNKNOWN */ "Unknown", "UNKNOWN" }, /*!< Valid, but unknown state */
  155. { /* 1 AST_DEVICE_NOT_INUSE */ "Not in use", "NOT_INUSE" }, /*!< Not used */
  156. { /* 2 AST_DEVICE IN USE */ "In use", "INUSE" }, /*!< In use */
  157. { /* 3 AST_DEVICE_BUSY */ "Busy", "BUSY" }, /*!< Busy */
  158. { /* 4 AST_DEVICE_INVALID */ "Invalid", "INVALID" }, /*!< Invalid - not known to Asterisk */
  159. { /* 5 AST_DEVICE_UNAVAILABLE */ "Unavailable", "UNAVAILABLE" }, /*!< Unavailable (not registered) */
  160. { /* 6 AST_DEVICE_RINGING */ "Ringing", "RINGING" }, /*!< Ring, ring, ring */
  161. { /* 7 AST_DEVICE_RINGINUSE */ "Ring+Inuse", "RINGINUSE" }, /*!< Ring and in use */
  162. { /* 8 AST_DEVICE_ONHOLD */ "On Hold", "ONHOLD" }, /*!< On Hold */
  163. };
  164. /*!\brief Mapping for channel states to device states */
  165. static const struct chan2dev {
  166. enum ast_channel_state chan;
  167. enum ast_device_state dev;
  168. } chan2dev[] = {
  169. { AST_STATE_DOWN, AST_DEVICE_NOT_INUSE },
  170. { AST_STATE_RESERVED, AST_DEVICE_INUSE },
  171. { AST_STATE_OFFHOOK, AST_DEVICE_INUSE },
  172. { AST_STATE_DIALING, AST_DEVICE_INUSE },
  173. { AST_STATE_RING, AST_DEVICE_INUSE },
  174. { AST_STATE_RINGING, AST_DEVICE_RINGING },
  175. { AST_STATE_UP, AST_DEVICE_INUSE },
  176. { AST_STATE_BUSY, AST_DEVICE_BUSY },
  177. { AST_STATE_DIALING_OFFHOOK, AST_DEVICE_INUSE },
  178. { AST_STATE_PRERING, AST_DEVICE_RINGING },
  179. };
  180. /*! \brief A device state provider (not a channel) */
  181. struct devstate_prov {
  182. char label[40];
  183. ast_devstate_prov_cb_type callback;
  184. AST_RWLIST_ENTRY(devstate_prov) list;
  185. };
  186. /*! \brief A list of providers */
  187. static AST_RWLIST_HEAD_STATIC(devstate_provs, devstate_prov);
  188. struct state_change {
  189. AST_LIST_ENTRY(state_change) list;
  190. enum ast_devstate_cache cachable;
  191. char device[1];
  192. };
  193. /*! \brief The state change queue. State changes are queued
  194. for processing by a separate thread */
  195. static AST_LIST_HEAD_STATIC(state_changes, state_change);
  196. /*! \brief The device state change notification thread */
  197. static pthread_t change_thread = AST_PTHREADT_NULL;
  198. /*! \brief Flag for the queue */
  199. static ast_cond_t change_pending;
  200. static volatile int shuttingdown;
  201. struct stasis_subscription *devstate_message_sub;
  202. static struct stasis_topic *device_state_topic_all;
  203. static struct stasis_cache *device_state_cache;
  204. static struct stasis_caching_topic *device_state_topic_cached;
  205. static struct stasis_topic_pool *device_state_topic_pool;
  206. static struct ast_manager_event_blob *devstate_to_ami(struct stasis_message *msg);
  207. static struct ast_event *devstate_to_event(struct stasis_message *msg);
  208. STASIS_MESSAGE_TYPE_DEFN(ast_device_state_message_type,
  209. .to_ami = devstate_to_ami,
  210. .to_event = devstate_to_event,
  211. );
  212. /* Forward declarations */
  213. static int getproviderstate(const char *provider, const char *address);
  214. /*! \brief Find devicestate as text message for output */
  215. const char *ast_devstate2str(enum ast_device_state devstate)
  216. {
  217. return devstatestring[devstate][0];
  218. }
  219. enum ast_device_state ast_state_chan2dev(enum ast_channel_state chanstate)
  220. {
  221. int i;
  222. chanstate &= 0xFFFF;
  223. for (i = 0; i < ARRAY_LEN(chan2dev); i++) {
  224. if (chan2dev[i].chan == chanstate) {
  225. return chan2dev[i].dev;
  226. }
  227. }
  228. return AST_DEVICE_UNKNOWN;
  229. }
  230. /* Parseable */
  231. const char *ast_devstate_str(enum ast_device_state state)
  232. {
  233. return devstatestring[state][1];
  234. }
  235. enum ast_device_state ast_devstate_val(const char *val)
  236. {
  237. if (!strcasecmp(val, "NOT_INUSE"))
  238. return AST_DEVICE_NOT_INUSE;
  239. else if (!strcasecmp(val, "INUSE"))
  240. return AST_DEVICE_INUSE;
  241. else if (!strcasecmp(val, "BUSY"))
  242. return AST_DEVICE_BUSY;
  243. else if (!strcasecmp(val, "INVALID"))
  244. return AST_DEVICE_INVALID;
  245. else if (!strcasecmp(val, "UNAVAILABLE"))
  246. return AST_DEVICE_UNAVAILABLE;
  247. else if (!strcasecmp(val, "RINGING"))
  248. return AST_DEVICE_RINGING;
  249. else if (!strcasecmp(val, "RINGINUSE"))
  250. return AST_DEVICE_RINGINUSE;
  251. else if (!strcasecmp(val, "ONHOLD"))
  252. return AST_DEVICE_ONHOLD;
  253. return AST_DEVICE_UNKNOWN;
  254. }
  255. /*! \brief Find out if device is active in a call or not
  256. \note find channels with the device's name in it
  257. This function is only used for channels that does not implement
  258. devicestate natively
  259. */
  260. enum ast_device_state ast_parse_device_state(const char *device)
  261. {
  262. struct ast_channel *chan;
  263. char match[AST_CHANNEL_NAME];
  264. enum ast_device_state res;
  265. snprintf(match, sizeof(match), "%s-", device);
  266. if (!(chan = ast_channel_get_by_name_prefix(match, strlen(match)))) {
  267. return AST_DEVICE_UNKNOWN;
  268. }
  269. if (ast_channel_hold_state(chan) == AST_CONTROL_HOLD) {
  270. res = AST_DEVICE_ONHOLD;
  271. } else {
  272. res = ast_state_chan2dev(ast_channel_state(chan));
  273. }
  274. ast_channel_unref(chan);
  275. return res;
  276. }
  277. static enum ast_device_state devstate_cached(const char *device)
  278. {
  279. struct stasis_message *cached_msg;
  280. struct ast_device_state_message *device_state;
  281. enum ast_device_state state;
  282. cached_msg = stasis_cache_get_by_eid(ast_device_state_cache(),
  283. ast_device_state_message_type(), device, NULL);
  284. if (!cached_msg) {
  285. return AST_DEVICE_UNKNOWN;
  286. }
  287. device_state = stasis_message_data(cached_msg);
  288. state = device_state->state;
  289. ao2_cleanup(cached_msg);
  290. return state;
  291. }
  292. /*! \brief Check device state through channel specific function or generic function */
  293. static enum ast_device_state _ast_device_state(const char *device, int check_cache)
  294. {
  295. char *number;
  296. const struct ast_channel_tech *chan_tech;
  297. enum ast_device_state res;
  298. /*! \brief Channel driver that provides device state */
  299. char *tech;
  300. /* If the last known state is cached, just return that */
  301. if (check_cache) {
  302. res = devstate_cached(device);
  303. if (res != AST_DEVICE_UNKNOWN) {
  304. return res;
  305. }
  306. }
  307. number = ast_strdupa(device);
  308. tech = strsep(&number, "/");
  309. if (!number) {
  310. /*! \brief Another provider of device state */
  311. char *provider;
  312. provider = strsep(&tech, ":");
  313. if (!tech) {
  314. return AST_DEVICE_INVALID;
  315. }
  316. /* We have a provider */
  317. number = tech;
  318. ast_debug(3, "Checking if I can find provider for \"%s\" - number: %s\n", provider, number);
  319. return getproviderstate(provider, number);
  320. }
  321. ast_debug(4, "No provider found, checking channel drivers for %s - %s\n", tech, number);
  322. chan_tech = ast_get_channel_tech(tech);
  323. if (!chan_tech) {
  324. return AST_DEVICE_INVALID;
  325. }
  326. /* Does the channel driver support device state notification? */
  327. if (!chan_tech->devicestate) {
  328. /* No, try the generic function */
  329. return ast_parse_device_state(device);
  330. }
  331. res = chan_tech->devicestate(number);
  332. if (res == AST_DEVICE_UNKNOWN) {
  333. res = ast_parse_device_state(device);
  334. }
  335. return res;
  336. }
  337. enum ast_device_state ast_device_state(const char *device)
  338. {
  339. /* This function is called from elsewhere in the code to find out the
  340. * current state of a device. Check the cache, first. */
  341. return _ast_device_state(device, 1);
  342. }
  343. /*! \brief Add device state provider */
  344. int ast_devstate_prov_add(const char *label, ast_devstate_prov_cb_type callback)
  345. {
  346. struct devstate_prov *devcb;
  347. struct devstate_prov *devprov;
  348. if (!callback || !(devprov = ast_calloc(1, sizeof(*devprov))))
  349. return -1;
  350. devprov->callback = callback;
  351. ast_copy_string(devprov->label, label, sizeof(devprov->label));
  352. AST_RWLIST_WRLOCK(&devstate_provs);
  353. AST_RWLIST_TRAVERSE(&devstate_provs, devcb, list) {
  354. if (!strcasecmp(devcb->label, label)) {
  355. ast_log(LOG_WARNING, "Device state provider '%s' already registered\n", label);
  356. ast_free(devprov);
  357. AST_RWLIST_UNLOCK(&devstate_provs);
  358. return -1;
  359. }
  360. }
  361. AST_RWLIST_INSERT_HEAD(&devstate_provs, devprov, list);
  362. AST_RWLIST_UNLOCK(&devstate_provs);
  363. return 0;
  364. }
  365. /*! \brief Remove device state provider */
  366. int ast_devstate_prov_del(const char *label)
  367. {
  368. struct devstate_prov *devcb;
  369. int res = -1;
  370. AST_RWLIST_WRLOCK(&devstate_provs);
  371. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&devstate_provs, devcb, list) {
  372. if (!strcasecmp(devcb->label, label)) {
  373. AST_RWLIST_REMOVE_CURRENT(list);
  374. ast_free(devcb);
  375. res = 0;
  376. break;
  377. }
  378. }
  379. AST_RWLIST_TRAVERSE_SAFE_END;
  380. AST_RWLIST_UNLOCK(&devstate_provs);
  381. return res;
  382. }
  383. /*! \brief Get provider device state */
  384. static int getproviderstate(const char *provider, const char *address)
  385. {
  386. struct devstate_prov *devprov;
  387. int res = AST_DEVICE_INVALID;
  388. AST_RWLIST_RDLOCK(&devstate_provs);
  389. AST_RWLIST_TRAVERSE(&devstate_provs, devprov, list) {
  390. ast_debug(5, "Checking provider %s with %s\n", devprov->label, provider);
  391. if (!strcasecmp(devprov->label, provider)) {
  392. res = devprov->callback(address);
  393. break;
  394. }
  395. }
  396. AST_RWLIST_UNLOCK(&devstate_provs);
  397. return res;
  398. }
  399. /*! Called by the state change thread to find out what the state is, and then
  400. * to queue up the state change event */
  401. static void do_state_change(const char *device, enum ast_devstate_cache cachable)
  402. {
  403. enum ast_device_state state;
  404. state = _ast_device_state(device, 0);
  405. ast_debug(3, "Changing state for %s - state %u (%s)\n", device, state, ast_devstate2str(state));
  406. ast_publish_device_state(device, state, cachable);
  407. }
  408. int ast_devstate_changed_literal(enum ast_device_state state, enum ast_devstate_cache cachable, const char *device)
  409. {
  410. struct state_change *change;
  411. /*
  412. * If we know the state change (how nice of the caller of this function!)
  413. * then we can just generate a device state event.
  414. *
  415. * Otherwise, we do the following:
  416. * - Queue an event up to another thread that the state has changed
  417. * - In the processing thread, it calls the callback provided by the
  418. * device state provider (which may or may not be a channel driver)
  419. * to determine the state.
  420. * - If the device state provider does not know the state, or this is
  421. * for a channel and the channel driver does not implement a device
  422. * state callback, then we will look through the channel list to
  423. * see if we can determine a state based on active calls.
  424. * - Once a state has been determined, a device state event is generated.
  425. */
  426. if (state != AST_DEVICE_UNKNOWN) {
  427. ast_publish_device_state(device, state, cachable);
  428. } else if (change_thread == AST_PTHREADT_NULL || !(change = ast_calloc(1, sizeof(*change) + strlen(device)))) {
  429. /* we could not allocate a change struct, or */
  430. /* there is no background thread, so process the change now */
  431. do_state_change(device, cachable);
  432. } else {
  433. /* queue the change */
  434. strcpy(change->device, device);
  435. change->cachable = cachable;
  436. AST_LIST_LOCK(&state_changes);
  437. AST_LIST_INSERT_TAIL(&state_changes, change, list);
  438. ast_cond_signal(&change_pending);
  439. AST_LIST_UNLOCK(&state_changes);
  440. }
  441. return 0;
  442. }
  443. int ast_devstate_changed(enum ast_device_state state, enum ast_devstate_cache cachable, const char *fmt, ...)
  444. {
  445. char buf[AST_MAX_EXTENSION];
  446. va_list ap;
  447. va_start(ap, fmt);
  448. vsnprintf(buf, sizeof(buf), fmt, ap);
  449. va_end(ap);
  450. return ast_devstate_changed_literal(state, cachable, buf);
  451. }
  452. /*! \brief Go through the dev state change queue and update changes in the dev state thread */
  453. static void *do_devstate_changes(void *data)
  454. {
  455. struct state_change *next, *current;
  456. while (!shuttingdown) {
  457. /* This basically pops off any state change entries, resets the list back to NULL, unlocks, and processes each state change */
  458. AST_LIST_LOCK(&state_changes);
  459. if (AST_LIST_EMPTY(&state_changes))
  460. ast_cond_wait(&change_pending, &state_changes.lock);
  461. next = AST_LIST_FIRST(&state_changes);
  462. AST_LIST_HEAD_INIT_NOLOCK(&state_changes);
  463. AST_LIST_UNLOCK(&state_changes);
  464. /* Process each state change */
  465. while ((current = next)) {
  466. next = AST_LIST_NEXT(current, list);
  467. do_state_change(current->device, current->cachable);
  468. ast_free(current);
  469. }
  470. }
  471. return NULL;
  472. }
  473. static struct ast_device_state_message *device_state_alloc(const char *device, enum ast_device_state state, enum ast_devstate_cache cachable, const struct ast_eid *eid)
  474. {
  475. struct ast_device_state_message *new_device_state;
  476. char *pos;
  477. size_t stuff_len;
  478. ast_assert(!ast_strlen_zero(device));
  479. stuff_len = strlen(device) + 1;
  480. if (eid) {
  481. stuff_len += sizeof(*eid);
  482. }
  483. new_device_state = ao2_alloc_options(sizeof(*new_device_state) + stuff_len, NULL,
  484. AO2_ALLOC_OPT_LOCK_NOLOCK);
  485. if (!new_device_state) {
  486. return NULL;
  487. }
  488. if (eid) {
  489. /* non-aggregate device state. */
  490. new_device_state->stuff[0] = *eid;
  491. new_device_state->eid = &new_device_state->stuff[0];
  492. pos = (char *) &new_device_state->stuff[1];
  493. } else {
  494. pos = (char *) &new_device_state->stuff[0];
  495. }
  496. strcpy(pos, device);/* Safe */
  497. new_device_state->device = pos;
  498. new_device_state->state = state;
  499. new_device_state->cachable = cachable;
  500. return new_device_state;
  501. }
  502. static void devstate_change_cb(void *data, struct stasis_subscription *sub, struct stasis_message *msg)
  503. {
  504. struct ast_device_state_message *device_state;
  505. if (ast_device_state_message_type() != stasis_message_type(msg)) {
  506. return;
  507. }
  508. device_state = stasis_message_data(msg);
  509. if (device_state->cachable == AST_DEVSTATE_CACHABLE || !device_state->eid) {
  510. /* Ignore cacheable and aggregate messages. */
  511. return;
  512. }
  513. /*
  514. * Non-cacheable device state aggregates are just the
  515. * device state republished as the aggregate.
  516. */
  517. ast_publish_device_state_full(device_state->device, device_state->state,
  518. device_state->cachable, NULL);
  519. }
  520. static void device_state_engine_cleanup(void)
  521. {
  522. shuttingdown = 1;
  523. AST_LIST_LOCK(&state_changes);
  524. ast_cond_signal(&change_pending);
  525. AST_LIST_UNLOCK(&state_changes);
  526. if (change_thread != AST_PTHREADT_NULL) {
  527. pthread_join(change_thread, NULL);
  528. }
  529. }
  530. /*! \brief Initialize the device state engine in separate thread */
  531. int ast_device_state_engine_init(void)
  532. {
  533. ast_cond_init(&change_pending, NULL);
  534. if (ast_pthread_create_background(&change_thread, NULL, do_devstate_changes, NULL) < 0) {
  535. ast_log(LOG_ERROR, "Unable to start device state change thread.\n");
  536. return -1;
  537. }
  538. ast_register_cleanup(device_state_engine_cleanup);
  539. return 0;
  540. }
  541. void ast_devstate_aggregate_init(struct ast_devstate_aggregate *agg)
  542. {
  543. memset(agg, 0, sizeof(*agg));
  544. agg->state = AST_DEVICE_INVALID;
  545. }
  546. void ast_devstate_aggregate_add(struct ast_devstate_aggregate *agg, enum ast_device_state state)
  547. {
  548. static enum ast_device_state state_order[] = {
  549. 1, /* AST_DEVICE_UNKNOWN */
  550. 3, /* AST_DEVICE_NOT_INUSE */
  551. 6, /* AST_DEVICE_INUSE */
  552. 7, /* AST_DEVICE_BUSY */
  553. 0, /* AST_DEVICE_INVALID */
  554. 2, /* AST_DEVICE_UNAVAILABLE */
  555. 5, /* AST_DEVICE_RINGING */
  556. 8, /* AST_DEVICE_RINGINUSE */
  557. 4, /* AST_DEVICE_ONHOLD */
  558. };
  559. if (state == AST_DEVICE_RINGING) {
  560. agg->ringing = 1;
  561. } else if (state == AST_DEVICE_INUSE || state == AST_DEVICE_ONHOLD || state == AST_DEVICE_BUSY) {
  562. agg->inuse = 1;
  563. }
  564. if (agg->ringing && agg->inuse) {
  565. agg->state = AST_DEVICE_RINGINUSE;
  566. } else if (state_order[state] > state_order[agg->state]) {
  567. agg->state = state;
  568. }
  569. }
  570. enum ast_device_state ast_devstate_aggregate_result(struct ast_devstate_aggregate *agg)
  571. {
  572. return agg->state;
  573. }
  574. struct stasis_topic *ast_device_state_topic_all(void)
  575. {
  576. return device_state_topic_all;
  577. }
  578. struct stasis_cache *ast_device_state_cache(void)
  579. {
  580. return device_state_cache;
  581. }
  582. struct stasis_topic *ast_device_state_topic_cached(void)
  583. {
  584. return stasis_caching_get_topic(device_state_topic_cached);
  585. }
  586. struct stasis_topic *ast_device_state_topic(const char *device)
  587. {
  588. return stasis_topic_pool_get_topic(device_state_topic_pool, device);
  589. }
  590. int ast_device_state_clear_cache(const char *device)
  591. {
  592. struct stasis_message *cached_msg;
  593. struct stasis_message *msg;
  594. cached_msg = stasis_cache_get_by_eid(ast_device_state_cache(),
  595. ast_device_state_message_type(), device, &ast_eid_default);
  596. if (!cached_msg) {
  597. /* nothing to clear */
  598. return -1;
  599. }
  600. msg = stasis_cache_clear_create(cached_msg);
  601. if (msg) {
  602. stasis_publish(ast_device_state_topic(device), msg);
  603. }
  604. ao2_cleanup(msg);
  605. ao2_cleanup(cached_msg);
  606. return 0;
  607. }
  608. int ast_publish_device_state_full(
  609. const char *device,
  610. enum ast_device_state state,
  611. enum ast_devstate_cache cachable,
  612. struct ast_eid *eid)
  613. {
  614. RAII_VAR(struct ast_device_state_message *, device_state, NULL, ao2_cleanup);
  615. RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
  616. struct stasis_topic *topic;
  617. ast_assert(!ast_strlen_zero(device));
  618. if (!ast_device_state_message_type()) {
  619. return -1;
  620. }
  621. device_state = device_state_alloc(device, state, cachable, eid);
  622. if (!device_state) {
  623. return -1;
  624. }
  625. message = stasis_message_create_full(ast_device_state_message_type(), device_state,
  626. eid);
  627. if (!message) {
  628. return -1;
  629. }
  630. /* When a device state is to be cached it is likely that something
  631. * external will either be monitoring it or will want to pull the
  632. * information from the cache, so we always publish to the device
  633. * specific topic. Cachable updates traditionally come from such things
  634. * as a SIP or PJSIP device.
  635. * When a device state is not to be cached we only publish to its
  636. * specific topic if something has already created the topic. Publishing
  637. * to its topic otherwise would create the topic, which may not be
  638. * necessary as it could be an ephemeral device. Uncachable updates
  639. * traditionally come from such things as Local channels.
  640. */
  641. if (cachable || stasis_topic_pool_topic_exists(device_state_topic_pool, device)) {
  642. topic = ast_device_state_topic(device);
  643. } else {
  644. topic = ast_device_state_topic_all();
  645. }
  646. if (!topic) {
  647. return -1;
  648. }
  649. stasis_publish(topic, message);
  650. return 0;
  651. }
  652. static const char *device_state_get_id(struct stasis_message *message)
  653. {
  654. struct ast_device_state_message *device_state;
  655. if (ast_device_state_message_type() != stasis_message_type(message)) {
  656. return NULL;
  657. }
  658. device_state = stasis_message_data(message);
  659. if (device_state->cachable == AST_DEVSTATE_NOT_CACHABLE) {
  660. return NULL;
  661. }
  662. return device_state->device;
  663. }
  664. /*!
  665. * \internal
  666. * \brief Callback to publish the aggregate device state cache entry message.
  667. * \since 12.2.0
  668. *
  669. * \param cache_topic Caching topic the aggregate message may be published over.
  670. * \param aggregate The aggregate shapshot message to publish.
  671. */
  672. static void device_state_aggregate_publish(struct stasis_topic *cache_topic, struct stasis_message *aggregate)
  673. {
  674. const char *device;
  675. struct stasis_topic *device_specific_topic;
  676. device = device_state_get_id(aggregate);
  677. if (!device) {
  678. return;
  679. }
  680. device_specific_topic = ast_device_state_topic(device);
  681. if (!device_specific_topic) {
  682. return;
  683. }
  684. stasis_publish(device_specific_topic, aggregate);
  685. }
  686. /*!
  687. * \internal
  688. * \brief Callback to calculate the aggregate device state cache entry.
  689. * \since 12.2.0
  690. *
  691. * \param entry Cache entry to calculate a new aggregate snapshot.
  692. * \param new_snapshot The shapshot that is being updated.
  693. *
  694. * \note Return a ref bumped pointer from stasis_cache_entry_get_aggregate()
  695. * if a new aggregate could not be calculated because of error.
  696. *
  697. * \return New aggregate-snapshot calculated on success.
  698. * Caller has a reference on return.
  699. */
  700. static struct stasis_message *device_state_aggregate_calc(struct stasis_cache_entry *entry, struct stasis_message *new_snapshot)
  701. {
  702. struct stasis_message *aggregate_snapshot;
  703. struct stasis_message *snapshot;
  704. struct ast_device_state_message *device_state;
  705. const char *device = NULL;
  706. struct ast_devstate_aggregate aggregate;
  707. int idx;
  708. if (!ast_device_state_message_type()) {
  709. return NULL;
  710. }
  711. /* Determine the new aggregate device state. */
  712. ast_devstate_aggregate_init(&aggregate);
  713. snapshot = stasis_cache_entry_get_local(entry);
  714. if (snapshot) {
  715. device_state = stasis_message_data(snapshot);
  716. device = device_state->device;
  717. ast_devstate_aggregate_add(&aggregate, device_state->state);
  718. }
  719. for (idx = 0; ; ++idx) {
  720. snapshot = stasis_cache_entry_get_remote(entry, idx);
  721. if (!snapshot) {
  722. break;
  723. }
  724. device_state = stasis_message_data(snapshot);
  725. device = device_state->device;
  726. ast_devstate_aggregate_add(&aggregate, device_state->state);
  727. }
  728. if (!device) {
  729. /* There are no device states cached. Delete the aggregate. */
  730. return NULL;
  731. }
  732. snapshot = stasis_cache_entry_get_aggregate(entry);
  733. if (snapshot) {
  734. device_state = stasis_message_data(snapshot);
  735. if (device_state->state == ast_devstate_aggregate_result(&aggregate)) {
  736. /* Aggregate device state did not change. */
  737. return ao2_bump(snapshot);
  738. }
  739. }
  740. device_state = device_state_alloc(device, ast_devstate_aggregate_result(&aggregate),
  741. AST_DEVSTATE_CACHABLE, NULL);
  742. if (!device_state) {
  743. /* Bummer. We have to keep the old aggregate snapshot. */
  744. return ao2_bump(snapshot);
  745. }
  746. aggregate_snapshot = stasis_message_create_full(ast_device_state_message_type(),
  747. device_state, NULL);
  748. ao2_cleanup(device_state);
  749. if (!aggregate_snapshot) {
  750. /* Bummer. We have to keep the old aggregate snapshot. */
  751. return ao2_bump(snapshot);
  752. }
  753. return aggregate_snapshot;
  754. }
  755. static void devstate_cleanup(void)
  756. {
  757. devstate_message_sub = stasis_unsubscribe_and_join(devstate_message_sub);
  758. device_state_topic_cached = stasis_caching_unsubscribe_and_join(device_state_topic_cached);
  759. ao2_cleanup(device_state_cache);
  760. device_state_cache = NULL;
  761. ao2_cleanup(device_state_topic_pool);
  762. device_state_topic_pool = NULL;
  763. ao2_cleanup(device_state_topic_all);
  764. device_state_topic_all = NULL;
  765. STASIS_MESSAGE_TYPE_CLEANUP(ast_device_state_message_type);
  766. }
  767. int devstate_init(void)
  768. {
  769. ast_register_cleanup(devstate_cleanup);
  770. if (STASIS_MESSAGE_TYPE_INIT(ast_device_state_message_type) != 0) {
  771. return -1;
  772. }
  773. device_state_topic_all = stasis_topic_create("devicestate:all");
  774. if (!device_state_topic_all) {
  775. return -1;
  776. }
  777. device_state_topic_pool = stasis_topic_pool_create(ast_device_state_topic_all());
  778. if (!device_state_topic_pool) {
  779. return -1;
  780. }
  781. device_state_cache = stasis_cache_create_full(device_state_get_id,
  782. device_state_aggregate_calc, device_state_aggregate_publish);
  783. if (!device_state_cache) {
  784. return -1;
  785. }
  786. device_state_topic_cached = stasis_caching_topic_create(ast_device_state_topic_all(),
  787. device_state_cache);
  788. if (!device_state_topic_cached) {
  789. return -1;
  790. }
  791. stasis_caching_accept_message_type(device_state_topic_cached, ast_device_state_message_type());
  792. stasis_caching_set_filter(device_state_topic_cached, STASIS_SUBSCRIPTION_FILTER_SELECTIVE);
  793. devstate_message_sub = stasis_subscribe(ast_device_state_topic_all(),
  794. devstate_change_cb, NULL);
  795. if (!devstate_message_sub) {
  796. ast_log(LOG_ERROR, "Failed to create subscription creating uncached device state aggregate events.\n");
  797. return -1;
  798. }
  799. stasis_subscription_accept_message_type(devstate_message_sub, ast_device_state_message_type());
  800. stasis_subscription_set_filter(devstate_message_sub, STASIS_SUBSCRIPTION_FILTER_SELECTIVE);
  801. return 0;
  802. }
  803. static struct ast_manager_event_blob *devstate_to_ami(struct stasis_message *msg)
  804. {
  805. struct ast_device_state_message *dev_state;
  806. dev_state = stasis_message_data(msg);
  807. /* Ignore non-aggregate states */
  808. if (dev_state->eid) {
  809. return NULL;
  810. }
  811. return ast_manager_event_blob_create(EVENT_FLAG_CALL, "DeviceStateChange",
  812. "Device: %s\r\n"
  813. "State: %s\r\n",
  814. dev_state->device, ast_devstate_str(dev_state->state));
  815. }
  816. /*! \brief Convert a \ref stasis_message to a \ref ast_event */
  817. static struct ast_event *devstate_to_event(struct stasis_message *message)
  818. {
  819. struct ast_event *event;
  820. struct ast_device_state_message *device_state;
  821. if (!message) {
  822. return NULL;
  823. }
  824. device_state = stasis_message_data(message);
  825. if (device_state->eid) {
  826. event = ast_event_new(AST_EVENT_DEVICE_STATE_CHANGE,
  827. AST_EVENT_IE_DEVICE, AST_EVENT_IE_PLTYPE_STR, device_state->device,
  828. AST_EVENT_IE_STATE, AST_EVENT_IE_PLTYPE_UINT, device_state->state,
  829. AST_EVENT_IE_CACHABLE, AST_EVENT_IE_PLTYPE_UINT, device_state->cachable,
  830. AST_EVENT_IE_EID, AST_EVENT_IE_PLTYPE_RAW, device_state->eid, sizeof(*device_state->eid),
  831. AST_EVENT_IE_END);
  832. } else {
  833. event = ast_event_new(AST_EVENT_DEVICE_STATE,
  834. AST_EVENT_IE_DEVICE, AST_EVENT_IE_PLTYPE_STR, device_state->device,
  835. AST_EVENT_IE_STATE, AST_EVENT_IE_PLTYPE_UINT, device_state->state,
  836. AST_EVENT_IE_CACHABLE, AST_EVENT_IE_PLTYPE_UINT, device_state->cachable,
  837. AST_EVENT_IE_END);
  838. }
  839. return event;
  840. }