devicestate.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  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 AstENUM ast_extension_states
  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. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  141. #include "asterisk/_private.h"
  142. #include "asterisk/channel.h"
  143. #include "asterisk/utils.h"
  144. #include "asterisk/lock.h"
  145. #include "asterisk/linkedlists.h"
  146. #include "asterisk/devicestate.h"
  147. #include "asterisk/pbx.h"
  148. #include "asterisk/app.h"
  149. #include "asterisk/astobj2.h"
  150. #include "asterisk/stasis.h"
  151. #include "asterisk/devicestate.h"
  152. #define DEVSTATE_TOPIC_BUCKETS 57
  153. /*! \brief Device state strings for printing */
  154. static const char * const devstatestring[][2] = {
  155. { /* 0 AST_DEVICE_UNKNOWN */ "Unknown", "UNKNOWN" }, /*!< Valid, but unknown state */
  156. { /* 1 AST_DEVICE_NOT_INUSE */ "Not in use", "NOT_INUSE" }, /*!< Not used */
  157. { /* 2 AST_DEVICE IN USE */ "In use", "INUSE" }, /*!< In use */
  158. { /* 3 AST_DEVICE_BUSY */ "Busy", "BUSY" }, /*!< Busy */
  159. { /* 4 AST_DEVICE_INVALID */ "Invalid", "INVALID" }, /*!< Invalid - not known to Asterisk */
  160. { /* 5 AST_DEVICE_UNAVAILABLE */ "Unavailable", "UNAVAILABLE" }, /*!< Unavailable (not registered) */
  161. { /* 6 AST_DEVICE_RINGING */ "Ringing", "RINGING" }, /*!< Ring, ring, ring */
  162. { /* 7 AST_DEVICE_RINGINUSE */ "Ring+Inuse", "RINGINUSE" }, /*!< Ring and in use */
  163. { /* 8 AST_DEVICE_ONHOLD */ "On Hold", "ONHOLD" }, /*!< On Hold */
  164. };
  165. /*!\brief Mapping for channel states to device states */
  166. static const struct chan2dev {
  167. enum ast_channel_state chan;
  168. enum ast_device_state dev;
  169. } chan2dev[] = {
  170. { AST_STATE_DOWN, AST_DEVICE_NOT_INUSE },
  171. { AST_STATE_RESERVED, AST_DEVICE_INUSE },
  172. { AST_STATE_OFFHOOK, AST_DEVICE_INUSE },
  173. { AST_STATE_DIALING, AST_DEVICE_INUSE },
  174. { AST_STATE_RING, AST_DEVICE_INUSE },
  175. { AST_STATE_RINGING, AST_DEVICE_RINGING },
  176. { AST_STATE_UP, AST_DEVICE_INUSE },
  177. { AST_STATE_BUSY, AST_DEVICE_BUSY },
  178. { AST_STATE_DIALING_OFFHOOK, AST_DEVICE_INUSE },
  179. { AST_STATE_PRERING, AST_DEVICE_RINGING },
  180. };
  181. /*! \brief A device state provider (not a channel) */
  182. struct devstate_prov {
  183. char label[40];
  184. ast_devstate_prov_cb_type callback;
  185. AST_RWLIST_ENTRY(devstate_prov) list;
  186. };
  187. /*! \brief A list of providers */
  188. static AST_RWLIST_HEAD_STATIC(devstate_provs, devstate_prov);
  189. struct state_change {
  190. AST_LIST_ENTRY(state_change) list;
  191. enum ast_devstate_cache cachable;
  192. char device[1];
  193. };
  194. /*! \brief The state change queue. State changes are queued
  195. for processing by a separate thread */
  196. static AST_LIST_HEAD_STATIC(state_changes, state_change);
  197. /*! \brief The device state change notification thread */
  198. static pthread_t change_thread = AST_PTHREADT_NULL;
  199. /*! \brief Flag for the queue */
  200. static ast_cond_t change_pending;
  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. /* Deprecated interface (not prefixed with ast_) */
  220. const char *devstate2str(enum ast_device_state devstate)
  221. {
  222. return devstatestring[devstate][0];
  223. }
  224. enum ast_device_state ast_state_chan2dev(enum ast_channel_state chanstate)
  225. {
  226. int i;
  227. chanstate &= 0xFFFF;
  228. for (i = 0; i < ARRAY_LEN(chan2dev); i++) {
  229. if (chan2dev[i].chan == chanstate) {
  230. return chan2dev[i].dev;
  231. }
  232. }
  233. return AST_DEVICE_UNKNOWN;
  234. }
  235. /* Parseable */
  236. const char *ast_devstate_str(enum ast_device_state state)
  237. {
  238. return devstatestring[state][1];
  239. }
  240. enum ast_device_state ast_devstate_val(const char *val)
  241. {
  242. if (!strcasecmp(val, "NOT_INUSE"))
  243. return AST_DEVICE_NOT_INUSE;
  244. else if (!strcasecmp(val, "INUSE"))
  245. return AST_DEVICE_INUSE;
  246. else if (!strcasecmp(val, "BUSY"))
  247. return AST_DEVICE_BUSY;
  248. else if (!strcasecmp(val, "INVALID"))
  249. return AST_DEVICE_INVALID;
  250. else if (!strcasecmp(val, "UNAVAILABLE"))
  251. return AST_DEVICE_UNAVAILABLE;
  252. else if (!strcasecmp(val, "RINGING"))
  253. return AST_DEVICE_RINGING;
  254. else if (!strcasecmp(val, "RINGINUSE"))
  255. return AST_DEVICE_RINGINUSE;
  256. else if (!strcasecmp(val, "ONHOLD"))
  257. return AST_DEVICE_ONHOLD;
  258. return AST_DEVICE_UNKNOWN;
  259. }
  260. /*! \brief Find out if device is active in a call or not
  261. \note find channels with the device's name in it
  262. This function is only used for channels that does not implement
  263. devicestate natively
  264. */
  265. enum ast_device_state ast_parse_device_state(const char *device)
  266. {
  267. struct ast_channel *chan;
  268. char match[AST_CHANNEL_NAME];
  269. enum ast_device_state res;
  270. snprintf(match, sizeof(match), "%s-", device);
  271. if (!(chan = ast_channel_get_by_name_prefix(match, strlen(match)))) {
  272. return AST_DEVICE_UNKNOWN;
  273. }
  274. if (ast_channel_hold_state(chan) == AST_CONTROL_HOLD) {
  275. res = AST_DEVICE_ONHOLD;
  276. } else {
  277. res = ast_state_chan2dev(ast_channel_state(chan));
  278. }
  279. ast_channel_unref(chan);
  280. return res;
  281. }
  282. static enum ast_device_state devstate_cached(const char *device)
  283. {
  284. struct stasis_message *cached_msg;
  285. struct ast_device_state_message *device_state;
  286. enum ast_device_state state;
  287. cached_msg = stasis_cache_get_by_eid(ast_device_state_cache(),
  288. ast_device_state_message_type(), device, NULL);
  289. if (!cached_msg) {
  290. return AST_DEVICE_UNKNOWN;
  291. }
  292. device_state = stasis_message_data(cached_msg);
  293. state = device_state->state;
  294. ao2_cleanup(cached_msg);
  295. return state;
  296. }
  297. /*! \brief Check device state through channel specific function or generic function */
  298. static enum ast_device_state _ast_device_state(const char *device, int check_cache)
  299. {
  300. char *number;
  301. const struct ast_channel_tech *chan_tech;
  302. enum ast_device_state res;
  303. /*! \brief Channel driver that provides device state */
  304. char *tech;
  305. /* If the last known state is cached, just return that */
  306. if (check_cache) {
  307. res = devstate_cached(device);
  308. if (res != AST_DEVICE_UNKNOWN) {
  309. return res;
  310. }
  311. }
  312. number = ast_strdupa(device);
  313. tech = strsep(&number, "/");
  314. if (!number) {
  315. /*! \brief Another provider of device state */
  316. char *provider;
  317. provider = strsep(&tech, ":");
  318. if (!tech) {
  319. return AST_DEVICE_INVALID;
  320. }
  321. /* We have a provider */
  322. number = tech;
  323. ast_debug(3, "Checking if I can find provider for \"%s\" - number: %s\n", provider, number);
  324. return getproviderstate(provider, number);
  325. }
  326. ast_debug(4, "No provider found, checking channel drivers for %s - %s\n", tech, number);
  327. chan_tech = ast_get_channel_tech(tech);
  328. if (!chan_tech) {
  329. return AST_DEVICE_INVALID;
  330. }
  331. /* Does the channel driver support device state notification? */
  332. if (!chan_tech->devicestate) {
  333. /* No, try the generic function */
  334. return ast_parse_device_state(device);
  335. }
  336. res = chan_tech->devicestate(number);
  337. if (res == AST_DEVICE_UNKNOWN) {
  338. res = ast_parse_device_state(device);
  339. }
  340. return res;
  341. }
  342. enum ast_device_state ast_device_state(const char *device)
  343. {
  344. /* This function is called from elsewhere in the code to find out the
  345. * current state of a device. Check the cache, first. */
  346. return _ast_device_state(device, 1);
  347. }
  348. /*! \brief Add device state provider */
  349. int ast_devstate_prov_add(const char *label, ast_devstate_prov_cb_type callback)
  350. {
  351. struct devstate_prov *devprov;
  352. if (!callback || !(devprov = ast_calloc(1, sizeof(*devprov))))
  353. return -1;
  354. devprov->callback = callback;
  355. ast_copy_string(devprov->label, label, sizeof(devprov->label));
  356. AST_RWLIST_WRLOCK(&devstate_provs);
  357. AST_RWLIST_INSERT_HEAD(&devstate_provs, devprov, list);
  358. AST_RWLIST_UNLOCK(&devstate_provs);
  359. return 0;
  360. }
  361. /*! \brief Remove device state provider */
  362. int ast_devstate_prov_del(const char *label)
  363. {
  364. struct devstate_prov *devcb;
  365. int res = -1;
  366. AST_RWLIST_WRLOCK(&devstate_provs);
  367. AST_RWLIST_TRAVERSE_SAFE_BEGIN(&devstate_provs, devcb, list) {
  368. if (!strcasecmp(devcb->label, label)) {
  369. AST_RWLIST_REMOVE_CURRENT(list);
  370. ast_free(devcb);
  371. res = 0;
  372. break;
  373. }
  374. }
  375. AST_RWLIST_TRAVERSE_SAFE_END;
  376. AST_RWLIST_UNLOCK(&devstate_provs);
  377. return res;
  378. }
  379. /*! \brief Get provider device state */
  380. static int getproviderstate(const char *provider, const char *address)
  381. {
  382. struct devstate_prov *devprov;
  383. int res = AST_DEVICE_INVALID;
  384. AST_RWLIST_RDLOCK(&devstate_provs);
  385. AST_RWLIST_TRAVERSE(&devstate_provs, devprov, list) {
  386. ast_debug(5, "Checking provider %s with %s\n", devprov->label, provider);
  387. if (!strcasecmp(devprov->label, provider)) {
  388. res = devprov->callback(address);
  389. break;
  390. }
  391. }
  392. AST_RWLIST_UNLOCK(&devstate_provs);
  393. return res;
  394. }
  395. /*! Called by the state change thread to find out what the state is, and then
  396. * to queue up the state change event */
  397. static void do_state_change(const char *device, enum ast_devstate_cache cachable)
  398. {
  399. enum ast_device_state state;
  400. state = _ast_device_state(device, 0);
  401. ast_debug(3, "Changing state for %s - state %u (%s)\n", device, state, ast_devstate2str(state));
  402. ast_publish_device_state(device, state, cachable);
  403. }
  404. int ast_devstate_changed_literal(enum ast_device_state state, enum ast_devstate_cache cachable, const char *device)
  405. {
  406. struct state_change *change;
  407. /*
  408. * If we know the state change (how nice of the caller of this function!)
  409. * then we can just generate a device state event.
  410. *
  411. * Otherwise, we do the following:
  412. * - Queue an event up to another thread that the state has changed
  413. * - In the processing thread, it calls the callback provided by the
  414. * device state provider (which may or may not be a channel driver)
  415. * to determine the state.
  416. * - If the device state provider does not know the state, or this is
  417. * for a channel and the channel driver does not implement a device
  418. * state callback, then we will look through the channel list to
  419. * see if we can determine a state based on active calls.
  420. * - Once a state has been determined, a device state event is generated.
  421. */
  422. if (state != AST_DEVICE_UNKNOWN) {
  423. ast_publish_device_state(device, state, cachable);
  424. } else if (change_thread == AST_PTHREADT_NULL || !(change = ast_calloc(1, sizeof(*change) + strlen(device)))) {
  425. /* we could not allocate a change struct, or */
  426. /* there is no background thread, so process the change now */
  427. do_state_change(device, cachable);
  428. } else {
  429. /* queue the change */
  430. strcpy(change->device, device);
  431. change->cachable = cachable;
  432. AST_LIST_LOCK(&state_changes);
  433. AST_LIST_INSERT_TAIL(&state_changes, change, list);
  434. ast_cond_signal(&change_pending);
  435. AST_LIST_UNLOCK(&state_changes);
  436. }
  437. return 0;
  438. }
  439. int ast_device_state_changed_literal(const char *dev)
  440. {
  441. return ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, dev);
  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. int ast_device_state_changed(const char *fmt, ...)
  453. {
  454. char buf[AST_MAX_EXTENSION];
  455. va_list ap;
  456. va_start(ap, fmt);
  457. vsnprintf(buf, sizeof(buf), fmt, ap);
  458. va_end(ap);
  459. return ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, buf);
  460. }
  461. /*! \brief Go through the dev state change queue and update changes in the dev state thread */
  462. static void *do_devstate_changes(void *data)
  463. {
  464. struct state_change *next, *current;
  465. for (;;) {
  466. /* This basically pops off any state change entries, resets the list back to NULL, unlocks, and processes each state change */
  467. AST_LIST_LOCK(&state_changes);
  468. if (AST_LIST_EMPTY(&state_changes))
  469. ast_cond_wait(&change_pending, &state_changes.lock);
  470. next = AST_LIST_FIRST(&state_changes);
  471. AST_LIST_HEAD_INIT_NOLOCK(&state_changes);
  472. AST_LIST_UNLOCK(&state_changes);
  473. /* Process each state change */
  474. while ((current = next)) {
  475. next = AST_LIST_NEXT(current, list);
  476. do_state_change(current->device, current->cachable);
  477. ast_free(current);
  478. }
  479. }
  480. return NULL;
  481. }
  482. 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)
  483. {
  484. struct ast_device_state_message *new_device_state;
  485. char *pos;
  486. size_t stuff_len;
  487. ast_assert(!ast_strlen_zero(device));
  488. stuff_len = strlen(device) + 1;
  489. if (eid) {
  490. stuff_len += sizeof(*eid);
  491. }
  492. new_device_state = ao2_alloc_options(sizeof(*new_device_state) + stuff_len, NULL,
  493. AO2_ALLOC_OPT_LOCK_NOLOCK);
  494. if (!new_device_state) {
  495. return NULL;
  496. }
  497. if (eid) {
  498. /* non-aggregate device state. */
  499. new_device_state->stuff[0] = *eid;
  500. new_device_state->eid = &new_device_state->stuff[0];
  501. pos = (char *) &new_device_state->stuff[1];
  502. } else {
  503. pos = (char *) &new_device_state->stuff[0];
  504. }
  505. strcpy(pos, device);/* Safe */
  506. new_device_state->device = pos;
  507. new_device_state->state = state;
  508. new_device_state->cachable = cachable;
  509. return new_device_state;
  510. }
  511. static void devstate_change_cb(void *data, struct stasis_subscription *sub, struct stasis_message *msg)
  512. {
  513. struct ast_device_state_message *device_state;
  514. if (ast_device_state_message_type() != stasis_message_type(msg)) {
  515. return;
  516. }
  517. device_state = stasis_message_data(msg);
  518. if (device_state->cachable == AST_DEVSTATE_CACHABLE || !device_state->eid) {
  519. /* Ignore cacheable and aggregate messages. */
  520. return;
  521. }
  522. /*
  523. * Non-cacheable device state aggregates are just the
  524. * device state republished as the aggregate.
  525. */
  526. ast_publish_device_state_full(device_state->device, device_state->state,
  527. device_state->cachable, NULL);
  528. }
  529. /*! \brief Initialize the device state engine in separate thread */
  530. int ast_device_state_engine_init(void)
  531. {
  532. ast_cond_init(&change_pending, NULL);
  533. if (ast_pthread_create_background(&change_thread, NULL, do_devstate_changes, NULL) < 0) {
  534. ast_log(LOG_ERROR, "Unable to start device state change thread.\n");
  535. return -1;
  536. }
  537. return 0;
  538. }
  539. void ast_devstate_aggregate_init(struct ast_devstate_aggregate *agg)
  540. {
  541. memset(agg, 0, sizeof(*agg));
  542. agg->state = AST_DEVICE_INVALID;
  543. }
  544. void ast_devstate_aggregate_add(struct ast_devstate_aggregate *agg, enum ast_device_state state)
  545. {
  546. static enum ast_device_state state_order[] = {
  547. 1, /* AST_DEVICE_UNKNOWN */
  548. 3, /* AST_DEVICE_NOT_INUSE */
  549. 6, /* AST_DEVICE_INUSE */
  550. 7, /* AST_DEVICE_BUSY */
  551. 0, /* AST_DEVICE_INVALID */
  552. 2, /* AST_DEVICE_UNAVAILABLE */
  553. 5, /* AST_DEVICE_RINGING */
  554. 8, /* AST_DEVICE_RINGINUSE */
  555. 4, /* AST_DEVICE_ONHOLD */
  556. };
  557. if (state == AST_DEVICE_RINGING) {
  558. agg->ringing = 1;
  559. } else if (state == AST_DEVICE_INUSE || state == AST_DEVICE_ONHOLD || state == AST_DEVICE_BUSY) {
  560. agg->inuse = 1;
  561. }
  562. if (agg->ringing && agg->inuse) {
  563. agg->state = AST_DEVICE_RINGINUSE;
  564. } else if (state_order[state] > state_order[agg->state]) {
  565. agg->state = state;
  566. }
  567. }
  568. enum ast_device_state ast_devstate_aggregate_result(struct ast_devstate_aggregate *agg)
  569. {
  570. return agg->state;
  571. }
  572. struct stasis_topic *ast_device_state_topic_all(void)
  573. {
  574. return device_state_topic_all;
  575. }
  576. struct stasis_cache *ast_device_state_cache(void)
  577. {
  578. return device_state_cache;
  579. }
  580. struct stasis_topic *ast_device_state_topic_cached(void)
  581. {
  582. return stasis_caching_get_topic(device_state_topic_cached);
  583. }
  584. struct stasis_topic *ast_device_state_topic(const char *device)
  585. {
  586. return stasis_topic_pool_get_topic(device_state_topic_pool, device);
  587. }
  588. int ast_device_state_clear_cache(const char *device)
  589. {
  590. struct stasis_message *cached_msg;
  591. struct stasis_message *msg;
  592. cached_msg = stasis_cache_get_by_eid(ast_device_state_cache(),
  593. ast_device_state_message_type(), device, &ast_eid_default);
  594. if (!cached_msg) {
  595. /* nothing to clear */
  596. return -1;
  597. }
  598. msg = stasis_cache_clear_create(cached_msg);
  599. if (msg) {
  600. stasis_publish(ast_device_state_topic(device), msg);
  601. }
  602. ao2_cleanup(msg);
  603. ao2_cleanup(cached_msg);
  604. return 0;
  605. }
  606. int ast_publish_device_state_full(
  607. const char *device,
  608. enum ast_device_state state,
  609. enum ast_devstate_cache cachable,
  610. struct ast_eid *eid)
  611. {
  612. RAII_VAR(struct ast_device_state_message *, device_state, NULL, ao2_cleanup);
  613. RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
  614. struct stasis_topic *device_specific_topic;
  615. ast_assert(!ast_strlen_zero(device));
  616. if (!ast_device_state_message_type()) {
  617. return -1;
  618. }
  619. device_state = device_state_alloc(device, state, cachable, eid);
  620. if (!device_state) {
  621. return -1;
  622. }
  623. message = stasis_message_create_full(ast_device_state_message_type(), device_state,
  624. eid);
  625. if (!message) {
  626. return -1;
  627. }
  628. device_specific_topic = ast_device_state_topic(device);
  629. if (!device_specific_topic) {
  630. return -1;
  631. }
  632. stasis_publish(device_specific_topic, message);
  633. return 0;
  634. }
  635. static const char *device_state_get_id(struct stasis_message *message)
  636. {
  637. struct ast_device_state_message *device_state;
  638. if (ast_device_state_message_type() != stasis_message_type(message)) {
  639. return NULL;
  640. }
  641. device_state = stasis_message_data(message);
  642. if (device_state->cachable == AST_DEVSTATE_NOT_CACHABLE) {
  643. return NULL;
  644. }
  645. return device_state->device;
  646. }
  647. /*!
  648. * \internal
  649. * \brief Callback to publish the aggregate device state cache entry message.
  650. * \since 12.2.0
  651. *
  652. * \param cache_topic Caching topic the aggregate message may be published over.
  653. * \param aggregate The aggregate shapshot message to publish.
  654. *
  655. * \return Nothing
  656. */
  657. static void device_state_aggregate_publish(struct stasis_topic *cache_topic, struct stasis_message *aggregate)
  658. {
  659. const char *device;
  660. struct stasis_topic *device_specific_topic;
  661. device = device_state_get_id(aggregate);
  662. if (!device) {
  663. return;
  664. }
  665. device_specific_topic = ast_device_state_topic(device);
  666. if (!device_specific_topic) {
  667. return;
  668. }
  669. stasis_publish(device_specific_topic, aggregate);
  670. }
  671. /*!
  672. * \internal
  673. * \brief Callback to calculate the aggregate device state cache entry.
  674. * \since 12.2.0
  675. *
  676. * \param entry Cache entry to calculate a new aggregate snapshot.
  677. * \param new_snapshot The shapshot that is being updated.
  678. *
  679. * \note Return a ref bumped pointer from stasis_cache_entry_get_aggregate()
  680. * if a new aggregate could not be calculated because of error.
  681. *
  682. * \return New aggregate-snapshot calculated on success.
  683. * Caller has a reference on return.
  684. */
  685. static struct stasis_message *device_state_aggregate_calc(struct stasis_cache_entry *entry, struct stasis_message *new_snapshot)
  686. {
  687. struct stasis_message *aggregate_snapshot;
  688. struct stasis_message *snapshot;
  689. struct ast_device_state_message *device_state;
  690. const char *device = NULL;
  691. struct ast_devstate_aggregate aggregate;
  692. int idx;
  693. if (!ast_device_state_message_type()) {
  694. return NULL;
  695. }
  696. /* Determine the new aggregate device state. */
  697. ast_devstate_aggregate_init(&aggregate);
  698. snapshot = stasis_cache_entry_get_local(entry);
  699. if (snapshot) {
  700. device_state = stasis_message_data(snapshot);
  701. device = device_state->device;
  702. ast_devstate_aggregate_add(&aggregate, device_state->state);
  703. }
  704. for (idx = 0; ; ++idx) {
  705. snapshot = stasis_cache_entry_get_remote(entry, idx);
  706. if (!snapshot) {
  707. break;
  708. }
  709. device_state = stasis_message_data(snapshot);
  710. device = device_state->device;
  711. ast_devstate_aggregate_add(&aggregate, device_state->state);
  712. }
  713. if (!device) {
  714. /* There are no device states cached. Delete the aggregate. */
  715. return NULL;
  716. }
  717. snapshot = stasis_cache_entry_get_aggregate(entry);
  718. if (snapshot) {
  719. device_state = stasis_message_data(snapshot);
  720. if (device_state->state == ast_devstate_aggregate_result(&aggregate)) {
  721. /* Aggregate device state did not change. */
  722. return ao2_bump(snapshot);
  723. }
  724. }
  725. device_state = device_state_alloc(device, ast_devstate_aggregate_result(&aggregate),
  726. AST_DEVSTATE_CACHABLE, NULL);
  727. if (!device_state) {
  728. /* Bummer. We have to keep the old aggregate snapshot. */
  729. return ao2_bump(snapshot);
  730. }
  731. aggregate_snapshot = stasis_message_create_full(ast_device_state_message_type(),
  732. device_state, NULL);
  733. ao2_cleanup(device_state);
  734. if (!aggregate_snapshot) {
  735. /* Bummer. We have to keep the old aggregate snapshot. */
  736. return ao2_bump(snapshot);
  737. }
  738. return aggregate_snapshot;
  739. }
  740. static void devstate_cleanup(void)
  741. {
  742. devstate_message_sub = stasis_unsubscribe_and_join(devstate_message_sub);
  743. device_state_topic_cached = stasis_caching_unsubscribe_and_join(device_state_topic_cached);
  744. ao2_cleanup(device_state_cache);
  745. device_state_cache = NULL;
  746. ao2_cleanup(device_state_topic_pool);
  747. device_state_topic_pool = NULL;
  748. ao2_cleanup(device_state_topic_all);
  749. device_state_topic_all = NULL;
  750. STASIS_MESSAGE_TYPE_CLEANUP(ast_device_state_message_type);
  751. }
  752. int devstate_init(void)
  753. {
  754. ast_register_cleanup(devstate_cleanup);
  755. if (STASIS_MESSAGE_TYPE_INIT(ast_device_state_message_type) != 0) {
  756. return -1;
  757. }
  758. device_state_topic_all = stasis_topic_create("ast_device_state_topic");
  759. if (!device_state_topic_all) {
  760. devstate_cleanup();
  761. return -1;
  762. }
  763. device_state_topic_pool = stasis_topic_pool_create(ast_device_state_topic_all());
  764. if (!device_state_topic_pool) {
  765. devstate_cleanup();
  766. return -1;
  767. }
  768. device_state_cache = stasis_cache_create_full(device_state_get_id,
  769. device_state_aggregate_calc, device_state_aggregate_publish);
  770. if (!device_state_cache) {
  771. devstate_cleanup();
  772. return -1;
  773. }
  774. device_state_topic_cached = stasis_caching_topic_create(ast_device_state_topic_all(),
  775. device_state_cache);
  776. if (!device_state_topic_cached) {
  777. devstate_cleanup();
  778. return -1;
  779. }
  780. devstate_message_sub = stasis_subscribe(ast_device_state_topic_all(),
  781. devstate_change_cb, NULL);
  782. if (!devstate_message_sub) {
  783. ast_log(LOG_ERROR, "Failed to create subscription creating uncached device state aggregate events.\n");
  784. devstate_cleanup();
  785. return -1;
  786. }
  787. return 0;
  788. }
  789. static struct ast_manager_event_blob *devstate_to_ami(struct stasis_message *msg)
  790. {
  791. struct ast_device_state_message *dev_state;
  792. dev_state = stasis_message_data(msg);
  793. /* Ignore non-aggregate states */
  794. if (dev_state->eid) {
  795. return NULL;
  796. }
  797. return ast_manager_event_blob_create(EVENT_FLAG_CALL, "DeviceStateChange",
  798. "Device: %s\r\n"
  799. "State: %s\r\n",
  800. dev_state->device, ast_devstate_str(dev_state->state));
  801. }
  802. /*! \brief Convert a \ref stasis_message to a \ref ast_event */
  803. static struct ast_event *devstate_to_event(struct stasis_message *message)
  804. {
  805. struct ast_event *event;
  806. struct ast_device_state_message *device_state;
  807. if (!message) {
  808. return NULL;
  809. }
  810. device_state = stasis_message_data(message);
  811. if (device_state->eid) {
  812. event = ast_event_new(AST_EVENT_DEVICE_STATE_CHANGE,
  813. AST_EVENT_IE_DEVICE, AST_EVENT_IE_PLTYPE_STR, device_state->device,
  814. AST_EVENT_IE_STATE, AST_EVENT_IE_PLTYPE_UINT, device_state->state,
  815. AST_EVENT_IE_CACHABLE, AST_EVENT_IE_PLTYPE_UINT, device_state->cachable,
  816. AST_EVENT_IE_EID, AST_EVENT_IE_PLTYPE_RAW, device_state->eid, sizeof(*device_state->eid),
  817. AST_EVENT_IE_END);
  818. } else {
  819. event = ast_event_new(AST_EVENT_DEVICE_STATE,
  820. AST_EVENT_IE_DEVICE, AST_EVENT_IE_PLTYPE_STR, device_state->device,
  821. AST_EVENT_IE_STATE, AST_EVENT_IE_PLTYPE_UINT, device_state->state,
  822. AST_EVENT_IE_CACHABLE, AST_EVENT_IE_PLTYPE_UINT, device_state->cachable,
  823. AST_EVENT_IE_END);
  824. }
  825. return event;
  826. }