Linux bluetooth development
 help / color / mirror / Atom feed
* [PATCH 1/3] Bluetooth: Use proper invalid value for tx_power
From: Johan Hedberg @ 2012-11-06 22:06 UTC (permalink / raw)
  To: linux-bluetooth

From: Johan Hedberg <johan.hedberg@intel.com>

The core specification defines 127 as the "not available" value (well,
"reserved" for BR/EDR and "not available" for LE - but essentially the
same). Therefore, instead of testing for 0 (which is in fact a valid
value) we should be using this invalid value to test if the tx_power is
available.

Signed-off-by: Johan Hedberg <johan.hedberg@intel.com>
---
 include/net/bluetooth/hci.h |    3 +++
 net/bluetooth/hci_core.c    |    2 ++
 net/bluetooth/hci_event.c   |    2 ++
 net/bluetooth/mgmt.c        |    2 +-
 4 files changed, 8 insertions(+), 1 deletion(-)

diff --git a/include/net/bluetooth/hci.h b/include/net/bluetooth/hci.h
index 6c414f4..344fea0 100644
--- a/include/net/bluetooth/hci.h
+++ b/include/net/bluetooth/hci.h
@@ -319,6 +319,9 @@ enum {
 #define HCI_FLOW_CTL_MODE_PACKET_BASED	0x00
 #define HCI_FLOW_CTL_MODE_BLOCK_BASED	0x01
 
+/* The core spec defines 127 as the "not available" value */
+#define HCI_TX_POWER_INVALID	127
+
 /* Extended Inquiry Response field types */
 #define EIR_FLAGS		0x01 /* flags */
 #define EIR_UUID16_SOME		0x02 /* 16-bit UUID, more available */
diff --git a/net/bluetooth/hci_core.c b/net/bluetooth/hci_core.c
index c68c409..0af08f3 100644
--- a/net/bluetooth/hci_core.c
+++ b/net/bluetooth/hci_core.c
@@ -1606,6 +1606,8 @@ struct hci_dev *hci_alloc_dev(void)
 	hdev->esco_type = (ESCO_HV1);
 	hdev->link_mode = (HCI_LM_ACCEPT);
 	hdev->io_capability = 0x03; /* No Input No Output */
+	hdev->inq_tx_power = HCI_TX_POWER_INVALID;
+	hdev->adv_tx_power = HCI_TX_POWER_INVALID;
 
 	hdev->sniff_max_interval = 800;
 	hdev->sniff_min_interval = 80;
diff --git a/net/bluetooth/hci_event.c b/net/bluetooth/hci_event.c
index c08ac7c..09c6571 100644
--- a/net/bluetooth/hci_event.c
+++ b/net/bluetooth/hci_event.c
@@ -202,6 +202,8 @@ static void hci_cc_reset(struct hci_dev *hdev, struct sk_buff *skb)
 			     BIT(HCI_PERIODIC_INQ));
 
 	hdev->discovery.state = DISCOVERY_STOPPED;
+	hdev->inq_tx_power = HCI_TX_POWER_INVALID;
+	hdev->adv_tx_power = HCI_TX_POWER_INVALID;
 }
 
 static void hci_cc_write_local_name(struct hci_dev *hdev, struct sk_buff *skb)
diff --git a/net/bluetooth/mgmt.c b/net/bluetooth/mgmt.c
index 26a0984..ad1054f 100644
--- a/net/bluetooth/mgmt.c
+++ b/net/bluetooth/mgmt.c
@@ -485,7 +485,7 @@ static void create_eir(struct hci_dev *hdev, u8 *data)
 		ptr += (name_len + 2);
 	}
 
