Metadata-Version: 2.4
Name: pybose
Version: 2026.12.1
Summary: An unofficial Python API for controlling Bose soundbars and speakers.
Home-page: https://github.com/cavefire/pybose
Author: cavefire
Author-email: timo@cavefire.net
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
Classifier: Operating System :: OS Independent
Requires-Python: >=3.6
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: zeroconf
Requires-Dist: websockets
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: license-file
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# Unofficial Bose API for Soundbars and Speakers

[![Python Tests](https://github.com/cavefire/pybose/actions/workflows/python-tests.yml/badge.svg)](https://github.com/cavefire/pybose/actions/workflows/python-tests.yml)

This Python project provides an unofficial API to control Bose Soundbars and Speakers locally. The API was reverse-engineered by analyzing the Bose app's API calls and is **not officially supported by Bose**. It allows users to interact with their Bose devices through local network communication and provides a basic feature set for device control.

Also check out my Homeassistant integration: [Bose-Homeassistant](https://github.com/cavefire/Bose-Homeassistant)

### Tested Devices
Reported as working by users of this library and of [Bose-Homeassistant](https://github.com/cavefire/Bose-Homeassistant):

- Bose Smart Ultra Soundbar
- Bose Smart Soundbar 900 / Soundbar 900
- Bose Smart Soundbar 700 / Soundbar 700
- Bose Smart Soundbar 600
- Bose Soundbar 500
- Bose Smart Soundbar 300 / Soundbar 300
- Bose Smart Speaker 500
- Bose Home Speaker 500
- Bose Home Speaker 300
- Bose Portable Smart Speaker / Portable Home Speaker
- Bose Music Amplifier

Other Bose devices that work with the Bose app may also work. Older SoundTouch devices use a different API and are not supported.

---

## Installation

```bash
pip install pybose
```

## Quick start

```python
import asyncio

from pybose import BoseAuth, BoseDiscovery, BoseSpeaker


async def main() -> None:
    auth = BoseAuth()
    auth.getControlToken("you@example.com", "your password")

    device = BoseDiscovery().discover_devices()[0]

    speaker = BoseSpeaker(bose_auth=auth, host=device["IP"], device_id=device["GUID"])
    await speaker.connect()
    try:
        print(await speaker.get_system_info())
        await speaker.set_audio_volume(20)
    finally:
        await speaker.disconnect()


asyncio.run(main())
```

`BoseAuth` and `BoseDiscovery` are synchronous (they block while talking to Bose's cloud or browsing the network); `BoseSpeaker` is asynchronous.

---

## Usage

### BoseAuth

Bose decided that in order to control your devices locally (!) you still need a token from their cloud. `BoseAuth` gets it the same way the official app does. There is no official documentation for this (at least none I could find), so these calls were reverse-engineered.

#### Signing in

```python
from pybose import BoseAuth

auth = BoseAuth()
token = auth.getControlToken(email, password)

token["access_token"]    # used by BoseSpeaker
token["refresh_token"]
token["bose_person_id"]
```

`getControlToken` returns the stored token while it is valid, refreshes it when it has expired, and only signs in with the email and password when it has to. Pass `forceNew=True` to always sign in again.

#### Keeping and refreshing the token

The access token is a JWT with a limited lifetime. To avoid signing in with the password every time, store the tokens and restore them later:

```python
# Save these after signing in
saved = {**auth.getCachedToken(), "azure_refresh_token": auth.get_azure_refresh_token()}

# Later
auth = BoseAuth()
auth.set_access_token(saved["access_token"], saved["refresh_token"], saved["bose_person_id"])
auth.set_azure_refresh_token(saved["azure_refresh_token"])

if not auth.is_token_valid():
    token = auth.do_token_refresh()
```

`get_token_validity_time()` returns the number of seconds the access token is still valid, which helps to refresh it in time.

#### Errors

All errors raised by `BoseAuth` are subclasses of `BoseAuthError`, which is itself a `ValueError`:

| Error | Meaning |
|---|---|
| `BoseAuthRejectedError` | Bose refused the credentials or the refresh token. Sign in again. |
| `BoseAuthUnavailableError` | The Bose sign-in service could not be reached or failed. Retry later. |
| `BoseLoginError` | Signing in with email and password failed. `step` names the failed step, `b2c_message` holds Bose's message and `page` describes an unexpected sign-in page. |
| `BoseLoginRejectedError` | Bose refused the email address or the password. Both a `BoseLoginError` and a `BoseAuthRejectedError`. |

```python
from pybose.BoseAuth import BoseLoginError

try:
    auth.getControlToken(email, password)
except BoseLoginError as err:
    print(f"Signing in failed at the {err.step} step: {err}")
```

---

### BoseDiscovery

Find speakers on the local network. You need both the **IP** and the **GUID** to connect to a speaker.

```python
from pybose import BoseDiscovery

for device in BoseDiscovery().discover_devices(timeout=5):
    print(f"GUID: {device['GUID']}, IP: {device['IP']}")
```

`BoseDiscovery` creates its own Zeroconf instance and closes it again after the search. You can also pass an existing one with `BoseDiscovery(zeroconf=...)`; it is then left open for you to keep using.

---

### BoseSpeaker

Control a speaker over its local WebSocket API.

```python
from pybose import BoseSpeaker

speaker = BoseSpeaker(
    host="192.168.1.50",
    device_id="your-device-GUID",
    bose_auth=auth,
    request_timeout=10,
)

receiver_id = speaker.attach_receiver(lambda message: print(message))

await speaker.connect()
await speaker.subscribe()
await speaker.set_power_state(True)

speaker.detach_receiver(receiver_id)
await speaker.disconnect()
```

Constructor options:

| Option | Default | Description |
|---|---|---|
| `host` | | IP address of the speaker |
| `device_id` | `None` | GUID of the speaker, as found by `BoseDiscovery` |
| `bose_auth` | `None` | A signed-in `BoseAuth` |
| `request_timeout` | `30` | Seconds to wait for an answer before a request fails. A speaker that is off or in standby simply stays quiet. |
| `auto_reconnect` | `True` | Reconnect when the connection is lost |
| `on_exception` | `None` | Called with every exception a request raises (unsupported resource, closed connection, error response), before it is raised |

**Notifications:** after `subscribe()`, the speaker sends messages whenever something changes (volume, now playing, sources, ...). Every callback added with `attach_receiver` gets each message as a dict with a `header` (including the `resource`) and a `body`. A callback that raises is logged and does not stop the others.

**Capabilities:** not every speaker supports every resource. `connect()` reads the speaker's capabilities, and `has_capability("/bluetooth/sink/status")` tells whether a resource is available. Calling an unsupported one raises `BoseFunctionNotSupportedException`; a request the speaker answers with an error raises `BoseRequestException`.

#### Available functions

| Area | Functions |
|---|---|
| Connection | `connect`, `disconnect`, `is_connected`, `subscribe`, `attach_receiver`, `detach_receiver`, `get_capabilities`, `has_capability`, `get_device_id` |
| System | `get_system_info`, `get_power_state`, `set_power_state`, `get_system_timeout`, `set_system_timeout`, `get_product_settings`, `get_network_status`, `get_wifi_status`, `get_battery_status` |
| Volume and playback | `get_audio_volume`, `set_audio_volume`, `set_audio_volume_muted`, `get_now_playing`, `play`, `pause`, `skip_next`, `skip_previous`, `seek`, `request_playback_preset` |
| Sources | `get_sources`, `set_source`, `switch_tv_source`, `set_chromecast` |
| Sound | `get_audio_setting`, `set_audio_setting`, `get_audio_mode`, `set_audio_mode`, `get_dual_mono_setting`, `set_dual_mono_setting`, `get_rebroadcast_latency_mode`, `set_rebroadcast_latency_mode`, `get_cec_settings`, `set_cec_settings` |
| Accessories | `get_accessories`, `put_accessories` |
| Bluetooth | `get_bluetooth_source_status`, `get_bluetooth_sink_status`, `get_bluetooth_sink_list`, `set_bluetooth_sink_pairable`, `connect_bluetooth_sink_device`, `disconnect_bluetooth_sink_device`, `remove_bluetooth_sink_device` |
| Groups | `get_active_groups`, `set_active_group`, `add_to_active_group`, `remove_from_active_group`, `stop_active_groups` |

**Note:** The device supports more. Feel free to add more, or open an issue if you have a specific need.

## Development

### Running Tests

This project includes both unit tests and integration tests.

#### Unit Tests
Unit tests mock external dependencies and can be run without credentials:

```bash
python -m pytest tests/unit/ -v
```

#### Integration Tests
Integration tests require real Bose account credentials and test against actual Bose APIs. Set the following environment variables:

```bash
export BOSE_EMAIL="your_email@example.com"
export BOSE_PASSWORD="your_password"
export BOSE_GWID="your_device_gwid"  # Optional, for product information tests
```

Run integration tests:

```bash
# Run all integration tests
python -m pytest tests/integration/ -v -m integration

# Run specific integration test
python -m pytest tests/integration/test_bose_auth_integration.py -v -m integration
```

#### Coverage Reports
Generate coverage reports in XML and JSON format:

```bash
python -m pytest tests/unit/ --cov=pybose --cov-report=xml --cov-report=json --cov-report=term
```

## Limitations
* **Unofficial API:** The API is not officially supported by Bose and may break at any time.
* **Cloud token:** Controlling a speaker locally still needs a token from Bose's cloud, which has to be refreshed regularly.
* **Rate Limiting:** The API may be rate-limited by Bose if too many requests are made in a short period of time.

## Contributing
This project is a work in progress, and contributions are welcome!
If you encounter issues, have feature requests, or want to contribute, feel free to submit a pull request or open an issue.

The file `AvailableMethods.txt` contains a list of all available `resources` I could find.
Best way to find out, what data these functions need, is to use the official app and sniff the network traffic. I used `Proxymon` for this. There should be a websocket connection to `ws://<device_ip>:8082` which contains all the data you need.

## Wishlist

The first item on my wishlist is a **Homeassistant** integration. I am currently working on this here: [Bose-Homeassistant](https://github.com/cavefire/Bose-Homeassistant)

**Other items on my wishlist:**

- [x] Implement token refresh
- [x] Implement groups
- [x] Implement source (TV / Optical / AUX) switching
- [x] Implement source (Bluetooth) switching
- [x] Implement equalizer settings
- [x] Implement bass module settings
- [x] Implement surround speaker settings

And lastly, a way to not use the BOSE cloud at all would be nice. But I am not sure, if this is possible at all.

## Disclaimer
This project is not affiliated with Bose Corporation. The API is reverse-engineered and may break at any time. Use at your own risk.

**Be respectful and avoid spamming the API with unnecessary requests to ensure this project remains functional for everyone.**


**To the BOSE legal team:**

All API keys used in this project are publicly available on the Bose website.

There was no need to be a computer specialist to find them, so: Please do not sue me for making people use their products in a way they want to.

If you have any issues with me publishing this, please contact me! I am happy to discuss this with you and make your products better.

## License
This project is licensed under GNU GPLv3 - see the [LICENSE](LICENSE) file for details.
