Asterisk - The Open Source Telephony Project  18.5.0
devicestate.c
Go to the documentation of this file.
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 AstENUM ast_extension_states
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  <synopsis>Raised when a device state changes</synopsis>
124  <syntax>
125  <parameter name="Device">
126  <para>The device whose state has changed</para>
127  </parameter>
128  <parameter name="State">
129  <para>The new state of the device</para>
130  </parameter>
131  </syntax>
132  <description>
133  <para>This differs from the <literal>ExtensionStatus</literal>
134  event because this event is raised for all device state changes,
135  not only for changes that affect dialplan hints.</para>
136  </description>
137  <see-also>
138  <ref type="managerEvent">ExtensionStatus</ref>
139  </see-also>
140  </managerEventInstance>
141  </managerEvent>
142 ***/
143 
144 #include "asterisk.h"
145 
146 #include "asterisk/_private.h"
147 #include "asterisk/channel.h"
148 #include "asterisk/utils.h"
149 #include "asterisk/lock.h"
150 #include "asterisk/linkedlists.h"
151 #include "asterisk/devicestate.h"
152 #include "asterisk/pbx.h"
153 #include "asterisk/app.h"
154 #include "asterisk/astobj2.h"
155 #include "asterisk/stasis.h"
156 #include "asterisk/devicestate.h"
157 
158 #define DEVSTATE_TOPIC_BUCKETS 57
159 
160 /*! \brief Device state strings for printing */
161 static const char * const devstatestring[][2] = {
162  { /* 0 AST_DEVICE_UNKNOWN */ "Unknown", "UNKNOWN" }, /*!< Valid, but unknown state */
163  { /* 1 AST_DEVICE_NOT_INUSE */ "Not in use", "NOT_INUSE" }, /*!< Not used */
164  { /* 2 AST_DEVICE IN USE */ "In use", "INUSE" }, /*!< In use */
165  { /* 3 AST_DEVICE_BUSY */ "Busy", "BUSY" }, /*!< Busy */
166  { /* 4 AST_DEVICE_INVALID */ "Invalid", "INVALID" }, /*!< Invalid - not known to Asterisk */
167  { /* 5 AST_DEVICE_UNAVAILABLE */ "Unavailable", "UNAVAILABLE" }, /*!< Unavailable (not registered) */
168  { /* 6 AST_DEVICE_RINGING */ "Ringing", "RINGING" }, /*!< Ring, ring, ring */
169  { /* 7 AST_DEVICE_RINGINUSE */ "Ring+Inuse", "RINGINUSE" }, /*!< Ring and in use */
170  { /* 8 AST_DEVICE_ONHOLD */ "On Hold", "ONHOLD" }, /*!< On Hold */
171 };
172 
173 /*!\brief Mapping for channel states to device states */
174 static const struct chan2dev {
177 } chan2dev[] = {
180  { AST_STATE_OFFHOOK, AST_DEVICE_INUSE },
181  { AST_STATE_DIALING, AST_DEVICE_INUSE },
182  { AST_STATE_RING, AST_DEVICE_INUSE },
184  { AST_STATE_UP, AST_DEVICE_INUSE },
186  { AST_STATE_DIALING_OFFHOOK, AST_DEVICE_INUSE },
187  { AST_STATE_PRERING, AST_DEVICE_RINGING },
188 };
189 
190 /*! \brief A device state provider (not a channel) */
192  char label[40];
195 };
196 
197 /*! \brief A list of providers */
199 
200 struct state_change {
202  enum ast_devstate_cache cachable;
203  char device[1];
204 };
205 
206 /*! \brief The state change queue. State changes are queued
207  for processing by a separate thread */
209 
210 /*! \brief The device state change notification thread */
211 static pthread_t change_thread = AST_PTHREADT_NULL;
212 
213 /*! \brief Flag for the queue */
215 static volatile int shuttingdown;
216 
218 
223 
224 static struct ast_manager_event_blob *devstate_to_ami(struct stasis_message *msg);
225 static struct ast_event *devstate_to_event(struct stasis_message *msg);
226 
227 
230  .to_event = devstate_to_event,
231 );
232 
233 /* Forward declarations */
234 static int getproviderstate(const char *provider, const char *address);
235 
236 /*! \brief Find devicestate as text message for output */
237 const char *ast_devstate2str(enum ast_device_state devstate)
238 {
239  return devstatestring[devstate][0];
240 }
241 
243 {
244  int i;
245  chanstate &= 0xFFFF;
246  for (i = 0; i < ARRAY_LEN(chan2dev); i++) {
247  if (chan2dev[i].chan == chanstate) {
248  return chan2dev[i].dev;
249  }
250  }
251  return AST_DEVICE_UNKNOWN;
252 }
253 
254 /* Parseable */
256 {
257  return devstatestring[state][1];
258 }
259 
261 {
262  if (!strcasecmp(val, "NOT_INUSE"))
263  return AST_DEVICE_NOT_INUSE;
264  else if (!strcasecmp(val, "INUSE"))
265  return AST_DEVICE_INUSE;
266  else if (!strcasecmp(val, "BUSY"))
267  return AST_DEVICE_BUSY;
268  else if (!strcasecmp(val, "INVALID"))
269  return AST_DEVICE_INVALID;
270  else if (!strcasecmp(val, "UNAVAILABLE"))
271  return AST_DEVICE_UNAVAILABLE;
272  else if (!strcasecmp(val, "RINGING"))
273  return AST_DEVICE_RINGING;
274  else if (!strcasecmp(val, "RINGINUSE"))
275  return AST_DEVICE_RINGINUSE;
276  else if (!strcasecmp(val, "ONHOLD"))
277  return AST_DEVICE_ONHOLD;
278 
279  return AST_DEVICE_UNKNOWN;
280 }
281 
282 /*! \brief Find out if device is active in a call or not
283  \note find channels with the device's name in it
284  This function is only used for channels that does not implement
285  devicestate natively
286 */
287 enum ast_device_state ast_parse_device_state(const char *device)
288 {
289  struct ast_channel *chan;
290  char match[AST_CHANNEL_NAME];
291  enum ast_device_state res;
292 
293  snprintf(match, sizeof(match), "%s-", device);
294 
295  if (!(chan = ast_channel_get_by_name_prefix(match, strlen(match)))) {
296  return AST_DEVICE_UNKNOWN;
297  }
298 
300  res = AST_DEVICE_ONHOLD;
301  } else {
303  }
304  ast_channel_unref(chan);
305 
306  return res;
307 }
308 
309 static enum ast_device_state devstate_cached(const char *device)
310 {
311  struct stasis_message *cached_msg;
312  struct ast_device_state_message *device_state;
313  enum ast_device_state state;
314 
317  if (!cached_msg) {
318  return AST_DEVICE_UNKNOWN;
319  }
320  device_state = stasis_message_data(cached_msg);
321  state = device_state->state;
322  ao2_cleanup(cached_msg);
323 
324  return state;
325 }
326 
327 /*! \brief Check device state through channel specific function or generic function */
328 static enum ast_device_state _ast_device_state(const char *device, int check_cache)
329 {
330  char *number;
331  const struct ast_channel_tech *chan_tech;
332  enum ast_device_state res;
333  /*! \brief Channel driver that provides device state */
334  char *tech;
335 
336  /* If the last known state is cached, just return that */
337  if (check_cache) {
338  res = devstate_cached(device);
339  if (res != AST_DEVICE_UNKNOWN) {
340  return res;
341  }
342  }
343 
344  number = ast_strdupa(device);
345  tech = strsep(&number, "/");
346  if (!number) {
347  /*! \brief Another provider of device state */
348  char *provider;
349 
350  provider = strsep(&tech, ":");
351  if (!tech) {
352  return AST_DEVICE_INVALID;
353  }
354  /* We have a provider */
355  number = tech;
356 
357  ast_debug(3, "Checking if I can find provider for \"%s\" - number: %s\n", provider, number);
358  return getproviderstate(provider, number);
359  }
360 
361  ast_debug(4, "No provider found, checking channel drivers for %s - %s\n", tech, number);
362 
363  chan_tech = ast_get_channel_tech(tech);
364  if (!chan_tech) {
365  return AST_DEVICE_INVALID;
366  }
367 
368  /* Does the channel driver support device state notification? */
369  if (!chan_tech->devicestate) {
370  /* No, try the generic function */
371  return ast_parse_device_state(device);
372  }
373 
374  res = chan_tech->devicestate(number);
375  if (res == AST_DEVICE_UNKNOWN) {
376  res = ast_parse_device_state(device);
377  }
378 
379  return res;
380 }
381 
382 enum ast_device_state ast_device_state(const char *device)
383 {
384  /* This function is called from elsewhere in the code to find out the
385  * current state of a device. Check the cache, first. */
386 
387  return _ast_device_state(device, 1);
388 }
389 
390 /*! \brief Add device state provider */
391 int ast_devstate_prov_add(const char *label, ast_devstate_prov_cb_type callback)
392 {
393  struct devstate_prov *devcb;
394  struct devstate_prov *devprov;
395 
396  if (!callback || !(devprov = ast_calloc(1, sizeof(*devprov))))
397  return -1;
398 
399  devprov->callback = callback;
400  ast_copy_string(devprov->label, label, sizeof(devprov->label));
401 
403  AST_RWLIST_TRAVERSE(&devstate_provs, devcb, list) {
404  if (!strcasecmp(devcb->label, label)) {
405  ast_log(LOG_WARNING, "Device state provider '%s' already registered\n", label);
406  ast_free(devprov);
408  return -1;
409  }
410  }
411  AST_RWLIST_INSERT_HEAD(&devstate_provs, devprov, list);
413 
414  return 0;
415 }
416 
417 /*! \brief Remove device state provider */
418 int ast_devstate_prov_del(const char *label)
419 {
420  struct devstate_prov *devcb;
421  int res = -1;
422 
425  if (!strcasecmp(devcb->label, label)) {
427  ast_free(devcb);
428  res = 0;
429  break;
430  }
431  }
434 
435  return res;
436 }
437 
438 /*! \brief Get provider device state */
439 static int getproviderstate(const char *provider, const char *address)
440 {
441  struct devstate_prov *devprov;
442  int res = AST_DEVICE_INVALID;
443 
445  AST_RWLIST_TRAVERSE(&devstate_provs, devprov, list) {
446  ast_debug(5, "Checking provider %s with %s\n", devprov->label, provider);
447 
448  if (!strcasecmp(devprov->label, provider)) {
449  res = devprov->callback(address);
450  break;
451  }
452  }
454 
455  return res;
456 }
457 
458 /*! Called by the state change thread to find out what the state is, and then
459  * to queue up the state change event */
460 static void do_state_change(const char *device, enum ast_devstate_cache cachable)
461 {
462  enum ast_device_state state;
463 
464  state = _ast_device_state(device, 0);
465 
466  ast_debug(3, "Changing state for %s - state %u (%s)\n", device, state, ast_devstate2str(state));
467 
468  ast_publish_device_state(device, state, cachable);
469 }
470 
471 int ast_devstate_changed_literal(enum ast_device_state state, enum ast_devstate_cache cachable, const char *device)
472 {
473  struct state_change *change;
474 
475  /*
476  * If we know the state change (how nice of the caller of this function!)
477  * then we can just generate a device state event.
478  *
479  * Otherwise, we do the following:
480  * - Queue an event up to another thread that the state has changed
481  * - In the processing thread, it calls the callback provided by the
482  * device state provider (which may or may not be a channel driver)
483  * to determine the state.
484  * - If the device state provider does not know the state, or this is
485  * for a channel and the channel driver does not implement a device
486  * state callback, then we will look through the channel list to
487  * see if we can determine a state based on active calls.
488  * - Once a state has been determined, a device state event is generated.
489  */
490 
491  if (state != AST_DEVICE_UNKNOWN) {
492  ast_publish_device_state(device, state, cachable);
493  } else if (change_thread == AST_PTHREADT_NULL || !(change = ast_calloc(1, sizeof(*change) + strlen(device)))) {
494  /* we could not allocate a change struct, or */
495  /* there is no background thread, so process the change now */
496  do_state_change(device, cachable);
497  } else {
498  /* queue the change */
499  strcpy(change->device, device);
500  change->cachable = cachable;
505  }
506 
507  return 0;
508 }
509 
511 {
512  char buf[AST_MAX_EXTENSION];
513  va_list ap;
514 
515  va_start(ap, fmt);
516  vsnprintf(buf, sizeof(buf), fmt, ap);
517  va_end(ap);
518 
519  return ast_devstate_changed_literal(state, cachable, buf);
520 }
521 
522 /*! \brief Go through the dev state change queue and update changes in the dev state thread */
523 static void *do_devstate_changes(void *data)
524 {
525  struct state_change *next, *current;
526 
527  while (!shuttingdown) {
528  /* This basically pops off any state change entries, resets the list back to NULL, unlocks, and processes each state change */
532  next = AST_LIST_FIRST(&state_changes);
535 
536  /* Process each state change */
537  while ((current = next)) {
538  next = AST_LIST_NEXT(current, list);
539  do_state_change(current->device, current->cachable);
540  ast_free(current);
541  }
542  }
543 
544  return NULL;
545 }
546 
548 {
549  struct ast_device_state_message *new_device_state;
550  char *pos;
551  size_t stuff_len;
552 
553  ast_assert(!ast_strlen_zero(device));
554 
555  stuff_len = strlen(device) + 1;
556  if (eid) {
557  stuff_len += sizeof(*eid);
558  }
559  new_device_state = ao2_alloc_options(sizeof(*new_device_state) + stuff_len, NULL,
561  if (!new_device_state) {
562  return NULL;
563  }
564 
565  if (eid) {
566  /* non-aggregate device state. */
567  new_device_state->stuff[0] = *eid;
568  new_device_state->eid = &new_device_state->stuff[0];
569  pos = (char *) &new_device_state->stuff[1];
570  } else {
571  pos = (char *) &new_device_state->stuff[0];
572  }
573 
574  strcpy(pos, device);/* Safe */
575  new_device_state->device = pos;
576 
577  new_device_state->state = state;
578  new_device_state->cachable = cachable;
579 
580  return new_device_state;
581 }
582 
583 static void devstate_change_cb(void *data, struct stasis_subscription *sub, struct stasis_message *msg)
584 {
585  struct ast_device_state_message *device_state;
586 
588  return;
589  }
590 
591  device_state = stasis_message_data(msg);
592  if (device_state->cachable == AST_DEVSTATE_CACHABLE || !device_state->eid) {
593  /* Ignore cacheable and aggregate messages. */
594  return;
595  }
596 
597  /*
598  * Non-cacheable device state aggregates are just the
599  * device state republished as the aggregate.
600  */
601  ast_publish_device_state_full(device_state->device, device_state->state,
602  device_state->cachable, NULL);
603 }
604 
606 {
607  shuttingdown = 1;
611 
613  pthread_join(change_thread, NULL);
614  }
615 }
616 
617 /*! \brief Initialize the device state engine in separate thread */
619 {
622  ast_log(LOG_ERROR, "Unable to start device state change thread.\n");
623  return -1;
624  }
626 
627  return 0;
628 }
629 
631 {
632  memset(agg, 0, sizeof(*agg));
633  agg->state = AST_DEVICE_INVALID;
634 }
635 
637 {
638  static enum ast_device_state state_order[] = {
639  1, /* AST_DEVICE_UNKNOWN */
640  3, /* AST_DEVICE_NOT_INUSE */
641  6, /* AST_DEVICE_INUSE */
642  7, /* AST_DEVICE_BUSY */
643  0, /* AST_DEVICE_INVALID */
644  2, /* AST_DEVICE_UNAVAILABLE */
645  5, /* AST_DEVICE_RINGING */
646  8, /* AST_DEVICE_RINGINUSE */
647  4, /* AST_DEVICE_ONHOLD */
648  };
649 
650  if (state == AST_DEVICE_RINGING) {
651  agg->ringing = 1;
652  } else if (state == AST_DEVICE_INUSE || state == AST_DEVICE_ONHOLD || state == AST_DEVICE_BUSY) {
653  agg->inuse = 1;
654  }
655 
656  if (agg->ringing && agg->inuse) {
658  } else if (state_order[state] > state_order[agg->state]) {
659  agg->state = state;
660  }
661 }
662 
664 {
665  return agg->state;
666 }
667 
669 {
670  return device_state_topic_all;
671 }
672 
674 {
675  return device_state_cache;
676 }
677 
679 {
680  return stasis_caching_get_topic(device_state_topic_cached);
681 }
682 
683 struct stasis_topic *ast_device_state_topic(const char *device)
684 {
685  return stasis_topic_pool_get_topic(device_state_topic_pool, device);
686 }
687 
688 int ast_device_state_clear_cache(const char *device)
689 {
690  struct stasis_message *cached_msg;
691  struct stasis_message *msg;
692 
695  if (!cached_msg) {
696  /* nothing to clear */
697  return -1;
698  }
699 
700  msg = stasis_cache_clear_create(cached_msg);
701  if (msg) {
703  }
704  ao2_cleanup(msg);
705  ao2_cleanup(cached_msg);
706  return 0;
707 }
708 
710  const char *device,
711  enum ast_device_state state,
712  enum ast_devstate_cache cachable,
713  struct ast_eid *eid)
714 {
715  RAII_VAR(struct ast_device_state_message *, device_state, NULL, ao2_cleanup);
717  struct stasis_topic *topic;
718 
719  ast_assert(!ast_strlen_zero(device));
720 
722  return -1;
723  }
724 
725  device_state = device_state_alloc(device, state, cachable, eid);
726  if (!device_state) {
727  return -1;
728  }
729 
731  eid);
732  if (!message) {
733  return -1;
734  }
735 
736  /* When a device state is to be cached it is likely that something
737  * external will either be monitoring it or will want to pull the
738  * information from the cache, so we always publish to the device
739  * specific topic. Cachable updates traditionally come from such things
740  * as a SIP or PJSIP device.
741  * When a device state is not to be cached we only publish to its
742  * specific topic if something has already created the topic. Publishing
743  * to its topic otherwise would create the topic, which may not be
744  * necessary as it could be an ephemeral device. Uncachable updates
745  * traditionally come from such things as Local channels.
746  */
747  if (cachable || stasis_topic_pool_topic_exists(device_state_topic_pool, device)) {
748  topic = ast_device_state_topic(device);
749  } else {
750  topic = ast_device_state_topic_all();
751  }
752 
753  if (!topic) {
754  return -1;
755  }
756 
757  stasis_publish(topic, message);
758  return 0;
759 }
760 
761 static const char *device_state_get_id(struct stasis_message *message)
762 {
763  struct ast_device_state_message *device_state;
764 
766  return NULL;
767  }
768 
769  device_state = stasis_message_data(message);
770  if (device_state->cachable == AST_DEVSTATE_NOT_CACHABLE) {
771  return NULL;
772  }
773 
774  return device_state->device;
775 }
776 
777 /*!
778  * \internal
779  * \brief Callback to publish the aggregate device state cache entry message.
780  * \since 12.2.0
781  *
782  * \param cache_topic Caching topic the aggregate message may be published over.
783  * \param aggregate The aggregate shapshot message to publish.
784  *
785  * \return Nothing
786  */
787 static void device_state_aggregate_publish(struct stasis_topic *cache_topic, struct stasis_message *aggregate)
788 {
789  const char *device;
790  struct stasis_topic *device_specific_topic;
791 
792  device = device_state_get_id(aggregate);
793  if (!device) {
794  return;
795  }
796  device_specific_topic = ast_device_state_topic(device);
797  if (!device_specific_topic) {
798  return;
799  }
800 
801  stasis_publish(device_specific_topic, aggregate);
802 }
803 
804 /*!
805  * \internal
806  * \brief Callback to calculate the aggregate device state cache entry.
807  * \since 12.2.0
808  *
809  * \param entry Cache entry to calculate a new aggregate snapshot.
810  * \param new_snapshot The shapshot that is being updated.
811  *
812  * \note Return a ref bumped pointer from stasis_cache_entry_get_aggregate()
813  * if a new aggregate could not be calculated because of error.
814  *
815  * \return New aggregate-snapshot calculated on success.
816  * Caller has a reference on return.
817  */
819 {
820  struct stasis_message *aggregate_snapshot;
821  struct stasis_message *snapshot;
822  struct ast_device_state_message *device_state;
823  const char *device = NULL;
824  struct ast_devstate_aggregate aggregate;
825  int idx;
826 
828  return NULL;
829  }
830 
831  /* Determine the new aggregate device state. */
832  ast_devstate_aggregate_init(&aggregate);
833  snapshot = stasis_cache_entry_get_local(entry);
834  if (snapshot) {
835  device_state = stasis_message_data(snapshot);
836  device = device_state->device;
837  ast_devstate_aggregate_add(&aggregate, device_state->state);
838  }
839  for (idx = 0; ; ++idx) {
840  snapshot = stasis_cache_entry_get_remote(entry, idx);
841  if (!snapshot) {
842  break;
843  }
844 
845  device_state = stasis_message_data(snapshot);
846  device = device_state->device;
847  ast_devstate_aggregate_add(&aggregate, device_state->state);
848  }
849 
850  if (!device) {
851  /* There are no device states cached. Delete the aggregate. */
852  return NULL;
853  }
854 
855  snapshot = stasis_cache_entry_get_aggregate(entry);
856  if (snapshot) {
857  device_state = stasis_message_data(snapshot);
858  if (device_state->state == ast_devstate_aggregate_result(&aggregate)) {
859  /* Aggregate device state did not change. */
860  return ao2_bump(snapshot);
861  }
862  }
863 
864  device_state = device_state_alloc(device, ast_devstate_aggregate_result(&aggregate),
866  if (!device_state) {
867  /* Bummer. We have to keep the old aggregate snapshot. */
868  return ao2_bump(snapshot);
869  }
871  device_state, NULL);
872  ao2_cleanup(device_state);
873  if (!aggregate_snapshot) {
874  /* Bummer. We have to keep the old aggregate snapshot. */
875  return ao2_bump(snapshot);
876  }
877 
878  return aggregate_snapshot;
879 }
880 
881 static void devstate_cleanup(void)
882 {
883  devstate_message_sub = stasis_unsubscribe_and_join(devstate_message_sub);
884  device_state_topic_cached = stasis_caching_unsubscribe_and_join(device_state_topic_cached);
885 
886  ao2_cleanup(device_state_cache);
887  device_state_cache = NULL;
888 
889  ao2_cleanup(device_state_topic_pool);
890  device_state_topic_pool = NULL;
891 
892  ao2_cleanup(device_state_topic_all);
893  device_state_topic_all = NULL;
894 
896 }
897 
898 int devstate_init(void)
899 {
901 
903  return -1;
904  }
905  device_state_topic_all = stasis_topic_create("devicestate:all");
906  if (!device_state_topic_all) {
907  return -1;
908  }
909  device_state_topic_pool = stasis_topic_pool_create(ast_device_state_topic_all());
910  if (!device_state_topic_pool) {
911  return -1;
912  }
913  device_state_cache = stasis_cache_create_full(device_state_get_id,
915  if (!device_state_cache) {
916  return -1;
917  }
918  device_state_topic_cached = stasis_caching_topic_create(ast_device_state_topic_all(),
919  device_state_cache);
920  if (!device_state_topic_cached) {
921  return -1;
922  }
925 
926  devstate_message_sub = stasis_subscribe(ast_device_state_topic_all(),
928  if (!devstate_message_sub) {
929  ast_log(LOG_ERROR, "Failed to create subscription creating uncached device state aggregate events.\n");
930  return -1;
931  }
934 
935  return 0;
936 }
937 
939 {
940  struct ast_device_state_message *dev_state;
941 
942  dev_state = stasis_message_data(msg);
943 
944  /* Ignore non-aggregate states */
945  if (dev_state->eid) {
946  return NULL;
947  }
948 
949  return ast_manager_event_blob_create(EVENT_FLAG_CALL, "DeviceStateChange",
950  "Device: %s\r\n"
951  "State: %s\r\n",
952  dev_state->device, ast_devstate_str(dev_state->state));
953 }
954 
955 /*! \brief Convert a \ref stasis_message to a \ref ast_event */
957 {
958  struct ast_event *event;
959  struct ast_device_state_message *device_state;
960 
961  if (!message) {
962  return NULL;
963  }
964 
965  device_state = stasis_message_data(message);
966 
967  if (device_state->eid) {
972  AST_EVENT_IE_EID, AST_EVENT_IE_PLTYPE_RAW, device_state->eid, sizeof(*device_state->eid),
974  } else {
980  }
981 
982  return event;
983 }
static struct stasis_message * device_state_aggregate_calc(struct stasis_cache_entry *entry, struct stasis_message *new_snapshot)
Definition: devicestate.c:818
A list of providers.
Definition: devicestate.c:198
Struct containing info for an AMI event to send out.
Definition: manager.h:491
enum sip_cc_notify_state state
Definition: chan_sip.c:959
static struct ast_manager_event_blob * devstate_to_ami(struct stasis_message *msg)
Definition: devicestate.c:938
Main Channel structure associated with a channel.
ast_device_state
Device States.
Definition: devicestate.h:52
An event.
Definition: event.c:81
static struct stasis_topic * device_state_topic_all
Definition: devicestate.c:219
int ast_channel_hold_state(const struct ast_channel *chan)
enum ast_device_state dev
Definition: devicestate.c:176
#define AST_LIST_LOCK(head)
Locks a list.
Definition: linkedlists.h:39
Asterisk locking-related definitions:
struct state_change * next
Definition: devicestate.c:201
Asterisk main include file. File version handling, generic pbx functions.
#define AST_LIST_FIRST(head)
Returns the first entry contained in a list.
Definition: linkedlists.h:420
#define ARRAY_LEN(a)
Definition: isdn_lib.c:42
int devstate_init(void)
Initialize the device state core.
Definition: devicestate.c:898
static int getproviderstate(const char *provider, const char *address)
Get provider device state.
Definition: devicestate.c:439
int stasis_caching_accept_message_type(struct stasis_caching_topic *caching_topic, struct stasis_message_type *type)
Indicate to a caching topic that we are interested in a message type.
Definition: stasis_cache.c:90
static struct ast_event * devstate_to_event(struct stasis_message *msg)
Convert a stasis_message to a ast_event.
Definition: devicestate.c:956
#define AST_RWLIST_HEAD_STATIC(name, type)
Defines a structure to be used to hold a read/write list of specified type, statically initialized...
Definition: linkedlists.h:332
void ast_devstate_aggregate_init(struct ast_devstate_aggregate *agg)
Initialize aggregate device state.
Definition: devicestate.c:630
enum ast_device_state ast_state_chan2dev(enum ast_channel_state chanstate)
Convert channel state to devicestate.
Definition: devicestate.c:242
static void devstate_change_cb(void *data, struct stasis_subscription *sub, struct stasis_message *msg)
Definition: devicestate.c:583
Definition: ast_expr2.c:325
struct ast_eid eid
const struct ast_channel_tech * ast_get_channel_tech(const char *name)
Get a channel technology structure by name.
Definition: channel.c:592
#define ast_channel_unref(c)
Decrease channel reference count.
Definition: channel.h:2981
Device state management.
A device state provider (not a channel)
Definition: devicestate.c:191
char * address
Definition: f2c.h:59
char buf[BUFSIZE]
Definition: eagi_proxy.c:66
void ast_devstate_aggregate_add(struct ast_devstate_aggregate *agg, enum ast_device_state state)
Add a device state to the aggregate device state.
Definition: devicestate.c:636
#define STASIS_MESSAGE_TYPE_INIT(name)
Boiler-plate messaging macro for initializing message types.
Definition: stasis.h:1501
#define AST_RWLIST_WRLOCK(head)
Write locks a list.
Definition: linkedlists.h:51
static void devstate_cleanup(void)
Definition: devicestate.c:881
Stasis Message Bus API. See Stasis Message Bus API for detailed documentation.
#define LOG_WARNING
Definition: logger.h:274
struct stasis_caching_topic * stasis_caching_topic_create(struct stasis_topic *original_topic, struct stasis_cache *cache)
Create a topic which monitors and caches messages from another topic.
Definition: stasis_cache.c:948
#define AST_LIST_UNLOCK(head)
Attempts to unlock a list.
Definition: linkedlists.h:139
struct stasis_cache * ast_device_state_cache(void)
Backend cache for ast_device_state_topic_cached()
Definition: devicestate.c:673
enum ast_device_state state
Definition: devicestate.h:250
#define AST_RWLIST_UNLOCK(head)
Attempts to unlock a read/write based list.
Definition: linkedlists.h:150
int ast_devstate_changed(enum ast_device_state state, enum ast_devstate_cache cachable, const char *fmt,...)
Tells Asterisk the State for Device is changed.
Definition: devicestate.c:510
enum ast_device_state ast_devstate_val(const char *val)
Convert device state from text to integer value.
Definition: devicestate.c:260
static enum ast_device_state devstate_cached(const char *device)
Definition: devicestate.c:309
ast_devstate_prov_cb_type callback
Definition: devicestate.c:193
#define AST_LIST_NEXT(elm, field)
Returns the next entry in the list after the given entry.
Definition: linkedlists.h:438
#define STASIS_MESSAGE_TYPE_CLEANUP(name)
Boiler-plate messaging macro for cleaning up message types.
Definition: stasis.h:1523
#define EVENT_FLAG_CALL
Definition: manager.h:72
struct stasis_message_type * stasis_message_type(const struct stasis_message *msg)
Get the message type for a stasis_message.
int stasis_subscription_set_filter(struct stasis_subscription *subscription, enum stasis_subscription_message_filter filter)
Set the message type filtering level on a subscription.
Definition: stasis.c:1079
static void do_state_change(const char *device, enum ast_devstate_cache cachable)
Definition: devicestate.c:460
ast_channel_state
ast_channel states
Definition: channelstate.h:35
static volatile int shuttingdown
Definition: devicestate.c:215
Definition: astman.c:222
#define ast_cond_wait(cond, mutex)
Definition: lock.h:203
#define ast_cond_init(cond, attr)
Definition: lock.h:199
struct stasis_message * stasis_cache_clear_create(struct stasis_message *message)
A message which instructs the caching topic to remove an entry from its cache.
Definition: stasis_cache.c:778
struct state_change::@380 list
enum ast_devstate_cache cachable
Definition: devicestate.h:252
struct stasis_message * stasis_cache_entry_get_aggregate(struct stasis_cache_entry *entry)
Get the aggregate cache entry snapshot.
Definition: stasis_cache.c:365
#define AST_LIST_EMPTY(head)
Checks whether the specified list contains any entries.
Definition: linkedlists.h:449
#define ao2_alloc_options(data_size, destructor_fn, options)
Definition: astobj2.h:406
#define ast_assert(a)
Definition: utils.h:695
struct stasis_message * stasis_cache_get_by_eid(struct stasis_cache *cache, struct stasis_message_type *type, const char *id, const struct ast_eid *eid)
Retrieve an item from the cache for a specific entity.
Definition: stasis_cache.c:659
static int match(struct ast_sockaddr *addr, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
Definition: chan_iax2.c:2315
struct stasis_topic * stasis_topic_pool_get_topic(struct stasis_topic_pool *pool, const char *topic_name)
Find or create a topic in the pool.
Definition: stasis.c:1884
#define NULL
Definition: resample.c:96
static struct stasis_caching_topic * device_state_topic_cached
Definition: devicestate.c:221
static const char * device_state_get_id(struct stasis_message *message)
Definition: devicestate.c:761
int ast_devstate_changed_literal(enum ast_device_state state, enum ast_devstate_cache cachable, const char *device)
Tells Asterisk the State for Device is changed.
Definition: devicestate.c:471
enum ast_devstate_cache cachable
Definition: devicestate.c:202
static void device_state_engine_cleanup(void)
Definition: devicestate.c:605
#define ast_cond_signal(cond)
Definition: lock.h:201
An Entity ID is essentially a MAC address, brief and unique.
Definition: utils.h:786
struct stasis_caching_topic * stasis_caching_unsubscribe_and_join(struct stasis_caching_topic *caching_topic)
Unsubscribes a caching topic from its upstream topic, blocking until all messages have been forwarded...
Definition: stasis_cache.c:146
struct ast_manager_event_blob * ast_manager_event_blob_create(int event_flags, const char *manager_event, const char *extra_fields_fmt,...)
Construct a ast_manager_event_blob.
Definition: manager.c:9727
Entity ID Used by All events Payload type: RAW This IE indicates which server the event originated fr...
Definition: event_defs.h:272
int ast_publish_device_state_full(const char *device, enum ast_device_state state, enum ast_devstate_cache cachable, struct ast_eid *eid)
Publish a device state update with EID.
Definition: devicestate.c:709
ast_mutex_t lock
Definition: devicestate.c:208
Utility functions.
struct ast_channel * ast_channel_get_by_name_prefix(const char *name, size_t name_len)
Find a channel by a name prefix.
Definition: channel.c:1434
pthread_cond_t ast_cond_t
Definition: lock.h:176
#define ast_strlen_zero(foo)
Definition: strings.h:52
struct stasis_topic_pool * stasis_topic_pool_create(struct stasis_topic *pooled_topic)
Create a topic pool that routes messages from dynamically generated topics to the given topic...
Definition: stasis.c:1833
#define ast_pthread_create_background(a, b, c, d)
Definition: utils.h:567
Number structure.
Definition: app_followme.c:154
#define ao2_bump(obj)
Definition: astobj2.h:491
static struct stasis_topic_pool * device_state_topic_pool
Definition: devicestate.c:222
#define AST_RWLIST_RDLOCK(head)
Read locks a list.
Definition: linkedlists.h:77
struct stasis_message_type * ast_device_state_message_type(void)
Get the Stasis message type for device state messages.
#define AST_RWLIST_INSERT_HEAD
Definition: linkedlists.h:717
int ast_device_state_engine_init(void)
Initialize the device state engine in separate thread.
Definition: devicestate.c:618
#define ast_debug(level,...)
Log a DEBUG message.
Definition: logger.h:452
#define ast_log
Definition: astobj2.c:42
struct stasis_topic * ast_device_state_topic_all(void)
Get the Stasis topic for device state messages.
Definition: devicestate.c:668
General Asterisk PBX channel definitions.
int ast_register_cleanup(void(*func)(void))
Register a function to be executed before Asterisk gracefully exits.
Definition: clicompat.c:19
#define RAII_VAR(vartype, varname, initval, dtor)
Declare a variable that will call a destructor function when it goes out of scope.
Definition: utils.h:911
static struct stasis_cache * device_state_cache
Definition: devicestate.c:220
const struct ast_eid * eid
The EID of the server where this message originated.
Definition: devicestate.h:248
static void device_state_aggregate_publish(struct stasis_topic *cache_topic, struct stasis_message *aggregate)
Definition: devicestate.c:787
#define AST_PTHREADT_NULL
Definition: lock.h:66
int ast_devstate_prov_del(const char *label)
Remove device state provider.
Definition: devicestate.c:418
int stasis_topic_pool_topic_exists(const struct stasis_topic_pool *pool, const char *topic_name)
Check if a topic exists in a pool.
Definition: stasis.c:1927
#define AST_MAX_EXTENSION
Definition: channel.h:135
#define AST_RWLIST_TRAVERSE
Definition: linkedlists.h:493
#define AST_RWLIST_REMOVE_CURRENT
Definition: linkedlists.h:569
#define ast_strdupa(s)
duplicate a string in memory from the stack
Definition: astmm.h:300
int ast_devstate_prov_add(const char *label, ast_devstate_prov_cb_type callback)
Add device state provider.
Definition: devicestate.c:391
struct stasis_cache * stasis_cache_create_full(snapshot_get_id id_fn, cache_aggregate_calc_fn aggregate_calc_fn, cache_aggregate_publish_fn aggregate_publish_fn)
Create a cache.
Definition: stasis_cache.c:334
A set of macros to manage forward-linked lists.
struct stasis_topic * stasis_topic_create(const char *name)
Create a new topic.
Definition: stasis.c:618
unsigned int ringing
Definition: devicestate.h:231
Event non-cachability flag Used by: All events Payload type: UINT.
Definition: event_defs.h:306
Structure to describe a channel "technology", ie a channel driver See for examples: ...
Definition: channel.h:629
Core PBX routines and definitions.
#define AST_RWLIST_TRAVERSE_SAFE_BEGIN
Definition: linkedlists.h:544
#define stasis_subscribe(topic, callback, data)
Definition: stasis.h:652
#define AST_LIST_HEAD_STATIC(name, type)
Defines a structure to be used to hold a list of specified type, statically initialized.
Definition: linkedlists.h:290
enum ast_channel_state chan
Definition: devicestate.c:175
int stasis_caching_set_filter(struct stasis_caching_topic *caching_topic, enum stasis_subscription_message_filter filter)
Set the message type filtering level on a cache.
Definition: stasis_cache.c:109
static const char *const devstatestring[][2]
Device state strings for printing.
Definition: devicestate.c:161
enum ast_device_state ast_device_state(const char *device)
Asks a channel for device state.
Definition: devicestate.c:382
int ast_device_state_clear_cache(const char *device)
Clear the device from the stasis cache.
Definition: devicestate.c:688
#define LOG_ERROR
Definition: logger.h:285
#define AST_LIST_INSERT_TAIL(head, elm, field)
Appends a list entry to the tail of a list.
Definition: linkedlists.h:730
struct stasis_message * stasis_cache_entry_get_remote(struct stasis_cache_entry *entry, int idx)
Get a remote entity&#39;s cache entry snapshot by index.
Definition: stasis_cache.c:375
static pthread_t change_thread
The device state change notification thread.
Definition: devicestate.c:211
void * stasis_message_data(const struct stasis_message *msg)
Get the data contained in a message.
const char * ast_devstate2str(enum ast_device_state devstate)
Find devicestate as text message for output.
Definition: devicestate.c:237
char device[1]
Definition: devicestate.c:203
#define AST_LIST_ENTRY(type)
Declare a forward link structure inside a list entry.
Definition: linkedlists.h:409
ast_devstate_cache
Device State Cachability.
Definition: devicestate.h:68
void stasis_publish(struct stasis_topic *topic, struct stasis_message *message)
Publish a message to a topic&#39;s subscribers.
Definition: stasis.c:1511
#define ast_free(a)
Definition: astmm.h:182
#define ast_calloc(num, len)
A wrapper for calloc()
Definition: astmm.h:204
#define AST_CHANNEL_NAME
Definition: channel.h:172
char label[40]
Definition: devicestate.c:192
static void to_ami(struct ast_sip_subscription *sub, struct ast_str **buf)
Prototypes for public functions only of internal interest,.
struct stasis_subscription * stasis_unsubscribe_and_join(struct stasis_subscription *subscription)
Cancel a subscription, blocking until the last message is processed.
Definition: stasis.c:1136
struct stasis_subscription * devstate_message_sub
Definition: devicestate.c:217
#define AST_RWLIST_ENTRY
Definition: linkedlists.h:414
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)
Definition: devicestate.c:547
Mapping for channel states to device states.
Definition: devicestate.c:174
struct ast_eid ast_eid_default
Global EID.
Definition: options.c:93
const char * ast_devstate_str(enum ast_device_state state)
Convert device state to text string that is easier to parse.
Definition: devicestate.c:255
struct stasis_topic * ast_device_state_topic(const char *device)
Get the Stasis topic for device state messages for a specific device.
Definition: devicestate.c:683
static void * do_devstate_changes(void *data)
Go through the dev state change queue and update changes in the dev state thread. ...
Definition: devicestate.c:523
#define AST_LIST_HEAD_INIT_NOLOCK(head)
Initializes a list head structure.
Definition: linkedlists.h:680
char * strsep(char **str, const char *delims)
struct stasis_message * stasis_cache_entry_get_local(struct stasis_cache_entry *entry)
Get the local entity&#39;s cache entry snapshot.
Definition: stasis_cache.c:370
static ast_cond_t change_pending
Flag for the queue.
Definition: devicestate.c:214
#define ao2_cleanup(obj)
Definition: astobj2.h:1958
struct ast_event * ast_event_new(enum ast_event_type event_type,...)
Create a new event.
Definition: event.c:402
void ast_copy_string(char *dst, const char *src, size_t size)
Size-limited null-terminating string copy.
Definition: strings.h:401
enum ast_device_state ast_parse_device_state(const char *device)
Find out if device is active in a call or not.
Definition: devicestate.c:287
enum ast_device_state(* ast_devstate_prov_cb_type)(const char *data)
Devicestate provider call back.
Definition: devicestate.h:74
struct stasis_topic * ast_device_state_topic_cached(void)
Get the Stasis caching topic for device state messages.
Definition: devicestate.c:678
int stasis_subscription_accept_message_type(struct stasis_subscription *subscription, const struct stasis_message_type *type)
Indicate to a subscription that we are interested in a message type.
Definition: stasis.c:1025
int(*const devicestate)(const char *device_number)
Definition: channel.h:676
struct stasis_forward * sub
Definition: res_corosync.c:240
You shouldn&#39;t care about the contents of this struct.
Definition: devicestate.h:230
The structure that contains device state.
Definition: devicestate.h:240
Definition: search.h:40
struct ast_eid stuff[0]
Definition: devicestate.h:254
STASIS_MESSAGE_TYPE_DEFN(ast_device_state_message_type,.to_ami=devstate_to_ami,.to_event=devstate_to_event,)
static enum ast_device_state _ast_device_state(const char *device, int check_cache)
Check device state through channel specific function or generic function.
Definition: devicestate.c:328
Generic State IE Used by AST_EVENT_DEVICE_STATE_CHANGE Payload type: UINT The actual state values dep...
Definition: event_defs.h:121
The state change queue. State changes are queued for processing by a separate thread.
Definition: devicestate.c:208
struct stasis_message * stasis_message_create_full(struct stasis_message_type *type, void *data, const struct ast_eid *eid)
Create a new message for an entity.
enum ast_device_state state
Definition: devicestate.h:233
struct stasis_topic * stasis_caching_get_topic(struct stasis_caching_topic *caching_topic)
Returns the topic of cached events from a caching topics.
Definition: stasis_cache.c:85
Device Name Used by AST_EVENT_DEVICE_STATE_CHANGE Payload type: STR.
Definition: event_defs.h:113
static struct prometheus_metrics_provider provider
Definition: bridges.c:178
Application convenience functions, designed to give consistent look and feel to Asterisk apps...
enum ast_device_state ast_devstate_aggregate_result(struct ast_devstate_aggregate *agg)
Get the aggregate device state result.
Definition: devicestate.c:663
#define AST_RWLIST_TRAVERSE_SAFE_END
Definition: linkedlists.h:616
#define ast_publish_device_state(device, state, cachable)
Publish a device state update.
Definition: devicestate.h:323
Definition: stasis_cache.c:173