2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Bluetooth Mobile Device channel driver
23 * \author Dave Bowerman <david.bowerman@gmail.com>
25 * \ingroup channel_drivers
28 /*! \li \ref chan_mobile.c uses the configuration file \ref chan_mobile.conf
29 * \addtogroup configuration_file Configuration Files
33 * \page chan_mobile.conf chan_mobile.conf
34 * \verbinclude chan_mobile.conf.sample
38 <depend>bluetooth</depend>
39 <defaultenabled>no</defaultenabled>
40 <support_level>extended</support_level>
45 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
50 #include <bluetooth/bluetooth.h>
51 #include <bluetooth/hci.h>
52 #include <bluetooth/hci_lib.h>
53 #include <bluetooth/sdp.h>
54 #include <bluetooth/sdp_lib.h>
55 #include <bluetooth/rfcomm.h>
56 #include <bluetooth/sco.h>
57 #include <bluetooth/l2cap.h>
59 #include "asterisk/compat.h"
60 #include "asterisk/lock.h"
61 #include "asterisk/channel.h"
62 #include "asterisk/config.h"
63 #include "asterisk/logger.h"
64 #include "asterisk/module.h"
65 #include "asterisk/pbx.h"
66 #include "asterisk/options.h"
67 #include "asterisk/utils.h"
68 #include "asterisk/linkedlists.h"
69 #include "asterisk/cli.h"
70 #include "asterisk/devicestate.h"
71 #include "asterisk/causes.h"
72 #include "asterisk/dsp.h"
73 #include "asterisk/app.h"
74 #include "asterisk/manager.h"
75 #include "asterisk/io.h"
77 #define MBL_CONFIG "chan_mobile.conf"
78 #define MBL_CONFIG_OLD "mobile.conf"
80 #define DEVICE_FRAME_SIZE 48
81 #define DEVICE_FRAME_FORMAT AST_FORMAT_SLINEAR
82 #define CHANNEL_FRAME_SIZE 320
84 static struct ast_format prefformat;
86 static int discovery_interval = 60; /* The device discovery interval, default 60 seconds. */
87 static pthread_t discovery_thread = AST_PTHREADT_NULL; /* The discovery thread */
88 static sdp_session_t *sdp_session;
90 AST_MUTEX_DEFINE_STATIC(unload_mutex);
91 static int unloading_flag = 0;
92 static inline int check_unloading(void);
93 static inline void set_unloading(void);
101 int dev_id; /* device id */
102 int hci_socket; /* device descriptor */
103 char id[31]; /* the 'name' from mobile.conf */
104 bdaddr_t addr; /* adddress of adapter */
105 unsigned int inuse:1; /* are we in use ? */
106 unsigned int alignment_detection:1; /* do alignment detection on this adpater? */
107 struct io_context *io; /*!< io context for audio connections */
108 struct io_context *accept_io; /*!< io context for sco listener */
109 int *sco_id; /*!< the io context id of the sco listener socket */
110 int sco_socket; /*!< sco listener socket */
111 pthread_t sco_listener_thread; /*!< sco listener thread */
112 AST_LIST_ENTRY(adapter_pvt) entry;
115 static AST_RWLIST_HEAD_STATIC(adapters, adapter_pvt);
117 struct msg_queue_entry;
120 struct ast_channel *owner; /* Channel we belong to, possibly NULL */
121 struct ast_frame fr; /* "null" frame */
122 ast_mutex_t lock; /*!< pvt lock */
123 /*! queue for messages we are expecting */
124 AST_LIST_HEAD_NOLOCK(msg_queue, msg_queue_entry) msg_queue;
125 enum mbl_type type; /* Phone or Headset */
126 char id[31]; /* The id from mobile.conf */
127 int group; /* group number for group dialling */
128 bdaddr_t addr; /* address of device */
129 struct adapter_pvt *adapter; /* the adapter we use */
130 char context[AST_MAX_CONTEXT]; /* the context for incoming calls */
131 struct hfp_pvt *hfp; /*!< hfp pvt */
132 int rfcomm_port; /* rfcomm port number */
133 int rfcomm_socket; /* rfcomm socket descriptor */
134 char rfcomm_buf[256];
135 char io_buf[CHANNEL_FRAME_SIZE + AST_FRIENDLY_OFFSET];
136 struct ast_smoother *smoother; /* our smoother, for making 48 byte frames */
137 int sco_socket; /* sco socket descriptor */
138 pthread_t monitor_thread; /* monitor thread handle */
139 int timeout; /*!< used to set the timeout for rfcomm data (may be used in the future) */
140 unsigned int no_callsetup:1;
141 unsigned int has_sms:1;
142 unsigned int do_alignment_detection:1;
143 unsigned int alignment_detection_triggered:1;
144 unsigned int blackberry:1;
145 short alignment_samples[4];
149 struct ast_sched_context *sched;
153 unsigned int outgoing:1; /*!< outgoing call */
154 unsigned int incoming:1; /*!< incoming call */
155 unsigned int outgoing_sms:1; /*!< outgoing sms */
156 unsigned int incoming_sms:1; /*!< outgoing sms */
157 unsigned int needcallerid:1; /*!< we need callerid */
158 unsigned int needchup:1; /*!< we need to send a chup */
159 unsigned int needring:1; /*!< we need to send a RING */
160 unsigned int answered:1; /*!< we sent/received an answer */
161 unsigned int connected:1; /*!< do we have an rfcomm connection to a device */
163 AST_LIST_ENTRY(mbl_pvt) entry;
166 static AST_RWLIST_HEAD_STATIC(devices, mbl_pvt);
168 static int handle_response_ok(struct mbl_pvt *pvt, char *buf);
169 static int handle_response_error(struct mbl_pvt *pvt, char *buf);
170 static int handle_response_ciev(struct mbl_pvt *pvt, char *buf);
171 static int handle_response_clip(struct mbl_pvt *pvt, char *buf);
172 static int handle_response_ring(struct mbl_pvt *pvt, char *buf);
173 static int handle_response_cmti(struct mbl_pvt *pvt, char *buf);
174 static int handle_response_cmgr(struct mbl_pvt *pvt, char *buf);
175 static int handle_response_cusd(struct mbl_pvt *pvt, char *buf);
176 static int handle_response_busy(struct mbl_pvt *pvt);
177 static int handle_response_no_dialtone(struct mbl_pvt *pvt, char *buf);
178 static int handle_response_no_carrier(struct mbl_pvt *pvt, char *buf);
179 static int handle_sms_prompt(struct mbl_pvt *pvt, char *buf);
182 static char *handle_cli_mobile_show_devices(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
183 static char *handle_cli_mobile_search(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
184 static char *handle_cli_mobile_rfcomm(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
185 static char *handle_cli_mobile_cusd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
187 static struct ast_cli_entry mbl_cli[] = {
188 AST_CLI_DEFINE(handle_cli_mobile_show_devices, "Show Bluetooth Cell / Mobile devices"),
189 AST_CLI_DEFINE(handle_cli_mobile_search, "Search for Bluetooth Cell / Mobile devices"),
190 AST_CLI_DEFINE(handle_cli_mobile_rfcomm, "Send commands to the rfcomm port for debugging"),
191 AST_CLI_DEFINE(handle_cli_mobile_cusd, "Send CUSD commands to the mobile"),
195 static char *app_mblstatus = "MobileStatus";
196 static char *mblstatus_synopsis = "MobileStatus(Device,Variable)";
197 static char *mblstatus_desc =
198 "MobileStatus(Device,Variable)\n"
199 " Device - Id of mobile device from mobile.conf\n"
200 " Variable - Variable to store status in will be 1-3.\n"
201 " In order, Disconnected, Connected & Free, Connected & Busy.\n";
203 static char *app_mblsendsms = "MobileSendSMS";
204 static char *mblsendsms_synopsis = "MobileSendSMS(Device,Dest,Message)";
205 static char *mblsendsms_desc =
206 "MobileSendSms(Device,Dest,Message)\n"
207 " Device - Id of device from mobile.conf\n"
208 " Dest - destination\n"
209 " Message - text of the message\n";
211 static struct ast_channel *mbl_new(int state, struct mbl_pvt *pvt, char *cid_num,
212 const struct ast_channel *requestor);
213 static struct ast_channel *mbl_request(const char *type, struct ast_format_cap *cap,
214 const struct ast_channel *requestor, const char *data, int *cause);
215 static int mbl_call(struct ast_channel *ast, const char *dest, int timeout);
216 static int mbl_hangup(struct ast_channel *ast);
217 static int mbl_answer(struct ast_channel *ast);
218 static int mbl_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
219 static struct ast_frame *mbl_read(struct ast_channel *ast);
220 static int mbl_write(struct ast_channel *ast, struct ast_frame *frame);
221 static int mbl_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
222 static int mbl_devicestate(const char *data);
224 static void do_alignment_detection(struct mbl_pvt *pvt, char *buf, int buflen);
226 static int mbl_queue_control(struct mbl_pvt *pvt, enum ast_control_frame_type control);
227 static int mbl_queue_hangup(struct mbl_pvt *pvt);
228 static int mbl_ast_hangup(struct mbl_pvt *pvt);
229 static int mbl_has_service(struct mbl_pvt *pvt);
231 static int rfcomm_connect(bdaddr_t src, bdaddr_t dst, int remote_channel);
232 static int rfcomm_write(int rsock, char *buf);
233 static int rfcomm_write_full(int rsock, char *buf, size_t count);
234 static int rfcomm_wait(int rsock, int *ms);
235 static ssize_t rfcomm_read(int rsock, char *buf, size_t count);
237 static int sco_connect(bdaddr_t src, bdaddr_t dst);
238 static int sco_write(int s, char *buf, int len);
239 static int sco_accept(int *id, int fd, short events, void *data);
240 static int sco_bind(struct adapter_pvt *adapter);
242 static void *do_sco_listen(void *data);
243 static int sdp_search(char *addr, int profile);
245 static int headset_send_ring(const void *data);
248 * bluetooth handsfree profile helpers
251 #define HFP_HF_ECNR (1 << 0)
252 #define HFP_HF_CW (1 << 1)
253 #define HFP_HF_CID (1 << 2)
254 #define HFP_HF_VOICE (1 << 3)
255 #define HFP_HF_VOLUME (1 << 4)
256 #define HFP_HF_STATUS (1 << 5)
257 #define HFP_HF_CONTROL (1 << 6)
259 #define HFP_AG_CW (1 << 0)
260 #define HFP_AG_ECNR (1 << 1)
261 #define HFP_AG_VOICE (1 << 2)
262 #define HFP_AG_RING (1 << 3)
263 #define HFP_AG_TAG (1 << 4)
264 #define HFP_AG_REJECT (1 << 5)
265 #define HFP_AG_STATUS (1 << 6)
266 #define HFP_AG_CONTROL (1 << 7)
267 #define HFP_AG_ERRORS (1 << 8)
269 #define HFP_CIND_UNKNOWN -1
270 #define HFP_CIND_NONE 0
271 #define HFP_CIND_SERVICE 1
272 #define HFP_CIND_CALL 2
273 #define HFP_CIND_CALLSETUP 3
274 #define HFP_CIND_CALLHELD 4
275 #define HFP_CIND_SIGNAL 5
276 #define HFP_CIND_ROAM 6
277 #define HFP_CIND_BATTCHG 7
279 /* call indicator values */
280 #define HFP_CIND_CALL_NONE 0
281 #define HFP_CIND_CALL_ACTIVE 1
283 /* callsetup indicator values */
284 #define HFP_CIND_CALLSETUP_NONE 0
285 #define HFP_CIND_CALLSETUP_INCOMING 1
286 #define HFP_CIND_CALLSETUP_OUTGOING 2
287 #define HFP_CIND_CALLSETUP_ALERTING 3
289 /* service indicator values */
290 #define HFP_CIND_SERVICE_NONE 0
291 #define HFP_CIND_SERVICE_AVAILABLE 1
294 * \brief This struct holds HFP features that we support.
297 int ecnr:1; /*!< echo-cancel/noise reduction */
298 int cw:1; /*!< call waiting and three way calling */
299 int cid:1; /*!< cli presentation (callier id) */
300 int voice:1; /*!< voice recognition activation */
301 int volume:1; /*!< remote volume control */
302 int status:1; /*!< enhanced call status */
303 int control:1; /*!< enhanced call control*/
307 * \brief This struct holds HFP features the AG supports.
310 int cw:1; /*!< three way calling */
311 int ecnr:1; /*!< echo-cancel/noise reduction */
312 int voice:1; /*!< voice recognition */
313 int ring:1; /*!< in band ring tone capability */
314 int tag:1; /*!< attach a number to a voice tag */
315 int reject:1; /*!< ability to reject a call */
316 int status:1; /*!< enhanced call status */
317 int control:1; /*!< enhanced call control*/
318 int errors:1; /*!< extended error result codes*/
322 * \brief This struct holds mappings for indications.
325 int service; /*!< whether we have service or not */
326 int call; /*!< call state */
327 int callsetup; /*!< bluetooth call setup indications */
328 int callheld; /*!< bluetooth call hold indications */
329 int signal; /*!< signal strength */
330 int roam; /*!< roaming indicator */
331 int battchg; /*!< battery charge indicator */
336 * \brief This struct holds state information about the current hfp connection.
339 struct mbl_pvt *owner; /*!< the mbl_pvt struct that owns this struct */
340 int initialized:1; /*!< whether a service level connection exists or not */
341 int nocallsetup:1; /*!< whether we detected a callsetup indicator */
342 struct hfp_ag brsf; /*!< the supported feature set of the AG */
343 int cind_index[16]; /*!< the cind/ciev index to name mapping for this AG */
344 int cind_state[16]; /*!< the cind/ciev state for this AG */
345 struct hfp_cind cind_map; /*!< the cind name to index mapping for this AG */
346 int rsock; /*!< our rfcomm socket */
347 int rport; /*!< our rfcomm port */
348 int sent_alerting; /*!< have we sent alerting? */
352 /* Our supported features.
353 * we only support caller id
355 static struct hfp_hf hfp_our_brsf = {
366 static int hfp_parse_ciev(struct hfp_pvt *hfp, char *buf, int *value);
367 static char *hfp_parse_clip(struct hfp_pvt *hfp, char *buf);
368 static int hfp_parse_cmti(struct hfp_pvt *hfp, char *buf);
369 static int hfp_parse_cmgr(struct hfp_pvt *hfp, char *buf, char **from_number, char **text);
370 static int hfp_parse_brsf(struct hfp_pvt *hfp, const char *buf);
371 static int hfp_parse_cind(struct hfp_pvt *hfp, char *buf);
372 static int hfp_parse_cind_test(struct hfp_pvt *hfp, char *buf);
373 static char *hfp_parse_cusd(struct hfp_pvt *hfp, char *buf);
375 static int hfp_brsf2int(struct hfp_hf *hf);
376 static struct hfp_ag *hfp_int2brsf(int brsf, struct hfp_ag *ag);
378 static int hfp_send_brsf(struct hfp_pvt *hfp, struct hfp_hf *brsf);
379 static int hfp_send_cind(struct hfp_pvt *hfp);
380 static int hfp_send_cind_test(struct hfp_pvt *hfp);
381 static int hfp_send_cmer(struct hfp_pvt *hfp, int status);
382 static int hfp_send_clip(struct hfp_pvt *hfp, int status);
383 static int hfp_send_vgs(struct hfp_pvt *hfp, int value);
386 static int hfp_send_vgm(struct hfp_pvt *hfp, int value);
388 static int hfp_send_dtmf(struct hfp_pvt *hfp, char digit);
389 static int hfp_send_cmgf(struct hfp_pvt *hfp, int mode);
390 static int hfp_send_cnmi(struct hfp_pvt *hfp);
391 static int hfp_send_cmgr(struct hfp_pvt *hfp, int index);
392 static int hfp_send_cmgs(struct hfp_pvt *hfp, const char *number);
393 static int hfp_send_sms_text(struct hfp_pvt *hfp, const char *message);
394 static int hfp_send_chup(struct hfp_pvt *hfp);
395 static int hfp_send_atd(struct hfp_pvt *hfp, const char *number);
396 static int hfp_send_ata(struct hfp_pvt *hfp);
397 static int hfp_send_cusd(struct hfp_pvt *hfp, const char *code);
400 * bluetooth headset profile helpers
402 static int hsp_send_ok(int rsock);
403 static int hsp_send_error(int rsock);
404 static int hsp_send_vgs(int rsock, int gain);
405 static int hsp_send_vgm(int rsock, int gain);
406 static int hsp_send_ring(int rsock);
410 * Hayes AT command helpers
449 static int at_match_prefix(char *buf, char *prefix);
450 static at_message_t at_read_full(int rsock, char *buf, size_t count);
451 static inline const char *at_msg2str(at_message_t msg);
453 struct msg_queue_entry {
454 at_message_t expected;
455 at_message_t response_to;
458 AST_LIST_ENTRY(msg_queue_entry) entry;
461 static int msg_queue_push(struct mbl_pvt *pvt, at_message_t expect, at_message_t response_to);
462 static int msg_queue_push_data(struct mbl_pvt *pvt, at_message_t expect, at_message_t response_to, void *data);
463 static struct msg_queue_entry *msg_queue_pop(struct mbl_pvt *pvt);
464 static void msg_queue_free_and_pop(struct mbl_pvt *pvt);
465 static void msg_queue_flush(struct mbl_pvt *pvt);
466 static struct msg_queue_entry *msg_queue_head(struct mbl_pvt *pvt);
472 static struct ast_channel_tech mbl_tech = {
474 .description = "Bluetooth Mobile Device Channel Driver",
475 .requester = mbl_request,
477 .hangup = mbl_hangup,
478 .answer = mbl_answer,
479 .send_digit_end = mbl_digit_end,
483 .devicestate = mbl_devicestate
486 /* CLI Commands implementation */
488 static char *handle_cli_mobile_show_devices(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
494 #define FORMAT1 "%-15.15s %-17.17s %-5.5s %-15.15s %-9.9s %-10.10s %-3.3s\n"
498 e->command = "mobile show devices";
500 "Usage: mobile show devices\n"
501 " Shows the state of Bluetooth Cell / Mobile devices.\n";
508 return CLI_SHOWUSAGE;
510 ast_cli(a->fd, FORMAT1, "ID", "Address", "Group", "Adapter", "Connected", "State", "SMS");
511 AST_RWLIST_RDLOCK(&devices);
512 AST_RWLIST_TRAVERSE(&devices, pvt, entry) {
513 ast_mutex_lock(&pvt->lock);
514 ba2str(&pvt->addr, bdaddr);
515 snprintf(group, sizeof(group), "%d", pvt->group);
516 ast_cli(a->fd, FORMAT1,
521 pvt->connected ? "Yes" : "No",
522 (!pvt->connected) ? "None" : (pvt->owner) ? "Busy" : (pvt->outgoing_sms || pvt->incoming_sms) ? "SMS" : (mbl_has_service(pvt)) ? "Free" : "No Service",
523 (pvt->has_sms) ? "Yes" : "No"
525 ast_mutex_unlock(&pvt->lock);
527 AST_RWLIST_UNLOCK(&devices);
534 static char *handle_cli_mobile_search(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
536 struct adapter_pvt *adapter;
537 inquiry_info *ii = NULL;
538 int max_rsp, num_rsp;
540 int i, phport, hsport;
544 #define FORMAT1 "%-17.17s %-30.30s %-6.6s %-7.7s %-4.4s\n"
545 #define FORMAT2 "%-17.17s %-30.30s %-6.6s %-7.7s %d\n"
549 e->command = "mobile search";
551 "Usage: mobile search\n"
552 " Searches for Bluetooth Cell / Mobile devices in range.\n";
559 return CLI_SHOWUSAGE;
561 /* find a free adapter */
562 AST_RWLIST_RDLOCK(&adapters);
563 AST_RWLIST_TRAVERSE(&adapters, adapter, entry) {
567 AST_RWLIST_UNLOCK(&adapters);
570 ast_cli(a->fd, "All Bluetooth adapters are in use at this time.\n");
576 flags = IREQ_CACHE_FLUSH;
578 ii = ast_alloca(max_rsp * sizeof(inquiry_info));
579 num_rsp = hci_inquiry(adapter->dev_id, len, max_rsp, NULL, &ii, flags);
581 ast_cli(a->fd, FORMAT1, "Address", "Name", "Usable", "Type", "Port");
582 for (i = 0; i < num_rsp; i++) {
583 ba2str(&(ii + i)->bdaddr, addr);
585 if (hci_read_remote_name(adapter->hci_socket, &(ii + i)->bdaddr, sizeof(name) - 1, name, 0) < 0)
586 strcpy(name, "[unknown]");
587 phport = sdp_search(addr, HANDSFREE_AGW_PROFILE_ID);
589 hsport = sdp_search(addr, HEADSET_PROFILE_ID);
592 ast_cli(a->fd, FORMAT2, addr, name, (phport > 0 || hsport > 0) ? "Yes" : "No",
593 (phport > 0) ? "Phone" : "Headset", (phport > 0) ? phport : hsport);
596 ast_cli(a->fd, "No Bluetooth Cell / Mobile devices found.\n");
604 static char *handle_cli_mobile_rfcomm(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
607 struct mbl_pvt *pvt = NULL;
611 e->command = "mobile rfcomm";
613 "Usage: mobile rfcomm <device ID> <command>\n"
614 " Send <command> to the rfcomm port on the device\n"
615 " with the specified <device ID>.\n";
622 return CLI_SHOWUSAGE;
624 AST_RWLIST_RDLOCK(&devices);
625 AST_RWLIST_TRAVERSE(&devices, pvt, entry) {
626 if (!strcmp(pvt->id, a->argv[2]))
629 AST_RWLIST_UNLOCK(&devices);
632 ast_cli(a->fd, "Device %s not found.\n", a->argv[2]);
636 ast_mutex_lock(&pvt->lock);
637 if (!pvt->connected) {
638 ast_cli(a->fd, "Device %s not connected.\n", a->argv[2]);
642 snprintf(buf, sizeof(buf), "%s\r", a->argv[3]);
643 rfcomm_write(pvt->rfcomm_socket, buf);
644 msg_queue_push(pvt, AT_OK, AT_UNKNOWN);
647 ast_mutex_unlock(&pvt->lock);
652 static char *handle_cli_mobile_cusd(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
655 struct mbl_pvt *pvt = NULL;
659 e->command = "mobile cusd";
661 "Usage: mobile cusd <device ID> <command>\n"
662 " Send cusd <command> to the rfcomm port on the device\n"
663 " with the specified <device ID>.\n";
670 return CLI_SHOWUSAGE;
672 AST_RWLIST_RDLOCK(&devices);
673 AST_RWLIST_TRAVERSE(&devices, pvt, entry) {
674 if (!strcmp(pvt->id, a->argv[2]))
677 AST_RWLIST_UNLOCK(&devices);
680 ast_cli(a->fd, "Device %s not found.\n", a->argv[2]);
684 ast_mutex_lock(&pvt->lock);
685 if (!pvt->connected) {
686 ast_cli(a->fd, "Device %s not connected.\n", a->argv[2]);
690 snprintf(buf, sizeof(buf), "%s", a->argv[3]);
691 if (hfp_send_cusd(pvt->hfp, buf) || msg_queue_push(pvt, AT_OK, AT_CUSD)) {
692 ast_cli(a->fd, "[%s] error sending CUSD\n", pvt->id);
697 ast_mutex_unlock(&pvt->lock);
704 Dialplan applications implementation
708 static int mbl_status_exec(struct ast_channel *ast, const char *data)
716 AST_DECLARE_APP_ARGS(args,
718 AST_APP_ARG(variable);
721 if (ast_strlen_zero(data))
724 parse = ast_strdupa(data);
726 AST_STANDARD_APP_ARGS(args, parse);
728 if (ast_strlen_zero(args.device) || ast_strlen_zero(args.variable))
733 AST_RWLIST_RDLOCK(&devices);
734 AST_RWLIST_TRAVERSE(&devices, pvt, entry) {
735 if (!strcmp(pvt->id, args.device))
738 AST_RWLIST_UNLOCK(&devices);
741 ast_mutex_lock(&pvt->lock);
746 ast_mutex_unlock(&pvt->lock);
749 snprintf(status, sizeof(status), "%d", stat);
750 pbx_builtin_setvar_helper(ast, args.variable, status);
756 static int mbl_sendsms_exec(struct ast_channel *ast, const char *data)
760 char *parse, *message;
762 AST_DECLARE_APP_ARGS(args,
765 AST_APP_ARG(message);
768 if (ast_strlen_zero(data))
771 parse = ast_strdupa(data);
773 AST_STANDARD_APP_ARGS(args, parse);
775 if (ast_strlen_zero(args.device)) {
776 ast_log(LOG_ERROR,"NULL device for message -- SMS will not be sent.\n");
780 if (ast_strlen_zero(args.dest)) {
781 ast_log(LOG_ERROR,"NULL destination for message -- SMS will not be sent.\n");
785 if (ast_strlen_zero(args.message)) {
786 ast_log(LOG_ERROR,"NULL Message to be sent -- SMS will not be sent.\n");
790 AST_RWLIST_RDLOCK(&devices);
791 AST_RWLIST_TRAVERSE(&devices, pvt, entry) {
792 if (!strcmp(pvt->id, args.device))
795 AST_RWLIST_UNLOCK(&devices);
798 ast_log(LOG_ERROR,"Bluetooth device %s wasn't found in the list -- SMS will not be sent.\n", args.device);
802 ast_mutex_lock(&pvt->lock);
803 if (!pvt->connected) {
804 ast_log(LOG_ERROR,"Bluetooth device %s wasn't connected -- SMS will not be sent.\n", args.device);
809 ast_log(LOG_ERROR,"Bluetooth device %s doesn't handle SMS -- SMS will not be sent.\n", args.device);
813 message = ast_strdup(args.message);
815 if (hfp_send_cmgs(pvt->hfp, args.dest)
816 || msg_queue_push_data(pvt, AT_SMS_PROMPT, AT_CMGS, message)) {
818 ast_log(LOG_ERROR, "[%s] problem sending SMS message\n", pvt->id);
822 ast_mutex_unlock(&pvt->lock);
829 ast_mutex_unlock(&pvt->lock);
836 Channel Driver callbacks
840 static struct ast_channel *mbl_new(int state, struct mbl_pvt *pvt, char *cid_num,
841 const struct ast_channel *requestor)
844 struct ast_channel *chn;
847 pvt->alignment_count = 0;
848 pvt->alignment_detection_triggered = 0;
849 if (pvt->adapter->alignment_detection)
850 pvt->do_alignment_detection = 1;
852 pvt->do_alignment_detection = 0;
854 ast_smoother_reset(pvt->smoother, DEVICE_FRAME_SIZE);
855 ast_dsp_digitreset(pvt->dsp);
857 chn = ast_channel_alloc(1, state, cid_num, pvt->id, 0, 0, pvt->context,
858 requestor ? ast_channel_linkedid(requestor) : "", 0,
859 "Mobile/%s-%04lx", pvt->id, ast_random() & 0xffff);
864 ast_channel_tech_set(chn, &mbl_tech);
865 ast_format_cap_add(ast_channel_nativeformats(chn), &prefformat);
866 ast_format_copy(ast_channel_rawreadformat(chn), &prefformat);
867 ast_format_copy(ast_channel_rawwriteformat(chn), &prefformat);
868 ast_format_copy(ast_channel_writeformat(chn), &prefformat);
869 ast_format_copy(ast_channel_readformat(chn), &prefformat);
870 ast_channel_tech_pvt_set(chn, pvt);
872 if (state == AST_STATE_RING)
873 ast_channel_rings_set(chn, 1);
875 ast_channel_language_set(chn, "en");
878 if (pvt->sco_socket != -1) {
879 ast_channel_set_fd(chn, 0, pvt->sco_socket);
888 static struct ast_channel *mbl_request(const char *type, struct ast_format_cap *cap,
889 const struct ast_channel *requestor, const char *data, int *cause)
892 struct ast_channel *chn = NULL;
894 char *dest_dev = NULL;
895 char *dest_num = NULL;
899 ast_log(LOG_WARNING, "Channel requested with no data\n");
900 *cause = AST_CAUSE_INCOMPATIBLE_DESTINATION;
904 if (!(ast_format_cap_iscompatible(cap, &prefformat))) {
906 ast_log(LOG_WARNING, "Asked to get a channel of unsupported format '%s'\n", ast_getformatname_multiple(tmp, sizeof(tmp), cap));
907 *cause = AST_CAUSE_FACILITY_NOT_IMPLEMENTED;
911 dest_dev = ast_strdupa(data);
913 dest_num = strchr(dest_dev, '/');
917 if (((dest_dev[0] == 'g') || (dest_dev[0] == 'G')) && ((dest_dev[1] >= '0') && (dest_dev[1] <= '9'))) {
918 group = atoi(&dest_dev[1]);
921 /* Find requested device and make sure it's connected. */
922 AST_RWLIST_RDLOCK(&devices);
923 AST_RWLIST_TRAVERSE(&devices, pvt, entry) {
924 if (group > -1 && pvt->group == group && pvt->connected && !pvt->owner) {
925 if (!mbl_has_service(pvt)) {
930 } else if (!strcmp(pvt->id, dest_dev)) {
934 AST_RWLIST_UNLOCK(&devices);
935 if (!pvt || !pvt->connected || pvt->owner) {
936 ast_log(LOG_WARNING, "Request to call on device %s which is not connected / already in use.\n", dest_dev);
937 *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL;
941 if ((pvt->type == MBL_TYPE_PHONE) && !dest_num) {
942 ast_log(LOG_WARNING, "Can't determine destination number.\n");
943 *cause = AST_CAUSE_INCOMPATIBLE_DESTINATION;
947 ast_mutex_lock(&pvt->lock);
948 chn = mbl_new(AST_STATE_DOWN, pvt, NULL, requestor);
949 ast_mutex_unlock(&pvt->lock);
951 ast_log(LOG_WARNING, "Unable to allocate channel structure.\n");
952 *cause = AST_CAUSE_REQUESTED_CHAN_UNAVAIL;
960 static int mbl_call(struct ast_channel *ast, const char *dest, int timeout)
964 char *dest_num = NULL;
966 dest_dev = ast_strdupa(dest);
968 pvt = ast_channel_tech_pvt(ast);
970 if (pvt->type == MBL_TYPE_PHONE) {
971 dest_num = strchr(dest_dev, '/');
973 ast_log(LOG_WARNING, "Cant determine destination number.\n");
979 if ((ast_channel_state(ast) != AST_STATE_DOWN) && (ast_channel_state(ast) != AST_STATE_RESERVED)) {
980 ast_log(LOG_WARNING, "mbl_call called on %s, neither down nor reserved\n", ast_channel_name(ast));
984 ast_debug(1, "Calling %s on %s\n", dest, ast_channel_name(ast));
986 ast_mutex_lock(&pvt->lock);
987 if (pvt->type == MBL_TYPE_PHONE) {
988 if (hfp_send_atd(pvt->hfp, dest_num)) {
989 ast_mutex_unlock(&pvt->lock);
990 ast_log(LOG_ERROR, "error sending ATD command on %s\n", pvt->id);
993 pvt->hangupcause = 0;
995 msg_queue_push(pvt, AT_OK, AT_D);
997 if (hsp_send_ring(pvt->rfcomm_socket)) {
998 ast_log(LOG_ERROR, "[%s] error ringing device\n", pvt->id);
999 ast_mutex_unlock(&pvt->lock);
1003 if ((pvt->ring_sched_id = ast_sched_add(pvt->sched, 6000, headset_send_ring, pvt)) == -1) {
1004 ast_log(LOG_ERROR, "[%s] error ringing device\n", pvt->id);
1005 ast_mutex_unlock(&pvt->lock);
1012 ast_mutex_unlock(&pvt->lock);
1018 static int mbl_hangup(struct ast_channel *ast)
1021 struct mbl_pvt *pvt;
1023 if (!ast_channel_tech_pvt(ast)) {
1024 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
1027 pvt = ast_channel_tech_pvt(ast);
1029 ast_debug(1, "[%s] hanging up device\n", pvt->id);
1031 ast_mutex_lock(&pvt->lock);
1032 ast_channel_set_fd(ast, 0, -1);
1033 close(pvt->sco_socket);
1034 pvt->sco_socket = -1;
1036 if (pvt->needchup) {
1037 hfp_send_chup(pvt->hfp);
1038 msg_queue_push(pvt, AT_OK, AT_CHUP);
1046 ast_channel_tech_pvt_set(ast, NULL);
1048 ast_mutex_unlock(&pvt->lock);
1050 ast_setstate(ast, AST_STATE_DOWN);
1056 static int mbl_answer(struct ast_channel *ast)
1059 struct mbl_pvt *pvt;
1061 pvt = ast_channel_tech_pvt(ast);
1063 if (pvt->type == MBL_TYPE_HEADSET)
1066 ast_mutex_lock(&pvt->lock);
1067 if (pvt->incoming) {
1068 hfp_send_ata(pvt->hfp);
1069 msg_queue_push(pvt, AT_OK, AT_A);
1072 ast_mutex_unlock(&pvt->lock);
1078 static int mbl_digit_end(struct ast_channel *ast, char digit, unsigned int duration)
1080 struct mbl_pvt *pvt = ast_channel_tech_pvt(ast);
1082 if (pvt->type == MBL_TYPE_HEADSET)
1085 ast_mutex_lock(&pvt->lock);
1086 if (hfp_send_dtmf(pvt->hfp, digit)) {
1087 ast_mutex_unlock(&pvt->lock);
1088 ast_debug(1, "[%s] error sending digit %c\n", pvt->id, digit);
1091 msg_queue_push(pvt, AT_OK, AT_VTS);
1092 ast_mutex_unlock(&pvt->lock);
1094 ast_debug(1, "[%s] dialed %c\n", pvt->id, digit);
1099 static struct ast_frame *mbl_read(struct ast_channel *ast)
1102 struct mbl_pvt *pvt = ast_channel_tech_pvt(ast);
1103 struct ast_frame *fr = &ast_null_frame;
1106 ast_debug(3, "*** mbl_read()\n");
1108 while (ast_mutex_trylock(&pvt->lock)) {
1109 CHANNEL_DEADLOCK_AVOIDANCE(ast);
1112 if (!pvt->owner || pvt->sco_socket == -1) {
1116 memset(&pvt->fr, 0x00, sizeof(struct ast_frame));
1117 pvt->fr.frametype = AST_FRAME_VOICE;
1118 ast_format_set(&pvt->fr.subclass.format, DEVICE_FRAME_FORMAT, 0);
1119 pvt->fr.src = "Mobile";
1120 pvt->fr.offset = AST_FRIENDLY_OFFSET;
1121 pvt->fr.mallocd = 0;
1122 pvt->fr.delivery.tv_sec = 0;
1123 pvt->fr.delivery.tv_usec = 0;
1124 pvt->fr.data.ptr = pvt->io_buf + AST_FRIENDLY_OFFSET;
1126 if ((r = read(pvt->sco_socket, pvt->fr.data.ptr, DEVICE_FRAME_SIZE)) == -1) {
1127 if (errno != EAGAIN && errno != EINTR) {
1128 ast_debug(1, "[%s] read error %d, going to wait for new connection\n", pvt->id, errno);
1129 close(pvt->sco_socket);
1130 pvt->sco_socket = -1;
1131 ast_channel_set_fd(ast, 0, -1);
1136 pvt->fr.datalen = r;
1137 pvt->fr.samples = r / 2;
1139 if (pvt->do_alignment_detection)
1140 do_alignment_detection(pvt, pvt->fr.data.ptr, r);
1142 fr = ast_dsp_process(ast, pvt->dsp, &pvt->fr);
1144 ast_mutex_unlock(&pvt->lock);
1149 ast_mutex_unlock(&pvt->lock);
1153 static int mbl_write(struct ast_channel *ast, struct ast_frame *frame)
1156 struct mbl_pvt *pvt = ast_channel_tech_pvt(ast);
1157 struct ast_frame *f;
1159 ast_debug(3, "*** mbl_write\n");
1161 if (frame->frametype != AST_FRAME_VOICE) {
1165 while (ast_mutex_trylock(&pvt->lock)) {
1166 CHANNEL_DEADLOCK_AVOIDANCE(ast);
1169 ast_smoother_feed(pvt->smoother, frame);
1171 while ((f = ast_smoother_read(pvt->smoother))) {
1172 sco_write(pvt->sco_socket, f->data.ptr, f->datalen);
1175 ast_mutex_unlock(&pvt->lock);
1181 static int mbl_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1184 struct mbl_pvt *pvt = ast_channel_tech_pvt(newchan);
1187 ast_debug(1, "fixup failed, no pvt on newchan\n");
1191 ast_mutex_lock(&pvt->lock);
1192 if (pvt->owner == oldchan)
1193 pvt->owner = newchan;
1194 ast_mutex_unlock(&pvt->lock);
1200 static int mbl_devicestate(const char *data)
1204 int res = AST_DEVICE_INVALID;
1205 struct mbl_pvt *pvt;
1207 device = ast_strdupa(S_OR(data, ""));
1209 ast_debug(1, "Checking device state for device %s\n", device);
1211 AST_RWLIST_RDLOCK(&devices);
1212 AST_RWLIST_TRAVERSE(&devices, pvt, entry) {
1213 if (!strcmp(pvt->id, device))
1216 AST_RWLIST_UNLOCK(&devices);
1221 ast_mutex_lock(&pvt->lock);
1222 if (pvt->connected) {
1224 res = AST_DEVICE_INUSE;
1226 res = AST_DEVICE_NOT_INUSE;
1228 if (!mbl_has_service(pvt))
1229 res = AST_DEVICE_UNAVAILABLE;
1231 ast_mutex_unlock(&pvt->lock);
1245 do_alignment_detection()
1247 This routine attempts to detect where we get misaligned sco audio data from the bluetooth adaptor.
1249 Its enabled by alignmentdetect=yes under the adapter entry in mobile.conf
1251 Some adapters suffer a problem where occasionally they will byte shift the audio stream one byte to the right.
1252 The result is static or white noise on the inbound (from the adapter) leg of the call.
1253 This is characterised by a sudden jump in magnitude of the value of the 16 bit samples.
1255 Here we look at the first 4 48 byte frames. We average the absolute values of each sample in the frame,
1256 then average the sum of the averages of frames 1, 2, and 3.
1257 Frame zero is usually zero.
1258 If the end result > 100, and it usually is if we have the problem, set a flag and compensate by shifting the bytes
1259 for each subsequent frame during the call.
1261 If the result is <= 100 then clear the flag so we don't come back in here...
1263 This seems to work OK....
1267 static void do_alignment_detection(struct mbl_pvt *pvt, char *buf, int buflen)
1274 if (pvt->alignment_detection_triggered) {
1275 for (i=buflen, p=buf+buflen-1; i>0; i--, p--)
1281 if (pvt->alignment_count < 4) {
1283 for (i=0, a=0; i<buflen/2; i++) {
1287 pvt->alignment_samples[pvt->alignment_count++] = a;
1291 ast_debug(1, "Alignment Detection result is [%-d %-d %-d %-d]\n", pvt->alignment_samples[0], pvt->alignment_samples[1], pvt->alignment_samples[2], pvt->alignment_samples[3]);
1293 a = abs(pvt->alignment_samples[1]) + abs(pvt->alignment_samples[2]) + abs(pvt->alignment_samples[3]);
1296 pvt->alignment_detection_triggered = 1;
1297 ast_debug(1, "Alignment Detection Triggered.\n");
1299 pvt->do_alignment_detection = 0;
1303 static int mbl_queue_control(struct mbl_pvt *pvt, enum ast_control_frame_type control)
1307 if (ast_channel_trylock(pvt->owner)) {
1308 DEADLOCK_AVOIDANCE(&pvt->lock);
1310 ast_queue_control(pvt->owner, control);
1311 ast_channel_unlock(pvt->owner);
1320 static int mbl_queue_hangup(struct mbl_pvt *pvt)
1324 if (ast_channel_trylock(pvt->owner)) {
1325 DEADLOCK_AVOIDANCE(&pvt->lock);
1327 if (pvt->hangupcause != 0) {
1328 ast_channel_hangupcause_set(pvt->owner, pvt->hangupcause);
1330 ast_queue_hangup(pvt->owner);
1331 ast_channel_unlock(pvt->owner);
1340 static int mbl_ast_hangup(struct mbl_pvt *pvt)
1343 ast_hangup(pvt->owner);
1349 * \brief Check if a mobile device has service.
1350 * \param pvt a mbl_pvt struct
1351 * \retval 1 this device has service
1352 * \retval 0 no service
1354 * \note This function will always indicate that service is available if the
1355 * given device does not support service indication.
1357 static int mbl_has_service(struct mbl_pvt *pvt)
1360 if (pvt->type != MBL_TYPE_PHONE)
1363 if (!pvt->hfp->cind_map.service)
1366 if (pvt->hfp->cind_state[pvt->hfp->cind_map.service] == HFP_CIND_SERVICE_AVAILABLE)
1378 static int rfcomm_connect(bdaddr_t src, bdaddr_t dst, int remote_channel)
1381 struct sockaddr_rc addr;
1384 if ((s = socket(PF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM)) < 0) {
1385 ast_debug(1, "socket() failed (%d).\n", errno);
1389 memset(&addr, 0, sizeof(addr));
1390 addr.rc_family = AF_BLUETOOTH;
1391 bacpy(&addr.rc_bdaddr, &src);
1392 addr.rc_channel = (uint8_t) 1;
1393 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
1394 ast_debug(1, "bind() failed (%d).\n", errno);
1399 memset(&addr, 0, sizeof(addr));
1400 addr.rc_family = AF_BLUETOOTH;
1401 bacpy(&addr.rc_bdaddr, &dst);
1402 addr.rc_channel = remote_channel;
1403 if (connect(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
1404 ast_debug(1, "connect() failed (%d).\n", errno);
1414 * \brief Write to an rfcomm socket.
1415 * \param rsock the socket to write to
1416 * \param buf the null terminated buffer to write
1418 * This function will write characters from buf. The buffer must be null
1424 static int rfcomm_write(int rsock, char *buf)
1426 return rfcomm_write_full(rsock, buf, strlen(buf));
1431 * \brief Write to an rfcomm socket.
1432 * \param rsock the socket to write to
1433 * \param buf the buffer to write
1434 * \param count the number of characters from the buffer to write
1436 * This function will write count characters from buf. It will always write
1437 * count chars unless it encounters an error.
1442 static int rfcomm_write_full(int rsock, char *buf, size_t count)
1447 ast_debug(1, "rfcomm_write() (%d) [%.*s]\n", rsock, (int) count, buf);
1449 if ((out_count = write(rsock, p, count)) == -1) {
1450 ast_debug(1, "rfcomm_write() error [%d]\n", errno);
1461 * \brief Wait for activity on an rfcomm socket.
1462 * \param rsock the socket to watch
1463 * \param ms a pointer to an int containing a timeout in ms
1464 * \return zero on timeout and the socket fd (non-zero) otherwise
1467 static int rfcomm_wait(int rsock, int *ms)
1469 int exception, outfd;
1470 outfd = ast_waitfor_n_fd(&rsock, 1, ms, &exception);
1477 #ifdef RFCOMM_READ_DEBUG
1478 #define rfcomm_read_debug(c) __rfcomm_read_debug(c)
1479 static void __rfcomm_read_debug(char c)
1482 ast_debug(2, "rfcomm_read: \\r\n");
1484 ast_debug(2, "rfcomm_read: \\n\n");
1486 ast_debug(2, "rfcomm_read: %c\n", c);
1489 #define rfcomm_read_debug(c)
1493 * \brief Append the given character to the given buffer and increase the
1496 static void inline rfcomm_append_buf(char **buf, size_t count, size_t *in_count, char c)
1498 if (*in_count < count) {
1505 * \brief Read a character from the given stream and check if it matches what
1508 static int rfcomm_read_and_expect_char(int rsock, char *result, char expected)
1516 if ((res = read(rsock, result, 1)) < 1) {
1519 rfcomm_read_debug(*result);
1521 if (*result != expected) {
1529 * \brief Read a character from the given stream and append it to the given
1530 * buffer if it matches the expected character.
1532 static int rfcomm_read_and_append_char(int rsock, char **buf, size_t count, size_t *in_count, char *result, char expected)
1540 if ((res = rfcomm_read_and_expect_char(rsock, result, expected)) < 1) {
1544 rfcomm_append_buf(buf, count, in_count, *result);
1549 * \brief Read until \verbatim '\r\n'. \endverbatim
1550 * This function consumes the \verbatim'\r\n'\endverbatim but does not add it to buf.
1552 static int rfcomm_read_until_crlf(int rsock, char **buf, size_t count, size_t *in_count)
1557 while ((res = read(rsock, &c, 1)) == 1) {
1558 rfcomm_read_debug(c);
1560 if ((res = rfcomm_read_and_expect_char(rsock, &c, '\n')) == 1) {
1562 } else if (res == -2) {
1563 rfcomm_append_buf(buf, count, in_count, '\r');
1565 rfcomm_append_buf(buf, count, in_count, '\r');
1570 rfcomm_append_buf(buf, count, in_count, c);
1576 * \brief Read the remainder of an AT SMS prompt.
1577 * \note the entire parsed string is \verbatim '\r\n> ' \endverbatim
1579 * By the time this function is executed, only a ' ' is left to read.
1581 static int rfcomm_read_sms_prompt(int rsock, char **buf, size_t count, size_t *in_count)
1584 if ((res = rfcomm_read_and_append_char(rsock, buf, count, in_count, NULL, ' ')) < 1)
1590 ast_log(LOG_ERROR, "error parsing SMS prompt on rfcomm socket\n");
1595 * \brief Read until a \verbatim \r\nOK\r\n \endverbatim message.
1597 static int rfcomm_read_until_ok(int rsock, char **buf, size_t count, size_t *in_count)
1602 /* here, we read until finding a \r\n, then we read one character at a
1603 * time looking for the string '\r\nOK\r\n'. If we only find a partial
1604 * match, we place that in the buffer and try again. */
1607 if ((res = rfcomm_read_until_crlf(rsock, buf, count, in_count)) != 1) {
1611 rfcomm_append_buf(buf, count, in_count, '\r');
1612 rfcomm_append_buf(buf, count, in_count, '\n');
1614 if ((res = rfcomm_read_and_expect_char(rsock, &c, '\r')) != 1) {
1619 rfcomm_append_buf(buf, count, in_count, c);
1623 if ((res = rfcomm_read_and_expect_char(rsock, &c, '\n')) != 1) {
1628 rfcomm_append_buf(buf, count, in_count, '\r');
1629 rfcomm_append_buf(buf, count, in_count, c);
1632 if ((res = rfcomm_read_and_expect_char(rsock, &c, 'O')) != 1) {
1637 rfcomm_append_buf(buf, count, in_count, '\r');
1638 rfcomm_append_buf(buf, count, in_count, '\n');
1639 rfcomm_append_buf(buf, count, in_count, c);
1643 if ((res = rfcomm_read_and_expect_char(rsock, &c, 'K')) != 1) {
1648 rfcomm_append_buf(buf, count, in_count, '\r');
1649 rfcomm_append_buf(buf, count, in_count, '\n');
1650 rfcomm_append_buf(buf, count, in_count, 'O');
1651 rfcomm_append_buf(buf, count, in_count, c);
1655 if ((res = rfcomm_read_and_expect_char(rsock, &c, '\r')) != 1) {
1660 rfcomm_append_buf(buf, count, in_count, '\r');
1661 rfcomm_append_buf(buf, count, in_count, '\n');
1662 rfcomm_append_buf(buf, count, in_count, 'O');
1663 rfcomm_append_buf(buf, count, in_count, 'K');
1664 rfcomm_append_buf(buf, count, in_count, c);
1668 if ((res = rfcomm_read_and_expect_char(rsock, &c, '\n')) != 1) {
1673 rfcomm_append_buf(buf, count, in_count, '\r');
1674 rfcomm_append_buf(buf, count, in_count, '\n');
1675 rfcomm_append_buf(buf, count, in_count, 'O');
1676 rfcomm_append_buf(buf, count, in_count, 'K');
1677 rfcomm_append_buf(buf, count, in_count, '\r');
1678 rfcomm_append_buf(buf, count, in_count, c);
1682 /* we have successfully parsed a '\r\nOK\r\n' string */
1691 * \brief Read the remainder of a +CMGR message.
1692 * \note the entire parsed string is \verbatim '+CMGR: ...\r\n...\r\n...\r\n...\r\nOK\r\n' \endverbatim
1694 static int rfcomm_read_cmgr(int rsock, char **buf, size_t count, size_t *in_count)
1698 /* append the \r\n that was stripped by the calling function */
1699 rfcomm_append_buf(buf, count, in_count, '\r');
1700 rfcomm_append_buf(buf, count, in_count, '\n');
1702 if ((res = rfcomm_read_until_ok(rsock, buf, count, in_count)) != 1) {
1703 ast_log(LOG_ERROR, "error reading +CMGR message on rfcomm socket\n");
1710 * \brief Read and AT result code.
1711 * \note the entire parsed string is \verbatim '\r\n<result code>\r\n' \endverbatim
1713 static int rfcomm_read_result(int rsock, char **buf, size_t count, size_t *in_count)
1718 if ((res = rfcomm_read_and_expect_char(rsock, &c, '\n')) < 1) {
1722 if ((res = rfcomm_read_and_append_char(rsock, buf, count, in_count, &c, '>')) == 1) {
1723 return rfcomm_read_sms_prompt(rsock, buf, count, in_count);
1724 } else if (res != -2) {
1728 rfcomm_append_buf(buf, count, in_count, c);
1729 res = rfcomm_read_until_crlf(rsock, buf, count, in_count);
1734 /* check for CMGR, which contains an embedded \r\n pairs terminated by
1735 * an \r\nOK\r\n message */
1736 if (*in_count >= 5 && !strncmp(*buf - *in_count, "+CMGR", 5)) {
1737 return rfcomm_read_cmgr(rsock, buf, count, in_count);
1743 ast_log(LOG_ERROR, "error parsing AT result on rfcomm socket\n");
1748 * \brief Read the remainder of an AT command.
1749 * \note the entire parsed string is \verbatim '<at command>\r' \endverbatim
1751 static int rfcomm_read_command(int rsock, char **buf, size_t count, size_t *in_count)
1756 while ((res = read(rsock, &c, 1)) == 1) {
1757 rfcomm_read_debug(c);
1758 /* stop when we get to '\r' */
1762 rfcomm_append_buf(buf, count, in_count, c);
1768 * \brief Read one Hayes AT message from an rfcomm socket.
1769 * \param rsock the rfcomm socket to read from
1770 * \param buf the buffer to store the result in
1771 * \param count the size of the buffer or the maximum number of characters to read
1773 * Here we need to read complete Hayes AT messages. The AT message formats we
1774 * support are listed below.
1777 * \r\n<result code>\r\n
1782 * These formats correspond to AT result codes, AT commands, and the AT SMS
1783 * prompt respectively. When messages are read the leading and trailing \verbatim '\r' \endverbatim
1784 * and \verbatim '\n' \endverbatim characters are discarded. If the given buffer is not large enough
1785 * to hold the response, what does not fit in the buffer will be dropped.
1787 * \note The rfcomm connection to the device is asynchronous, so there is no
1788 * guarantee that responses will be returned in a single read() call. We handle
1789 * this by blocking until we can read an entire response.
1791 * \retval 0 end of file
1792 * \retval -1 read error
1793 * \retval -2 parse error
1794 * \retval other the number of characters added to buf
1796 static ssize_t rfcomm_read(int rsock, char *buf, size_t count)
1799 size_t in_count = 0;
1802 if ((res = rfcomm_read_and_expect_char(rsock, &c, '\r')) == 1) {
1803 res = rfcomm_read_result(rsock, &buf, count, &in_count);
1804 } else if (res == -2) {
1805 rfcomm_append_buf(&buf, count, &in_count, c);
1806 res = rfcomm_read_command(rsock, &buf, count, &in_count);
1817 sco helpers and callbacks
1821 static int sco_connect(bdaddr_t src, bdaddr_t dst)
1824 struct sockaddr_sco addr;
1827 if ((s = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO)) < 0) {
1828 ast_debug(1, "socket() failed (%d).\n", errno);
1832 /* XXX this does not work with the do_sco_listen() thread (which also bind()s
1833 * to this address). Also I am not sure if it is necessary. */
1835 memset(&addr, 0, sizeof(addr));
1836 addr.sco_family = AF_BLUETOOTH;
1837 bacpy(&addr.sco_bdaddr, &src);
1838 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
1839 ast_debug(1, "bind() failed (%d).\n", errno);
1845 memset(&addr, 0, sizeof(addr));
1846 addr.sco_family = AF_BLUETOOTH;
1847 bacpy(&addr.sco_bdaddr, &dst);
1849 if (connect(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
1850 ast_debug(1, "sco connect() failed (%d).\n", errno);
1859 static int sco_write(int s, char *buf, int len)
1865 ast_debug(3, "sco_write() not ready\n");
1869 ast_debug(3, "sco_write()\n");
1871 r = write(s, buf, len);
1873 ast_debug(3, "sco write error %d\n", errno);
1882 * \brief Accept SCO connections.
1883 * This function is an ast_io callback function used to accept incoming sco
1884 * audio connections.
1886 static int sco_accept(int *id, int fd, short events, void *data)
1888 struct adapter_pvt *adapter = (struct adapter_pvt *) data;
1889 struct sockaddr_sco addr;
1891 struct mbl_pvt *pvt;
1894 struct sco_options so;
1897 addrlen = sizeof(struct sockaddr_sco);
1898 if ((sock = accept(fd, (struct sockaddr *)&addr, &addrlen)) == -1) {
1899 ast_log(LOG_ERROR, "error accepting audio connection on adapter %s\n", adapter->id);
1904 getsockopt(sock, SOL_SCO, SCO_OPTIONS, &so, &len);
1906 ba2str(&addr.sco_bdaddr, saddr);
1907 ast_debug(1, "Incoming Audio Connection from device %s MTU is %d\n", saddr, so.mtu);
1909 /* figure out which device this sco connection belongs to */
1911 AST_RWLIST_RDLOCK(&devices);
1912 AST_RWLIST_TRAVERSE(&devices, pvt, entry) {
1913 if (!bacmp(&pvt->addr, &addr.sco_bdaddr))
1916 AST_RWLIST_UNLOCK(&devices);
1918 ast_log(LOG_WARNING, "could not find device for incoming audio connection\n");
1923 ast_mutex_lock(&pvt->lock);
1924 if (pvt->sco_socket != -1) {
1925 close(pvt->sco_socket);
1926 pvt->sco_socket = -1;
1929 pvt->sco_socket = sock;
1931 ast_channel_set_fd(pvt->owner, 0, sock);
1933 ast_debug(1, "incoming audio connection for pvt without owner\n");
1936 ast_mutex_unlock(&pvt->lock);
1942 * \brief Bind an SCO listener socket for the given adapter.
1943 * \param adapter an adapter_pvt
1944 * \return -1 on error, non zero on success
1946 static int sco_bind(struct adapter_pvt *adapter)
1948 struct sockaddr_sco addr;
1951 if ((adapter->sco_socket = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO)) < 0) {
1952 ast_log(LOG_ERROR, "Unable to create sco listener socket for adapter %s.\n", adapter->id);
1956 memset(&addr, 0, sizeof(addr));
1957 addr.sco_family = AF_BLUETOOTH;
1958 bacpy(&addr.sco_bdaddr, &adapter->addr);
1959 if (bind(adapter->sco_socket, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
1960 ast_log(LOG_ERROR, "Unable to bind sco listener socket. (%d)\n", errno);
1961 goto e_close_socket;
1963 if (setsockopt(adapter->sco_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1) {
1964 ast_log(LOG_ERROR, "Unable to setsockopt sco listener socket.\n");
1965 goto e_close_socket;
1967 if (listen(adapter->sco_socket, 5) < 0) {
1968 ast_log(LOG_ERROR, "Unable to listen sco listener socket.\n");
1969 goto e_close_socket;
1972 return adapter->sco_socket;
1975 close(adapter->sco_socket);
1976 adapter->sco_socket = -1;
1983 * Hayes AT command helpers.
1987 * \brief Match the given buffer with the given prefix.
1988 * \param buf the buffer to match
1989 * \param prefix the prefix to match
1991 static int at_match_prefix(char *buf, char *prefix)
1993 return !strncmp(buf, prefix, strlen(prefix));
1997 * \brief Read an AT message and clasify it.
1998 * \param rsock an rfcomm socket
1999 * \param buf the buffer to store the result in
2000 * \param count the size of the buffer or the maximum number of characters to read
2001 * \return the type of message received, in addition buf will contain the
2002 * message received and will be null terminated
2005 static at_message_t at_read_full(int rsock, char *buf, size_t count)
2008 if ((s = rfcomm_read(rsock, buf, count - 1)) < 1)
2012 if (!strcmp("OK", buf)) {
2014 } else if (!strcmp("ERROR", buf)) {
2016 } else if (!strcmp("RING", buf)) {
2018 } else if (!strcmp("AT+CKPD=200", buf)) {
2020 } else if (!strcmp("> ", buf)) {
2021 return AT_SMS_PROMPT;
2022 } else if (at_match_prefix(buf, "+CMTI:")) {
2024 } else if (at_match_prefix(buf, "+CIEV:")) {
2026 } else if (at_match_prefix(buf, "+BRSF:")) {
2028 } else if (at_match_prefix(buf, "+CIND:")) {
2030 } else if (at_match_prefix(buf, "+CLIP:")) {
2032 } else if (at_match_prefix(buf, "+CMGR:")) {
2034 } else if (at_match_prefix(buf, "+VGM:")) {
2036 } else if (at_match_prefix(buf, "+VGS:")) {
2038 } else if (at_match_prefix(buf, "+CMS ERROR:")) {
2039 return AT_CMS_ERROR;
2040 } else if (at_match_prefix(buf, "AT+VGM=")) {
2042 } else if (at_match_prefix(buf, "AT+VGS=")) {
2044 } else if (at_match_prefix(buf, "+CUSD:")) {
2046 } else if (at_match_prefix(buf, "BUSY")) {
2048 } else if (at_match_prefix(buf, "NO DIALTONE")) {
2049 return AT_NO_DIALTONE;
2050 } else if (at_match_prefix(buf, "NO CARRIER")) {
2051 return AT_NO_CARRIER;
2052 } else if (at_match_prefix(buf, "*ECAV:")) {
2060 * \brief Get the string representation of the given AT message.
2061 * \param msg the message to process
2062 * \return a string describing the given message
2064 static inline const char *at_msg2str(at_message_t msg)
2068 case AT_PARSE_ERROR:
2069 return "PARSE ERROR";
2071 return "READ ERROR";
2095 return "SMS PROMPT";
2097 return "+CMS ERROR";
2100 case AT_NO_DIALTONE:
2101 return "NO DIALTONE";
2103 return "NO CARRIER";
2138 * bluetooth handsfree profile helpers
2142 * \brief Parse a ECAV event.
2143 * \param hfp an hfp_pvt struct
2144 * \param buf the buffer to parse (null terminated)
2145 * \return -1 on error (parse error) or a ECAM value on success
2147 * Example string: *ECAV: <ccid>,<ccstatus>,<calltype>[,<processid>]
2148 * [,exitcause][,<number>,<type>]
2150 * Example indicating busy: *ECAV: 1,7,1
2152 static int hfp_parse_ecav(struct hfp_pvt *hfp, char *buf)
2158 if (!sscanf(buf, "*ECAV: %2d,%2d,%2d", &ccid, &ccstatus, &calltype)) {
2159 ast_debug(1, "[%s] error parsing ECAV event '%s'\n", hfp->owner->id, buf);
2167 * \brief Enable Sony Erricson extensions / indications.
2168 * \param hfp an hfp_pvt struct
2170 static int hfp_send_ecam(struct hfp_pvt *hfp)
2172 return rfcomm_write(hfp->rsock, "AT*ECAM=1\r");
2176 * \brief Parse a CIEV event.
2177 * \param hfp an hfp_pvt struct
2178 * \param buf the buffer to parse (null terminated)
2179 * \param value a pointer to an int to store the event value in (can be NULL)
2180 * \return 0 on error (parse error, or unknown event) or a HFP_CIND_* value on
2183 static int hfp_parse_ciev(struct hfp_pvt *hfp, char *buf, int *value)
2189 if (!sscanf(buf, "+CIEV: %d,%d", &i, value)) {
2190 ast_debug(2, "[%s] error parsing CIEV event '%s'\n", hfp->owner->id, buf);
2191 return HFP_CIND_NONE;
2194 if (i >= ARRAY_LEN(hfp->cind_state)) {
2195 ast_debug(2, "[%s] CIEV event index too high (%s)\n", hfp->owner->id, buf);
2196 return HFP_CIND_NONE;
2199 hfp->cind_state[i] = *value;
2200 return hfp->cind_index[i];
2204 * \brief Parse a CLIP event.
2205 * \param hfp an hfp_pvt struct
2206 * \param buf the buffer to parse (null terminated)
2207 * \note buf will be modified when the CID string is parsed
2208 * \return NULL on error (parse error) or a pointer to the caller id
2209 * information in buf
2211 static char *hfp_parse_clip(struct hfp_pvt *hfp, char *buf)
2217 /* parse clip info in the following format:
2218 * +CLIP: "123456789",128,...
2222 for (i = 0; i < s && state != 3; i++) {
2224 case 0: /* search for start of the number (") */
2225 if (buf[i] == '"') {
2229 case 1: /* mark the number */
2233 case 2: /* search for the end of the number (") */
2234 if (buf[i] == '"') {
2250 * \brief Parse a CMTI notification.
2251 * \param hfp an hfp_pvt struct
2252 * \param buf the buffer to parse (null terminated)
2253 * \note buf will be modified when the CMTI message is parsed
2254 * \return -1 on error (parse error) or the index of the new sms message
2256 static int hfp_parse_cmti(struct hfp_pvt *hfp, char *buf)
2260 /* parse cmti info in the following format:
2261 * +CMTI: <mem>,<index>
2263 if (!sscanf(buf, "+CMTI: %*[^,],%d", &index)) {
2264 ast_debug(2, "[%s] error parsing CMTI event '%s'\n", hfp->owner->id, buf);
2272 * \brief Parse a CMGR message.
2273 * \param hfp an hfp_pvt struct
2274 * \param buf the buffer to parse (null terminated)
2275 * \param from_number a pointer to a char pointer which will store the from
2277 * \param text a pointer to a char pointer which will store the message text
2278 * \note buf will be modified when the CMGR message is parsed
2279 * \retval -1 parse error
2282 static int hfp_parse_cmgr(struct hfp_pvt *hfp, char *buf, char **from_number, char **text)
2287 /* parse cmgr info in the following format:
2288 * +CMGR: <msg status>,"+123456789",...\r\n
2293 for (i = 0; i < s && state != 6; i++) {
2295 case 0: /* search for start of the number section (,) */
2296 if (buf[i] == ',') {
2300 case 1: /* find the opening quote (") */
2301 if (buf[i] == '"') {
2304 case 2: /* mark the start of the number */
2306 *from_number = &buf[i];
2310 case 3: /* search for the end of the number (") */
2311 if (buf[i] == '"') {
2316 case 4: /* search for the start of the message text (\n) */
2317 if (buf[i] == '\n') {
2321 case 5: /* mark the start of the message text */
2338 * \brief Parse a CUSD answer.
2339 * \param hfp an hfp_pvt struct
2340 * \param buf the buffer to parse (null terminated)
2341 * \note buf will be modified when the CUSD string is parsed
2342 * \return NULL on error (parse error) or a pointer to the cusd message
2343 * information in buf
2345 static char *hfp_parse_cusd(struct hfp_pvt *hfp, char *buf)
2347 int i, message_start, message_end;
2351 /* parse cusd message in the following format:
2352 * +CUSD: 0,"100,00 EURO, valid till 01.01.2010, you are using tariff "Mega Tariff". More informations *111#."
2358 /* Find the start of the message (") */
2359 for (i = 0; i < s; i++) {
2360 if (buf[i] == '"') {
2361 message_start = i + 1;
2366 if (message_start == 0 || message_start >= s) {
2370 /* Find the end of the message (") */
2371 for (i = s; i > 0; i--) {
2372 if (buf[i] == '"') {
2378 if (message_end == 0) {
2382 if (message_start >= message_end) {
2386 cusd = &buf[message_start];
2387 buf[message_end] = '\0';
2393 * \brief Convert a hfp_hf struct to a BRSF int.
2394 * \param hf an hfp_hf brsf object
2395 * \return an integer representing the given brsf struct
2397 static int hfp_brsf2int(struct hfp_hf *hf)
2401 brsf |= hf->ecnr ? HFP_HF_ECNR : 0;
2402 brsf |= hf->cw ? HFP_HF_CW : 0;
2403 brsf |= hf->cid ? HFP_HF_CID : 0;
2404 brsf |= hf->voice ? HFP_HF_VOICE : 0;
2405 brsf |= hf->volume ? HFP_HF_VOLUME : 0;
2406 brsf |= hf->status ? HFP_HF_STATUS : 0;
2407 brsf |= hf->control ? HFP_HF_CONTROL : 0;
2413 * \brief Convert a BRSF int to an hfp_ag struct.
2414 * \param brsf a brsf integer
2415 * \param ag a AG (hfp_ag) brsf object
2416 * \return a pointer to the given hfp_ag object populated with the values from
2417 * the given brsf integer
2419 static struct hfp_ag *hfp_int2brsf(int brsf, struct hfp_ag *ag)
2421 ag->cw = brsf & HFP_AG_CW ? 1 : 0;
2422 ag->ecnr = brsf & HFP_AG_ECNR ? 1 : 0;
2423 ag->voice = brsf & HFP_AG_VOICE ? 1 : 0;
2424 ag->ring = brsf & HFP_AG_RING ? 1 : 0;
2425 ag->tag = brsf & HFP_AG_TAG ? 1 : 0;
2426 ag->reject = brsf & HFP_AG_REJECT ? 1 : 0;
2427 ag->status = brsf & HFP_AG_STATUS ? 1 : 0;
2428 ag->control = brsf & HFP_AG_CONTROL ? 1 : 0;
2429 ag->errors = brsf & HFP_AG_ERRORS ? 1 : 0;
2436 * \brief Send a BRSF request.
2437 * \param hfp an hfp_pvt struct
2438 * \param brsf an hfp_hf brsf struct
2440 * \retval 0 on success
2441 * \retval -1 on error
2443 static int hfp_send_brsf(struct hfp_pvt *hfp, struct hfp_hf *brsf)
2446 snprintf(cmd, sizeof(cmd), "AT+BRSF=%d\r", hfp_brsf2int(brsf));
2447 return rfcomm_write(hfp->rsock, cmd);
2451 * \brief Send the CIND read command.
2452 * \param hfp an hfp_pvt struct
2454 static int hfp_send_cind(struct hfp_pvt *hfp)
2456 return rfcomm_write(hfp->rsock, "AT+CIND?\r");
2460 * \brief Send the CIND test command.
2461 * \param hfp an hfp_pvt struct
2463 static int hfp_send_cind_test(struct hfp_pvt *hfp)
2465 return rfcomm_write(hfp->rsock, "AT+CIND=?\r");
2469 * \brief Enable or disable indicator events reporting.
2470 * \param hfp an hfp_pvt struct
2471 * \param status enable or disable events reporting (should be 1 or 0)
2473 static int hfp_send_cmer(struct hfp_pvt *hfp, int status)
2476 snprintf(cmd, sizeof(cmd), "AT+CMER=3,0,0,%d\r", status ? 1 : 0);
2477 return rfcomm_write(hfp->rsock, cmd);
2481 * \brief Send the current speaker gain level.
2482 * \param hfp an hfp_pvt struct
2483 * \param value the value to send (must be between 0 and 15)
2485 static int hfp_send_vgs(struct hfp_pvt *hfp, int value)
2488 snprintf(cmd, sizeof(cmd), "AT+VGS=%d\r", value);
2489 return rfcomm_write(hfp->rsock, cmd);
2494 * \brief Send the current microphone gain level.
2495 * \param hfp an hfp_pvt struct
2496 * \param value the value to send (must be between 0 and 15)
2498 static int hfp_send_vgm(struct hfp_pvt *hfp, int value)
2501 snprintf(cmd, sizeof(cmd), "AT+VGM=%d\r", value);
2502 return rfcomm_write(hfp->rsock, cmd);
2507 * \brief Enable or disable calling line identification.
2508 * \param hfp an hfp_pvt struct
2509 * \param status enable or disable calling line identification (should be 1 or
2512 static int hfp_send_clip(struct hfp_pvt *hfp, int status)
2515 snprintf(cmd, sizeof(cmd), "AT+CLIP=%d\r", status ? 1 : 0);
2516 return rfcomm_write(hfp->rsock, cmd);
2520 * \brief Send a DTMF command.
2521 * \param hfp an hfp_pvt struct
2522 * \param digit the dtmf digit to send
2523 * \return the result of rfcomm_write() or -1 on an invalid digit being sent
2525 static int hfp_send_dtmf(struct hfp_pvt *hfp, char digit)
2542 snprintf(cmd, sizeof(cmd), "AT+VTS=%c\r", digit);
2543 return rfcomm_write(hfp->rsock, cmd);
2550 * \brief Set the SMS mode.
2551 * \param hfp an hfp_pvt struct
2552 * \param mode the sms mode (0 = PDU, 1 = Text)
2554 static int hfp_send_cmgf(struct hfp_pvt *hfp, int mode)
2557 snprintf(cmd, sizeof(cmd), "AT+CMGF=%d\r", mode);
2558 return rfcomm_write(hfp->rsock, cmd);
2562 * \brief Setup SMS new message indication.
2563 * \param hfp an hfp_pvt struct
2565 static int hfp_send_cnmi(struct hfp_pvt *hfp)
2567 return rfcomm_write(hfp->rsock, "AT+CNMI=2,1,0,0,0\r");
2571 * \brief Read an SMS message.
2572 * \param hfp an hfp_pvt struct
2573 * \param index the location of the requested message
2575 static int hfp_send_cmgr(struct hfp_pvt *hfp, int index)
2578 snprintf(cmd, sizeof(cmd), "AT+CMGR=%d\r", index);
2579 return rfcomm_write(hfp->rsock, cmd);
2583 * \brief Start sending an SMS message.
2584 * \param hfp an hfp_pvt struct
2585 * \param number the destination of the message
2587 static int hfp_send_cmgs(struct hfp_pvt *hfp, const char *number)
2590 snprintf(cmd, sizeof(cmd), "AT+CMGS=\"%s\"\r", number);
2591 return rfcomm_write(hfp->rsock, cmd);
2595 * \brief Send the text of an SMS message.
2596 * \param hfp an hfp_pvt struct
2597 * \param message the text of the message
2599 static int hfp_send_sms_text(struct hfp_pvt *hfp, const char *message)
2602 snprintf(cmd, sizeof(cmd), "%.160s\x1a", message);
2603 return rfcomm_write(hfp->rsock, cmd);
2607 * \brief Send AT+CHUP.
2608 * \param hfp an hfp_pvt struct
2610 static int hfp_send_chup(struct hfp_pvt *hfp)
2612 return rfcomm_write(hfp->rsock, "AT+CHUP\r");
2617 * \param hfp an hfp_pvt struct
2618 * \param number the number to send
2620 static int hfp_send_atd(struct hfp_pvt *hfp, const char *number)
2623 snprintf(cmd, sizeof(cmd), "ATD%s;\r", number);
2624 return rfcomm_write(hfp->rsock, cmd);
2629 * \param hfp an hfp_pvt struct
2631 static int hfp_send_ata(struct hfp_pvt *hfp)
2633 return rfcomm_write(hfp->rsock, "ATA\r");
2638 * \param hfp an hfp_pvt struct
2639 * \param code the CUSD code to send
2641 static int hfp_send_cusd(struct hfp_pvt *hfp, const char *code)
2644 snprintf(cmd, sizeof(cmd), "AT+CUSD=1,\"%s\",15\r", code);
2645 return rfcomm_write(hfp->rsock, cmd);
2649 * \brief Parse BRSF data.
2650 * \param hfp an hfp_pvt struct
2651 * \param buf the buffer to parse (null terminated)
2653 static int hfp_parse_brsf(struct hfp_pvt *hfp, const char *buf)
2657 if (!sscanf(buf, "+BRSF:%d", &brsf))
2660 hfp_int2brsf(brsf, &hfp->brsf);
2666 * \brief Parse and store the given indicator.
2667 * \param hfp an hfp_pvt struct
2668 * \param group the indicator group
2669 * \param indicator the indicator to parse
2671 static int hfp_parse_cind_indicator(struct hfp_pvt *hfp, int group, char *indicator)
2675 /* store the current indicator */
2676 if (group >= ARRAY_LEN(hfp->cind_state)) {
2677 ast_debug(1, "ignoring CIND state '%s' for group %d, we only support up to %d indicators\n", indicator, group, (int) sizeof(hfp->cind_state));
2681 if (!sscanf(indicator, "%d", &value)) {
2682 ast_debug(1, "error parsing CIND state '%s' for group %d\n", indicator, group);
2686 hfp->cind_state[group] = value;
2691 * \brief Read the result of the AT+CIND? command.
2692 * \param hfp an hfp_pvt struct
2693 * \param buf the buffer to parse (null terminated)
2694 * \note hfp_send_cind_test() and hfp_parse_cind_test() should be called at
2695 * least once before this function is called.
2697 static int hfp_parse_cind(struct hfp_pvt *hfp, char *buf)
2699 int i, state, group;
2701 char *indicator = NULL;
2703 /* parse current state of all of our indicators. The list is in the
2705 * +CIND: 1,0,2,0,0,0,0
2710 for (i = 0; i < s; i++) {
2712 case 0: /* search for start of the status indicators (a space) */
2713 if (buf[i] == ' ') {
2718 case 1: /* mark this indicator */
2719 indicator = &buf[i];
2722 case 2: /* search for the start of the next indicator (a comma) */
2723 if (buf[i] == ',') {
2726 hfp_parse_cind_indicator(hfp, group, indicator);
2735 /* store the last indicator */
2737 hfp_parse_cind_indicator(hfp, group, indicator);
2743 * \brief Parse the result of the AT+CIND=? command.
2744 * \param hfp an hfp_pvt struct
2745 * \param buf the buffer to parse (null terminated)
2747 static int hfp_parse_cind_test(struct hfp_pvt *hfp, char *buf)
2749 int i, state, group;
2751 char *indicator = NULL;
2753 hfp->nocallsetup = 1;
2755 /* parse the indications list. It is in the follwing format:
2756 * +CIND: ("ind1",(0-1)),("ind2",(0-5))
2761 for (i = 0; i < s; i++) {
2763 case 0: /* search for start of indicator block */
2764 if (buf[i] == '(') {
2769 case 1: /* search for '"' in indicator block */
2770 if (buf[i] == '"') {
2774 case 2: /* mark the start of the indicator name */
2775 indicator = &buf[i];
2778 case 3: /* look for the end of the indicator name */
2779 if (buf[i] == '"') {
2784 case 4: /* find the start of the value range */
2785 if (buf[i] == '(') {
2789 case 5: /* mark the start of the value range */
2792 case 6: /* find the end of the value range */
2793 if (buf[i] == ')') {
2798 case 7: /* process the values we found */
2799 if (group < sizeof(hfp->cind_index)) {
2800 if (!strcmp(indicator, "service")) {
2801 hfp->cind_map.service = group;
2802 hfp->cind_index[group] = HFP_CIND_SERVICE;
2803 } else if (!strcmp(indicator, "call")) {
2804 hfp->cind_map.call = group;
2805 hfp->cind_index[group] = HFP_CIND_CALL;
2806 } else if (!strcmp(indicator, "callsetup")) {
2807 hfp->nocallsetup = 0;
2808 hfp->cind_map.callsetup = group;
2809 hfp->cind_index[group] = HFP_CIND_CALLSETUP;
2810 } else if (!strcmp(indicator, "call_setup")) { /* non standard call setup identifier */
2811 hfp->nocallsetup = 0;
2812 hfp->cind_map.callsetup = group;
2813 hfp->cind_index[group] = HFP_CIND_CALLSETUP;
2814 } else if (!strcmp(indicator, "callheld")) {
2815 hfp->cind_map.callheld = group;
2816 hfp->cind_index[group] = HFP_CIND_CALLHELD;
2817 } else if (!strcmp(indicator, "signal")) {
2818 hfp->cind_map.signal = group;
2819 hfp->cind_index[group] = HFP_CIND_SIGNAL;
2820 } else if (!strcmp(indicator, "roam")) {
2821 hfp->cind_map.roam = group;
2822 hfp->cind_index[group] = HFP_CIND_ROAM;
2823 } else if (!strcmp(indicator, "battchg")) {
2824 hfp->cind_map.battchg = group;
2825 hfp->cind_index[group] = HFP_CIND_BATTCHG;
2827 hfp->cind_index[group] = HFP_CIND_UNKNOWN;
2828 ast_debug(2, "ignoring unknown CIND indicator '%s'\n", indicator);
2831 ast_debug(1, "can't store indicator %d (%s), we only support up to %d indicators", group, indicator, (int) sizeof(hfp->cind_index));
2839 hfp->owner->no_callsetup = hfp->nocallsetup;
2846 * Bluetooth Headset Profile helpers
2850 * \brief Send an OK AT response.
2851 * \param rsock the rfcomm socket to use
2853 static int hsp_send_ok(int rsock)
2855 return rfcomm_write(rsock, "\r\nOK\r\n");
2859 * \brief Send an ERROR AT response.
2860 * \param rsock the rfcomm socket to use
2862 static int hsp_send_error(int rsock)
2864 return rfcomm_write(rsock, "\r\nERROR\r\n");
2868 * \brief Send a speaker gain unsolicited AT response
2869 * \param rsock the rfcomm socket to use
2870 * \param gain the speaker gain value
2872 static int hsp_send_vgs(int rsock, int gain)
2875 snprintf(cmd, sizeof(cmd), "\r\n+VGS=%d\r\n", gain);
2876 return rfcomm_write(rsock, cmd);
2880 * \brief Send a microphone gain unsolicited AT response
2881 * \param rsock the rfcomm socket to use
2882 * \param gain the microphone gain value
2884 static int hsp_send_vgm(int rsock, int gain)
2887 snprintf(cmd, sizeof(cmd), "\r\n+VGM=%d\r\n", gain);
2888 return rfcomm_write(rsock, cmd);
2892 * \brief Send a RING unsolicited AT response.
2893 * \param rsock the rfcomm socket to use
2895 static int hsp_send_ring(int rsock)
2897 return rfcomm_write(rsock, "\r\nRING\r\n");
2901 * message queue functions
2905 * \brief Add an item to the back of the queue.
2906 * \param pvt a mbl_pvt structure
2907 * \param expect the msg we expect to receive
2908 * \param response_to the message that was sent to generate the expected
2911 static int msg_queue_push(struct mbl_pvt *pvt, at_message_t expect, at_message_t response_to)
2913 struct msg_queue_entry *msg;
2914 if (!(msg = ast_calloc(1, sizeof(*msg)))) {
2917 msg->expected = expect;
2918 msg->response_to = response_to;
2920 AST_LIST_INSERT_TAIL(&pvt->msg_queue, msg, entry);
2925 * \brief Add an item to the back of the queue with data.
2926 * \param pvt a mbl_pvt structure
2927 * \param expect the msg we expect to receive
2928 * \param response_to the message that was sent to generate the expected
2930 * \param data data associated with this message, it will be freed when the
2933 static int msg_queue_push_data(struct mbl_pvt *pvt, at_message_t expect, at_message_t response_to, void *data)
2935 struct msg_queue_entry *msg;
2936 if (!(msg = ast_calloc(1, sizeof(*msg)))) {
2939 msg->expected = expect;
2940 msg->response_to = response_to;
2943 AST_LIST_INSERT_TAIL(&pvt->msg_queue, msg, entry);
2948 * \brief Remove an item from the front of the queue.
2949 * \param pvt a mbl_pvt structure
2950 * \return a pointer to the removed item
2952 static struct msg_queue_entry *msg_queue_pop(struct mbl_pvt *pvt)
2954 return AST_LIST_REMOVE_HEAD(&pvt->msg_queue, entry);
2958 * \brief Remove an item from the front of the queue, and free it.
2959 * \param pvt a mbl_pvt structure
2961 static void msg_queue_free_and_pop(struct mbl_pvt *pvt)
2963 struct msg_queue_entry *msg;
2964 if ((msg = msg_queue_pop(pvt))) {
2966 ast_free(msg->data);
2972 * \brief Remove all itmes from the queue and free them.
2973 * \param pvt a mbl_pvt structure
2975 static void msg_queue_flush(struct mbl_pvt *pvt)
2977 struct msg_queue_entry *msg;
2978 while ((msg = msg_queue_head(pvt)))
2979 msg_queue_free_and_pop(pvt);
2983 * \brief Get the head of a queue.
2984 * \param pvt a mbl_pvt structure
2985 * \return a pointer to the head of the given msg queue
2987 static struct msg_queue_entry *msg_queue_head(struct mbl_pvt *pvt)
2989 return AST_LIST_FIRST(&pvt->msg_queue);
3000 static int sdp_search(char *addr, int profile)
3003 sdp_session_t *session = 0;
3006 uint32_t range = 0x0000ffff;
3007 sdp_list_t *response_list, *search_list, *attrid_list;
3009 sdp_list_t *proto_list;
3010 sdp_record_t *sdprec;
3012 str2ba(addr, &bdaddr);
3014 session = sdp_connect(BDADDR_ANY, &bdaddr, SDP_RETRY_IF_BUSY);
3016 ast_debug(1, "sdp_connect() failed on device %s.\n", addr);
3020 sdp_uuid32_create(&svc_uuid, profile);
3021 search_list = sdp_list_append(0, &svc_uuid);
3022 attrid_list = sdp_list_append(0, &range);
3023 response_list = 0x00;
3024 status = sdp_service_search_attr_req(session, search_list, SDP_ATTR_REQ_RANGE, attrid_list, &response_list);
3026 if (response_list) {
3027 sdprec = (sdp_record_t *) response_list->data;
3029 if (sdp_get_access_protos(sdprec, &proto_list) == 0) {
3030 port = sdp_get_proto_port(proto_list, RFCOMM_UUID);
3031 sdp_list_free(proto_list, 0);
3033 sdp_record_free(sdprec);
3034 sdp_list_free(response_list, 0);
3036 ast_debug(1, "No responses returned for device %s.\n", addr);
3038 ast_debug(1, "sdp_service_search_attr_req() failed on device %s.\n", addr);
3040 sdp_list_free(search_list, 0);
3041 sdp_list_free(attrid_list, 0);
3048 static sdp_session_t *sdp_register(void)
3050 uint32_t service_uuid_int[] = {0, 0, 0, GENERIC_AUDIO_SVCLASS_ID};
3051 uint8_t rfcomm_channel = 1;
3052 const char *service_name = "Asterisk PABX";
3053 const char *service_dsc = "Asterisk PABX";
3054 const char *service_prov = "Asterisk";
3056 uuid_t root_uuid, l2cap_uuid, rfcomm_uuid, svc_uuid, svc_class1_uuid, svc_class2_uuid;
3057 sdp_list_t *l2cap_list = 0, *rfcomm_list = 0, *root_list = 0, *proto_list = 0, *access_proto_list = 0, *svc_uuid_list = 0;
3058 sdp_data_t *channel = 0;
3060 sdp_session_t *session = 0;
3062 sdp_record_t *record = sdp_record_alloc();
3064 sdp_uuid128_create(&svc_uuid, &service_uuid_int);
3065 sdp_set_service_id(record, svc_uuid);
3067 sdp_uuid32_create(&svc_class1_uuid, GENERIC_AUDIO_SVCLASS_ID);
3068 sdp_uuid32_create(&svc_class2_uuid, HEADSET_PROFILE_ID);
3070 svc_uuid_list = sdp_list_append(0, &svc_class1_uuid);
3071 svc_uuid_list = sdp_list_append(svc_uuid_list, &svc_class2_uuid);
3072 sdp_set_service_classes(record, svc_uuid_list);
3074 sdp_uuid16_create(&root_uuid, PUBLIC_BROWSE_GROUP);
3075 root_list = sdp_list_append(0, &root_uuid);
3076 sdp_set_browse_groups( record, root_list );
3078 sdp_uuid16_create(&l2cap_uuid, L2CAP_UUID);
3079 l2cap_list = sdp_list_append(0, &l2cap_uuid);
3080 proto_list = sdp_list_append(0, l2cap_list);
3082 sdp_uuid16_create(&rfcomm_uuid, RFCOMM_UUID);
3083 channel = sdp_data_alloc(SDP_UINT8, &rfcomm_channel);
3084 rfcomm_list = sdp_list_append(0, &rfcomm_uuid);
3085 sdp_list_append(rfcomm_list, channel);
3086 sdp_list_append(proto_list, rfcomm_list);
3088 access_proto_list = sdp_list_append(0, proto_list);
3089 sdp_set_access_protos(record, access_proto_list);
3091 sdp_set_info_attr(record, service_name, service_prov, service_dsc);
3093 if (!(session = sdp_connect(BDADDR_ANY, BDADDR_LOCAL, SDP_RETRY_IF_BUSY)))
3094 ast_log(LOG_WARNING, "Failed to connect sdp and create session.\n");
3096 if (sdp_record_register(session, record, 0) < 0) {
3097 ast_log(LOG_WARNING, "Failed to sdp_record_register error: %d\n", errno);
3102 sdp_data_free(channel);
3103 sdp_list_free(rfcomm_list, 0);
3104 sdp_list_free(root_list, 0);
3105 sdp_list_free(access_proto_list, 0);
3106 sdp_list_free(svc_uuid_list, 0);
3119 * \brief Handle the BRSF response.
3120 * \param pvt a mbl_pvt structure
3121 * \param buf a null terminated buffer containing an AT message
3125 static int handle_response_brsf(struct mbl_pvt *pvt, char *buf)
3127 struct msg_queue_entry *entry;
3128 if ((entry = msg_queue_head(pvt)) && entry->expected == AT_BRSF) {
3129 if (hfp_parse_brsf(pvt->hfp, buf)) {
3130 ast_debug(1, "[%s] error parsing BRSF\n", pvt->id);
3134 if (msg_queue_push(pvt, AT_OK, AT_BRSF)) {
3135 ast_debug(1, "[%s] error handling BRSF\n", pvt->id);
3139 msg_queue_free_and_pop(pvt);
3141 ast_debug(1, "[%s] received unexpected AT message 'BRSF' when expecting %s, ignoring\n", pvt->id, at_msg2str(entry->expected));
3143 ast_debug(1, "[%s] received unexpected AT message 'BRSF'\n", pvt->id);
3149 msg_queue_free_and_pop(pvt);
3154 * \brief Handle the CIND response.
3155 * \param pvt a mbl_pvt structure
3156 * \param buf a null terminated buffer containing an AT message
3160 static int handle_response_cind(struct mbl_pvt *pvt, char *buf)
3162 struct msg_queue_entry *entry;
3163 if ((entry = msg_queue_head(pvt)) && entry->expected == AT_CIND) {
3164 switch (entry->response_to) {
3166 if (hfp_parse_cind_test(pvt->hfp, buf) || msg_queue_push(pvt, AT_OK, AT_CIND_TEST)) {
3167 ast_debug(1, "[%s] error performing CIND test\n", pvt->id);
3172 if (hfp_parse_cind(pvt->hfp, buf) || msg_queue_push(pvt, AT_OK, AT_CIND)) {
3173 ast_debug(1, "[%s] error getting CIND state\n", pvt->id);
3178 ast_debug(1, "[%s] error getting CIND state\n", pvt->id);
3181 msg_queue_free_and_pop(pvt);
3183 ast_debug(1, "[%s] received unexpected AT message 'CIND' when expecting %s, ignoring\n", pvt->id, at_msg2str(entry->expected));
3185 ast_debug(1, "[%s] received unexpected AT message 'CIND'\n", pvt->id);
3191 msg_queue_free_and_pop(pvt);
3196 * \brief Handle OK AT messages.
3197 * \param pvt a mbl_pvt structure
3198 * \param buf a null terminated buffer containing an AT message
3202 static int handle_response_ok(struct mbl_pvt *pvt, char *buf)
3204 struct msg_queue_entry *entry;
3205 if ((entry = msg_queue_head(pvt)) && entry->expected == AT_OK) {
3206 switch (entry->response_to) {
3208 /* initialization stuff */
3210 ast_debug(1, "[%s] BSRF sent successfully\n", pvt->id);
3212 /* If this is a blackberry do CMER now, otherwise
3213 * continue with CIND as normal. */
3214 if (pvt->blackberry) {
3215 if (hfp_send_cmer(pvt->hfp, 1) || msg_queue_push(pvt, AT_OK, AT_CMER)) {
3216 ast_debug(1, "[%s] error sending CMER\n", pvt->id);
3220 if (hfp_send_cind_test(pvt->hfp) || msg_queue_push(pvt, AT_CIND, AT_CIND_TEST)) {
3221 ast_debug(1, "[%s] error sending CIND test\n", pvt->id);
3227 ast_debug(1, "[%s] CIND test sent successfully\n", pvt->id);
3229 ast_debug(2, "[%s] call: %d\n", pvt->id, pvt->hfp->cind_map.call);
3230 ast_debug(2, "[%s] callsetup: %d\n", pvt->id, pvt->hfp->cind_map.callsetup);
3231 ast_debug(2, "[%s] service: %d\n", pvt->id, pvt->hfp->cind_map.service);
3233 if (hfp_send_cind(pvt->hfp) || msg_queue_push(pvt, AT_CIND, AT_CIND)) {
3234 ast_debug(1, "[%s] error requesting CIND state\n", pvt->id);
3239 ast_debug(1, "[%s] CIND sent successfully\n", pvt->id);
3241 /* check if a call is active */
3242 if (pvt->hfp->cind_state[pvt->hfp->cind_map.call]) {
3243 ast_verb(3, "Bluetooth Device %s has a call in progress - delaying connection.\n", pvt->id);
3247 /* If this is NOT a blackberry proceed with CMER,
3248 * otherwise send CLIP. */
3249 if (!pvt->blackberry) {
3250 if (hfp_send_cmer(pvt->hfp, 1) || msg_queue_push(pvt, AT_OK, AT_CMER)) {
3251 ast_debug(1, "[%s] error sending CMER\n", pvt->id);
3255 if (hfp_send_clip(pvt->hfp, 1) || msg_queue_push(pvt, AT_OK, AT_CLIP)) {
3256 ast_debug(1, "[%s] error enabling calling line notification\n", pvt->id);
3262 ast_debug(1, "[%s] CMER sent successfully\n", pvt->id);
3264 /* If this is a blackberry proceed with the CIND test,
3265 * otherwise send CLIP. */
3266 if (pvt->blackberry) {
3267 if (hfp_send_cind_test(pvt->hfp) || msg_queue_push(pvt, AT_CIND, AT_CIND_TEST)) {
3268 ast_debug(1, "[%s] error sending CIND test\n", pvt->id);
3272 if (hfp_send_clip(pvt->hfp, 1) || msg_queue_push(pvt, AT_OK, AT_CLIP)) {
3273 ast_debug(1, "[%s] error enabling calling line notification\n", pvt->id);
3279 ast_debug(1, "[%s] caling line indication enabled\n", pvt->id);
3280 if (hfp_send_ecam(pvt->hfp) || msg_queue_push(pvt, AT_OK, AT_ECAM)) {
3281 ast_debug(1, "[%s] error enabling Sony Ericsson call monitoring extensions\n", pvt->id);
3287 ast_debug(1, "[%s] Sony Ericsson call monitoring is active on device\n", pvt->id);
3288 if (hfp_send_vgs(pvt->hfp, 15) || msg_queue_push(pvt, AT_OK, AT_VGS)) {
3289 ast_debug(1, "[%s] error synchronizing gain settings\n", pvt->id);
3294 pvt->hfp->initialized = 1;
3295 ast_verb(3, "Bluetooth Device %s initialized and ready.\n", pvt->id);
3299 ast_debug(1, "[%s] volume level synchronization successful\n", pvt->id);
3301 /* set the SMS operating mode to text mode */
3303 if (hfp_send_cmgf(pvt->hfp, 1) || msg_queue_push(pvt, AT_OK, AT_CMGF)) {
3304 ast_debug(1, "[%s] error setting CMGF\n", pvt->id);
3310 ast_debug(1, "[%s] sms text mode enabled\n", pvt->id);
3311 /* turn on SMS new message indication */
3312 if (hfp_send_cnmi(pvt->hfp) || msg_queue_push(pvt, AT_OK, AT_CNMI)) {
3313 ast_debug(1, "[%s] error setting CNMI\n", pvt->id);
3318 ast_debug(1, "[%s] sms new message indication enabled\n", pvt->id);
3321 /* end initialization stuff */
3324 ast_debug(1, "[%s] answer sent successfully\n", pvt->id);
3328 ast_debug(1, "[%s] dial sent successfully\n", pvt->id);
3331 mbl_queue_control(pvt, AST_CONTROL_PROGRESS);
3334 ast_debug(1, "[%s] successful hangup\n", pvt->id);
3337 ast_debug(1, "[%s] successfully sent sms message\n", pvt->id);
3338 pvt->outgoing_sms = 0;
3341 ast_debug(1, "[%s] digit sent successfully\n", pvt->id);
3344 ast_debug(1, "[%s] CUSD code sent successfully\n", pvt->id);
3348 ast_debug(1, "[%s] received OK for unhandled request: %s\n", pvt->id, at_msg2str(entry->response_to));
3351 msg_queue_free_and_pop(pvt);
3353 ast_debug(1, "[%s] received AT message 'OK' when expecting %s, ignoring\n", pvt->id, at_msg2str(entry->expected));
3355 ast_debug(1, "[%s] received unexpected AT message 'OK'\n", pvt->id);
3360 msg_queue_free_and_pop(pvt);
3365 * \brief Handle ERROR AT messages.
3366 * \param pvt a mbl_pvt structure
3367 * \param buf a null terminated buffer containing an AT message
3371 static int handle_response_error(struct mbl_pvt *pvt, char *buf)
3373 struct msg_queue_entry *entry;
3374 if ((entry = msg_queue_head(pvt))
3375 && (entry->expected == AT_OK
3376 || entry->expected == AT_ERROR
3377 || entry->expected == AT_CMS_ERROR
3378 || entry->expected == AT_CMGR
3379 || entry->expected == AT_SMS_PROMPT)) {
3380 switch (entry->response_to) {
3382 /* initialization stuff */
3384 ast_debug(1, "[%s] error reading BSRF\n", pvt->id);
3387 ast_debug(1, "[%s] error during CIND test\n", pvt->id);
3390 ast_debug(1, "[%s] error requesting CIND state\n", pvt->id);
3393 ast_debug(1, "[%s] error during CMER request\n", pvt->id);
3396 ast_debug(1, "[%s] error enabling calling line indication\n", pvt->id);
3399 ast_debug(1, "[%s] volume level synchronization failed\n", pvt->id);
3401 /* this is not a fatal error, let's continue with initialization */
3403 /* set the SMS operating mode to text mode */
3404 if (hfp_send_cmgf(pvt->hfp, 1) || msg_queue_push(pvt, AT_OK, AT_CMGF)) {
3405 ast_debug(1, "[%s] error setting CMGF\n", pvt->id);
3411 ast_debug(1, "[%s] error setting CMGF\n", pvt->id);
3412 ast_debug(1, "[%s] no SMS support\n", pvt->id);
3416 ast_debug(1, "[%s] error setting CNMI\n", pvt->id);
3417 ast_debug(1, "[%s] no SMS support\n", pvt->id);
3420 ast_debug(1, "[%s] Mobile does not support Sony Ericsson extensions\n", pvt->id);
3422 /* this is not a fatal error, let's continue with the initialization */
3424 if (hfp_send_vgs(pvt->hfp, 15) || msg_queue_push(pvt, AT_OK, AT_VGS)) {
3425 ast_debug(1, "[%s] error synchronizing gain settings\n", pvt->id);
3430 pvt->hfp->initialized = 1;
3431 ast_verb(3, "Bluetooth Device %s initialized and ready.\n", pvt->id);
3434 /* end initialization stuff */
3437 ast_debug(1, "[%s] answer failed\n", pvt->id);
3438 mbl_queue_hangup(pvt);
3441 ast_debug(1, "[%s] dial failed\n", pvt->id);
3443 mbl_queue_control(pvt, AST_CONTROL_CONGESTION);
3446 ast_debug(1, "[%s] error sending hangup, disconnecting\n", pvt->id);
3449 ast_debug(1, "[%s] error reading sms message\n", pvt->id);
3450 pvt->incoming_sms = 0;
3453 ast_debug(1, "[%s] error sending sms message\n", pvt->id);
3454 pvt->outgoing_sms = 0;
3457 ast_debug(1, "[%s] error sending digit\n", pvt->id);
3460 ast_verb(0, "[%s] error sending CUSD command\n", pvt->id);
3464 ast_debug(1, "[%s] received ERROR for unhandled request: %s\n", pvt->id, at_msg2str(entry->response_to));
3467 msg_queue_free_and_pop(pvt);
3469 ast_debug(1, "[%s] received AT message 'ERROR' when expecting %s, ignoring\n", pvt->id, at_msg2str(entry->expected));
3471 ast_debug(1, "[%s] received unexpected AT message 'ERROR'\n", pvt->id);
3477 msg_queue_free_and_pop(pvt);
3482 * \brief Handle AT+CIEV messages.
3483 * \param pvt a mbl_pvt structure
3484 * \param buf a null terminated buffer containing an AT message
3488 static int handle_response_ciev(struct mbl_pvt *pvt, char *buf)
3491 switch (hfp_parse_ciev(pvt->hfp, buf, &i)) {
3494 case HFP_CIND_CALL_NONE:
3495 ast_debug(1, "[%s] line disconnected\n", pvt->id);
3497 ast_debug(1, "[%s] hanging up owner\n", pvt->id);
3498 if (mbl_queue_hangup(pvt)) {
3499 ast_log(LOG_ERROR, "[%s] error queueing hangup, disconnectiong...\n", pvt->id);
3504 pvt->needcallerid = 0;
3508 case HFP_CIND_CALL_ACTIVE:
3509 if (pvt->outgoing) {
3510 ast_debug(1, "[%s] remote end answered\n", pvt->id);
3511 mbl_queue_control(pvt, AST_CONTROL_ANSWER);
3512 } else if (pvt->incoming && pvt->answered) {
3513 ast_setstate(pvt->owner, AST_STATE_UP);
3514 } else if (pvt->incoming) {
3515 /* user answered from handset, disconnecting */
3516 ast_verb(3, "[%s] user answered bluetooth device from handset, disconnecting\n", pvt->id);
3517 mbl_queue_hangup(pvt);
3524 case HFP_CIND_CALLSETUP:
3526 case HFP_CIND_CALLSETUP_NONE:
3527 if (pvt->hfp->cind_state[pvt->hfp->cind_map.call] != HFP_CIND_CALL_ACTIVE) {
3529 if (pvt->hfp->sent_alerting == 1) {
3530 handle_response_busy(pvt);
3532 if (mbl_queue_hangup(pvt)) {
3533 ast_log(LOG_ERROR, "[%s] error queueing hangup, disconnectiong...\n", pvt->id);
3538 pvt->needcallerid = 0;
3543 case HFP_CIND_CALLSETUP_INCOMING:
3544 ast_debug(1, "[%s] incoming call, waiting for caller id\n", pvt->id);
3545 pvt->needcallerid = 1;
3548 case HFP_CIND_CALLSETUP_OUTGOING:
3549 if (pvt->outgoing) {
3550 pvt->hfp->sent_alerting = 0;
3551 ast_debug(1, "[%s] outgoing call\n", pvt->id);
3553 ast_verb(3, "[%s] user dialed from handset, disconnecting\n", pvt->id);
3557 case HFP_CIND_CALLSETUP_ALERTING:
3558 if (pvt->outgoing) {
3559 ast_debug(1, "[%s] remote alerting\n", pvt->id);
3560 mbl_queue_control(pvt, AST_CONTROL_RINGING);
3561 pvt->hfp->sent_alerting = 1;
3567 ast_debug(1, "[%s] error parsing CIND: %s\n", pvt->id, buf);
3574 * \brief Handle AT+CLIP messages.
3575 * \param pvt a mbl_pvt structure
3576 * \param buf a null terminated buffer containing an AT message
3580 static int handle_response_clip(struct mbl_pvt *pvt, char *buf)
3583 struct msg_queue_entry *msg;
3584 struct ast_channel *chan;
3586 if ((msg = msg_queue_head(pvt)) && msg->expected == AT_CLIP) {
3587 msg_queue_free_and_pop(pvt);
3589 pvt->needcallerid = 0;
3590 if (!(clip = hfp_parse_clip(pvt->hfp, buf))) {
3591 ast_debug(1, "[%s] error parsing CLIP: %s\n", pvt->id, buf);
3594 if (!(chan = mbl_new(AST_STATE_RING, pvt, clip, NULL))) {
3595 ast_log(LOG_ERROR, "[%s] unable to allocate channel for incoming call\n", pvt->id);
3596 hfp_send_chup(pvt->hfp);
3597 msg_queue_push(pvt, AT_OK, AT_CHUP);
3601 /* from this point on, we need to send a chup in the event of a
3605 if (ast_pbx_start(chan)) {
3606 ast_log(LOG_ERROR, "[%s] unable to start pbx on incoming call\n", pvt->id);
3607 mbl_ast_hangup(pvt);
3616 * \brief Handle RING messages.
3617 * \param pvt a mbl_pvt structure
3618 * \param buf a null terminated buffer containing an AT message
3622 static int handle_response_ring(struct mbl_pvt *pvt, char *buf)
3624 if (pvt->needcallerid) {
3625 ast_debug(1, "[%s] got ring while waiting for caller id\n", pvt->id);
3626 return msg_queue_push(pvt, AT_CLIP, AT_UNKNOWN);
3633 * \brief Handle AT+CMTI messages.
3634 * \param pvt a mbl_pvt structure
3635 * \param buf a null terminated buffer containing an AT message
3639 static int handle_response_cmti(struct mbl_pvt *pvt, char *buf)
3641 int index = hfp_parse_cmti(pvt->hfp, buf);
3643 ast_debug(1, "[%s] incoming sms message\n", pvt->id);
3645 if (hfp_send_cmgr(pvt->hfp, index)
3646 || msg_queue_push(pvt, AT_CMGR, AT_CMGR)) {
3647 ast_debug(1, "[%s] error sending CMGR to retrieve SMS message\n", pvt->id);
3651 pvt->incoming_sms = 1;
3654 ast_debug(1, "[%s] error parsing incoming sms message alert, disconnecting\n", pvt->id);
3660 * \brief Handle AT+CMGR messages.
3661 * \param pvt a mbl_pvt structure
3662 * \param buf a null terminated buffer containing an AT message
3666 static int handle_response_cmgr(struct mbl_pvt *pvt, char *buf)
3668 char *from_number = NULL, *text = NULL;
3669 struct ast_channel *chan;
3670 struct msg_queue_entry *msg;
3672 if ((msg = msg_queue_head(pvt)) && msg->expected == AT_CMGR) {
3673 msg_queue_free_and_pop(pvt);
3675 if (hfp_parse_cmgr(pvt->hfp, buf, &from_number, &text)) {
3676 ast_debug(1, "[%s] error parsing sms message, disconnecting\n", pvt->id);
3680 ast_debug(1, "[%s] successfully read sms message\n", pvt->id);
3681 pvt->incoming_sms = 0;
3683 /* XXX this channel probably does not need to be associated with this pvt */
3684 if (!(chan = mbl_new(AST_STATE_DOWN, pvt, NULL, NULL))) {
3685 ast_debug(1, "[%s] error creating sms message channel, disconnecting\n", pvt->id);
3689 ast_channel_exten_set(chan, "sms");
3690 pbx_builtin_setvar_helper(chan, "SMSSRC", from_number);
3691 pbx_builtin_setvar_helper(chan, "SMSTXT", text);
3693 if (ast_pbx_start(chan)) {
3694 ast_log(LOG_ERROR, "[%s] unable to start pbx on incoming sms\n", pvt->id);
3695 mbl_ast_hangup(pvt);
3698 ast_debug(1, "[%s] got unexpected +CMGR message, ignoring\n", pvt->id);
3705 * \brief Send an SMS message from the queue.
3706 * \param pvt a mbl_pvt structure
3707 * \param buf a null terminated buffer containing an AT message
3711 static int handle_sms_prompt(struct mbl_pvt *pvt, char *buf)
3713 struct msg_queue_entry *msg;
3714 if (!(msg = msg_queue_head(pvt))) {
3715 ast_debug(1, "[%s] error, got sms prompt with no pending sms messages\n", pvt->id);
3719 if (msg->expected != AT_SMS_PROMPT) {
3720 ast_debug(1, "[%s] error, got sms prompt but no pending sms messages\n", pvt->id);
3724 if (hfp_send_sms_text(pvt->hfp, msg->data)
3725 || msg_queue_push(pvt, AT_OK, AT_CMGS)) {
3726 msg_queue_free_and_pop(pvt);
3727 ast_debug(1, "[%s] error sending sms message\n", pvt->id);
3731 msg_queue_free_and_pop(pvt);
3736 * \brief Handle CUSD messages.
3737 * \param pvt a mbl_pvt structure
3738 * \param buf a null terminated buffer containing an AT message
3742 static int handle_response_cusd(struct mbl_pvt *pvt, char *buf)
3746 if (!(cusd = hfp_parse_cusd(pvt->hfp, buf))) {
3747 ast_verb(0, "[%s] error parsing CUSD: %s\n", pvt->id, buf);
3751 ast_verb(0, "[%s] CUSD response: %s\n", pvt->id, cusd);
3757 * \brief Handle BUSY messages.
3758 * \param pvt a mbl_pvt structure
3762 static int handle_response_busy(struct mbl_pvt *pvt)
3764 pvt->hangupcause = AST_CAUSE_USER_BUSY;
3766 mbl_queue_control(pvt, AST_CONTROL_BUSY);
3771 * \brief Handle NO DIALTONE messages.
3772 * \param pvt a mbl_pvt structure
3773 * \param buf a null terminated buffer containing an AT message
3777 static int handle_response_no_dialtone(struct mbl_pvt *pvt, char *buf)
3779 ast_verb(1, "[%s] mobile reports NO DIALTONE\n", pvt->id);
3781 mbl_queue_control(pvt, AST_CONTROL_CONGESTION);
3786 * \brief Handle NO CARRIER messages.
3787 * \param pvt a mbl_pvt structure
3788 * \param buf a null terminated buffer containing an AT message
3792 static int handle_response_no_carrier(struct mbl_pvt *pvt, char *buf)
3794 ast_verb(1, "[%s] mobile reports NO CARRIER\n", pvt->id);
3796 mbl_queue_control(pvt, AST_CONTROL_CONGESTION);
3801 static void *do_monitor_phone(void *data)
3803 struct mbl_pvt *pvt = (struct mbl_pvt *)data;
3804 struct hfp_pvt *hfp = pvt->hfp;
3807 at_message_t at_msg;
3808 struct msg_queue_entry *entry;
3810 /* Note: At one point the initialization procedure was neatly contained
3811 * in the hfp_init() function, but that initialization method did not
3812 * work with non standard devices. As a result, the initialization
3813 * procedure is not spread throughout the event handling loop.
3816 /* start initialization with the BRSF request */
3817 ast_mutex_lock(&pvt->lock);
3818 pvt->timeout = 10000;
3819 if (hfp_send_brsf(hfp, &hfp_our_brsf) || msg_queue_push(pvt, AT_BRSF, AT_BRSF)) {
3820 ast_debug(1, "[%s] error sending BRSF\n", hfp->owner->id);
3823 ast_mutex_unlock(&pvt->lock);
3825 while (!check_unloading()) {
3826 ast_mutex_lock(&pvt->lock);
3828 ast_mutex_unlock(&pvt->lock);
3830 if (!rfcomm_wait(pvt->rfcomm_socket, &t)) {
3831 ast_debug(1, "[%s] timeout waiting for rfcomm data, disconnecting\n", pvt->id);
3832 ast_mutex_lock(&pvt->lock);
3833 if (!hfp->initialized) {
3834 if ((entry = msg_queue_head(pvt))) {
3835 switch (entry->response_to) {
3837 if (pvt->blackberry)
3838 ast_debug(1, "[%s] timeout during CIND test\n", hfp->owner->id);
3840 ast_debug(1, "[%s] timeout during CIND test, try setting 'blackberry=yes'\n", hfp->owner->id);
3843 if (pvt->blackberry)
3844 ast_debug(1, "[%s] timeout after sending CMER, try setting 'blackberry=no'\n", hfp->owner->id);