Debian Codegraph @

main/devicestate.c

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