devicestate.c 29 KB

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