-	if (hdev->inq_tx_power) {
+	if (hdev->inq_tx_power != HCI_TX_POWER_INVALID) {
 		ptr[0] = 2;
 		ptr[1] = EIR_TX_POWER;
 		ptr[2] = (u8) hdev->inq_tx_power;
-- 
1.7.10.4


^ permalink raw reply related

* About a newer bluez version
From: Pacho Ramos @ 2012-11-06 20:18 UTC (permalink / raw)
  To: linux-bluetooth

[-- Attachment #1: Type: text/plain, Size: 164 bytes --]

Hello

Looks like there are a lot of fixed committed to git since bluez-4.101,
do you plan to release a new tarball including them soon?

Thanks for the info

[-- Attachment #2: This is a digitally signed message part --]
[-- Type: application/pgp-signature, Size: 198 bytes --]

^ permalink raw reply

* [PATCH] bluetooth: ath3k: Add support for VAIO VPCEH [0489:e027]
From: Marcos Chaparro @ 2012-11-06 19:19 UTC (permalink / raw)
  To: gustavo, marcel, johan.hedberg, linux-bluetooth
  Cc: linux-kernel, Marcos Chaparro

Added Atheros AR3011 internal bluetooth device found in Sony VAIO VPCEH to the
devices list.
Before this, the bluetooth module was identified as an Foxconn / Hai bluetooth
device [0489:e027], now it claims to be an AtherosAR3011 Bluetooth
[0cf3:3005].

T:  Bus=01 Lev=02 Prnt=02 Port=04 Cnt=02 Dev#=  4 Spd=12   MxCh= 0
D:  Ver= 1.10 Cls=e0(wlcon) Sub=01 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=0489 ProdID=e027 Rev= 0.01
C:* #Ifs= 2 Cfg#= 1 Atr=e0 MxPwr=100mA
I:* If#= 0 Alt= 0 #EPs= 3 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
E:  Ad=81(I) Atr=03(Int.) MxPS=  16 Ivl=1ms
E:  Ad=82(I) Atr=02(Bulk) MxPS=  64 Ivl=0ms
E:  Ad=02(O) Atr=02(Bulk) MxPS=  64 Ivl=0ms
I:* If#= 1 Alt= 0 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
E:  Ad=83(I) Atr=01(Isoc) MxPS=   0 Ivl=1ms
E:  Ad=03(O) Atr=01(Isoc) MxPS=   0 Ivl=1ms
I:  If#= 1 Alt= 1 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
E:  Ad=83(I) Atr=01(Isoc) MxPS=   9 Ivl=1ms
E:  Ad=03(O) Atr=01(Isoc) MxPS=   9 Ivl=1ms
I:  If#= 1 Alt= 2 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
E:  Ad=83(I) Atr=01(Isoc) MxPS=  17 Ivl=1ms
E:  Ad=03(O) Atr=01(Isoc) MxPS=  17 Ivl=1ms
I:  If#= 1 Alt= 3 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
E:  Ad=83(I) Atr=01(Isoc) MxPS=  25 Ivl=1ms
E:  Ad=03(O) Atr=01(Isoc) MxPS=  25 Ivl=1ms
I:  If#= 1 Alt= 4 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
E:  Ad=83(I) Atr=01(Isoc) MxPS=  33 Ivl=1ms
E:  Ad=03(O) Atr=01(Isoc) MxPS=  33 Ivl=1ms
I:  If#= 1 Alt= 5 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
E:  Ad=83(I) Atr=01(Isoc) MxPS=  49 Ivl=1ms
E:  Ad=03(O) Atr=01(Isoc) MxPS=  49 Ivl=1ms

Signed-off-by: Marcos Chaparro <marcos@mrkindustries.com.ar>
---
 drivers/bluetooth/ath3k.c |    1 +
 drivers/bluetooth/btusb.c |    1 +
 2 files changed, 2 insertions(+)

diff --git a/drivers/bluetooth/ath3k.c b/drivers/bluetooth/ath3k.c
index fc2de55..b00000e 100644
--- a/drivers/bluetooth/ath3k.c
+++ b/drivers/bluetooth/ath3k.c
@@ -67,6 +67,7 @@ static struct usb_device_id ath3k_table[] = {
 	{ USB_DEVICE(0x13d3, 0x3304) },
 	{ USB_DEVICE(0x0930, 0x0215) },
 	{ USB_DEVICE(0x0489, 0xE03D) },
+	{ USB_DEVICE(0x0489, 0xE027) },
 
 	/* Atheros AR9285 Malbec with sflash firmware */
 	{ USB_DEVICE(0x03F0, 0x311D) },
diff --git a/drivers/bluetooth/btusb.c b/drivers/bluetooth/btusb.c
index debda27..ee82f2f 100644
--- a/drivers/bluetooth/btusb.c
+++ b/drivers/bluetooth/btusb.c
@@ -124,6 +124,7 @@ static struct usb_device_id blacklist_table[] = {
 	{ USB_DEVICE(0x13d3, 0x3304), .driver_info = BTUSB_IGNORE },
 	{ USB_DEVICE(0x0930, 0x0215), .driver_info = BTUSB_IGNORE },
 	{ USB_DEVICE(0x0489, 0xe03d), .driver_info = BTUSB_IGNORE },
+	{ USB_DEVICE(0x0489, 0xe027), .driver_info = BTUSB_IGNORE },
 
 	/* Atheros AR9285 Malbec with sflash firmware */
 	{ USB_DEVICE(0x03f0, 0x311d), .driver_info = BTUSB_IGNORE },
-- 
1.7.10.4

^ permalink raw reply related

* Re: [PATCH] ath3k: Add support for VAIO VPCEH [0489:e027]
From: Gustavo Padovan @ 2012-11-06 11:02 UTC (permalink / raw)
  To: Marcos Chaparro
  Cc: Marcel Holtmann, Johan Hedberg, linux-bluetooth, linux-kernel
In-Reply-To: <201211012138.20988.marcos@mrkindustries.com.ar>

Hi Marcos, 

* Marcos Chaparro <marcos@mrkindustries.com.ar> [2012-11-01 21:38:20 -0300]:

> Added Atheros AR3011 internal bluetooth device found in Sony VAIO VPCEH to the 
> devices list.
> Before this, the bluetooth module was identified as an Foxconn / Hai bluetooth 
> device [0489:e027], now it claims to be an AtherosAR3011 Bluetooth 
> [0cf3:3005].
> 
> # cat /sys/kernel/debug/usb/devices
> T:  Bus=01 Lev=02 Prnt=02 Port=04 Cnt=02 Dev#=  4 Spd=12   MxCh= 0
> D:  Ver= 1.10 Cls=e0(wlcon) Sub=01 Prot=01 MxPS=64 #Cfgs=  1
> P:  Vendor=0489 ProdID=e027 Rev= 0.01
> C:* #Ifs= 2 Cfg#= 1 Atr=e0 MxPwr=100mA
> I:* If#= 0 Alt= 0 #EPs= 3 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
> E:  Ad=81(I) Atr=03(Int.) MxPS=  16 Ivl=1ms
> E:  Ad=82(I) Atr=02(Bulk) MxPS=  64 Ivl=0ms
> E:  Ad=02(O) Atr=02(Bulk) MxPS=  64 Ivl=0ms
> I:* If#= 1 Alt= 0 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
> E:  Ad=83(I) Atr=01(Isoc) MxPS=   0 Ivl=1ms
> E:  Ad=03(O) Atr=01(Isoc) MxPS=   0 Ivl=1ms
> I:  If#= 1 Alt= 1 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
> E:  Ad=83(I) Atr=01(Isoc) MxPS=   9 Ivl=1ms
> E:  Ad=03(O) Atr=01(Isoc) MxPS=   9 Ivl=1ms
> I:  If#= 1 Alt= 2 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
> E:  Ad=83(I) Atr=01(Isoc) MxPS=  17 Ivl=1ms
> E:  Ad=03(O) Atr=01(Isoc) MxPS=  17 Ivl=1ms
> I:  If#= 1 Alt= 3 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
> E:  Ad=83(I) Atr=01(Isoc) MxPS=  25 Ivl=1ms
> E:  Ad=03(O) Atr=01(Isoc) MxPS=  25 Ivl=1ms
> I:  If#= 1 Alt= 4 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
> E:  Ad=83(I) Atr=01(Isoc) MxPS=  33 Ivl=1ms
> E:  Ad=03(O) Atr=01(Isoc) MxPS=  33 Ivl=1ms
> I:  If#= 1 Alt= 5 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
> E:  Ad=83(I) Atr=01(Isoc) MxPS=  49 Ivl=1ms
> E:  Ad=03(O) Atr=01(Isoc) MxPS=  49 Ivl=1ms
> 
> Signed-off by: Marcos A Chaparro <marcos@mrkindustries.com.ar>
> ---
> 
> Updated usb /sys/kernel/debug/usb/devices output. A complete powercycle flushed 
> the device firmware.
> 
> diff --git a/linux-3.7-rc3.orig/drivers/bluetooth/ath3k.c b/linux-3.7-
> rc3.new/drivers/bluetooth/ath3k.c
> index fc2de55..b00000e 100644
> --- a/linux-3.7-rc3.orig/drivers/bluetooth/ath3k.c
> +++ b/linux-3.7-rc3.new/drivers/bluetooth/ath3k.c
> @@ -67,6 +67,7 @@ static struct usb_device_id ath3k_table[] = {
>         { USB_DEVICE(0x13d3, 0x3304) },
>         { USB_DEVICE(0x0930, 0x0215) },
>         { USB_DEVICE(0x0489, 0xE03D) },
> +       { USB_DEVICE(0x0489, 0xE027) },
>  
>         /* Atheros AR9285 Malbec with sflash firmware */
>         { USB_DEVICE(0x03F0, 0x311D) },
> diff --git a/linux-3.7-rc3.orig/drivers/bluetooth/btusb.c b/linux-3.7-
> rc3.new/drivers/bluetooth/btusb.c
> index debda27..ee82f2f 100644
> --- a/linux-3.7-rc3.orig/drivers/bluetooth/btusb.c
> +++ b/linux-3.7-rc3.new/drivers/bluetooth/btusb.c
> @@ -124,6 +124,7 @@ static struct usb_device_id blacklist_table[] = {
>         { USB_DEVICE(0x13d3, 0x3304), .driver_info = BTUSB_IGNORE },
>         { USB_DEVICE(0x0930, 0x0215), .driver_info = BTUSB_IGNORE },
>         { USB_DEVICE(0x0489, 0xe03d), .driver_info = BTUSB_IGNORE },
> +       { USB_DEVICE(0x0489, 0xe027), .driver_info = BTUSB_IGNORE },
>  
>         /* Atheros AR9285 Malbec with sflash firmware */
>         { USB_DEVICE(0x03f0, 0x311d), .driver_info = BTUSB_IGNORE },

Please generate your patch with git format-patch. It is currently not applying
because your patch has a few wrong information. Then use git send-email to
send your patch.

	Gustavo

^ permalink raw reply

* Multiple adapters do not work
From: Sietse Achterop @ 2012-11-06  9:10 UTC (permalink / raw)
  To: linux-bluetooth

     Dear list,

I am trying to use multiple adapters to	control	multiple bluetooth devices.
But it doesn't work. I already mailed it to this list but got no replay.
I know that normally this isn't	the way	to do this, but I am trying to avoid another
problem.

I bind 4 devices to 4 adapters as follows:

  rfcomm -i hci0 bind rfcomm1 10:00:E8:6C:D8:14 1
  rfcomm -i hci1 bind rfcomm2 10:00:E8:6C:D8:1D 1
  rfcomm -i hci2 bind rfcomm3 10:00:E8:6C:EC:98 1
  rfcomm -i hci3 bind rfcomm4 10:00:E8:6C:D7:D9 1

But, using minicom, I can only connect to the first device,
the others give	either
   cannot open /dev/rfcomm3: Connection refused
or
   cannot open /dev/rfcomm4: No such file or directory

All devices are available:
  crw-rw---- 1 root dialout 216, 1 Nov  6 09:49 /dev/rfcomm1
  crw-rw---- 1 root dialout 216, 2 Nov  6 09:46 /dev/rfcomm2
  crw-rw---- 1 root dialout 216, 3 Nov  6 09:46 /dev/rfcomm3
  crw-rw---- 1 root dialout 216, 4 Nov  6 09:46 /dev/rfcomm4

What am I doing wrong?
 (Using	Ubuntu 12.04 with bluez-4.101 install from source.)

   Regards,
     Sietse


PS On a side note: I think there is a bug in the rfcomm manual page.

   I don't understand the desciption of	the -i parameter, but it is the	same for years,	The desciption looks mangled.
     -i <hciX> | <bdaddr>
              The command is applied to device -A Enable authentication.  -E Enable encryption.  -S Secure connection.  -M Become the master of a piconet.  hciX , which must be the
name or
              the address of an installed Bluetooth device. If not specified, the command will be use the first available Bluetooth device.
   The mentioning of -A	to -M should be	removed	I guess.

^ permalink raw reply

* Re: [RFC 0/3] LE Connection parameter tuning (first step)
From: Vinicius Costa Gomes @ 2012-11-05 14:52 UTC (permalink / raw)
  To: Kim Schulz; +Cc: linux-bluetooth
In-Reply-To: <2375c7de623938c6e2f1fe8e7687db7d@server1.devteam.dk>

Hi,

On 14:42 Mon 05 Nov, Kim Schulz wrote:
> Den 2012-11-05 14:25, Vinicius Costa Gomes skrev:
> >Hi,
> >
> >Right now, we are using only one set of (hardcoded) connection
> >parameters for LE.  I guess the first step to have different
> >connection parameters classes for different Profiles requirements
> >(think "Low Latency", "Low Power", etc.) is to have a nice set of
> >parameters. For that we need to measure and see which are the sweet
> >spots, This series aims to help the measuring part.
> >
> >This is an idea so we can easily change the connection parameters
> >without need for recompiling the kernel side, so tests can be more
> >practical.
> >
> [snip]
> 
> 
> Good idea to split them out as every single profile defines their
> own. Have you
> concidered what should happen if two LE connections to two different
> profils should
> happen at the same time and the connection parameters are different?
> i.e. should bluez
> maybe have a per-profile set of connection parameters?

The current plan is to have the most restrictive (in terms of latency)
set of parameters to prevail over the others.

> Also make room in the struct for Preferred Connection Paramters (the
> values read
> from the peer DB after connection) as these can differ from the ones
> the profile proposes.

I don't think that this information should be in the kernel side, but thank
you for reminding me of this. About the problem, that could be dealt with
having that as another set of parameters (perhaps with a higher priority). 

> 
> -- 
> Kim Schulz
> --
> To unsubscribe from this list: send the line "unsubscribe linux-bluetooth" in
> the body of a message to majordomo@vger.kernel.org
> More majordomo info at  http://vger.kernel.org/majordomo-info.html


Cheers,
-- 
Vinicius

^ permalink raw reply

* Re: [RFC 0/3] LE Connection parameter tuning (first step)
From: Kim Schulz @ 2012-11-05 13:42 UTC (permalink / raw)
  To: linux-bluetooth
In-Reply-To: <1352121943-18001-1-git-send-email-vinicius.gomes@openbossa.org>

Den 2012-11-05 14:25, Vinicius Costa Gomes skrev:
> Hi,
>
> Right now, we are using only one set of (hardcoded) connection
> parameters for LE.  I guess the first step to have different
> connection parameters classes for different Profiles requirements
> (think "Low Latency", "Low Power", etc.) is to have a nice set of
> parameters. For that we need to measure and see which are the sweet
> spots, This series aims to help the measuring part.
>
> This is an idea so we can easily change the connection parameters
> without need for recompiling the kernel side, so tests can be more
> practical.
>
[snip]


Good idea to split them out as every single profile defines their own. 
Have you
concidered what should happen if two LE connections to two different 
profils should
happen at the same time and the connection parameters are different? 
i.e. should bluez
maybe have a per-profile set of connection parameters?
Also make room in the struct for Preferred Connection Paramters (the 
values read
from the peer DB after connection) as these can differ from the ones 
the profile proposes.

-- 
Kim Schulz

^ permalink raw reply

* [RFC 3/3] Bluetooth: Add support for setting LE connection parameters via debugfs
From: Vinicius Costa Gomes @ 2012-11-05 13:25 UTC (permalink / raw)
  To: linux-bluetooth; +Cc: Vinicius Costa Gomes
In-Reply-To: <1352121943-18001-1-git-send-email-vinicius.gomes@openbossa.org>

This will allow for much more pratical measures of the impact of
different connection parameters in different scenarios.

Signed-off-by: Vinicius Costa Gomes <vinicius.gomes@openbossa.org>
---
 net/bluetooth/hci_sysfs.c | 43 +++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 43 insertions(+)

diff --git a/net/bluetooth/hci_sysfs.c b/net/bluetooth/hci_sysfs.c
index a9554ec..8474d02 100644
--- a/net/bluetooth/hci_sysfs.c
+++ b/net/bluetooth/hci_sysfs.c
@@ -550,6 +550,48 @@ static int le_conn_parameters_show(struct seq_file *f, void *p)
 	return 0;
 }
 
+static ssize_t le_conn_parameters_write(struct file *filp,
+					const char __user *ubuf,
+					size_t cnt, loff_t *ppos)
+{
+	struct seq_file *seqf = filp->private_data;
+	struct hci_dev *hdev = seqf->private;
+	struct le_conn_params params;
+	char buffer[36];
+	int n;
+
+	/* No partial writes */
+	if (*ppos != 0)
+		return 0;
+
+	/* Format: '0x0000 0x0000 0x0000 0x0000 0x0000' length 35 */
+	if (cnt != 35)
+		return -ENOSPC;
+
+	memset(buffer, 0, sizeof(buffer));
+
+	n = copy_from_user(buffer, ubuf, cnt);
+	if (n < 0)
+		return n;
+
+	memset(&params, 0, sizeof(params));
+
+	n = sscanf(buffer, "%hx %hx %hx %hx %hx", &params.scan_interval,
+		   &params.scan_window, &params.conn_interval_min,
+		   &params.conn_interval_max, &params.supervision_timeout);
+
+	if (n < 5)
+		return -EINVAL;
+
+	hci_dev_lock(hdev);
+
+	memcpy(&hdev->le_conn_params, &params, sizeof(params));
+
+	hci_dev_unlock(hdev);
+
+	return cnt;
+}
+
 static int le_conn_parameters_open(struct inode *inode, struct file *file)
 {
 	return single_open(file, le_conn_parameters_show, inode->i_private);
@@ -557,6 +599,7 @@ static int le_conn_parameters_open(struct inode *inode, struct file *file)
 
 static const struct file_operations le_conn_parameters_fops = {
 	.open		= le_conn_parameters_open,
+	.write		= le_conn_parameters_write,
 	.read		= seq_read,
 	.llseek		= seq_lseek,
 	.release	= single_release,
-- 
1.7.12.4


^ permalink raw reply related

* [RFC 2/3] Bluetooth: Add LE connection parameters to debugfs
From: Vinicius Costa Gomes @ 2012-11-05 13:25 UTC (permalink / raw)
  To: linux-bluetooth; +Cc: Vinicius Costa Gomes
In-Reply-To: <1352121943-18001-1-git-send-email-vinicius.gomes@openbossa.org>

Only reading the parameters is supported for now.

Signed-off-by: Vinicius Costa Gomes <vinicius.gomes@openbossa.org>
---
 net/bluetooth/hci_sysfs.c | 34 ++++++++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)

diff --git a/net/bluetooth/hci_sysfs.c b/net/bluetooth/hci_sysfs.c
index 55cceee..a9554ec 100644
--- a/net/bluetooth/hci_sysfs.c
+++ b/net/bluetooth/hci_sysfs.c
@@ -532,6 +532,36 @@ static int auto_accept_delay_get(void *data, u64 *val)
 DEFINE_SIMPLE_ATTRIBUTE(auto_accept_delay_fops, auto_accept_delay_get,
 			auto_accept_delay_set, "%llu\n");
 
+
+static int le_conn_parameters_show(struct seq_file *f, void *p)
+{
+	struct hci_dev *hdev = f->private;
+	struct le_conn_params *params = &hdev->le_conn_params;
+
+	hci_dev_lock(hdev);
+
+	seq_printf(f, "0x%.4x 0x%.4x 0x%.4x 0x%.4x 0x%.4x\n",
+		   params->scan_interval, params->scan_window,
+		   params->conn_interval_min, params->conn_interval_max,
+		   params->supervision_timeout);
+
+	hci_dev_unlock(hdev);
+
+	return 0;
+}
+
+static int le_conn_parameters_open(struct inode *inode, struct file *file)
+{
+	return single_open(file, le_conn_parameters_show, inode->i_private);
+}
+
+static const struct file_operations le_conn_parameters_fops = {
+	.open		= le_conn_parameters_open,
+	.read		= seq_read,
+	.llseek		= seq_lseek,
+	.release	= single_release,
+};
+
 void hci_init_sysfs(struct hci_dev *hdev)
 {
 	struct device *dev = &hdev->dev;
@@ -573,6 +603,10 @@ int hci_add_sysfs(struct hci_dev *hdev)
 
 	debugfs_create_file("auto_accept_delay", 0444, hdev->debugfs, hdev,
 			    &auto_accept_delay_fops);
+
+	debugfs_create_file("le_conn_parameters", 0644, hdev->debugfs, hdev,
+			    &le_conn_parameters_fops);
+
 	return 0;
 }
 
-- 
1.7.12.4


^ permalink raw reply related

* [RFC 1/3] Bluetooth: Keep the LE connection parameters in its own structure
From: Vinicius Costa Gomes @ 2012-11-05 13:25 UTC (permalink / raw)
  To: linux-bluetooth; +Cc: Vinicius Costa Gomes
In-Reply-To: <1352121943-18001-1-git-send-email-vinicius.gomes@openbossa.org>

This will allow for easier parameterization of these fields. This is
the first step for allowing to change the parameters during runtime.

Signed-off-by: Vinicius Costa Gomes <vinicius.gomes@openbossa.org>
---
 include/net/bluetooth/hci_core.h | 10 ++++++++++
 net/bluetooth/hci_conn.c         | 11 ++++++-----
 net/bluetooth/hci_event.c        | 10 ++++++++++
 3 files changed, 26 insertions(+), 5 deletions(-)

diff --git a/include/net/bluetooth/hci_core.h b/include/net/bluetooth/hci_core.h
index ce6dbeb..f477d43 100644
--- a/include/net/bluetooth/hci_core.h
+++ b/include/net/bluetooth/hci_core.h
@@ -123,6 +123,14 @@ struct le_scan_params {
 	int timeout;
 };
 
+struct le_conn_params {
+	u16 scan_interval;
+	u16 scan_window;
+	u16 conn_interval_min;
+	u16 conn_interval_max;
+	u16 supervision_timeout;
+};
+
 #define HCI_MAX_SHORT_NAME_LENGTH	10
 
 struct amp_assoc {
@@ -278,6 +286,8 @@ struct hci_dev {
 	struct work_struct	le_scan;
 	struct le_scan_params	le_scan_params;
 
+	struct le_conn_params	le_conn_params;
+
 	__s8			adv_tx_power;
 
 	int (*open)(struct hci_dev *hdev);
diff --git a/net/bluetooth/hci_conn.c b/net/bluetooth/hci_conn.c
index 25bfce0..d8ff5c0 100644
--- a/net/bluetooth/hci_conn.c
+++ b/net/bluetooth/hci_conn.c
@@ -35,6 +35,7 @@ static void hci_le_create_connection(struct hci_conn *conn)
 {
 	struct hci_dev *hdev = conn->hdev;
 	struct hci_cp_le_create_conn cp;
+	struct le_conn_params *params = &hdev->le_conn_params;
 
 	conn->state = BT_CONNECT;
 	conn->out = true;
@@ -42,13 +43,13 @@ static void hci_le_create_connection(struct hci_conn *conn)
 	conn->sec_level = BT_SECURITY_LOW;
 
 	memset(&cp, 0, sizeof(cp));
-	cp.scan_interval = __constant_cpu_to_le16(0x0060);
-	cp.scan_window = __constant_cpu_to_le16(0x0030);
+	cp.scan_interval = __cpu_to_le16(params->scan_interval);
+	cp.scan_window = __cpu_to_le16(params->scan_window);
 	bacpy(&cp.peer_addr, &conn->dst);
 	cp.peer_addr_type = conn->dst_type;
-	cp.conn_interval_min = __constant_cpu_to_le16(0x0028);
-	cp.conn_interval_max = __constant_cpu_to_le16(0x0038);
-	cp.supervision_timeout = __constant_cpu_to_le16(0x002a);
+	cp.conn_interval_min = __cpu_to_le16(params->conn_interval_min);
+	cp.conn_interval_max = __cpu_to_le16(params->conn_interval_max);
+	cp.supervision_timeout = __cpu_to_le16(params->supervision_timeout);
 	cp.min_ce_len = __constant_cpu_to_le16(0x0000);
 	cp.max_ce_len = __constant_cpu_to_le16(0x0000);
 
diff --git a/net/bluetooth/hci_event.c b/net/bluetooth/hci_event.c
index c08ac7c..3675dbd 100644
--- a/net/bluetooth/hci_event.c
+++ b/net/bluetooth/hci_event.c
@@ -1298,6 +1298,16 @@ static void hci_cc_write_le_host_supported(struct hci_dev *hdev,
 			hdev->host_features[0] |= LMP_HOST_LE_BREDR;
 		else
 			hdev->host_features[0] &= ~LMP_HOST_LE_BREDR;
+
+		if (sent->le || sent->simul) {
+			struct le_conn_params *params = &hdev->le_conn_params;
+
+			params->scan_interval = 0x0060;
+			params->scan_window = 0x0030;
+			params->conn_interval_min = 0x0028;
+			params->conn_interval_max = 0x0038;
+			params->supervision_timeout = 0x002a;
+		}
 	}
 
 	if (test_bit(HCI_MGMT, &hdev->dev_flags) &&
-- 
1.7.12.4


^ permalink raw reply related

* [RFC 0/3] LE Connection parameter tuning (first step)
From: Vinicius Costa Gomes @ 2012-11-05 13:25 UTC (permalink / raw)
  To: linux-bluetooth; +Cc: Vinicius Costa Gomes

Hi,

Right now, we are using only one set of (hardcoded) connection
parameters for LE.  I guess the first step to have different
connection parameters classes for different Profiles requirements
(think "Low Latency", "Low Power", etc.) is to have a nice set of
parameters. For that we need to measure and see which are the sweet
spots, This series aims to help the measuring part.

This is an idea so we can easily change the connection parameters
without need for recompiling the kernel side, so tests can be more
practical.

It works, but just lightly tested. This is more to get some feedback
on how to proceed with the LE connection parameters thing.

Cheers,


Vinicius Costa Gomes (3):
  Bluetooth: Keep the LE connection parameters in its own structure
  Bluetooth: Add LE connection parameters to debugfs
  Bluetooth: Add support for setting LE connection parameters via
    debugfs

 include/net/bluetooth/hci_core.h | 10 ++++++
 net/bluetooth/hci_conn.c         | 11 +++---
 net/bluetooth/hci_event.c        | 10 ++++++
 net/bluetooth/hci_sysfs.c        | 77 ++++++++++++++++++++++++++++++++++++++++
 4 files changed, 103 insertions(+), 5 deletions(-)

-- 
1.7.12.4


^ permalink raw reply

* [PATCH v2 20/20] test: Enable speed and cadence calculation in test-cyclingspeed
From: Andrzej Kaczmarek @ 2012-11-05  8:55 UTC (permalink / raw)
  To: linux-bluetooth; +Cc: Andrzej Kaczmarek
In-Reply-To: <1352105705-13988-1-git-send-email-andrzej.kaczmarek@tieto.com>

This patch allows to enable instantenous speed and cadence calculation
based on measurement received from remote device.

To enable calculations additional parameter "--circumference <value>"
needs to be used when calling script which sets wheel circumference in mm.

Both speed and cadence are enabled at the same time. Speed is calculated
in km/h and cadence in rpm.
---
 test/test-cyclingspeed | 71 ++++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 69 insertions(+), 2 deletions(-)

diff --git a/test/test-cyclingspeed b/test/test-cyclingspeed
index 92fe935..841456c 100755
--- a/test/test-cyclingspeed
+++ b/test/test-cyclingspeed
@@ -14,23 +14,86 @@ import dbus.service
 import dbus.mainloop.glib
 from optparse import OptionParser, make_option
 
+class MeasurementQ:
+	def __init__(self, wrap_v):
+		self._now = [None, None]
+		self._prev = [None, None]
+		self._wrap_v = wrap_v
+
+	def can_calc(self):
+		return ((self._now[0] is not None)
+			and (self._now[1] is not None)
+			and (self._prev[0] is not None)
+			and (self._prev[1] is not None))
+
+	def delta_v(self):
+		delta = self._now[0] - self._prev[0]
+		if (delta < 0) and (self._wrap_v):
+			delta = delta + 65536
+		return delta
+
+	def delta_t(self):
+		delta = self._now[1] - self._prev[1]
+		if delta < 0:
+			delta = delta + 65536
+		return delta
+
+	def put(self, data):
+		self._prev = self._now
+		self._now = data
+
 class Watcher(dbus.service.Object):
+	_wheel = MeasurementQ(False)
+	_crank = MeasurementQ(True)
+	_circumference = None
+
+	def enable_calc(self, v):
+		self._circumference = v
+
 	@dbus.service.method("org.bluez.CyclingSpeedWatcher",
 					in_signature="oa{sv}", out_signature="")
 	def MeasurementReceived(self, device, measure):
 		print("Measurement received from %s" % device)
 
+		rev = None
+		evt = None
 		if "WheelRevolutions" in measure:
+			rev = measure["WheelRevolutions"]
 			print("WheelRevolutions: ", measure["WheelRevolutions"])
-
 		if "LastWheelEventTime" in measure:
+			evt = measure["LastWheelEventTime"]
 			print("LastWheelEventTime: ", measure["LastWheelEventTime"])
+		self._wheel.put( [rev, evt] )
 
+		rev = None
+		evt = None
 		if "CrankRevolutions" in measure:
+			rev = measure["CrankRevolutions"]
 			print("CrankRevolutions: ", measure["CrankRevolutions"])
-
 		if "LastCrankEventTime" in measure:
+			evt = measure["LastCrankEventTime"]
 			print("LastCrankEventTime: ", measure["LastCrankEventTime"])
+		self._crank.put( [rev, evt] )
+
+		if self._circumference is None:
+			return
+
+		if self._wheel.can_calc():
+			delta_v = self._wheel.delta_v()
+			delta_t = self._wheel.delta_t()
+
+			if (delta_v >= 0) and (delta_t > 0):
+				speed = delta_v * self._circumference * 1024 / delta_t # mm/s
+				speed = speed * 0.0036 # mm/s -> km/h
+				print("(calculated) Speed: %.2f km/h" % speed)
+
+		if self._crank.can_calc():
+			delta_v = self._crank.delta_v()
+			delta_t = self._crank.delta_t()
+
+			if delta_t > 0:
+				cadence = delta_v * 1024 / delta_t
+				print("(calculated) Cadence: %d rpm" % cadence)
 
 def properties_changed(interface, changed, invalidated):
 	if "Location" in changed:
@@ -46,6 +109,8 @@ if __name__ == "__main__":
 			type="string", dest="adapter"),
 		make_option("-b", "--device", action="store",
 			type="string", dest="address"),
+		make_option("-c", "--circumference", action="store",
+			type="int", dest="circumference"),
 		]
 
 	parser = OptionParser(option_list=option_list)
@@ -77,6 +142,8 @@ if __name__ == "__main__":
 
 	watcher_path = "/test/watcher"
 	watcher = Watcher(bus, watcher_path)
+	if options.circumference:
+		watcher.enable_calc(options.circumference)
 	cscmanager.RegisterWatcher(watcher_path)
 
 	csc = dbus.Interface(bus.get_object("org.bluez", device_path),
-- 
1.8.0


^ permalink raw reply related

* [PATCH v2 19/20] test: Add cyclingspeed test script
From: Andrzej Kaczmarek @ 2012-11-05  8:55 UTC (permalink / raw)
  To: linux-bluetooth; +Cc: Andrzej Kaczmarek
In-Reply-To: <1352105705-13988-1-git-send-email-andrzej.kaczmarek@tieto.com>

---
 Makefile.tools         |   2 +-
 test/test-cyclingspeed | 124 +++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 125 insertions(+), 1 deletion(-)
 create mode 100755 test/test-cyclingspeed

diff --git a/Makefile.tools b/Makefile.tools
index f7c85ef..ee62d83 100644
--- a/Makefile.tools
+++ b/Makefile.tools
@@ -215,4 +215,4 @@ EXTRA_DIST += test/sap_client.py test/hsplay test/hsmicro \
 		test/test-health test/test-health-sink test/service-record.dtd \
 		test/service-did.xml test/service-spp.xml test/service-opp.xml \
 		test/service-ftp.xml test/simple-player test/test-nap \
-		test/test-heartrate test/test-alert
+		test/test-heartrate test/test-alert test/test-cycling
diff --git a/test/test-cyclingspeed b/test/test-cyclingspeed
new file mode 100755
index 0000000..92fe935
--- /dev/null
+++ b/test/test-cyclingspeed
@@ -0,0 +1,124 @@
+#!/usr/bin/python
+
+from __future__ import absolute_import, print_function, unicode_literals
+
+'''
+Cycling Speed and Cadence test script
+'''
+
+import gobject
+
+import sys
+import dbus
+import dbus.service
+import dbus.mainloop.glib
+from optparse import OptionParser, make_option
+
+class Watcher(dbus.service.Object):
+	@dbus.service.method("org.bluez.CyclingSpeedWatcher",
+					in_signature="oa{sv}", out_signature="")
+	def MeasurementReceived(self, device, measure):
+		print("Measurement received from %s" % device)
+
+		if "WheelRevolutions" in measure:
+			print("WheelRevolutions: ", measure["WheelRevolutions"])
+
+		if "LastWheelEventTime" in measure:
+			print("LastWheelEventTime: ", measure["LastWheelEventTime"])
+
+		if "CrankRevolutions" in measure:
+			print("CrankRevolutions: ", measure["CrankRevolutions"])
+
+		if "LastCrankEventTime" in measure:
+			print("LastCrankEventTime: ", measure["LastCrankEventTime"])
+
+def properties_changed(interface, changed, invalidated):
+	if "Location" in changed:
+		print("Sensor location: %s" % changed["Location"])
+
+if __name__ == "__main__":
+	dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
+
+	bus = dbus.SystemBus()
+
+	option_list = [
+		make_option("-i", "--adapter", action="store",
+			type="string", dest="adapter"),
+		make_option("-b", "--device", action="store",
+			type="string", dest="address"),
+		]
+
+	parser = OptionParser(option_list=option_list)
+
+	(options, args) = parser.parse_args()
+
+	if not options.address:
+		print("Usage: %s [-i <adapter>] -b <bdaddr> [-c <value>] [cmd]" % (sys.argv[0]))
+		print("Possible commands:")
+		print("\tShowSupportedLocations")
+		print("\tSetLocation <location>")
+		print("\tSetCumulativeWheelRevolutions <value>")
+		sys.exit(1)
+
+	manager = dbus.Interface(bus.get_object("org.bluez", "/"),
+					"org.bluez.Manager")
+	if options.adapter:
+		adapter_path = manager.FindAdapter(options.adapter)
+	else:
+		adapter_path = manager.DefaultAdapter()
+
+	adapter = dbus.Interface(bus.get_object("org.bluez", adapter_path),
+							"org.bluez.Adapter")
+
+	device_path = adapter.FindDevice(options.address)
+
+	cscmanager = dbus.Interface(bus.get_object("org.bluez", adapter_path),
+						"org.bluez.CyclingSpeedManager")
+
+	watcher_path = "/test/watcher"
+	watcher = Watcher(bus, watcher_path)
+	cscmanager.RegisterWatcher(watcher_path)
+
+	csc = dbus.Interface(bus.get_object("org.bluez", device_path),
+						"org.bluez.CyclingSpeed")
+
+	bus.add_signal_receiver(properties_changed, bus_name="org.bluez",
+				path=device_path,
+				dbus_interface="org.freedesktop.DBus.Properties",
+				signal_name="PropertiesChanged")
+
+	device_prop = dbus.Interface(bus.get_object("org.bluez", device_path),
+					"org.freedesktop.DBus.Properties")
+
+	properties = device_prop.GetAll("org.bluez.CyclingSpeed")
+
+	if "Location" in properties:
+		print("Sensor location: %s" % properties["Location"])
+	else:
+		print("Sensor location is not supported")
+
+	if len(args) > 0:
+		if args[0] == "ShowSupportedLocations":
+			if properties["MultipleSensorLocationsSupported"]:
+				print("Supported locations: ", properties["SupportedLocations"])
+			else:
+				print("Multiple sensor locations not supported")
+
+		elif args[0] == "SetLocation":
+			if properties["MultipleSensorLocationsSupported"]:
+				device_prop.Set("org.bluez.CyclingSpeed", "Location", args[1])
+			else:
+				print("Multiple sensor locations not supported")
+
+		elif args[0] == "SetCumulativeWheelRevolutions":
+			if properties["WheelRevolutionDataSupported"]:
+				csc.SetCumulativeWheelRevolutions(dbus.UInt32(args[1]))
+			else:
+				print("Wheel revolution data not supported")
+
+		else:
+			print("Unknown command")
+			sys.exit(1)
+
+	mainloop = gobject.MainLoop()
+	mainloop.run()
-- 
1.8.0


^ permalink raw reply related

* [PATCH v2 18/20] build: Add CSCP API document to EXTRA_DIST
From: Andrzej Kaczmarek @ 2012-11-05  8:55 UTC (permalink / raw)
  To: linux-bluetooth; +Cc: Andrzej Kaczmarek
In-Reply-To: <1352105705-13988-1-git-send-email-andrzej.kaczmarek@tieto.com>

---
 Makefile.am | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/Makefile.am b/Makefile.am
index 092ac6f..d2dc65e 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -412,7 +412,7 @@ EXTRA_DIST += doc/manager-api.txt \
 		doc/sap-api.txt doc/media-api.txt doc/assigned-numbers.txt \
 		doc/supported-features.txt doc/alert-api.txt doc/mgmt-api.txt \
 		doc/oob-api.txt doc/proximity-api.txt doc/heartrate-api.txt \
-		doc/thermometer-api.txt
+		doc/thermometer-api.txt doc/cyclingspeed-api.txt
 
 AM_CFLAGS += @DBUS_CFLAGS@ @GLIB_CFLAGS@
 
-- 
1.8.0


^ permalink raw reply related

* [PATCH v2 17/20] doc: Rename cycling API to cyclingspeed
From: Andrzej Kaczmarek @ 2012-11-05  8:55 UTC (permalink / raw)
  To: linux-bluetooth; +Cc: Andrzej Kaczmarek
In-Reply-To: <1352105705-13988-1-git-send-email-andrzej.kaczmarek@tieto.com>

---
 doc/cycling-api.txt      | 100 -----------------------------------------------
 doc/cyclingspeed-api.txt | 100 +++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 100 insertions(+), 100 deletions(-)
 delete mode 100644 doc/cycling-api.txt
 create mode 100644 doc/cyclingspeed-api.txt

diff --git a/doc/cycling-api.txt b/doc/cycling-api.txt
deleted file mode 100644
index 08e11c8..0000000
--- a/doc/cycling-api.txt
+++ /dev/null
@@ -1,100 +0,0 @@
-Cycling Speed and Cadence API description
-*****************************************
-
-Copyright (C) 2012	Tieto Poland
-
-Cycling Speed and Cadence Manager hierarchy
-===========================================
-
-Service		org.bluez
-Interface	org.bluez.CyclingSpeedManager
-Object path	[variable prefix]/{hci0,hci1,...}
-
-Methods		RegisterWatcher(object agent)
-
-			Registers a watcher to monitor cycling speed and
-			cadence measurements.
-
-			Possible Errors: org.bluez.Error.InvalidArguments
-
-		UnregisterWatcher(object agent)
-
-			Unregisters a watcher.
-
-Cycling Speed and Cadence Profile hierarchy
-===========================================
-
-Service		org.bluez
-Interface	org.bluez.CyclingSpeed
-Object path	[variable prefix]/{hci0,hci1,...}/dev_XX_XX_XX_XX_XX_XX
-
-Methods		SetCumulativeWheelRevolutions(uint32 value)
-
-			Sets cumulative wheel revolutions value if
-			Cumulative Wheel Revolutions feature is supported.
-
-			Possible Errors: org.bluez.Error.NotSupported
-
-Properties	string Location (optional) [readwrite]
-
-			Current sensor location, if supported.
-			If Multiple Sensor Locations feature is supported,
-			this property can be set to one of values read from
-			SupportedLocations property.
-
-			Possible values: "other", "top-of-shoe", "in-shoe",
-					"hip", "front-wheel", "left-crank",
-					"right-crank", "left-pedal",
-					"right-pedal", "front-hub",
-					"rear-dropout", "chainstay",
-					"rear-wheel", "rear-hub"
-
-		array{string} SupportedLocations (optional) [readonly]
-
-			List of locations supported by sensor, only present
-			if Multiple Sensor Locations feature is supported.
-
-		boolean WheelRevolutionDataSupported [readonly]
-
-			true if sensor can read and set Cumulative Wheel
-			Revolutions value, false otherwise.
-
-		boolean MultipleSensorLocationsSupported [readonly]
-
-			true if sensor supports Multiple Sensor Locations
-			feature and can set Location, false otherwise.
-
-Cycling Speed and Cadence Watcher hierarchy
-===========================================
-
-Service		unique name
-Interface	org.bluez.CyclingSpeedWatcher
-Object path	freely definable
-
-Methods		void MeasurementReceived(object device, dict measurement)
-
-			This callback is called whenever wheel and/or crank
-			revolutions measurement is received from sensor.
-
-			Measurement:
-
-				uint32 WheelRevolutions (optional):
-
-					Cumulative number of wheel revolutions.
-
-				uint16 LastWheelEventTime (optional):
-
-					Time of last event from wheel sensor.
-					Value is expressed in 1/1024 second
-					units and can roll over during a ride.
-
-				uint16 CrankRevolutions (optional):
-
-					Cumulative number of crank revolutions.
-					This value can occasionally roll over.
-
-				uint16 LastCrankEventTime (optional):
-
-					Time of last event from crank sensor.
-					Value is expressed in 1/1024 second
-					units and can roll over during a ride.
diff --git a/doc/cyclingspeed-api.txt b/doc/cyclingspeed-api.txt
new file mode 100644
index 0000000..08e11c8
--- /dev/null
+++ b/doc/cyclingspeed-api.txt
@@ -0,0 +1,100 @@
+Cycling Speed and Cadence API description
+*****************************************
+
+Copyright (C) 2012	Tieto Poland
+
+Cycling Speed and Cadence Manager hierarchy
+===========================================
+
+Service		org.bluez
+Interface	org.bluez.CyclingSpeedManager
+Object path	[variable prefix]/{hci0,hci1,...}
+
+Methods		RegisterWatcher(object agent)
+
+			Registers a watcher to monitor cycling speed and
+			cadence measurements.
+
+			Possible Errors: org.bluez.Error.InvalidArguments
+
+		UnregisterWatcher(object agent)
+
+			Unregisters a watcher.
+
+Cycling Speed and Cadence Profile hierarchy
+===========================================
+
+Service		org.bluez
+Interface	org.bluez.CyclingSpeed
+Object path	[variable prefix]/{hci0,hci1,...}/dev_XX_XX_XX_XX_XX_XX
+
+Methods		SetCumulativeWheelRevolutions(uint32 value)
+
+			Sets cumulative wheel revolutions value if
+			Cumulative Wheel Revolutions feature is supported.
+
+			Possible Errors: org.bluez.Error.NotSupported
+
+Properties	string Location (optional) [readwrite]
+
+			Current sensor location, if supported.
+			If Multiple Sensor Locations feature is supported,
+			this property can be set to one of values read from
+			SupportedLocations property.
+
+			Possible values: "other", "top-of-shoe", "in-shoe",
+					"hip", "front-wheel", "left-crank",
+					"right-crank", "left-pedal",
+					"right-pedal", "front-hub",
+					"rear-dropout", "chainstay",
+					"rear-wheel", "rear-hub"
+
+		array{string} SupportedLocations (optional) [readonly]
+
+			List of locations supported by sensor, only present
+			if Multiple Sensor Locations feature is supported.
+
+		boolean WheelRevolutionDataSupported [readonly]
+
+			true if sensor can read and set Cumulative Wheel
+			Revolutions value, false otherwise.
+
+		boolean MultipleSensorLocationsSupported [readonly]
+
+			true if sensor supports Multiple Sensor Locations
+			feature and can set Location, false otherwise.
+
+Cycling Speed and Cadence Watcher hierarchy
+===========================================
+
+Service		unique name
+Interface	org.bluez.CyclingSpeedWatcher
+Object path	freely definable
+
+Methods		void MeasurementReceived(object device, dict measurement)
+
+			This callback is called whenever wheel and/or crank
+			revolutions measurement is received from sensor.
+
+			Measurement:
+
+				uint32 WheelRevolutions (optional):
+
+					Cumulative number of wheel revolutions.
+
+				uint16 LastWheelEventTime (optional):
+
+					Time of last event from wheel sensor.
+					Value is expressed in 1/1024 second
+					units and can roll over during a ride.
+
+				uint16 CrankRevolutions (optional):
+
+					Cumulative number of crank revolutions.
+					This value can occasionally roll over.
+
+				uint16 LastCrankEventTime (optional):
+
+					Time of last event from crank sensor.
+					Value is expressed in 1/1024 second
+					units and can roll over during a ride.
-- 
1.8.0


^ permalink raw reply related

* [PATCH v2 16/20] doc: Remove Get-/SetProperties from CSC API document
From: Andrzej Kaczmarek @ 2012-11-05  8:55 UTC (permalink / raw)
  To: linux-bluetooth; +Cc: Andrzej Kaczmarek
In-Reply-To: <1352105705-13988-1-git-send-email-andrzej.kaczmarek@tieto.com>

cyclingspeed plugin uses DBus.Properties instead of custom methods.
---
 doc/cycling-api.txt | 20 +-------------------
 1 file changed, 1 insertion(+), 19 deletions(-)

diff --git a/doc/cycling-api.txt b/doc/cycling-api.txt
index adbcd33..08e11c8 100644
--- a/doc/cycling-api.txt
+++ b/doc/cycling-api.txt
@@ -28,31 +28,13 @@ Service		org.bluez
 Interface	org.bluez.CyclingSpeed
 Object path	[variable prefix]/{hci0,hci1,...}/dev_XX_XX_XX_XX_XX_XX
 
-Methods		void SetProperty(string name, variant value)
-
-			Changes the value of the specified property. Only
-			read-write properties can be changed. On success
-			this will emit a PropertyChanged signal.
-
-			Possible Errors: org.bluez.Error.InvalidArguments
-
-		dict GetProperties()
-
-			Returns all properties for the interface. See the
-			Properties section for the available properties.
-
-		SetCumulativeWheelRevolutions(uint32 value)
+Methods		SetCumulativeWheelRevolutions(uint32 value)
 
 			Sets cumulative wheel revolutions value if
 			Cumulative Wheel Revolutions feature is supported.
 
 			Possible Errors: org.bluez.Error.NotSupported
 
-Signals		PropertyChanged(string name, variant value)
-
-			This signal indicates a changed value of the given
-			property.
-
 Properties	string Location (optional) [readwrite]
 
 			Current sensor location, if supported.
-- 
1.8.0


^ permalink raw reply related

* [PATCH v2 15/20] core: Add CyclingSpeedWatcher interface to default policy
From: Andrzej Kaczmarek @ 2012-11-05  8:55 UTC (permalink / raw)
  To: linux-bluetooth; +Cc: Andrzej Kaczmarek
In-Reply-To: <1352105705-13988-1-git-send-email-andrzej.kaczmarek@tieto.com>

---
 src/bluetooth.conf | 1 +
 1 file changed, 1 insertion(+)

diff --git a/src/bluetooth.conf b/src/bluetooth.conf
index 2db43d9..a1269a4 100644
--- a/src/bluetooth.conf
+++ b/src/bluetooth.conf
@@ -19,6 +19,7 @@
     <allow send_interface="org.bluez.AlertAgent"/>
     <allow send_interface="org.bluez.Profile"/>
     <allow send_interface="org.bluez.HeartRateWatcher"/>
+    <allow send_interface="org.bluez.CyclingSpeedWatcher"/>
   </policy>
 
   <policy at_console="true">
-- 
1.8.0


^ permalink raw reply related

* [PATCH v2 14/20] cyclingspeed: Add support for Set Cumulative Value
From: Andrzej Kaczmarek @ 2012-11-05  8:54 UTC (permalink / raw)
  To: linux-bluetooth; +Cc: Andrzej Kaczmarek
In-Reply-To: <1352105705-13988-1-git-send-email-andrzej.kaczmarek@tieto.com>

---
 profiles/cyclingspeed/cyclingspeed.c | 92 +++++++++++++++++++++++++++++++++++-
 1 file changed, 91 insertions(+), 1 deletion(-)

diff --git a/profiles/cyclingspeed/cyclingspeed.c b/profiles/cyclingspeed/cyclingspeed.c
index d899c00..0a2cb52 100644
--- a/profiles/cyclingspeed/cyclingspeed.c
+++ b/profiles/cyclingspeed/cyclingspeed.c
@@ -75,6 +75,7 @@ struct controlpoint_req {
 	uint8_t			opcode;
 	guint			timeout;
 	GDBusPendingReply	reply_id;
+	DBusMessage		*msg;
 
 	uint8_t			pending_location;
 };
@@ -289,6 +290,15 @@ static gboolean controlpoint_timeout(gpointer user_data)
 		g_dbus_pending_property_error(req->reply_id,
 				ERROR_INTERFACE ".Failed",
 				"Operation failed (timeout)");
+	} else if (req->opcode == SET_CUMULATIVE_VALUE) {
+		DBusMessage *reply;
+
+		reply = btd_error_failed(req->msg,
+						"Operation failed (timeout)");
+
+		g_dbus_send_message(btd_get_dbus_connection(), reply);
+
+		dbus_message_unref(req->msg);
 	}
 
 	req->csc->pending_req = NULL;
@@ -309,6 +319,15 @@ static void controlpoint_write_cb(guint8 status, const guint8 *pdu, guint16 len,
 			g_dbus_pending_property_error(req->reply_id,
 					ERROR_INTERFACE ".Failed",
 					"Operation failed (%d)", status);
+		} else if  (req->opcode == SET_CUMULATIVE_VALUE) {
+			DBusMessage *reply;
+
+			reply = btd_error_failed(req->msg,
+						"Operation failed");
+
+			g_dbus_send_message(btd_get_dbus_connection(), reply);
+
+			dbus_message_unref(req->msg);
 		}
 
 		req->csc->pending_req = NULL;
@@ -623,6 +642,34 @@ static void controlpoint_property_reply(struct controlpoint_req *req,
 	}
 }
 
+static void controlpoint_method_reply(struct controlpoint_req *req,
+								uint8_t code)
+{
+	DBusMessage *reply;
+
+	switch (code) {
+	case RSP_SUCCESS:
+		reply = dbus_message_new_method_return(req->msg);
+		break;
+	case RSP_NOT_SUPPORTED:
+		reply = btd_error_not_supported(req->msg);
+		break;
+	case RSP_INVALID_PARAM:
+		reply = btd_error_invalid_args(req->msg);
+		break;
+	case RSP_FAILED:
+		reply = btd_error_failed(req->msg, "Failed");
+		break;
+	default:
+		reply = btd_error_failed(req->msg, "Unknown error");
+		break;
+	}
+
+	g_dbus_send_message(btd_get_dbus_connection(), reply);
+
+	dbus_message_unref(req->msg);
+}
+
 static void controlpoint_ind_handler(const uint8_t *pdu, uint16_t len,
 							gpointer user_data)
 {
@@ -674,6 +721,10 @@ static void controlpoint_ind_handler(const uint8_t *pdu, uint16_t len,
 	}
 
 	switch (req->opcode) {
+	case SET_CUMULATIVE_VALUE:
+		controlpoint_method_reply(req, rsp_code);
+		break;
+
 	case REQUEST_SUPPORTED_SENSOR_LOC:
 		if (rsp_code == RSP_SUCCESS) {
 			csc->num_locations = len;
@@ -1081,6 +1132,44 @@ static const GDBusPropertyTable cyclingspeed_device_properties[] = {
 	{ }
 };
 
+static DBusMessage *set_cumulative_wheel_rev(DBusConnection *conn,
+						DBusMessage *msg, void *data)
+{
+	struct csc *csc = data;
+	dbus_uint32_t value;
+	struct controlpoint_req *req;
+	uint8_t att_val[5]; /* uint8 opcode + uint32 value */
+
+	if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_UINT32, &value,
+							DBUS_TYPE_INVALID))
+		return btd_error_invalid_args(msg);
+
+	if (csc->pending_req != NULL)
+		return btd_error_in_progress(msg);
+
+	req = g_new(struct controlpoint_req, 1);
+	req->csc = csc;
+	req->opcode = SET_CUMULATIVE_VALUE;
+	req->msg = dbus_message_ref(msg);
+
+	csc->pending_req = req;
+
+	att_val[0] = SET_CUMULATIVE_VALUE;
+	att_put_u32(value, att_val + 1);
+
+	gatt_write_char(csc->attrib, csc->controlpoint_val_handle, att_val,
+		sizeof(att_val), controlpoint_write_cb, req);
+
+	return NULL;
+}
+
+static const GDBusMethodTable cyclingspeed_device_methods[] = {
+	{ GDBUS_ASYNC_METHOD("SetCumulativeWheelRevolutions",
+			GDBUS_ARGS({ "value", "u" }), NULL,
+			set_cumulative_wheel_rev) },
+	{ }
+};
+
 int csc_device_register(struct btd_device *device, struct gatt_primary *prim)
 {
 	struct btd_adapter *adapter;
@@ -1100,7 +1189,8 @@ int csc_device_register(struct btd_device *device, struct gatt_primary *prim)
 	if (!g_dbus_register_interface(btd_get_dbus_connection(),
 						device_get_path(device),
 						CYCLINGSPEED_INTERFACE,
-						NULL, NULL,
+						cyclingspeed_device_methods,
+						NULL,
 						cyclingspeed_device_properties,
 						csc, destroy_csc)) {
 		error("D-Bus failed to register %s interface",
-- 
1.8.0


^ permalink raw reply related

* [PATCH v2 13/20] cyclingspeed: Add support for Update Sensor Location
From: Andrzej Kaczmarek @ 2012-11-05  8:54 UTC (permalink / raw)
  To: linux-bluetooth; +Cc: Andrzej Kaczmarek
In-Reply-To: <1352105705-13988-1-git-send-email-andrzej.kaczmarek@tieto.com>

---
 profiles/cyclingspeed/cyclingspeed.c | 122 ++++++++++++++++++++++++++++++++++-
 1 file changed, 121 insertions(+), 1 deletion(-)

diff --git a/profiles/cyclingspeed/cyclingspeed.c b/profiles/cyclingspeed/cyclingspeed.c
index 3222a9b..d899c00 100644
--- a/profiles/cyclingspeed/cyclingspeed.c
+++ b/profiles/cyclingspeed/cyclingspeed.c
@@ -74,6 +74,9 @@ struct controlpoint_req {
 	struct csc		*csc;
 	uint8_t			opcode;
 	guint			timeout;
+	GDBusPendingReply	reply_id;
+
+	uint8_t			pending_location;
 };
 
 struct csc_adapter {
@@ -148,6 +151,17 @@ static const gchar *location2str(uint8_t value)
 	return location_enum[0];
 }
 
+static int str2location(const char *location)
+{
+	size_t i;
+
+	for (i = 0; i < G_N_ELEMENTS(location_enum); i++)
+		if (!strcmp(location_enum[i], location))
+			return i;
+
+	return -1;
+}
+
 static gint cmp_adapter(gconstpointer a, gconstpointer b)
 {
 	const struct csc_adapter *cadapter = a;
@@ -271,6 +285,12 @@ static gboolean controlpoint_timeout(gpointer user_data)
 {
 	struct controlpoint_req *req = user_data;
 
+	if (req->opcode == UPDATE_SENSOR_LOC) {
+		g_dbus_pending_property_error(req->reply_id,
+				ERROR_INTERFACE ".Failed",
+				"Operation failed (timeout)");
+	}
+
 	req->csc->pending_req = NULL;
 	g_free(req);
 
@@ -285,6 +305,12 @@ static void controlpoint_write_cb(guint8 status, const guint8 *pdu, guint16 len,
 	if (status != 0) {
 		error("SC Control Point write failed (opcode=%d)", req->opcode);
 
+		if (req->opcode == UPDATE_SENSOR_LOC) {
+			g_dbus_pending_property_error(req->reply_id,
+					ERROR_INTERFACE ".Failed",
+					"Operation failed (%d)", status);
+		}
+
 		req->csc->pending_req = NULL;
 		g_free(req);
 
@@ -563,6 +589,40 @@ static void measurement_notify_handler(const uint8_t *pdu, uint16_t len,
 	process_measurement(csc, pdu + 3, len - 3);
 }
 
+static void controlpoint_property_reply(struct controlpoint_req *req,
+								uint8_t code)
+{
+	switch (code) {
+	case RSP_SUCCESS:
+		g_dbus_pending_property_success(req->reply_id);
+		break;
+
+	case RSP_NOT_SUPPORTED:
+		g_dbus_pending_property_error(req->reply_id,
+					ERROR_INTERFACE ".NotSupported",
+					"Feature is not supported");
+		break;
+
+	case RSP_INVALID_PARAM:
+		g_dbus_pending_property_error(req->reply_id,
+					ERROR_INTERFACE ".InvalidArguments",
+					"Invalid arguments in method call");
+		break;
+
+	case RSP_FAILED:
+		g_dbus_pending_property_error(req->reply_id,
+					ERROR_INTERFACE ".Failed",
+					"Operation failed");
+		break;
+
+	default:
+		g_dbus_pending_property_error(req->reply_id,
+					ERROR_INTERFACE ".Failed",
+					"Operation failed (%d)", code);
+		break;
+	}
+}
+
 static void controlpoint_ind_handler(const uint8_t *pdu, uint16_t len,
 							gpointer user_data)
 {
@@ -622,6 +682,16 @@ static void controlpoint_ind_handler(const uint8_t *pdu, uint16_t len,
 			error("Failed to read Supported Sendor Locations");
 		}
 		break;
+
+	case UPDATE_SENSOR_LOC:
+		csc->location = req->pending_location;
+
+		controlpoint_property_reply(req, rsp_code);
+
+		g_dbus_emit_property_changed(btd_get_dbus_connection(),
+					device_get_path(csc->dev),
+					CYCLINGSPEED_INTERFACE, "Location");
+		break;
 	}
 
 	csc->pending_req = NULL;
@@ -888,6 +958,56 @@ static gboolean property_get_location(const GDBusPropertyTable *property,
 	return TRUE;
 }
 
+static void property_set_location(const GDBusPropertyTable *property,
+					DBusMessageIter *iter,
+					GDBusPendingPropertySet id, void *data)
+{
+	struct csc *csc = data;
+	char *loc;
+	int loc_val;
+	uint8_t att_val[2];
+	struct controlpoint_req *req;
+
+	if (csc->pending_req != NULL)
+		return g_dbus_pending_property_error(id,
+					ERROR_INTERFACE ".InProgress",
+					"Operation already in progress");
+
+	if (!(csc->feature & MULTI_SENSOR_LOC_SUPPORT))
+		return g_dbus_pending_property_error(id,
+					ERROR_INTERFACE ".NotSupported",
+					"Feature is not supported");
+
+	if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_STRING)
+		return g_dbus_pending_property_error(id,
+					ERROR_INTERFACE ".InvalidArguments",
+					"Invalid arguments in method call");
+
+	dbus_message_iter_get_basic(iter, &loc);
+
+	loc_val = str2location(loc);
+
+	if (loc_val < 0)
+		return g_dbus_pending_property_error(id,
+					ERROR_INTERFACE ".InvalidArguments",
+					"Invalid arguments in method call");
+
+	req = g_new(struct controlpoint_req, 1);
+	req->csc = csc;
+	req->reply_id = id;
+	req->opcode = UPDATE_SENSOR_LOC;
+	req->pending_location = loc_val;
+
+	csc->pending_req = req;
+
+	att_val[0] = UPDATE_SENSOR_LOC;
+	att_val[1] = loc_val;
+
+	gatt_write_char(csc->attrib, csc->controlpoint_val_handle, att_val,
+		sizeof(att_val), controlpoint_write_cb, req);
+
+}
+
 static gboolean property_exists_location(const GDBusPropertyTable *property,
 								void *data)
 {
@@ -952,7 +1072,7 @@ static gboolean property_get_multi_loc_sup(const GDBusPropertyTable *property,
 }
 
 static const GDBusPropertyTable cyclingspeed_device_properties[] = {
-	{ "Location", "s", property_get_location, NULL,
+	{ "Location", "s", property_get_location, property_set_location,
 						property_exists_location },
 	{ "SupportedLocations", "as", property_get_locations, NULL,
 						property_exists_locations },
-- 
1.8.0


^ permalink raw reply related

* [PATCH v2 12/20] cyclingspeed: Add support for Request Supported Sensor Locations
From: Andrzej Kaczmarek @ 2012-11-05  8:54 UTC (permalink / raw)
  To: linux-bluetooth; +Cc: Andrzej Kaczmarek
In-Reply-To: <1352105705-13988-1-git-send-email-andrzej.kaczmarek@tieto.com>

---
 profiles/cyclingspeed/cyclingspeed.c | 61 +++++++++++++++++++++++++++++++++---
 1 file changed, 57 insertions(+), 4 deletions(-)

diff --git a/profiles/cyclingspeed/cyclingspeed.c b/profiles/cyclingspeed/cyclingspeed.c
index ffef6ae..3222a9b 100644
--- a/profiles/cyclingspeed/cyclingspeed.c
+++ b/profiles/cyclingspeed/cyclingspeed.c
@@ -101,6 +101,8 @@ struct csc {
 	uint16_t		feature;
 	gboolean		has_location;
 	uint8_t			location;
+	uint8_t			num_locations;
+	uint8_t			*locations;
 
 	struct controlpoint_req	*pending_req;
 };
@@ -250,6 +252,7 @@ static void destroy_csc(gpointer user_data)
 
 	btd_device_unref(csc->dev);
 	g_free(csc->svc_range);
+	g_free(csc->locations);
 	g_free(csc);
 }
 
@@ -274,7 +277,6 @@ static gboolean controlpoint_timeout(gpointer user_data)
 	return FALSE;
 }
 
-__attribute__((unused)) /* TODO: remove once controlpoint ops are implemented */
 static void controlpoint_write_cb(guint8 status, const guint8 *pdu, guint16 len,
 							gpointer user_data)
 {
@@ -293,6 +295,20 @@ static void controlpoint_write_cb(guint8 status, const guint8 *pdu, guint16 len,
 									req);
 }
 
+static void read_supported_locations(struct csc *csc)
+{
+	struct controlpoint_req *req;
+
+	req = g_new0(struct controlpoint_req, 1);
+	req->csc = csc;
+	req->opcode = REQUEST_SUPPORTED_SENSOR_LOC;
+
+	csc->pending_req = req;
+
+	gatt_write_char(csc->attrib, csc->controlpoint_val_handle, &req->opcode,
+			sizeof(req->opcode), controlpoint_write_cb, req);
+}
+
 static void read_feature_cb(guint8 status, const guint8 *pdu,
 						guint16 len, gpointer user_data)
 {
@@ -317,6 +333,10 @@ static void read_feature_cb(guint8 status, const guint8 *pdu,
 	}
 
 	csc->feature = att_get_u16(value);
+
+	if ((csc->feature & MULTI_SENSOR_LOC_SUPPORT)
+						&& (csc->locations == NULL))
+		read_supported_locations(csc);
 }
 
 static void read_location_cb(guint8 status, const guint8 *pdu,
@@ -550,6 +570,7 @@ static void controlpoint_ind_handler(const uint8_t *pdu, uint16_t len,
 	struct controlpoint_req *req = csc->pending_req;
 	uint8_t opcode;
 	uint8_t req_opcode;
+	uint8_t rsp_code;
 	uint8_t *opdu;
 	uint16_t olen;
 	size_t plen;
@@ -583,7 +604,7 @@ static void controlpoint_ind_handler(const uint8_t *pdu, uint16_t len,
 	}
 
 	req_opcode = *pdu;
-	/* skip response code for now */
+	rsp_code = *(pdu + 1);
 	pdu += 2;
 	len -= 2;
 
@@ -592,7 +613,16 @@ static void controlpoint_ind_handler(const uint8_t *pdu, uint16_t len,
 		goto done;
 	}
 
-	/* TODO: handle response */
+	switch (req->opcode) {
+	case REQUEST_SUPPORTED_SENSOR_LOC:
+		if (rsp_code == RSP_SUCCESS) {
+			csc->num_locations = len;
+			csc->locations = g_memdup(pdu, len);
+		} else {
+			error("Failed to read Supported Sendor Locations");
+		}
+		break;
+	}
 
 	csc->pending_req = NULL;
 	g_source_remove(req->timeout);
@@ -866,6 +896,29 @@ static gboolean property_exists_location(const GDBusPropertyTable *property,
 	return csc->has_location;
 }
 
+static gboolean property_get_locations(const GDBusPropertyTable *property,
+					DBusMessageIter *iter, void *data)
+{
+	struct csc *csc = data;
+	DBusMessageIter entry;
+	int i;
+
+	if (!(csc->feature & MULTI_SENSOR_LOC_SUPPORT))
+		return FALSE;
+
+	dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY,
+					DBUS_TYPE_STRING_AS_STRING, &entry);
+	for (i = 0; i < csc->num_locations; i++) {
+		char *loc = g_strdup(location2str(csc->locations[i]));
+		dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING, &loc);
+		g_free(loc);
+	}
+
+	dbus_message_iter_close_container(iter, &entry);
+
+	return TRUE;
+}
+
 static gboolean property_exists_locations(const GDBusPropertyTable *property,
 								void *data)
 {
@@ -901,7 +954,7 @@ static gboolean property_get_multi_loc_sup(const GDBusPropertyTable *property,
 static const GDBusPropertyTable cyclingspeed_device_properties[] = {
 	{ "Location", "s", property_get_location, NULL,
 						property_exists_location },
-	{ "SupportedLocations", "as", NULL, NULL,
+	{ "SupportedLocations", "as", property_get_locations, NULL,
 						property_exists_locations },
 	{ "WheelRevolutionDataSupported", "b", property_get_wheel_rev_sup },
 	{ "MultipleLocationsSupported", "b", property_get_multi_loc_sup },
-- 
1.8.0


^ permalink raw reply related

* [PATCH v2 11/20] cyclingspeed: Add stub to use SC Control Point
From: Andrzej Kaczmarek @ 2012-11-05  8:54 UTC (permalink / raw)
  To: linux-bluetooth; +Cc: Andrzej Kaczmarek
In-Reply-To: <1352105705-13988-1-git-send-email-andrzej.kaczmarek@tieto.com>

This patch implements common functions to use SC Control Point.
Individual procedures will be implemented in subsequent patches.
---
 profiles/cyclingspeed/cyclingspeed.c | 145 +++++++++++++++++++++++++++++++++--
 1 file changed, 140 insertions(+), 5 deletions(-)

diff --git a/profiles/cyclingspeed/cyclingspeed.c b/profiles/cyclingspeed/cyclingspeed.c
index 5a65507..ffef6ae 100644
--- a/profiles/cyclingspeed/cyclingspeed.c
+++ b/profiles/cyclingspeed/cyclingspeed.c
@@ -41,6 +41,11 @@
 #include "log.h"
 #include "cyclingspeed.h"
 
+/* min length for ATT indication or notification: opcode (1b) + handle (2b) */
+#define ATT_HDR_LEN 3
+
+#define ATT_TIMEOUT 30
+
 #define CYCLINGSPEED_INTERFACE		"org.bluez.CyclingSpeed"
 #define CYCLINGSPEED_MANAGER_INTERFACE	"org.bluez.CyclingSpeedManager"
 #define CYCLINGSPEED_WATCHER_INTERFACE	"org.bluez.CyclingSpeedWatcher"
@@ -52,6 +57,25 @@
 #define WHEEL_REV_PRESENT	0x01
 #define CRANK_REV_PRESENT	0x02
 
+#define SET_CUMULATIVE_VALUE		0x01
+#define START_SENSOR_CALIBRATION	0x02
+#define UPDATE_SENSOR_LOC		0x03
+#define REQUEST_SUPPORTED_SENSOR_LOC	0x04
+#define RESPONSE_CODE			0x10
+
+#define RSP_SUCCESS		0x01
+#define RSP_NOT_SUPPORTED	0x02
+#define RSP_INVALID_PARAM	0x03
+#define RSP_FAILED		0x04
+
+struct csc;
+
+struct controlpoint_req {
+	struct csc		*csc;
+	uint8_t			opcode;
+	guint			timeout;
+};
+
 struct csc_adapter {
 	struct btd_adapter	*adapter;
 	GSList			*devices;	/* list of registered devices */
@@ -66,6 +90,8 @@ struct csc {
 	guint			attioid;
 	/* attio id for measurement characteristics value notifications */
 	guint			attio_measurement_id;
+	/* attio id for SC Control Point characteristics value indications */
+	guint			attio_controlpoint_id;
 
 	struct att_range	*svc_range;
 
@@ -75,6 +101,8 @@ struct csc {
 	uint16_t		feature;
 	gboolean		has_location;
 	uint8_t			location;
+
+	struct controlpoint_req	*pending_req;
 };
 
 struct watcher {
@@ -216,6 +244,7 @@ static void destroy_csc(gpointer user_data)
 
 	if (csc->attrib != NULL) {
 		g_attrib_unregister(csc->attrib, csc->attio_measurement_id);
+		g_attrib_unregister(csc->attrib, csc->attio_controlpoint_id);
 		g_attrib_unref(csc->attrib);
 	}
 
@@ -235,6 +264,35 @@ static void char_write_cb(guint8 status, const guint8 *pdu, guint16 len,
 	g_free(msg);
 }
 
+static gboolean controlpoint_timeout(gpointer user_data)
+{
+	struct controlpoint_req *req = user_data;
+
+	req->csc->pending_req = NULL;
+	g_free(req);
+
+	return FALSE;
+}
+
+__attribute__((unused)) /* TODO: remove once controlpoint ops are implemented */
+static void controlpoint_write_cb(guint8 status, const guint8 *pdu, guint16 len,
+							gpointer user_data)
+{
+	struct controlpoint_req *req = user_data;
+
+	if (status != 0) {
+		error("SC Control Point write failed (opcode=%d)", req->opcode);
+
+		req->csc->pending_req = NULL;
+		g_free(req);
+
+		return;
+	}
+
+	req->timeout = g_timeout_add_seconds(ATT_TIMEOUT, controlpoint_timeout,
+									req);
+}
+
 static void read_feature_cb(guint8 status, const guint8 *pdu,
 						guint16 len, gpointer user_data)
 {
@@ -316,6 +374,8 @@ static void discover_desc_cb(guint8 status, const guint8 *pdu,
 	for (i = 0; i < list->num; i++) {
 		uint8_t *value;
 		uint16_t handle, uuid;
+		uint8_t attr_val[2];
+		char *msg;
 
 		value = list->data[i];
 		handle = att_get_u16(value);
@@ -325,9 +385,6 @@ static void discover_desc_cb(guint8 status, const guint8 *pdu,
 			continue;
 
 		if (g_strcmp0(ch->uuid, CSC_MEASUREMENT_UUID) == 0) {
-			char *msg;
-			uint8_t attr_val[2];
-
 			ch->csc->measurement_ccc_handle = handle;
 
 			if (g_slist_length(ch->csc->cadapter->watchers) == 0) {
@@ -339,10 +396,16 @@ static void discover_desc_cb(guint8 status, const guint8 *pdu,
 				msg = g_strdup("Enable measurement");
 			}
 
-			gatt_write_char(ch->csc->attrib, handle, attr_val,
-					sizeof(attr_val), char_write_cb, msg);
+		} else if (g_strcmp0(ch->uuid, SC_CONTROL_POINT_UUID) == 0) {
+			att_put_u16(GATT_CLIENT_CHARAC_CFG_IND_BIT, attr_val);
+			msg = g_strdup("Enable SC Control Point indications");
+		} else {
+			break;
 		}
 
+		gatt_write_char(ch->csc->attrib, handle, attr_val,
+					sizeof(attr_val), char_write_cb, msg);
+
 		/* We only want CCC, can break here */
 		break;
 	}
@@ -480,6 +543,67 @@ static void measurement_notify_handler(const uint8_t *pdu, uint16_t len,
 	process_measurement(csc, pdu + 3, len - 3);
 }
 
+static void controlpoint_ind_handler(const uint8_t *pdu, uint16_t len,
+							gpointer user_data)
+{
+	struct csc *csc = user_data;
+	struct controlpoint_req *req = csc->pending_req;
+	uint8_t opcode;
+	uint8_t req_opcode;
+	uint8_t *opdu;
+	uint16_t olen;
+	size_t plen;
+
+	if (len < ATT_HDR_LEN) {
+		error("Invalid PDU received");
+		return;
+	}
+
+	/* skip ATT header */
+	pdu += ATT_HDR_LEN;
+	len -= ATT_HDR_LEN;
+
+	if (len < 1) {
+		error("Op Code missing");
+		goto done;
+	}
+
+	opcode = *pdu;
+	pdu++;
+	len--;
+
+	if (opcode != RESPONSE_CODE) {
+		DBG("Unsupported Op Code received (%d)", opcode);
+		goto done;
+	}
+
+	if (len < 2) {
+		error("Invalid Response Code PDU received");
+		goto done;
+	}
+
+	req_opcode = *pdu;
+	/* skip response code for now */
+	pdu += 2;
+	len -= 2;
+
+	if (req == NULL || req->opcode != req_opcode) {
+		DBG("Indication received without pending request");
+		goto done;
+	}
+
+	/* TODO: handle response */
+
+	csc->pending_req = NULL;
+	g_source_remove(req->timeout);
+	g_free(req);
+
+done:
+	opdu = g_attrib_get_buffer(csc->attrib, &plen);
+	olen = enc_confirmation(opdu, plen);
+	if (olen > 0)
+		g_attrib_send(csc->attrib, 0, opdu, olen, NULL, NULL, NULL);
+}
 
 static void discover_char_cb(GSList *chars, guint8 status, gpointer user_data)
 {
@@ -513,6 +637,12 @@ static void discover_char_cb(GSList *chars, guint8 status, gpointer user_data)
 		} else if (g_strcmp0(c->uuid, SC_CONTROL_POINT_UUID) == 0) {
 			DBG("SC Control Point supported");
 			csc->controlpoint_val_handle = c->value_handle;
+
+			csc->attio_controlpoint_id = g_attrib_register(
+					csc->attrib, ATT_OP_HANDLE_IND,
+					c->value_handle,
+					controlpoint_ind_handler, csc, NULL);
+
 			discover_desc(csc, c, c_next);
 		}
 	}
@@ -580,6 +710,11 @@ static void attio_disconnected_cb(gpointer user_data)
 		csc->attio_measurement_id = 0;
 	}
 
+	if (csc->attio_controlpoint_id > 0) {
+		g_attrib_unregister(csc->attrib, csc->attio_controlpoint_id);
+		csc->attio_controlpoint_id = 0;
+	}
+
 	g_attrib_unref(csc->attrib);
 	csc->attrib = NULL;
 }
-- 
1.8.0


^ permalink raw reply related

* [PATCH v2 10/20] cyclingspeed: Add DBus.Properties for org.bluez.CyclingSpeed interface
From: Andrzej Kaczmarek @ 2012-11-05  8:54 UTC (permalink / raw)
  To: linux-bluetooth; +Cc: Andrzej Kaczmarek
In-Reply-To: <1352105705-13988-1-git-send-email-andrzej.kaczmarek@tieto.com>

---
 profiles/cyclingspeed/cyclingspeed.c | 96 +++++++++++++++++++++++++++++++++++-
 1 file changed, 95 insertions(+), 1 deletion(-)

diff --git a/profiles/cyclingspeed/cyclingspeed.c b/profiles/cyclingspeed/cyclingspeed.c
index ae058f2..5a65507 100644
--- a/profiles/cyclingspeed/cyclingspeed.c
+++ b/profiles/cyclingspeed/cyclingspeed.c
@@ -103,6 +103,21 @@ struct characteristic {
 
 static GSList *csc_adapters = NULL;
 
+static const char * const location_enum[] = {
+	"other", "top-of-shoe", "in-shoe", "hip", "front-wheel", "left-crank",
+	"right-crank", "left-pedal", "right-pedal", "front-hub",
+	"rear-dropout", "chainstay", "rear-wheel", "rear-hub"
+};
+
+static const gchar *location2str(uint8_t value)
+{
+	if (value < G_N_ELEMENTS(location_enum))
+		return location_enum[value];
+
+	info("Body Sensor Location [%d] is RFU", value);
+	return location_enum[0];
+}
+
 static gint cmp_adapter(gconstpointer a, gconstpointer b)
 {
 	const struct csc_adapter *cadapter = a;
@@ -692,6 +707,72 @@ void csc_adapter_unregister(struct btd_adapter *adapter)
 					CYCLINGSPEED_MANAGER_INTERFACE);
 }
 
+static gboolean property_get_location(const GDBusPropertyTable *property,
+					DBusMessageIter *iter, void *data)
+{
+	struct csc *csc = data;
+	const char *loc;
+
+	if (!csc->has_location)
+		return FALSE;
+
+	loc = location2str(csc->location);
+
+	dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &loc);
+
+	return TRUE;
+}
+
+static gboolean property_exists_location(const GDBusPropertyTable *property,
+								void *data)
+{
+	struct csc *csc = data;
+
+	return csc->has_location;
+}
+
+static gboolean property_exists_locations(const GDBusPropertyTable *property,
+								void *data)
+{
+	struct csc *csc = data;
+
+	return !!(csc->feature & MULTI_SENSOR_LOC_SUPPORT);
+}
+
+static gboolean property_get_wheel_rev_sup(const GDBusPropertyTable *property,
+					DBusMessageIter *iter, void *data)
+{
+	struct csc *csc = data;
+	dbus_bool_t val;
+
+	val = !!(csc->feature & WHEEL_REV_SUPPORT);
+	dbus_message_iter_append_basic(iter, DBUS_TYPE_BOOLEAN, &val);
+
+	return TRUE;
+}
+
+static gboolean property_get_multi_loc_sup(const GDBusPropertyTable *property,
+					DBusMessageIter *iter, void *data)
+{
+	struct csc *csc = data;
+	dbus_bool_t val;
+
+	val = !!(csc->feature & MULTI_SENSOR_LOC_SUPPORT);
+	dbus_message_iter_append_basic(iter, DBUS_TYPE_BOOLEAN, &val);
+
+	return TRUE;
+}
+
+static const GDBusPropertyTable cyclingspeed_device_properties[] = {
+	{ "Location", "s", property_get_location, NULL,
+						property_exists_location },
+	{ "SupportedLocations", "as", NULL, NULL,
+						property_exists_locations },
+	{ "WheelRevolutionDataSupported", "b", property_get_wheel_rev_sup },
+	{ "MultipleLocationsSupported", "b", property_get_multi_loc_sup },
+	{ }
+};
+
 int csc_device_register(struct btd_device *device, struct gatt_primary *prim)
 {
 	struct btd_adapter *adapter;
@@ -708,6 +789,18 @@ int csc_device_register(struct btd_device *device, struct gatt_primary *prim)
 	csc->dev = btd_device_ref(device);
 	csc->cadapter = cadapter;
 
+	if (!g_dbus_register_interface(btd_get_dbus_connection(),
+						device_get_path(device),
+						CYCLINGSPEED_INTERFACE,
+						NULL, NULL,
+						cyclingspeed_device_properties,
+						csc, destroy_csc)) {
+		error("D-Bus failed to register %s interface",
+						CYCLINGSPEED_INTERFACE);
+		destroy_csc(csc);
+		return -EIO;
+	}
+
 	csc->svc_range = g_new0(struct att_range, 1);
 	csc->svc_range->start = prim->range.start;
 	csc->svc_range->end = prim->range.end;
@@ -741,5 +834,6 @@ void csc_device_unregister(struct btd_device *device)
 
 	cadapter->devices = g_slist_remove(cadapter->devices, csc);
 
-	destroy_csc(csc);
+	g_dbus_unregister_interface(btd_get_dbus_connection(),
+			device_get_path(device), CYCLINGSPEED_INTERFACE);
 }
-- 
1.8.0


^ permalink raw reply related

* [PATCH v2 09/20] cyclingspeed: Process measurement notifications
From: Andrzej Kaczmarek @ 2012-11-05  8:54 UTC (permalink / raw)
  To: linux-bluetooth; +Cc: Andrzej Kaczmarek
In-Reply-To: <1352105705-13988-1-git-send-email-andrzej.kaczmarek@tieto.com>

---
 profiles/cyclingspeed/cyclingspeed.c | 139 ++++++++++++++++++++++++++++++++++-
 1 file changed, 138 insertions(+), 1 deletion(-)

diff --git a/profiles/cyclingspeed/cyclingspeed.c b/profiles/cyclingspeed/cyclingspeed.c
index 4f0a0a5..ae058f2 100644
--- a/profiles/cyclingspeed/cyclingspeed.c
+++ b/profiles/cyclingspeed/cyclingspeed.c
@@ -43,6 +43,14 @@
 
 #define CYCLINGSPEED_INTERFACE		"org.bluez.CyclingSpeed"
 #define CYCLINGSPEED_MANAGER_INTERFACE	"org.bluez.CyclingSpeedManager"
+#define CYCLINGSPEED_WATCHER_INTERFACE	"org.bluez.CyclingSpeedWatcher"
+
+#define WHEEL_REV_SUPPORT		0x01
+#define CRANK_REV_SUPPORT		0x02
+#define MULTI_SENSOR_LOC_SUPPORT	0x04
+
+#define WHEEL_REV_PRESENT	0x01
+#define CRANK_REV_PRESENT	0x02
 
 struct csc_adapter {
 	struct btd_adapter	*adapter;
@@ -56,6 +64,8 @@ struct csc {
 
 	GAttrib			*attrib;
 	guint			attioid;
+	/* attio id for measurement characteristics value notifications */
+	guint			attio_measurement_id;
 
 	struct att_range	*svc_range;
 
@@ -74,6 +84,18 @@ struct watcher {
 	char			*path;
 };
 
+struct measurement {
+	struct csc	*csc;
+
+	bool		has_wheel_rev;
+	uint32_t	wheel_rev;
+	uint16_t	last_wheel_time;
+
+	bool		has_crank_rev;
+	uint16_t	crank_rev;
+	uint16_t	last_crank_time;
+};
+
 struct characteristic {
 	struct csc	*csc;
 	char		uuid[MAX_LEN_UUID_STR + 1];
@@ -177,8 +199,10 @@ static void destroy_csc(gpointer user_data)
 	if (csc->attioid > 0)
 		btd_device_remove_attio_callback(csc->dev, csc->attioid);
 
-	if (csc->attrib != NULL)
+	if (csc->attrib != NULL) {
+		g_attrib_unregister(csc->attrib, csc->attio_measurement_id);
 		g_attrib_unref(csc->attrib);
+	}
 
 	btd_device_unref(csc->dev);
 	g_free(csc->svc_range);
@@ -339,6 +363,109 @@ static void discover_desc(struct csc *csc, struct gatt_char *c,
 	gatt_find_info(csc->attrib, start, end, discover_desc_cb, ch);
 }
 
+static void update_watcher(gpointer data, gpointer user_data)
+{
+	struct watcher *w = data;
+	struct measurement *m = user_data;
+	struct csc *csc = m->csc;
+	const gchar *path = device_get_path(csc->dev);
+	DBusMessageIter iter;
+	DBusMessageIter dict;
+	DBusMessage *msg;
+
+	msg = dbus_message_new_method_call(w->srv, w->path,
+			CYCLINGSPEED_WATCHER_INTERFACE, "MeasurementReceived");
+	if (msg == NULL)
+		return;
+
+	dbus_message_iter_init_append(msg, &iter);
+
+	dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH , &path);
+
+	dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
+			DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
+			DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
+			DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);
+
+	if (m->has_wheel_rev) {
+		dict_append_entry(&dict, "WheelRevolutions",
+					DBUS_TYPE_UINT32, &m->wheel_rev);
+		dict_append_entry(&dict, "LastWheelEventTime",
+					DBUS_TYPE_UINT16, &m->last_wheel_time);
+	}
+
+	if (m->has_crank_rev) {
+		dict_append_entry(&dict, "CrankRevolutions",
+					DBUS_TYPE_UINT16, &m->crank_rev);
+		dict_append_entry(&dict, "LastCrankEventTime",
+					DBUS_TYPE_UINT16, &m->last_crank_time);
+	}
+
+	dbus_message_iter_close_container(&iter, &dict);
+
+	dbus_message_set_no_reply(msg, TRUE);
+	g_dbus_send_message(btd_get_dbus_connection(), msg);
+}
+
+static void process_measurement(struct csc *csc, const uint8_t *pdu,
+								uint16_t len)
+{
+	struct measurement m;
+	uint8_t flags;
+
+	flags = *pdu;
+
+	pdu++;
+	len--;
+
+	memset(&m, 0, sizeof(m));
+
+	if ((flags & WHEEL_REV_PRESENT) && (csc->feature & WHEEL_REV_SUPPORT)) {
+		if (len < 6) {
+			error("Wheel revolutions data fields missing");
+			return;
+		}
+
+		m.has_wheel_rev = true;
+		m.wheel_rev = att_get_u32(pdu);
+		m.last_wheel_time = att_get_u16(pdu + 4);
+		pdu += 6;
+		len -= 6;
+	}
+
+	if ((flags & CRANK_REV_PRESENT) && (csc->feature & CRANK_REV_SUPPORT)) {
+		if (len < 4) {
+			error("Crank revolutions data fields missing");
+			return;
+		}
+
+		m.has_crank_rev = true;
+		m.crank_rev = att_get_u16(pdu);
+		m.last_crank_time = att_get_u16(pdu + 2);
+		pdu += 4;
+		len -= 4;
+	}
+
+	/* Notify all registered watchers */
+	m.csc = csc;
+	g_slist_foreach(csc->cadapter->watchers, update_watcher, &m);
+}
+
+static void measurement_notify_handler(const uint8_t *pdu, uint16_t len,
+							gpointer user_data)
+{
+	struct csc *csc = user_data;
+
+	/* should be at least opcode (1b) + handle (2b) */
+	if (len < 3) {
+		error("Invalid PDU received");
+		return;
+	}
+
+	process_measurement(csc, pdu + 3, len - 3);
+}
+
+
 static void discover_char_cb(GSList *chars, guint8 status, gpointer user_data)
 {
 	struct csc *csc = user_data;
@@ -356,6 +483,11 @@ static void discover_char_cb(GSList *chars, guint8 status, gpointer user_data)
 				(chars->next ? chars->next->data : NULL);
 
 		if (g_strcmp0(c->uuid, CSC_MEASUREMENT_UUID) == 0) {
+			csc->attio_measurement_id =
+				g_attrib_register(csc->attrib,
+					ATT_OP_HANDLE_NOTIFY, c->value_handle,
+					measurement_notify_handler, csc, NULL);
+
 			discover_desc(csc, c, c_next);
 		} else if (g_strcmp0(c->uuid, CSC_FEATURE_UUID) == 0) {
 			feature_val_handle = c->value_handle;
@@ -428,6 +560,11 @@ static void attio_disconnected_cb(gpointer user_data)
 
 	DBG("");
 
+	if (csc->attio_measurement_id > 0) {
+		g_attrib_unregister(csc->attrib, csc->attio_measurement_id);
+		csc->attio_measurement_id = 0;
+	}
+
 	g_attrib_unref(csc->attrib);
 	csc->attrib = NULL;
 }
-- 
1.8.0


^ permalink raw reply related

* [PATCH v2 08/20] cyclingspeed: Add support to enable measurement notifications
From: Andrzej Kaczmarek @ 2012-11-05  8:54 UTC (permalink / raw)
  To: linux-bluetooth; +Cc: Andrzej Kaczmarek
In-Reply-To: <1352105705-13988-1-git-send-email-andrzej.kaczmarek@tieto.com>

---
 profiles/cyclingspeed/cyclingspeed.c | 72 +++++++++++++++++++++++++++++++++++-
 1 file changed, 71 insertions(+), 1 deletion(-)

diff --git a/profiles/cyclingspeed/cyclingspeed.c b/profiles/cyclingspeed/cyclingspeed.c
index deae8a9..4f0a0a5 100644
--- a/profiles/cyclingspeed/cyclingspeed.c
+++ b/profiles/cyclingspeed/cyclingspeed.c
@@ -185,6 +185,17 @@ static void destroy_csc(gpointer user_data)
 	g_free(csc);
 }
 
+static void char_write_cb(guint8 status, const guint8 *pdu, guint16 len,
+							gpointer user_data)
+{
+	char *msg = user_data;
+
+	if (status != 0)
+		error("%s failed", msg);
+
+	g_free(msg);
+}
+
 static void read_feature_cb(guint8 status, const guint8 *pdu,
 						guint16 len, gpointer user_data)
 {
@@ -274,9 +285,25 @@ static void discover_desc_cb(guint8 status, const guint8 *pdu,
 		if (uuid != GATT_CLIENT_CHARAC_CFG_UUID)
 			continue;
 
-		if (g_strcmp0(ch->uuid, CSC_MEASUREMENT_UUID) == 0)
+		if (g_strcmp0(ch->uuid, CSC_MEASUREMENT_UUID) == 0) {
+			char *msg;
+			uint8_t attr_val[2];
+
 			ch->csc->measurement_ccc_handle = handle;
 
+			if (g_slist_length(ch->csc->cadapter->watchers) == 0) {
+				att_put_u16(0x0000, attr_val);
+				msg = g_strdup("Disable measurement");
+			} else {
+				att_put_u16(GATT_CLIENT_CHARAC_CFG_NOTIF_BIT,
+								attr_val);
+				msg = g_strdup("Enable measurement");
+			}
+
+			gatt_write_char(ch->csc->attrib, handle, attr_val,
+					sizeof(attr_val), char_write_cb, msg);
+		}
+
 		/* We only want CCC, can break here */
 		break;
 	}
@@ -348,6 +375,40 @@ static void discover_char_cb(GSList *chars, guint8 status, gpointer user_data)
 							read_feature_cb, csc);
 }
 
+static void enable_measurement(gpointer data, gpointer user_data)
+{
+	struct csc *csc = data;
+	uint16_t handle = csc->measurement_ccc_handle;
+	uint8_t value[2];
+	char *msg;
+
+	if (csc->attrib == NULL || !handle)
+		return;
+
+	att_put_u16(GATT_CLIENT_CHARAC_CFG_NOTIF_BIT, value);
+	msg = g_strdup("Enable measurement");
+
+	gatt_write_char(csc->attrib, handle, value, sizeof(value),
+							char_write_cb, msg);
+}
+
+static void disable_measurement(gpointer data, gpointer user_data)
+{
+	struct csc *csc = data;
+	uint16_t handle = csc->measurement_ccc_handle;
+	uint8_t value[2];
+	char *msg;
+
+	if (csc->attrib == NULL || !handle)
+		return;
+
+	att_put_u16(0x0000, value);
+	msg = g_strdup("Disable measurement");
+
+	gatt_write_char(csc->attrib, handle, value, sizeof(value),
+							char_write_cb, msg);
+}
+
 static void attio_connected_cb(GAttrib *attrib, gpointer user_data)
 {
 	struct csc *csc = user_data;
@@ -380,6 +441,9 @@ static void watcher_exit_cb(DBusConnection *conn, void *user_data)
 
 	cadapter->watchers = g_slist_remove(cadapter->watchers, watcher);
 	g_dbus_remove_watch(conn, watcher->id);
+
+	if (g_slist_length(cadapter->watchers) == 0)
+		g_slist_foreach(cadapter->devices, disable_measurement, 0);
 }
 
 static DBusMessage *register_watcher(DBusConnection *conn, DBusMessage *msg,
@@ -405,6 +469,9 @@ static DBusMessage *register_watcher(DBusConnection *conn, DBusMessage *msg,
 	watcher->srv = g_strdup(sender);
 	watcher->path = g_strdup(path);
 
+	if (g_slist_length(cadapter->watchers) == 0)
+		g_slist_foreach(cadapter->devices, enable_measurement, 0);
+
 	cadapter->watchers = g_slist_prepend(cadapter->watchers, watcher);
 
 	DBG("cycling watcher [%s] registered", path);
@@ -431,6 +498,9 @@ static DBusMessage *unregister_watcher(DBusConnection *conn, DBusMessage *msg,
 	cadapter->watchers = g_slist_remove(cadapter->watchers, watcher);
 	g_dbus_remove_watch(conn, watcher->id);
 
+	if (g_slist_length(cadapter->watchers) == 0)
+		g_slist_foreach(cadapter->devices, disable_measurement, 0);
+
 	DBG("cycling watcher [%s] unregistered", path);
 
 	return dbus_message_new_method_return(msg);
-- 
1.8.0


^ permalink raw reply related

* [PATCH v2 07/20] cyclingspeed: Add CyclingSpeedManager interface
From: Andrzej Kaczmarek @ 2012-11-05  8:54 UTC (permalink / raw)
  To: linux-bluetooth; +Cc: Andrzej Kaczmarek
In-Reply-To: <1352105705-13988-1-git-send-email-andrzej.kaczmarek@tieto.com>

This patch registers org.bluez.CyclingSpeedManager interface for each
adapter to allow registration and deregistration of measurement watchers.
---
 profiles/cyclingspeed/cyclingspeed.c | 151 ++++++++++++++++++++++++++++++++++-
 1 file changed, 150 insertions(+), 1 deletion(-)

diff --git a/profiles/cyclingspeed/cyclingspeed.c b/profiles/cyclingspeed/cyclingspeed.c
index 95e3b98..deae8a9 100644
--- a/profiles/cyclingspeed/cyclingspeed.c
+++ b/profiles/cyclingspeed/cyclingspeed.c
@@ -33,6 +33,7 @@
 #include "adapter.h"
 #include "device.h"
 #include "dbus-common.h"
+#include "error.h"
 #include "gattrib.h"
 #include "att.h"
 #include "gatt.h"
@@ -41,10 +42,12 @@
 #include "cyclingspeed.h"
 
 #define CYCLINGSPEED_INTERFACE		"org.bluez.CyclingSpeed"
+#define CYCLINGSPEED_MANAGER_INTERFACE	"org.bluez.CyclingSpeedManager"
 
 struct csc_adapter {
 	struct btd_adapter	*adapter;
 	GSList			*devices;	/* list of registered devices */
+	GSList			*watchers;
 };
 
 struct csc {
@@ -64,6 +67,13 @@ struct csc {
 	uint8_t			location;
 };
 
+struct watcher {
+	struct csc_adapter	*cadapter;
+	guint			id;
+	char			*srv;
+	char			*path;
+};
+
 struct characteristic {
 	struct csc	*csc;
 	char		uuid[MAX_LEN_UUID_STR + 1];
@@ -93,6 +103,19 @@ static gint cmp_device(gconstpointer a, gconstpointer b)
 	return -1;
 }
 
+static gint cmp_watcher(gconstpointer a, gconstpointer b)
+{
+	const struct watcher *watcher = a;
+	const struct watcher *match = b;
+	int ret;
+
+	ret = g_strcmp0(watcher->srv, match->srv);
+	if (ret != 0)
+		return ret;
+
+	return g_strcmp0(watcher->path, match->path);
+}
+
 static struct csc_adapter *find_csc_adapter(struct btd_adapter *adapter)
 {
 	GSList *l = g_slist_find_custom(csc_adapters, adapter, cmp_adapter);
@@ -103,10 +126,47 @@ static struct csc_adapter *find_csc_adapter(struct btd_adapter *adapter)
 	return l->data;
 }
 
+static void destroy_watcher(gpointer user_data)
+{
+	struct watcher *watcher = user_data;
+
+	g_free(watcher->path);
+	g_free(watcher->srv);
+	g_free(watcher);
+}
+
+static struct watcher *find_watcher(GSList *list, const char *sender,
+							const char *path)
+{
+	struct watcher *match;
+	GSList *l;
+
+	match = g_new0(struct watcher, 1);
+	match->srv = g_strdup(sender);
+	match->path = g_strdup(path);
+
+	l = g_slist_find_custom(list, match, cmp_watcher);
+	destroy_watcher(match);
+
+	if (l != NULL)
+		return l->data;
+
+	return NULL;
+}
+
+static void remove_watcher(gpointer user_data)
+{
+	struct watcher *watcher = user_data;
+
+	g_dbus_remove_watch(btd_get_dbus_connection(), watcher->id);
+}
+
 static void destroy_csc_adapter(gpointer user_data)
 {
 	struct csc_adapter *cadapter = user_data;
 
+	g_slist_free_full(cadapter->watchers, remove_watcher);
+
 	g_free(cadapter);
 }
 
@@ -311,6 +371,81 @@ static void attio_disconnected_cb(gpointer user_data)
 	csc->attrib = NULL;
 }
 
+static void watcher_exit_cb(DBusConnection *conn, void *user_data)
+{
+	struct watcher *watcher = user_data;
+	struct csc_adapter *cadapter = watcher->cadapter;
+
+	DBG("cycling watcher [%s] disconnected", watcher->path);
+
+	cadapter->watchers = g_slist_remove(cadapter->watchers, watcher);
+	g_dbus_remove_watch(conn, watcher->id);
+}
+
+static DBusMessage *register_watcher(DBusConnection *conn, DBusMessage *msg,
+								void *data)
+{
+	struct csc_adapter *cadapter = data;
+	struct watcher *watcher;
+	const char *sender = dbus_message_get_sender(msg);
+	char *path;
+
+	if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_OBJECT_PATH, &path,
+							DBUS_TYPE_INVALID))
+		return btd_error_invalid_args(msg);
+
+	watcher = find_watcher(cadapter->watchers, sender, path);
+	if (watcher != NULL)
+		return btd_error_already_exists(msg);
+
+	watcher = g_new0(struct watcher, 1);
+	watcher->cadapter = cadapter;
+	watcher->id = g_dbus_add_disconnect_watch(conn, sender, watcher_exit_cb,
+						watcher, destroy_watcher);
+	watcher->srv = g_strdup(sender);
+	watcher->path = g_strdup(path);
+
+	cadapter->watchers = g_slist_prepend(cadapter->watchers, watcher);
+
+	DBG("cycling watcher [%s] registered", path);
+
+	return dbus_message_new_method_return(msg);
+}
+
+static DBusMessage *unregister_watcher(DBusConnection *conn, DBusMessage *msg,
+								void *data)
+{
+	struct csc_adapter *cadapter = data;
+	struct watcher *watcher;
+	const char *sender = dbus_message_get_sender(msg);
+	char *path;
+
+	if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_OBJECT_PATH, &path,
+							DBUS_TYPE_INVALID))
+		return btd_error_invalid_args(msg);
+
+	watcher = find_watcher(cadapter->watchers, sender, path);
+	if (watcher == NULL)
+		return btd_error_does_not_exist(msg);
+
+	cadapter->watchers = g_slist_remove(cadapter->watchers, watcher);
+	g_dbus_remove_watch(conn, watcher->id);
+
+	DBG("cycling watcher [%s] unregistered", path);
+
+	return dbus_message_new_method_return(msg);
+}
+
+static const GDBusMethodTable cyclingspeed_manager_methods[] = {
+	{ GDBUS_METHOD("RegisterWatcher",
+			GDBUS_ARGS({ "agent", "o" }), NULL,
+			register_watcher) },
+	{ GDBUS_METHOD("UnregisterWatcher",
+			GDBUS_ARGS({ "agent", "o" }), NULL,
+			unregister_watcher) },
+	{ }
+};
+
 int csc_adapter_register(struct btd_adapter *adapter)
 {
 	struct csc_adapter *cadapter;
@@ -320,6 +455,18 @@ int csc_adapter_register(struct btd_adapter *adapter)
 
 	csc_adapters = g_slist_prepend(csc_adapters, cadapter);
 
+	if (!g_dbus_register_interface(btd_get_dbus_connection(),
+						adapter_get_path(adapter),
+						CYCLINGSPEED_MANAGER_INTERFACE,
+						cyclingspeed_manager_methods,
+						NULL, NULL, cadapter,
+						destroy_csc_adapter)) {
+		error("D-Bus failed to register %s interface",
+						CYCLINGSPEED_MANAGER_INTERFACE);
+		destroy_csc_adapter(cadapter);
+		return -EIO;
+	}
+
 	return 0;
 }
 
@@ -333,7 +480,9 @@ void csc_adapter_unregister(struct btd_adapter *adapter)
 
 	csc_adapters = g_slist_remove(csc_adapters, cadapter);
 
-	destroy_csc_adapter(cadapter);
+	g_dbus_unregister_interface(btd_get_dbus_connection(),
+					adapter_get_path(cadapter->adapter),
+					CYCLINGSPEED_MANAGER_INTERFACE);
 }
 
 int csc_device_register(struct btd_device *device, struct gatt_primary *prim)
-- 
1.8.0


^ permalink raw reply related


This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox