devicestate.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2008, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  * Russell Bryant <russell@digium.com>
00008  *
00009  * See http://www.asterisk.org for more information about
00010  * the Asterisk project. Please do not directly contact
00011  * any of the maintainers of this project for assistance;
00012  * the project provides a web site, mailing lists and IRC
00013  * channels for your use.
00014  *
00015  * This program is free software, distributed under the terms of
00016  * the GNU General Public License Version 2. See the LICENSE file
00017  * at the top of the source tree.
00018  */
00019 
00020 /*! \file
00021  *
00022  * \brief Device state management
00023  *
00024  * \author Mark Spencer <markster@digium.com>
00025  * \author Russell Bryant <russell@digium.com>
00026  *
00027  * \arg \ref AstExtState
00028  */
00029 
00030 /*! \page AstExtState Extension and device states in Asterisk
00031  *
00032  * (Note that these descriptions of device states and extension
00033  * states have not been updated to the way things work
00034  * in Asterisk 1.6.)
00035  *
00036  * Asterisk has an internal system that reports states
00037  * for an extension. By using the dialplan priority -1,
00038  * also called a \b hint, a connection can be made from an
00039  * extension to one or many devices. The state of the extension
00040  * now depends on the combined state of the devices.
00041  *
00042  * The device state is basically based on the current calls.
00043  * If the devicestate engine can find a call from or to the
00044  * device, it's in use.
00045  *
00046  * Some channel drivers implement a callback function for
00047  * a better level of reporting device states. The SIP channel
00048  * has a complicated system for this, which is improved
00049  * by adding call limits to the configuration.
00050  *
00051  * Functions that want to check the status of an extension
00052  * register themself as a \b watcher.
00053  * Watchers in this system can subscribe either to all extensions
00054  * or just a specific extensions.
00055  *
00056  * For non-device related states, there's an API called
00057  * devicestate providers. This is an extendible system for
00058  * delivering state information from outside sources or
00059  * functions within Asterisk. Currently we have providers
00060  * for app_meetme.c - the conference bridge - and call
00061  * parking (metermaids).
00062  *
00063  * There are manly three subscribers to extension states
00064  * within Asterisk:
00065  * - AMI, the manager interface
00066  * - app_queue.c - the Queue dialplan application
00067  * - SIP subscriptions, a.k.a. "blinking lamps" or
00068  *   "buddy lists"
00069  *
00070  * The CLI command "show hints" show last known state
00071  *
00072  * \note None of these handle user states, like an IM presence
00073  * system. res_xmpp.c can subscribe and watch such states
00074  * in jabber/xmpp based systems.
00075  *
00076  * \section AstDevStateArch Architecture for devicestates
00077  *
00078  * When a channel driver or asterisk app changes state for
00079  * a watched object, it alerts the core. The core queues
00080  * a change. When the change is processed, there's a query
00081  * sent to the channel driver/provider if there's a function
00082  * to handle that, otherwise a channel walk is issued to find
00083  * a channel that involves the object.
00084  *
00085  * The changes are queued and processed by a separate thread.
00086  * This thread calls the watchers subscribing to status
00087  * changes for the object. For manager, this results
00088  * in events. For SIP, NOTIFY requests.
00089  *
00090  * - Device states
00091  *    \arg \ref devicestate.c
00092  *    \arg \ref devicestate.h
00093  *
00094  * \section AstExtStateArch Architecture for extension states
00095  *
00096  * Hints are connected to extension. If an extension changes state
00097  * it checks the hint devices. If there is a hint, the callbacks into
00098  * device states are checked. The aggregated state is set for the hint
00099  * and reported back.
00100  *
00101  * - Extension states
00102  *    \arg \ref AstENUM ast_extension_states
00103  *    \arg \ref pbx.c
00104  *    \arg \ref pbx.h
00105  * - Structures
00106  *    - \ref ast_state_cb struct.  Callbacks for watchers
00107  *    - Callback ast_state_cb_type
00108  *    - \ref ast_hint struct.
00109  * - Functions
00110  *    - ast_extension_state_add()
00111  *    - ast_extension_state_del()
00112  *    - ast_get_hint()
00113  *
00114  */
00115 
00116 /*** MODULEINFO
00117    <support_level>core</support_level>
00118  ***/
00119 
00120 /*** DOCUMENTATION
00121    <managerEvent language="en_US" name="DeviceStateChange">
00122       <managerEventInstance class="EVENT_FLAG_CALL">
00123          <synopsis>Raised when a device state changes</synopsis>
00124          <syntax>
00125             <parameter name="Device">
00126                <para>The device whose state has changed</para>
00127             </parameter>
00128             <parameter name="State">
00129                <para>The new state of the device</para>
00130             </parameter>
00131          </syntax>
00132          <description>
00133             <para>This differs from the <literal>ExtensionStatus</literal>
00134             event because this event is raised for all device state changes,
00135             not only for changes that affect dialplan hints.</para>
00136          </description>
00137          <see-also>
00138             <ref type="managerEvent">ExtensionStatus</ref>
00139          </see-also>
00140       </managerEventInstance>
00141    </managerEvent>
00142 ***/
00143 
00144 #include "asterisk.h"
00145 
00146 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 422663 $")
00147 
00148 #include "asterisk/_private.h"
00149 #include "asterisk/channel.h"
00150 #include "asterisk/utils.h"
00151 #include "asterisk/lock.h"
00152 #include "asterisk/linkedlists.h"
00153 #include "asterisk/devicestate.h"
00154 #include "asterisk/pbx.h"
00155 #include "asterisk/app.h"
00156 #include "asterisk/astobj2.h"
00157 #include "asterisk/stasis.h"
00158 #include "asterisk/devicestate.h"
00159 
00160 #define DEVSTATE_TOPIC_BUCKETS 57
00161 
00162 /*! \brief Device state strings for printing */
00163 static const char * const devstatestring[][2] = {
00164    { /* 0 AST_DEVICE_UNKNOWN */     "Unknown",     "UNKNOWN"     }, /*!< Valid, but unknown state */
00165    { /* 1 AST_DEVICE_NOT_INUSE */   "Not in use",  "NOT_INUSE"   }, /*!< Not used */
00166    { /* 2 AST_DEVICE IN USE */      "In use",      "INUSE"       }, /*!< In use */
00167    { /* 3 AST_DEVICE_BUSY */        "Busy",        "BUSY"        }, /*!< Busy */
00168    { /* 4 AST_DEVICE_INVALID */     "Invalid",     "INVALID"     }, /*!< Invalid - not known to Asterisk */
00169    { /* 5 AST_DEVICE_UNAVAILABLE */ "Unavailable", "UNAVAILABLE" }, /*!< Unavailable (not registered) */
00170    { /* 6 AST_DEVICE_RINGING */     "Ringing",     "RINGING"     }, /*!< Ring, ring, ring */
00171    { /* 7 AST_DEVICE_RINGINUSE */   "Ring+Inuse",  "RINGINUSE"   }, /*!< Ring and in use */
00172    { /* 8 AST_DEVICE_ONHOLD */      "On Hold",     "ONHOLD"      }, /*!< On Hold */
00173 };
00174 
00175 /*!\brief Mapping for channel states to device states */
00176 static const struct chan2dev {
00177    enum ast_channel_state chan;
00178    enum ast_device_state dev;
00179 } chan2dev[] = {
00180    { AST_STATE_DOWN,            AST_DEVICE_NOT_INUSE },
00181    { AST_STATE_RESERVED,        AST_DEVICE_INUSE },
00182    { AST_STATE_OFFHOOK,         AST_DEVICE_INUSE },
00183    { AST_STATE_DIALING,         AST_DEVICE_INUSE },
00184    { AST_STATE_RING,            AST_DEVICE_INUSE },
00185    { AST_STATE_RINGING,         AST_DEVICE_RINGING },
00186    { AST_STATE_UP,              AST_DEVICE_INUSE },
00187    { AST_STATE_BUSY,            AST_DEVICE_BUSY },
00188    { AST_STATE_DIALING_OFFHOOK, AST_DEVICE_INUSE },
00189    { AST_STATE_PRERING,         AST_DEVICE_RINGING },
00190 };
00191 
00192 /*! \brief  A device state provider (not a channel) */
00193 struct devstate_prov {
00194    char label[40];
00195    ast_devstate_prov_cb_type callback;
00196    AST_RWLIST_ENTRY(devstate_prov) list;
00197 };
00198 
00199 /*! \brief A list of providers */
00200 static AST_RWLIST_HEAD_STATIC(devstate_provs, devstate_prov);
00201 
00202 struct state_change {
00203    AST_LIST_ENTRY(state_change) list;
00204    enum ast_devstate_cache cachable;
00205    char device[1];
00206 };
00207 
00208 /*! \brief The state change queue. State changes are queued
00209    for processing by a separate thread */
00210 static AST_LIST_HEAD_STATIC(state_changes, state_change);
00211 
00212 /*! \brief The device state change notification thread */
00213 static pthread_t change_thread = AST_PTHREADT_NULL;
00214 
00215 /*! \brief Flag for the queue */
00216 static ast_cond_t change_pending;
00217 
00218 struct stasis_subscription *devstate_message_sub;
00219 
00220 static struct stasis_topic *device_state_topic_all;
00221 static struct stasis_cache *device_state_cache;
00222 static struct stasis_caching_topic *device_state_topic_cached;
00223 static struct stasis_topic_pool *device_state_topic_pool;
00224 
00225 static struct ast_manager_event_blob *devstate_to_ami(struct stasis_message *msg);
00226 static struct ast_event *devstate_to_event(struct stasis_message *msg);
00227 
00228 
00229 STASIS_MESSAGE_TYPE_DEFN(ast_device_state_message_type,
00230    .to_ami = devstate_to_ami,
00231    .to_event = devstate_to_event,
00232 );
00233 
00234 /* Forward declarations */
00235 static int getproviderstate(const char *provider, const char *address);
00236 
00237 /*! \brief Find devicestate as text message for output */
00238 const char *ast_devstate2str(enum ast_device_state devstate)
00239 {
00240    return devstatestring[devstate][0];
00241 }
00242 
00243 /* Deprecated interface (not prefixed with ast_) */
00244 const char *devstate2str(enum ast_device_state devstate)
00245 {
00246    return devstatestring[devstate][0];
00247 }
00248 
00249 enum ast_device_state ast_state_chan2dev(enum ast_channel_state chanstate)
00250 {
00251    int i;
00252    chanstate &= 0xFFFF;
00253    for (i = 0; i < ARRAY_LEN(chan2dev); i++) {
00254       if (chan2dev[i].chan == chanstate) {
00255          return chan2dev[i].dev;
00256       }
00257    }
00258    return AST_DEVICE_UNKNOWN;
00259 }
00260 
00261 /* Parseable */
00262 const char *ast_devstate_str(enum ast_device_state state)
00263 {
00264    return devstatestring[state][1];
00265 }
00266 
00267 enum ast_device_state ast_devstate_val(const char *val)
00268 {
00269    if (!strcasecmp(val, "NOT_INUSE"))
00270       return AST_DEVICE_NOT_INUSE;
00271    else if (!strcasecmp(val, "INUSE"))
00272       return AST_DEVICE_INUSE;
00273    else if (!strcasecmp(val, "BUSY"))
00274       return AST_DEVICE_BUSY;
00275    else if (!strcasecmp(val, "INVALID"))
00276       return AST_DEVICE_INVALID;
00277    else if (!strcasecmp(val, "UNAVAILABLE"))
00278       return AST_DEVICE_UNAVAILABLE;
00279    else if (!strcasecmp(val, "RINGING"))
00280       return AST_DEVICE_RINGING;
00281    else if (!strcasecmp(val, "RINGINUSE"))
00282       return AST_DEVICE_RINGINUSE;
00283    else if (!strcasecmp(val, "ONHOLD"))
00284       return AST_DEVICE_ONHOLD;
00285 
00286    return AST_DEVICE_UNKNOWN;
00287 }
00288 
00289 /*! \brief Find out if device is active in a call or not
00290    \note find channels with the device's name in it
00291    This function is only used for channels that does not implement
00292    devicestate natively
00293 */
00294 enum ast_device_state ast_parse_device_state(const char *device)
00295 {
00296    struct ast_channel *chan;
00297    char match[AST_CHANNEL_NAME];
00298    enum ast_device_state res;
00299 
00300    snprintf(match, sizeof(match), "%s-", device);
00301 
00302    if (!(chan = ast_channel_get_by_name_prefix(match, strlen(match)))) {
00303       return AST_DEVICE_UNKNOWN;
00304    }
00305 
00306    if (ast_channel_hold_state(chan) == AST_CONTROL_HOLD) {
00307       res = AST_DEVICE_ONHOLD;
00308    } else {
00309       res = ast_state_chan2dev(ast_channel_state(chan));
00310    }
00311    ast_channel_unref(chan);
00312 
00313    return res;
00314 }
00315 
00316 static enum ast_device_state devstate_cached(const char *device)
00317 {
00318    struct stasis_message *cached_msg;
00319    struct ast_device_state_message *device_state;
00320    enum ast_device_state state;
00321 
00322    cached_msg = stasis_cache_get_by_eid(ast_device_state_cache(),
00323       ast_device_state_message_type(), device, NULL);
00324    if (!cached_msg) {
00325       return AST_DEVICE_UNKNOWN;
00326    }
00327    device_state = stasis_message_data(cached_msg);
00328    state = device_state->state;
00329    ao2_cleanup(cached_msg);
00330 
00331    return state;
00332 }
00333 
00334 /*! \brief Check device state through channel specific function or generic function */
00335 static enum ast_device_state _ast_device_state(const char *device, int check_cache)
00336 {
00337    char *number;
00338    const struct ast_channel_tech *chan_tech;
00339    enum ast_device_state res;
00340    /*! \brief Channel driver that provides device state */
00341    char *tech;
00342 
00343    /* If the last known state is cached, just return that */
00344    if (check_cache) {
00345       res = devstate_cached(device);
00346       if (res != AST_DEVICE_UNKNOWN) {
00347          return res;
00348       }
00349    }
00350 
00351    number = ast_strdupa(device);
00352    tech = strsep(&number, "/");
00353    if (!number) {
00354       /*! \brief Another provider of device state */
00355       char *provider;
00356 
00357       provider = strsep(&tech, ":");
00358       if (!tech) {
00359          return AST_DEVICE_INVALID;
00360       }
00361       /* We have a provider */
00362       number = tech;
00363 
00364       ast_debug(3, "Checking if I can find provider for \"%s\" - number: %s\n", provider, number);
00365       return getproviderstate(provider, number);
00366    }
00367 
00368    ast_debug(4, "No provider found, checking channel drivers for %s - %s\n", tech, number);
00369 
00370    chan_tech = ast_get_channel_tech(tech);
00371    if (!chan_tech) {
00372       return AST_DEVICE_INVALID;
00373    }
00374 
00375    /* Does the channel driver support device state notification? */
00376    if (!chan_tech->devicestate) {
00377       /* No, try the generic function */
00378       return ast_parse_device_state(device);
00379    }
00380 
00381    res = chan_tech->devicestate(number);
00382    if (res == AST_DEVICE_UNKNOWN) {
00383       res = ast_parse_device_state(device);
00384    }
00385 
00386    return res;
00387 }
00388 
00389 enum ast_device_state ast_device_state(const char *device)
00390 {
00391    /* This function is called from elsewhere in the code to find out the
00392     * current state of a device.  Check the cache, first. */
00393 
00394    return _ast_device_state(device, 1);
00395 }
00396 
00397 /*! \brief Add device state provider */
00398 int ast_devstate_prov_add(const char *label, ast_devstate_prov_cb_type callback)
00399 {
00400    struct devstate_prov *devprov;
00401 
00402    if (!callback || !(devprov = ast_calloc(1, sizeof(*devprov))))
00403       return -1;
00404 
00405    devprov->callback = callback;
00406    ast_copy_string(devprov->label, label, sizeof(devprov->label));
00407 
00408    AST_RWLIST_WRLOCK(&devstate_provs);
00409    AST_RWLIST_INSERT_HEAD(&devstate_provs, devprov, list);
00410    AST_RWLIST_UNLOCK(&devstate_provs);
00411 
00412    return 0;
00413 }
00414 
00415 /*! \brief Remove device state provider */
00416 int ast_devstate_prov_del(const char *label)
00417 {
00418    struct devstate_prov *devcb;
00419    int res = -1;
00420 
00421    AST_RWLIST_WRLOCK(&devstate_provs);
00422    AST_RWLIST_TRAVERSE_SAFE_BEGIN(&devstate_provs, devcb, list) {
00423       if (!strcasecmp(devcb->label, label)) {
00424          AST_RWLIST_REMOVE_CURRENT(list);
00425          ast_free(devcb);
00426          res = 0;
00427          break;
00428       }
00429    }
00430    AST_RWLIST_TRAVERSE_SAFE_END;
00431    AST_RWLIST_UNLOCK(&devstate_provs);
00432 
00433    return res;
00434 }
00435 
00436 /*! \brief Get provider device state */
00437 static int getproviderstate(const char *provider, const char *address)
00438 {
00439    struct devstate_prov *devprov;
00440    int res = AST_DEVICE_INVALID;
00441 
00442    AST_RWLIST_RDLOCK(&devstate_provs);
00443    AST_RWLIST_TRAVERSE(&devstate_provs, devprov, list) {
00444       ast_debug(5, "Checking provider %s with %s\n", devprov->label, provider);
00445 
00446       if (!strcasecmp(devprov->label, provider)) {
00447          res = devprov->callback(address);
00448          break;
00449       }
00450    }
00451    AST_RWLIST_UNLOCK(&devstate_provs);
00452 
00453    return res;
00454 }
00455 
00456 /*! Called by the state change thread to find out what the state is, and then
00457  *  to queue up the state change event */
00458 static void do_state_change(const char *device, enum ast_devstate_cache cachable)
00459 {
00460    enum ast_device_state state;
00461 
00462    state = _ast_device_state(device, 0);
00463 
00464    ast_debug(3, "Changing state for %s - state %u (%s)\n", device, state, ast_devstate2str(state));
00465 
00466    ast_publish_device_state(device, state, cachable);
00467 }
00468 
00469 int ast_devstate_changed_literal(enum ast_device_state state, enum ast_devstate_cache cachable, const char *device)
00470 {
00471    struct state_change *change;
00472 
00473    /*
00474     * If we know the state change (how nice of the caller of this function!)
00475     * then we can just generate a device state event.
00476     *
00477     * Otherwise, we do the following:
00478     *   - Queue an event up to another thread that the state has changed
00479     *   - In the processing thread, it calls the callback provided by the
00480     *     device state provider (which may or may not be a channel driver)
00481     *     to determine the state.
00482     *   - If the device state provider does not know the state, or this is
00483     *     for a channel and the channel driver does not implement a device
00484     *     state callback, then we will look through the channel list to
00485     *     see if we can determine a state based on active calls.
00486     *   - Once a state has been determined, a device state event is generated.
00487     */
00488 
00489    if (state != AST_DEVICE_UNKNOWN) {
00490       ast_publish_device_state(device, state, cachable);
00491    } else if (change_thread == AST_PTHREADT_NULL || !(change = ast_calloc(1, sizeof(*change) + strlen(device)))) {
00492       /* we could not allocate a change struct, or */
00493       /* there is no background thread, so process the change now */
00494       do_state_change(device, cachable);
00495    } else {
00496       /* queue the change */
00497       strcpy(change->device, device);
00498       change->cachable = cachable;
00499       AST_LIST_LOCK(&state_changes);
00500       AST_LIST_INSERT_TAIL(&state_changes, change, list);
00501       ast_cond_signal(&change_pending);
00502       AST_LIST_UNLOCK(&state_changes);
00503    }
00504 
00505    return 0;
00506 }
00507 
00508 int ast_device_state_changed_literal(const char *dev)
00509 {
00510    return ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, dev);
00511 }
00512 
00513 int ast_devstate_changed(enum ast_device_state state, enum ast_devstate_cache cachable, const char *fmt, ...)
00514 {
00515    char buf[AST_MAX_EXTENSION];
00516    va_list ap;
00517 
00518    va_start(ap, fmt);
00519    vsnprintf(buf, sizeof(buf), fmt, ap);
00520    va_end(ap);
00521 
00522    return ast_devstate_changed_literal(state, cachable, buf);
00523 }
00524 
00525 int ast_device_state_changed(const char *fmt, ...)
00526 {
00527    char buf[AST_MAX_EXTENSION];
00528    va_list ap;
00529 
00530    va_start(ap, fmt);
00531    vsnprintf(buf, sizeof(buf), fmt, ap);
00532    va_end(ap);
00533 
00534    return ast_devstate_changed_literal(AST_DEVICE_UNKNOWN, AST_DEVSTATE_CACHABLE, buf);
00535 }
00536 
00537 /*! \brief Go through the dev state change queue and update changes in the dev state thread */
00538 static void *do_devstate_changes(void *data)
00539 {
00540    struct state_change *next, *current;
00541 
00542    for (;;) {
00543       /* This basically pops off any state change entries, resets the list back to NULL, unlocks, and processes each state change */
00544       AST_LIST_LOCK(&state_changes);
00545       if (AST_LIST_EMPTY(&state_changes))
00546          ast_cond_wait(&change_pending, &state_changes.lock);
00547       next = AST_LIST_FIRST(&state_changes);
00548       AST_LIST_HEAD_INIT_NOLOCK(&state_changes);
00549       AST_LIST_UNLOCK(&state_changes);
00550 
00551       /* Process each state change */
00552       while ((current = next)) {
00553          next = AST_LIST_NEXT(current, list);
00554          do_state_change(current->device, current->cachable);
00555          ast_free(current);
00556       }
00557    }
00558 
00559    return NULL;
00560 }
00561 
00562 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)
00563 {
00564    struct ast_device_state_message *new_device_state;
00565    char *pos;
00566    size_t stuff_len;
00567 
00568    ast_assert(!ast_strlen_zero(device));
00569 
00570    stuff_len = strlen(device) + 1;
00571    if (eid) {
00572       stuff_len += sizeof(*eid);
00573    }
00574    new_device_state = ao2_alloc_options(sizeof(*new_device_state) + stuff_len, NULL,
00575       AO2_ALLOC_OPT_LOCK_NOLOCK);
00576    if (!new_device_state) {
00577       return NULL;
00578    }
00579 
00580    if (eid) {
00581       /* non-aggregate device state. */
00582       new_device_state->stuff[0] = *eid;
00583       new_device_state->eid = &new_device_state->stuff[0];
00584       pos = (char *) &new_device_state->stuff[1];
00585    } else {
00586       pos = (char *) &new_device_state->stuff[0];
00587    }
00588 
00589    strcpy(pos, device);/* Safe */
00590    new_device_state->device = pos;
00591 
00592    new_device_state->state = state;
00593    new_device_state->cachable = cachable;
00594 
00595    return new_device_state;
00596 }
00597 
00598 static void devstate_change_cb(void *data, struct stasis_subscription *sub, struct stasis_message *msg)
00599 {
00600    struct ast_device_state_message *device_state;
00601 
00602    if (ast_device_state_message_type() != stasis_message_type(msg)) {
00603       return;
00604    }
00605 
00606    device_state = stasis_message_data(msg);
00607    if (device_state->cachable == AST_DEVSTATE_CACHABLE || !device_state->eid) {
00608       /* Ignore cacheable and aggregate messages. */
00609       return;
00610    }
00611 
00612    /*
00613     * Non-cacheable device state aggregates are just the
00614     * device state republished as the aggregate.
00615     */
00616    ast_publish_device_state_full(device_state->device, device_state->state,
00617       device_state->cachable, NULL);
00618 }
00619 
00620 /*! \brief Initialize the device state engine in separate thread */
00621 int ast_device_state_engine_init(void)
00622 {
00623    ast_cond_init(&change_pending, NULL);
00624    if (ast_pthread_create_background(&change_thread, NULL, do_devstate_changes, NULL) < 0) {
00625       ast_log(LOG_ERROR, "Unable to start device state change thread.\n");
00626       return -1;
00627    }
00628 
00629    return 0;
00630 }
00631 
00632 void ast_devstate_aggregate_init(struct ast_devstate_aggregate *agg)
00633 {
00634    memset(agg, 0, sizeof(*agg));
00635    agg->state = AST_DEVICE_INVALID;
00636 }
00637 
00638 void ast_devstate_aggregate_add(struct ast_devstate_aggregate *agg, enum ast_device_state state)
00639 {
00640    static enum ast_device_state state_order[] = {
00641       1, /* AST_DEVICE_UNKNOWN */
00642       3, /* AST_DEVICE_NOT_INUSE */
00643       6, /* AST_DEVICE_INUSE */
00644       7, /* AST_DEVICE_BUSY */
00645       0, /* AST_DEVICE_INVALID */
00646       2, /* AST_DEVICE_UNAVAILABLE */
00647       5, /* AST_DEVICE_RINGING */
00648       8, /* AST_DEVICE_RINGINUSE */
00649       4, /* AST_DEVICE_ONHOLD */
00650    };
00651 
00652    if (state == AST_DEVICE_RINGING) {
00653       agg->ringing = 1;
00654    } else if (state == AST_DEVICE_INUSE || state == AST_DEVICE_ONHOLD || state == AST_DEVICE_BUSY) {
00655       agg->inuse = 1;
00656    }
00657 
00658    if (agg->ringing && agg->inuse) {
00659       agg->state = AST_DEVICE_RINGINUSE;
00660    } else if (state_order[state] > state_order[agg->state]) {
00661       agg->state = state;
00662    }
00663 }
00664 
00665 enum ast_device_state ast_devstate_aggregate_result(struct ast_devstate_aggregate *agg)
00666 {
00667    return agg->state;
00668 }
00669 
00670 struct stasis_topic *ast_device_state_topic_all(void)
00671 {
00672    return device_state_topic_all;
00673 }
00674 
00675 struct stasis_cache *ast_device_state_cache(void)
00676 {
00677    return device_state_cache;
00678 }
00679 
00680 struct stasis_topic *ast_device_state_topic_cached(void)
00681 {
00682    return stasis_caching_get_topic(device_state_topic_cached);
00683 }
00684 
00685 struct stasis_topic *ast_device_state_topic(const char *device)
00686 {
00687    return stasis_topic_pool_get_topic(device_state_topic_pool, device);
00688 }
00689 
00690 int ast_device_state_clear_cache(const char *device)
00691 {
00692    struct stasis_message *cached_msg;
00693    struct stasis_message *msg;
00694 
00695    cached_msg = stasis_cache_get_by_eid(ast_device_state_cache(),
00696       ast_device_state_message_type(), device, &ast_eid_default);
00697    if (!cached_msg) {
00698       /* nothing to clear */
00699       return -1;
00700    }
00701 
00702    msg = stasis_cache_clear_create(cached_msg);
00703    if (msg) {
00704       stasis_publish(ast_device_state_topic(device), msg);
00705    }
00706    ao2_cleanup(msg);
00707    ao2_cleanup(cached_msg);
00708    return 0;
00709 }
00710 
00711 int ast_publish_device_state_full(
00712    const char *device,
00713    enum ast_device_state state,
00714    enum ast_devstate_cache cachable,
00715    struct ast_eid *eid)
00716 {
00717    RAII_VAR(struct ast_device_state_message *, device_state, NULL, ao2_cleanup);
00718    RAII_VAR(struct stasis_message *, message, NULL, ao2_cleanup);
00719    struct stasis_topic *device_specific_topic;
00720 
00721    ast_assert(!ast_strlen_zero(device));
00722 
00723    if (!ast_device_state_message_type()) {
00724       return -1;
00725    }
00726 
00727    device_state = device_state_alloc(device, state, cachable, eid);
00728    if (!device_state) {
00729       return -1;
00730    }
00731 
00732    message = stasis_message_create_full(ast_device_state_message_type(), device_state,
00733       eid);
00734    if (!message) {
00735       return -1;
00736    }
00737 
00738    device_specific_topic = ast_device_state_topic(device);
00739    if (!device_specific_topic) {
00740       return -1;
00741    }
00742 
00743    stasis_publish(device_specific_topic, message);
00744    return 0;
00745 }
00746 
00747 static const char *device_state_get_id(struct stasis_message *message)
00748 {
00749    struct ast_device_state_message *device_state;
00750 
00751    if (ast_device_state_message_type() != stasis_message_type(message)) {
00752       return NULL;
00753    }
00754 
00755    device_state = stasis_message_data(message);
00756    if (device_state->cachable == AST_DEVSTATE_NOT_CACHABLE) {
00757       return NULL;
00758    }
00759 
00760    return device_state->device;
00761 }
00762 
00763 /*!
00764  * \internal
00765  * \brief Callback to publish the aggregate device state cache entry message.
00766  * \since 12.2.0
00767  *
00768  * \param cache_topic Caching topic the aggregate message may be published over.
00769  * \param aggregate The aggregate shapshot message to publish.
00770  *
00771  * \return Nothing
00772  */
00773 static void device_state_aggregate_publish(struct stasis_topic *cache_topic, struct stasis_message *aggregate)
00774 {
00775    const char *device;
00776    struct stasis_topic *device_specific_topic;
00777 
00778    device = device_state_get_id(aggregate);
00779    if (!device) {
00780       return;
00781    }
00782    device_specific_topic = ast_device_state_topic(device);
00783    if (!device_specific_topic) {
00784       return;
00785    }
00786 
00787    stasis_publish(device_specific_topic, aggregate);
00788 }
00789 
00790 /*!
00791  * \internal
00792  * \brief Callback to calculate the aggregate device state cache entry.
00793  * \since 12.2.0
00794  *
00795  * \param entry Cache entry to calculate a new aggregate snapshot.
00796  * \param new_snapshot The shapshot that is being updated.
00797  *
00798  * \note Return a ref bumped pointer from stasis_cache_entry_get_aggregate()
00799  * if a new aggregate could not be calculated because of error.
00800  *
00801  * \return New aggregate-snapshot calculated on success.
00802  * Caller has a reference on return.
00803  */
00804 static struct stasis_message *device_state_aggregate_calc(struct stasis_cache_entry *entry, struct stasis_message *new_snapshot)
00805 {
00806    struct stasis_message *aggregate_snapshot;
00807    struct stasis_message *snapshot;
00808    struct ast_device_state_message *device_state;
00809    const char *device = NULL;
00810    struct ast_devstate_aggregate aggregate;
00811    int idx;
00812 
00813    if (!ast_device_state_message_type()) {
00814       return NULL;
00815    }
00816 
00817    /* Determine the new aggregate device state. */
00818    ast_devstate_aggregate_init(&aggregate);
00819    snapshot = stasis_cache_entry_get_local(entry);
00820    if (snapshot) {
00821       device_state = stasis_message_data(snapshot);
00822       device = device_state->device;
00823       ast_devstate_aggregate_add(&aggregate, device_state->state);
00824    }
00825    for (idx = 0; ; ++idx) {
00826       snapshot = stasis_cache_entry_get_remote(entry, idx);
00827       if (!snapshot) {
00828          break;
00829       }
00830 
00831       device_state = stasis_message_data(snapshot);
00832       device = device_state->device;
00833       ast_devstate_aggregate_add(&aggregate, device_state->state);
00834    }
00835 
00836    if (!device) {
00837       /* There are no device states cached.  Delete the aggregate. */
00838       return NULL;
00839    }
00840 
00841    snapshot = stasis_cache_entry_get_aggregate(entry);
00842    if (snapshot) {
00843       device_state = stasis_message_data(snapshot);
00844       if (device_state->state == ast_devstate_aggregate_result(&aggregate)) {
00845          /* Aggregate device state did not change. */
00846          return ao2_bump(snapshot);
00847       }
00848    }
00849 
00850    device_state = device_state_alloc(device, ast_devstate_aggregate_result(&aggregate),
00851       AST_DEVSTATE_CACHABLE, NULL);
00852    if (!device_state) {
00853       /* Bummer.  We have to keep the old aggregate snapshot. */
00854       return ao2_bump(snapshot);
00855    }
00856    aggregate_snapshot = stasis_message_create_full(ast_device_state_message_type(),
00857       device_state, NULL);
00858    ao2_cleanup(device_state);
00859    if (!aggregate_snapshot) {
00860       /* Bummer.  We have to keep the old aggregate snapshot. */
00861       return ao2_bump(snapshot);
00862    }
00863 
00864    return aggregate_snapshot;
00865 }
00866 
00867 static void devstate_cleanup(void)
00868 {
00869    devstate_message_sub = stasis_unsubscribe_and_join(devstate_message_sub);
00870    device_state_topic_cached = stasis_caching_unsubscribe_and_join(device_state_topic_cached);
00871 
00872    ao2_cleanup(device_state_cache);
00873    device_state_cache = NULL;
00874 
00875    ao2_cleanup(device_state_topic_pool);
00876    device_state_topic_pool = NULL;
00877 
00878    ao2_cleanup(device_state_topic_all);
00879    device_state_topic_all = NULL;
00880 
00881    STASIS_MESSAGE_TYPE_CLEANUP(ast_device_state_message_type);
00882 }
00883 
00884 int devstate_init(void)
00885 {
00886    ast_register_cleanup(devstate_cleanup);
00887 
00888    if (STASIS_MESSAGE_TYPE_INIT(ast_device_state_message_type) != 0) {
00889       return -1;
00890    }
00891    device_state_topic_all = stasis_topic_create("ast_device_state_topic");
00892    if (!device_state_topic_all) {
00893       devstate_cleanup();
00894       return -1;
00895    }
00896    device_state_topic_pool = stasis_topic_pool_create(ast_device_state_topic_all());
00897    if (!device_state_topic_pool) {
00898       devstate_cleanup();
00899       return -1;
00900    }
00901    device_state_cache = stasis_cache_create_full(device_state_get_id,
00902       device_state_aggregate_calc, device_state_aggregate_publish);
00903    if (!device_state_cache) {
00904       devstate_cleanup();
00905       return -1;
00906    }
00907    device_state_topic_cached = stasis_caching_topic_create(ast_device_state_topic_all(),
00908       device_state_cache);
00909    if (!device_state_topic_cached) {
00910       devstate_cleanup();
00911       return -1;
00912    }
00913 
00914    devstate_message_sub = stasis_subscribe(ast_device_state_topic_all(),
00915       devstate_change_cb, NULL);
00916    if (!devstate_message_sub) {
00917       ast_log(LOG_ERROR, "Failed to create subscription creating uncached device state aggregate events.\n");
00918       devstate_cleanup();
00919       return -1;
00920    }
00921 
00922    return 0;
00923 }
00924 
00925 static struct ast_manager_event_blob *devstate_to_ami(struct stasis_message *msg)
00926 {
00927    struct ast_device_state_message *dev_state;
00928 
00929    dev_state = stasis_message_data(msg);
00930 
00931    /* Ignore non-aggregate states */
00932    if (dev_state->eid) {
00933       return NULL;
00934    }
00935 
00936    return ast_manager_event_blob_create(EVENT_FLAG_CALL, "DeviceStateChange",
00937       "Device: %s\r\n"
00938       "State: %s\r\n",
00939       dev_state->device, ast_devstate_str(dev_state->state));
00940 }
00941 
00942 /*! \brief Convert a \ref stasis_message to a \ref ast_event */
00943 static struct ast_event *devstate_to_event(struct stasis_message *message)
00944 {
00945    struct ast_event *event;
00946    struct ast_device_state_message *device_state;
00947 
00948    if (!message) {
00949       return NULL;
00950    }
00951 
00952    device_state = stasis_message_data(message);
00953 
00954    if (device_state->eid) {
00955       event = ast_event_new(AST_EVENT_DEVICE_STATE_CHANGE,
00956                    AST_EVENT_IE_DEVICE, AST_EVENT_IE_PLTYPE_STR, device_state->device,
00957                    AST_EVENT_IE_STATE, AST_EVENT_IE_PLTYPE_UINT, device_state->state,
00958                    AST_EVENT_IE_CACHABLE, AST_EVENT_IE_PLTYPE_UINT, device_state->cachable,
00959                    AST_EVENT_IE_EID, AST_EVENT_IE_PLTYPE_RAW, device_state->eid, sizeof(*device_state->eid),
00960                    AST_EVENT_IE_END);
00961    } else {
00962       event = ast_event_new(AST_EVENT_DEVICE_STATE,
00963                    AST_EVENT_IE_DEVICE, AST_EVENT_IE_PLTYPE_STR, device_state->device,
00964                    AST_EVENT_IE_STATE, AST_EVENT_IE_PLTYPE_UINT, device_state->state,
00965                    AST_EVENT_IE_CACHABLE, AST_EVENT_IE_PLTYPE_UINT, device_state->cachable,
00966                    AST_EVENT_IE_END);
00967    }
00968 
00969    return event;
00970 }

Generated on Thu Apr 16 06:27:32 2015 for Asterisk - The Open Source Telephony Project by  doxygen 1.5.6