Code Monkey home page Code Monkey logo

homebridge-bluetooth's Introduction

homebridge-bluetooth

NPM version

Homebridge plugin for exposing services and characteristics of nearby Bluetooth Low Energy (BLE) peripherals as HomeKit accesories. Ideal for wireless DIY home automation projects if you'd like to control them comfortably with Siri on any Apple device.

Homebridge runs on top of Node.js server and is an open-source implementation of the Apple HomeKit protocol. HomeKit provides the API between your Apple device (i.e. Watch) and your home automation server (i.e. Raspberry Pi). This Homebridge plugin relays the communication from the home automation server to the BLE peripheral device (i.e. Arduino 101). Take a peek into the examples folder for inspiration.

Installation

Make sure your systems matches the prerequisites. You need to have a C compiler, Node.js server and if you're running on Linux the libbluez-dev library.

Install Homebridge & Noble

Homebridge is a lightweight framework built on top of Node.js server that provides the HomeKit bridge for your Apple devices to connect to. Noble is BLE central module library for Node.js that abstracts away intricacies of each OS BLE stack implementation and provides a nice universal high-level API.

[sudo] npm install -g noble
[sudo] npm install -g --unsafe-perm homebridge node-gyp
[sudo] npm install -g homebridge-bluetooth

Note Depending on your privileges -g flag may need root permissions to install to the global npm module directory.

Configure Homebridge

Homebridge is setup via config.json file sitting in the ~/.homebridge/ directory. The example config included in the repository has lots of comments and is a good starting point. Each BLE peripheral device is uniquely identified by it's address. Services and characteristics are identified by UUID. Also, each of the examples comes with it's own config.json file.

The easiest way to find the address of a BLE device is to start the plugin with a random/default address and then check the output for Ignored | MyDevice - 01:23:45:67:89:ab message. Alternatively you can run [sudo] hcitool lescan to discover available BLE devices.

Mapping of services and characteristics from Bluetooth to HomeKit relies on two things - matching read/write/nofity permissions and matching data type. To see what is available, take a look at the very long list here. Services are towards the bottom of the file. Each characteristic has pre-defined permissions that represent the expected way to use it - i.e. it doesn't make sense to write (set) the current temperature. These permissions must match the corresponding permissions of the Bluetooth characteristic. All data are assumed to use little endian encoding for multi-byte values.

The following table summarizes permission matching for a very popular BLEPeripheral library that can run on most Arduino boards:

HomeKit Characteristic.Perms[...] BLEPeripheral BLECharacteristic(...)
READ BLEWrite
WRITE BLERead
NOTIFY BLENotify

Similar to permissions, matching of the exchanged data type for BLEPeripheral is summarized here:

HomeKit Characteristic.Formats[...] BLEPeripheral BLETypedCharacteristic<...>
BOOL BLECharCharacteristic
INT BLEIntCharacteristic
FLOAT BLEFloatCharacteristic
STRING BLECharacteristic
UINT8 BLEUnsignedCharCharacteristic
UINT16 BLEUnsignedShortCharacteristic
UINT32 BLEUnsignedIntCharacteristic
UINT64 BLEUnsignedLongCharacteristic

For instance if you'd like create a HomeKit thermometer, you have to implement the TemperatureSensor service. According to the list of available services and characteristics the service has one mandatory characteristic - CurrentTemperature and a handful of optional ones.

The CurrentTemperature characteristic communicates a FLOAT value and needs READ and NOTIFY permissions. Using the BLEPeripheral library, the characteristic would be implemented as:

BLEService temperatureSensorService("SERVICE-UUID-HERE");
BLEFloatCharacteristic currentTemperatureCharacteristic("CHARACTERISTIC-UUID-HERE", BLERead | BLENotify);

The corresponding entry in the config.json file that connects to the characteristic above is:

"services" : [ {
    "name": "The Best HomeKit Thermometer",
    "type": "TemperatureSensor",
    "UUID": "SERVICE-UUID-HERE",
    "characteristics": [ {
        "type": "CurrentTemperature",
        "UUID": "CHARACTERISTIC-UUID-HERE"
    } ]
} ]

Note All UUIDs should be randomly generated to prevent collisions. This page is a good place to get your own.

Run Homebridge

Depending on your privileges, accessing the BLE kernel subsystem may need root permissions.

[sudo] homebridge -D

Note Running with -D turns on additional debugging output that is very helpful for getting addresses and UUIDs of your BLE devices that needs to match with the config.json file.

Note See this section of Noble readme for more details about running without sudo.

Troubleshooting

If you encouter a different problem, please, open an issue.

Home app can't discover any nearby accessories

Make sure the Apple device and the Homebridge server are on the same subnet and connected to the same wifi router.

Sometimes, homebridge server might think that, it has successfully paired with iOS, but iOS doesn't agree. Try to delete the persist/ directory in the ~/.homebridge/ configuration folder. This removes all pairings that normally persist from session to session.

rm -rf ~/.homebridge/persist/

From time to time it looks like iOS ignores HomeKit bridges with username that it has already paired with. Try to change the username in the bridge section of config.json to a new value never used before.

"username": "CC:22:3D:E3:CE:30"  ->  "username": "DD:33:4E:F4:DF:41"

BLE peripheral is discovered, but immediately disconnects

This isssue seems to be happening on some versions of Raspbian running on the Pi 3. Resetting the BLE adapter seems to resolve the issue:

[sudo] hciconfig hci0 reset

Obviously, the solution is not really addressing the core of the problem, but it seems to help.

FAQ

Can I contribute my own example or a new feature?

Sure thing! All contributions are welcome. Just do a pull-request or open a new issue if you see something broken.

Is this thing secure?

No. Not even close. Connection from your Apple device to Homebridge server is encrypted. However, all BLE communication is currently unencrypted and anyone with the right spoofing equipment can listen to it. Moreover, once the attacker has figured out what devices you have, he can also connect to any of your peripherals and control them directly. So don't use this if you're paranoid or if NSA is after you. You wouldn't sleep well.

MFi certified HomeKit BLE encryption uses quite-strong Ed25519 elliptic cypher. BLE has built-in support for encryption, but it seems that Apple has decided to build their own thing as usual. It makes some sense in this case since a lot is at stake - once HomeKit becomes widespread a security bug literally means open doors to your house. Hooray - let's connect billions of unsecured IoT devices to the internet! What could possibly go wrong??

Moreover, from bits and pieces available on the Internet, it seems that Apple has changed the specs several times and caused a lot of trouble for the manufacturers, since slower microprocessors tend to have a hard time doing all the involved encryption math. Initial pairing can take literally minutes. Pairing procedure uses SRP (Secure Remote Password (3072-bit) protocol with an 8-digit code (the number you have to type in when first pairing with Homebridge). After pairing, per session communication always uses unique keys derived by HKDF-SHA-512 and encrypted by the ChaCha20-Poly1305.

Theoretically, one should be able to get rid of the Homebridge 'middle-man' since HomeKit over BLE allows direct connection to any Apple device. While there are many good HomeKit IP stacks around BLE implementations are few and far between. There's only one implementation I'm aware of here, but it can't be easily ported to other boards.

BTW, I think it might be possible to re-write the BLE implementation above with BLEPeripheral library instead of Nordic Semi's SoftDevice to make it run essentially everywhere. If anyone is interested in this project, please, let me know and maybe we can figure a plan and come up with something useful and fun to use.

Implementing a HomeKit over BLE stack correctly requires access to MFi internal documentation, which isn't publicly available, unless you're a registered developer at a company with big $$$. Making BLE accessories is simple, but making them secure seems to be very, very hard.

What are the prerequisites for installation?

Linux (Debian Based, Kernel 3.6 or newer)

A supported BLE (Bluetooth 4.0) USB dongle is required, if your device doesn't have it built-in.

  • Install Node.js

    Node.js is an asynchronous event driven JavaScript server, ideal for building scalable, low-latency network applications. Homebridge is built on top of this server. It is being developed so quickly that package repositories of most distributions contain a very old version. Getting latest from the official website is recommended.

  • Install libbluetooth-dev and libavahi-compat-libdnssd-dev

    These libraries and their dependencies are required by Noble package and provide access to the kernel Bluetooth subsystem.

    sudo apt-get install bluetooth bluez libbluetooth-dev libudev-dev libavahi-compat-libdnssd-dev

macOS (10.10 or newer)

Check this link to see if your mac has built-in BLE (Bluetooth 4.0) support. All macs from 2012 and newer are generally fine.

  • Install Node.js

    Node.js is an asynchronous event driven JavaScript server, ideal for building scalable, low-latency network applications. Homebridge is built on top of this server. It is being developed so quickly that package repositories of most distributions contain a very old version. Getting latest from the official website is recommended.

  • Install XCode

    XCode comes with a C compiler that is needed to compile the JavaScript to C bindings required by Noble package.

Windows (8.1 or newer)

Pull request is welcomed here... Both Homebridge and Noble should run on Windows, but I don't have a machine to test.

On what devices was this plugin tested?

Here's a list of testing devices. The list is by no means exhaustive and the plugin will work with many more.

License

This work is licensed under the MIT license. See license for more details.

homebridge-bluetooth's People

Contributors

dnicolson avatar qkdreyer avatar vojtamolda avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

homebridge-bluetooth's Issues

Install fails on Homebridge on Raspberry Pi3+

Upon running npm install -g noble I get below error:

make: *** [binding.target.mk:109: Release/obj.target/binding/src/BluetoothHciSocket.o] Error 1
make: Leaving directory '/usr/local/lib/node_modules/noble/node_modules/bluetooth-hci-socket/build'
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:194:23)
gyp ERR! stack     at ChildProcess.emit (events.js:314:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12)
gyp ERR! System Linux 5.4.51-v7+
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /usr/local/lib/node_modules/noble/node_modules/bluetooth-hci-socket
gyp ERR! node -v v12.19.0
gyp ERR! node-gyp -v v5.1.0
gyp ERR! not ok
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: xpc-connection@~0.1.4 (node_modules/noble/node_modules/xpc-connection):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"arm"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/noble/node_modules/bluetooth-hci-socket):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] install: `node-gyp rebuild`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1

+ [email protected]
updated 1 package in 47.272s

If I run it with sudo (which I believe I am not supposed to, as my node_modules is owned by my current user), I get this error:

pi@homebridge:~ $ sudo npm install -g noble

> [email protected] install /usr/local/lib/node_modules/noble/node_modules/usb
> prebuild-install --verbose || node-gyp rebuild

prebuild-install info begin Prebuild-install version 5.3.6
prebuild-install WARN install EACCES: permission denied, access '/root/.npm'
gyp WARN EACCES current user ("nobody") does not have permission to access the dev dir "/root/.cache/node-gyp/12.19.0"
gyp WARN EACCES attempting to reinstall using temporary dev dir "/usr/local/lib/node_modules/noble/node_modules/usb/.node-gyp"
gyp WARN install got an error, rolling back install
gyp WARN install got an error, rolling back install
gyp ERR! configure error
gyp ERR! stack Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/noble/node_modules/usb/.node-gyp'
gyp ERR! System Linux 5.4.51-v7+
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /usr/local/lib/node_modules/noble/node_modules/usb
gyp ERR! node -v v12.19.0
gyp ERR! node-gyp -v v5.1.0
gyp ERR! not ok

> [email protected] install /usr/local/lib/node_modules/noble/node_modules/bluetooth-hci-socket
> node-gyp rebuild

gyp WARN EACCES current user ("nobody") does not have permission to access the dev dir "/root/.cache/node-gyp/12.19.0"
gyp WARN EACCES attempting to reinstall using temporary dev dir "/usr/local/lib/node_modules/noble/node_modules/bluetooth-hci-socket/.node-gyp"
gyp WARN install got an error, rolling back install
gyp WARN install got an error, rolling back install
gyp ERR! configure error
gyp ERR! stack Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/noble/node_modules/bluetooth-hci-socket/.node-gyp'
gyp ERR! System Linux 5.4.51-v7+
gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /usr/local/lib/node_modules/noble/node_modules/bluetooth-hci-socket
gyp ERR! node -v v12.19.0
gyp ERR! node-gyp -v v5.1.0
gyp ERR! not ok
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: xpc-connection@~0.1.4 (node_modules/noble/node_modules/xpc-connection):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"arm"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/noble/node_modules/usb):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] install: `prebuild-install --verbose || node-gyp rebuild`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/noble/node_modules/bluetooth-hci-socket):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] install: `node-gyp rebuild`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1

+ [email protected]
updated 1 package in 13.782s

Any ideas on how I can proceed?

Arduino UNO

Hey

Anyone ever got this working with UNO and hm-10 dongle?

Got any example code?

Regards

Matt

let homebridge control a bluetooth projector, streamer?

hi,

Is it somehow possible to let homebridge turn of my (xiaomi mi laser projecter with mi tv) streamer via a bluetooth turn off command?

I see a lot of questions on the internet on how to use a bluetooth keyboard with a PI, but I want my PI to send a turn off/on, next etc command to media devices.

thanks a lot!

Example sketches for Lightblue Bean?

Hi There,

I am trying to run it on Lightblue Bean but I get the error ble_protocol.h: No such file or directory after I have imported the CurieBLE and CurieIMU libraries.

In file included from /Users/xx/Documents/Arduino/libraries/CurieBLE/src/BLECharacteristic.h:23:0,
                 from /Users/xx/Documents/Arduino/libraries/CurieBLE/src/CurieBLE.h:20,
                 from /var/folders/0z/1bn_g74n64l51gh8czxrbyt80000gn/T/untitled1440007012.tmp/sketch_dec18b/sketch_dec18b.ino:2:
/Users/xx/Documents/Arduino/libraries/CurieBLE/src/BLECommon.h:25:54: fatal error: ../src/services/ble_service/ble_protocol.h: No such file or directory
 #include "../src/services/ble_service/ble_protocol.h"

You have any idea what could be wrong?

Thanks in advance.

Problem restarting Homebridge

If you restart the homebridge after installing the plug-in, the same content is repeated in the log and will not run.

[3/26/2020, 8:32:20 PM] [HB Supervisor] Homebridge Process Ended. Code: 1, Signal: null
[3/26/2020, 8:32:25 PM] [HB Supervisor] Restarting Homebridge...
[3/26/2020, 8:32:25 PM] [HB Supervisor] Starting Homebridge with extra flags: -I
[3/26/2020, 8:32:25 PM] [HB Supervisor] Started Homebridge with PID: 2335
[3/26/2020, 8:32:29 PM] Loaded config.json with 0 accessories and 1 platforms.
[3/26/2020, 8:32:29 PM] ---
[3/26/2020, 8:32:29 PM] Loaded plugin: homebridge-bluetooth
Homebridge API version: 2.4
internal/modules/cjs/loader.js:985
throw err;
^

Error: Cannot find module 'bluetooth-hci-socket'
Require stack:

  • /usr/lib/node_modules/homebridge-bluetooth/node_modules/noble/lib/hci-socket/hci.js
  • /usr/lib/node_modules/homebridge-bluetooth/node_modules/noble/lib/hci-socket/bindings.js
  • /usr/lib/node_modules/homebridge-bluetooth/node_modules/noble/lib/resolve-bindings.js
  • /usr/lib/node_modules/homebridge-bluetooth/node_modules/noble/index.js
  • /usr/lib/node_modules/homebridge-bluetooth/index.js
  • /usr/lib/node_modules/homebridge/lib/plugin.js
  • /usr/lib/node_modules/homebridge/lib/server.js
  • /usr/lib/node_modules/homebridge/lib/cli.js
  • /usr/lib/node_modules/homebridge/bin/homebridge
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:982:15)
    at Function.Module._load (internal/modules/cjs/loader.js:864:27)
    at Module.require (internal/modules/cjs/loader.js:1044:19)
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object. (/usr/lib/node_modules/homebridge-bluetooth/node_modules/noble/lib/hci-socket/hci.js:6:26)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Module.require (internal/modules/cjs/loader.js:1044:19) {
    code: 'MODULE_NOT_FOUND',
    requireStack: [
    '/usr/lib/node_modules/homebridge-bluetooth/node_modules/noble/lib/hci-socket/hci.js',
    '/usr/lib/node_modules/homebridge-bluetooth/node_modules/noble/lib/hci-socket/bindings.js',
    '/usr/lib/node_modules/homebridge-bluetooth/node_modules/noble/lib/resolve-bindings.js',
    '/usr/lib/node_modules/homebridge-bluetooth/node_modules/noble/index.js',
    '/usr/lib/node_modules/homebridge-bluetooth/index.js',
    '/usr/lib/node_modules/homebridge/lib/plugin.js',
    '/usr/lib/node_modules/homebridge/lib/server.js',
    '/usr/lib/node_modules/homebridge/lib/cli.js',
    '/usr/lib/node_modules/homebridge/bin/homebridge'
    ]
    }

Schlage bluetooth lock question

Hello,

I'm sure I'm missing something or this is not the right place to ask, nevertheless...

I Have a Raspberry Pi 4 running Home Assistant and a Schlage Sense lock (i.e. bluetooth).

  • The Lock is HomeKit compliant,
  • The Raspberry has bluetooth builtin...
    but
  • Home Assistant doesn't know how to deal with a bluetooth lock
  • Home Assistant can deal with a Homekit lock,

So you got my question : would your homebridge (I say your because there was also a Homebridge addon for Home Assistant but I can't say if it has something to do with yours)... Would it be usefull to install your Homebridge on the Pi ? Would it make the Schlage lock visible as a HomeKit lock on the Wifi network ( which, I hope, would allow Home Assistant to see it)?

The Pi is running Ubuntu Server 20.04 and Home Assistant is running on Docker on the Ubuntu Server.

Thanks for your help

Regards

V.

Question about adding devices that donโ€™t match HAP

Hi
Not sure if Iโ€™m asking in the right place Iโ€™m very new to all this, we are talking complete noob that has ideas and wants to make them work. Ok that aside this plugin is fantastic and makes connecting to a BLE device a breeze, my question is if it would be possible to add support for adding devices that donโ€™t communicate using HAP (reverse engineered devices). Is it possible to write a small script that works together with this plugin and simply converts the values from the device to HAP recognisable values and HAP values to reverse engineered device.
The device Iโ€™m trying to make work with Home is a BLE dimmer switch that is controlled using hex values 0-10000 (0x0000 - 0x1027 please note 0x1027 is actually 0x2710 all the values are reversed something about endianness as I found out) 0x0000 is off and 0x1027 is 100% or fully on. So far I can connect and send the default HAP value for On 0x01 which somehow turns the BLE dimmer to full but it bricks the dim switch and can no longer be switched off physically. When using a BLE terminal app I can send the hex values from 0x0000 to 0x1027 and I get full functionality.
The brightness and on off is all controlled by the same characteristic but there is a seperate characteristic that returns 0x00 when off and 0x01 for on, in the native app this characteristic updates the icon but actual control is done by the brightness characteristic

  1. Will my idea of a translator script work or would it be easier to write a complete new plugin to get this to work, translating 0x0000 - 0x1027 values to int values 1-100 for brightness control
  2. How would I go about writing a script I have zero idea where to start

Iโ€™m sorry if Iโ€™m out of place asking this question here, as I said earlier Iโ€™m a complete noob and donโ€™t understand enough to get what I want done and would greatly appreciate any help or direction where to get help. Again I apologise if Iโ€™m asking in the wrong place.

Jon

Incompatibility to NodeJS > 9.9.0

I tried to upgrade my NodeJS from 9.9.0 to 12.16.2 but the rebuild after fails due to the node_module bluetooth-hci-socket in the homebridge-bluetooth folder.
There is a workaround to accomplish the upgrade for the default /usr/local/lib/node_modules/bluetooth-hci-socket. Maybe this is adaptable to the bluetooth-hci-socket of the homebridge-bluetooth plugin?

Problem with discovery and connecting of multiple BLE peripherals

When connecting to multiple BLE peripherals, plugin can sometimes discover only a handful of configured peripherals and then stop scanning.

The issue is timing dependent. Sometimes all BLE devices can be discovered simultaneously and at once. Then everything works as expected. However, if some devices take longer to discover (typically those with weaker signal) these poor things are never discovered and connected to. Scanning for new devices is not resumed after each connect(...) operation. This happens because of a somewhat less documented feature of the Noble library - scanning automatically stops once connect(...) is called.

Successful runs, when all devices are discovered at the same time looks like this:

[Bluetooth] Started | poweredOn
[Bluetooth] Discovered | Adafruit Bluefruit LE - FE:00:22:36:1D:49
[Bluetooth] Discovered | Adafruit Bluefruit LE - 15:34:95:60:FA:79
[Bluetooth] [Bluefruit] Connected | Adafruit Bluefruit LE - FE:00:22:36:1D:49
...
[Bluetooth] [Orangefruit] Connected | Adafruit Bluefruit LE - 15:34:95:60:FA:79
...

Unsuccessful runs, when some of the devices are not discovered looks like this. Usually, the peripheral with weaker signal ([Orangefruit] in this case) is not discovered:

[Bluetooth] Started | poweredOn
[Bluetooth] Discovered | Adafruit Bluefruit LE - FE:00:22:36:1D:49
[Bluetooth] [Bluefruit] Connected | Adafruit Bluefruit LE - FE:00:22:36:1D:49
...

Bluetooth Shower controls

I have a Mira Mode dual-head shower that I can control via bluetooth, from my phone (preheat, set/view temp, valve select, on/off, etc).

Could this plugin be used to connect that?

How do I decode the data/encode the commands to send to the BLE device?

Can those commands be sniffed when I perform them from my phone?

Infinitely stuck activity spinner in the Home app on iOS

Hi,

I'm trying to develop my own window covering BLE peripheral/accessory. So far I have:

  • Set up Homebridge on Raspberry Pi 2 with a bluetooth dongle. Homebridge loads fine and finds the BLEPeripheral (in this case RedBear Blend Micro with Nordic nRF8001)

Here's the config.json:

{
"bridge": {
  "name": "Raspberry Pi 2",
  "username": "00:13:EF:80:00:12",
  "port": 51826,
  "pin": "031-45-154"
  },
  
"description": "Raspberry Pi 2 Homebridge-Bluetooth",

"platforms": [
{
  "platform": "Bluetooth",
  "accessories": [
    {
    "name": "Smart Shades",
    "name_note": "Name of the accessory as shown in the Home app on iOS.",

    "address": "D0:5F:2E:E2:11:22",
    "address_note": "Bluetooth address of the accessory. Non-matching devices are ignored.",

    "services": [
      {
      "name": "Smart Blinds",
      "name_note": "Name of the service as shown in the Home app on iOS.",

      "type": "WindowCovering",
      "type_note1": "Type of the service - i.e. Lightbulb, Switch, Lock, HumiditySensor, ...",
      "type_note2": "Must match this list - https://github.com/KhaosT/HAP-NodeJS/blob/master/lib/gen/HomeKitTypes.js",
      "type_note3": "Service.Lightbulb has a mandatory On characteristic and Brightness, Hue and Saturation are optional.",

      "UUID": "A7B10010-EEEE-5377-FF6C-D104768A1214",
      "UUID_note": "Bluetooth UUID of the service. Capitalization and dashes doesn't matter.",

      "characteristics": [
      {
        "type": "CurrentPosition",
        "type_note1": "Type of the characteristic - i.e. On, Brightness, CurrentHumidity, CurrentTemperature, ...",
        "type_note2": "Must match this list - https://github.com/KhaosT/HAP-NodeJS/blob/master/lib/gen/HomeKitTypes.js",
        "type_note3": "Characteristic.On is a BOOL value and expects READ, WRITE and NOTIFY permissions.",

        "UUID": "A7B10011-EEEE-5377-FF6C-D104768A1214",
        "UUID_note": "Bluetooth UUID of the characteristic. Capitalization and dashes doesn't matter."
      },
      {
        "type": "TargetPosition",
        "type_note1": "Type of the characteristic - i.e. On, Brightness, CurrentHumidity, CurrentTemperature, ...",
        "type_note2": "Must match this list - https://github.com/KhaosT/HAP-NodeJS/blob/master/lib/gen/HomeKitTypes.js",
        "type_note3": "Characteristic.Brightness is an INT value and expects READ, WRITE and NOTIFY permissions.",

        "UUID": "A7B10012-EEEE-5377-FF6C-D104768A1214",
        "UUID_note": "Bluetooth UUID of the characteristic. Capitalization and dashes doesn't matter."
      }
      ],
      "characteristics_note1": "List of Bluetooth characteristics that will be exposed to HomeKit.",
      "characteristics_note2": "Characteristics with non-matching UUIDs are ignored."
      }
    ],
    "services_note1": "List of Bluetooth services that will be exposed to HomeKit.",
    "services_note2": "Services with non-matching UUIDs are ignored."
    }
  ]
  }
  ]
}

This is what happens when I launch Homebridge and start interacting with my iPhone:

screen shot 2017-09-05 at 22 55 43

  • I developed the code with two characteristics TargetPosition and CurrentPosition.
#include <SPI.h>
#include <BLEPeripheral.h>


const int pinLED = 13;

BLEPeripheral ble = BLEPeripheral(6,7,4);
BLEService informationService("180A");
BLECharacteristic modelCharacteristic("2A24", BLERead, "101");
BLECharacteristic manufacturerCharacteristic("2A29", BLERead, "Arduino");
BLECharacteristic serialNumberCharacteristic("2A25", BLERead, "2.71828");

BLEService windowCoveringService("A7B10010-EEEE-5377-FF6C-D104768A1214");
BLEUnsignedCharCharacteristic currentPositionCharacteristic("A7B10011-EEEE-5377-FF6C-D104768A1214", BLERead | BLENotify);
BLEUnsignedCharCharacteristic targetPositionCharacteristic("A7B10012-EEEE-5377-FF6C-D104768A1214", BLEWrite | BLERead | BLENotify);
//BLEUnsignedIntCharacteristic positionStateCharacteristic("A7B10013-EEEE-5377-FF6C-D104768A1214", BLERead | BLENotify);

void setup() {
  
  Serial.begin(115200);
  pinMode(pinLED, OUTPUT);
  digitalWrite(pinLED, true);

  ble.setLocalName("Smart Blinds");
  ble.setAdvertisedServiceUuid(windowCoveringService.uuid());
  ble.addAttribute(informationService);
  ble.addAttribute(modelCharacteristic);
  ble.addAttribute(manufacturerCharacteristic);
  ble.addAttribute(serialNumberCharacteristic);

  ble.addAttribute(windowCoveringService);
  ble.addAttribute(currentPositionCharacteristic);
  ble.addAttribute(targetPositionCharacteristic);
  //ble.addAttribute(positionStateCharacteristic);
  
  currentPositionCharacteristic.setValue(100);
  //positionStateCharacteristic.setValueLE(positionState);

  ble.setEventHandler(BLEConnected, centralConnect);
  ble.setEventHandler(BLEDisconnected, centralDisconnect);
  targetPositionCharacteristic.setEventHandler(BLEWritten, characteristicWrite);
  currentPositionCharacteristic.setEventHandler(BLESubscribed, characteristicSubscribe);

  delay(5000);

  ble.begin();
  Serial.println("Bluetooth on");
}

void loop() {
  ble.poll();
}


void centralConnect(BLECentral& central) {
  Serial.print("Central connected | ");
  Serial.println(central.address());
}

void centralDisconnect(BLECentral& central) {
  Serial.print("Central disconnected | ");
  Serial.println(central.address());
}

void characteristicWrite(BLECentral& central, BLECharacteristic& characteristic) {
  Serial.print("Characteristic written | ");
  Serial.println(characteristic.uuid());
  unsigned char targetPosition = (unsigned char) targetPositionCharacteristic.value();
  Serial.print("Target position set: ");
  Serial.println(targetPosition);
  setBlinds(targetPosition);

}

void characteristicSubscribe(BLECentral& central, BLECharacteristic& characteristic) {

	Serial.println("Characteristic event, subscribed");
	
	//Central subscribes just fine

}

void setBlinds(unsigned char targetPosition) {
	
  //This is where the code to drive the motor will go

  currentPositionCharacteristic.setValue(0);
  
  //When the current position value is set, no notification is sent to the central
  
  Serial.print("Current position: ");
  Serial.println(currentPositionCharacteristic.value());
  digitalWrite(pinLED, false);
  
}

When I attempt to open/close the blinds using iOS, the value is written from the central (Homebridge) to the peripheral (RedBear Blend Micro) TargetPosition characteristic as per the first screenshot. Interestingly, TargetPosition characteristic also sends the notification back to the central.

My issue is that whatever I tried, the CurrentPosition characteristic just refuses to send the notification back to the central when its value changes to let the central know that the operation has finished. The central is subscribed to the characteristic because serial prints out some text when the event handler is triggered at the point when the central subscribes.

As the central doesn't get an updated value for the CurrentPosition characteristic, presumably HomeKit has no idea where the blinds are so it simply displays a spinner next to the icon which just doesn't stop spinning (infinite loop).

smart blinds

Where am I going wrong?

Any help at all would be appreciated!

GarageMate Bluetooth accessory - How to configure?

I have a GarageMate (https://www.bluemate.com/) Bluetooth device that triggers my garage door opener, and I've been able to successfully pair it with my Raspberry Pi running homebridge. Using the gatttool utility, I was able to obtain the primary services and characteristics of the GarageMate device. Now, I'm attempting to update my config.json configuration file with the proper information. Unfortunately, it's not going well. The homebridge-bluetooth platform aborts.

GarageMate explained that reading Core Characteristic 0x2A57 from Core Service 0x1815 would activate the device. These are the UUID values I was able to obtain from gatttool:

attr handle: 0x0039, end grp handle: 0xffff uuid: 00001815-0000-1000-8000-00805f9b34fb
handle: 0x003a, char properties: 0x0a, char value handle: 0x003b, uuid: 00002a57-0000-1000-8000-00805f9b34fb

The GarageMate implements a momentary contact closure via two wires to the garage door opener. It doesn't understand in any manner whether the door is open or closed or blocked. In my understanding, it's a simple button-press. I'd expect to configure it as follows:

"name": "GarageMate",
"address": "01:23:45:67:89:AB",
"services": [ {
    "name": "Garage Door",
    "type": "Automation_IO",
    "UUID": "00001815-0000-1000-8000-00805f9b34fb",
    "characteristics": [ {
        "type": "Button",
        "UUID": "00002a57-0000-1000-8000-00805f9b34fb"
      } ]
   } ]

Thank you for your assistance!

Adding a custom BLE device

I'd like to add a custom thermostat (Danfoss Eco 2) that I currently use through an iOS app. I was wondering if there was somebody who could push me in the right direction towards my goal, I'm pretty new to Homebridge and IoT.

I guess I need to somehow intercept my iOS app's communication with the thermostat when I send commands, and then try to replicate this somehow in Homebridge. Or is there another way?

I tried to follow the link from this repos readme, but it returns a 404: https://github.com/homebridge/HAP-NodeJS/blob/master/lib/gen/HomeKitTypes.js

Plugin Modification help

I am after advice on how to modify this Bluetooth-plugin such that it will reach to the BLE door opener that I have.

I have the following code that will toggle the door. But I am unsure as to what the best location and architecture is to put into the homebridge plugin.

Thanks, I am new to NodeJS and homebridge.

noble.on('discover', function(peripheral) {
  console.log("hello world - discovered " +peripheral.advertisement.localName+ ": " + peripheral.uuid );
  if(peripheral.uuid == "568c300974984c9b96ea051f02a46fea")
  {
   peripheral.connect(function(error) {
     console.log('connected to peripheral: ' + peripheral.advertisement.localName);
     console.log('advertising the following service uuid\'s: ' + peripheral.advertisement.serviceUuids);
     peripheral.discoverServices(['1802'], function(error, services) {
       for (var i in services) {
        deviceInformationService =services[i];
        deviceInformationService.discoverCharacteristics(['2a06'], function(error, characteristics) {
          for (var i in characteristics) {
            console.log('  ' + i + " Service UUDI:"+characteristics[i]._serviceUuid+ ' uuid: ' + characteristics[i].uuid +" name:"+characteristics[i].name + " ServiceProperties:"+characteristics[i].properties);
          }
          var alertLevelCharacteristic = characteristics[0];
            console.log("The door just triggered, uncomment the lines below to actually make it open");
            // alertLevelCharacteristic.write(new Buffer([0x00,0x80,0x54,0x03,0xb3,0xf6,0x35,0x84]), true, function(error) {
            //   console.log('Door toggled');
            // });
            peripheral.disconnect()
         });
       }
     });
   });
  }
});

How to control electric heater?

I have an electric heater that I would like to control, the heater uses a bluetooth app for remote control. Is it possible to use this plugin to do that?

I need on/off, heater on/off, and temperature up/down commands

again didn't receive values

Now, a step further ... I connect my sensor from iPhone BLE Scanner. Reading the values, the App sends "0C4", (log on my sensor) the sensor gives back the values, all things ok, so fare.
On Raspberry:
The log on the raspberry tell me, Service and Characteristic on the sensor are connected, Homebridge events to get the characteristic too. if I push a request on the homekit app on my mobile, I should see the same or equal behavior (the plugin send 0C4), but nothing happened. The plugin sends nothing.

I tried the node red version to communicate with the sensor - all things good, so noble couldn't be the problem. Any ideas?

Support for MacOS

I'm getting an error with the Bluetooth-hci-socket about operating system not supported

Issue with initializing accessory

Good Day,

After some reinstalls of homebridge I was able to get your plugin installed. However, I seems to be getting the following error when running home bridge with your accessory sample:

[11/12/2016, 11:37:05 PM] ---
[11/12/2016, 11:37:05 PM] Loaded config.json with 1 accessories and 0 platforms.
[11/12/2016, 11:37:05 PM] ---
[11/12/2016, 11:37:05 PM] Loading 1 accessories...
[11/12/2016, 11:37:05 PM] [Arduino 101] Initializing BLE Accessory accessory...
/usr/local/lib/node_modules/homebridge-bluetooth/index.js:18
  this.lights.service = trim_uuid(config.lights.service);
                                               ^
TypeError: Cannot read property 'service' of undefined
    at new BLEAccessory (/usr/local/lib/node_modules/homebridge-bluetooth/index.js:18:48)
    at Server._loadAccessories (/usr/local/lib/node_modules/homebridge/lib/server.js:262:29)
    at Server.run (/usr/local/lib/node_modules/homebridge/lib/server.js:78:38)
    at module.exports (/usr/local/lib/node_modules/homebridge/lib/cli.js:40:10)
    at Object.<anonymous> (/usr/local/lib/node_modules/homebridge/bin/homebridge:17:22)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)

Any thoughts?

Output signal strength (RSSI) for discovered devices

Currently, the plugin only logs the name and address when a new BLE device is discovered. Per discussion in #2 it would be helpful to output the RSSI (signal strength in dB) as well.

console

RSSI can be used to tell which peripheral device is closer to the central and also detect possible problems with a weak signal.

Multiple event firings due to leaking BLE event listeners on Raspberry Pi 3

I'm having trouble getting this running on the Pi.

I had modified your code to always convert data to utf8. This works perfectly for my devices and running this plugin on my mac. However, when used on the Pi, I get the following error and I can't seem to figure out why as the utf8 module was installed.

/usr/local/lib/node_modules/homebridge-lifebot/source/characteristic.js:156
  buffer = Buffer.from(value, 'utf8');
                  ^
TypeError: utf8 is not a function
    at Function.from (native)
    at Function.from (native)
    at BluetoothCharacteristic.toBuffer (/usr/local/lib/node_modules/homebridge-lifebot/source/characteristic.js:156:19)
    at BluetoothCharacteristic.set (/usr/local/lib/node_modules/homebridge-lifebot/source/characteristic.js:118:23)
    at emitMany (events.js:108:13)
    at emit (events.js:182:7)
    at Characteristic.setValue (/usr/local/lib/node_modules/homebridge/node_modules/hap-nodejs/lib/Characteristic.js:155:10)
    at Bridge.<anonymous> (/usr/local/lib/node_modules/homebridge/node_modules/hap-nodejs/lib/Accessory.js:740:22)
    at Array.forEach (native)
    at Bridge.Accessory._handleSetCharacteristics (/usr/local/lib/node_modules/homebridge/node_modules/hap-nodejs/lib/Accessory.js:685:8)

Characteristic doesn't receive value

I use ESP32, got BLE working correctly and send periodically Notification Values.

On a mobile with BLE Scanner: The sensor is seen, periodically NOTIFY update values are received.
On the raspberry: Sensor is connected, Service and Characteristic is "connected".
In the Homekit (also tested in the EVE App): Sensor is seen, correct service and characteristic. I can start "identify" the sensor with positive response. I see the action "Identify" in the Raspi log too.
But ... never get values or value updates. I would expect the same behavior, like the BLE Scanner do. I'm confused. please help.

Tv commands

Hey,
Could i command my bluetooth tv with it ?

Thank you !

How to configure ZWave lock?

Hi,

I've been hoping to connect my lock via bluetooth (which it currently uses on my phone) instead of zwave - as this seemed to drain the battery really quick.

installed homebridge and it started ok, thermostat loaded........
installed homebridge-bluetooth

When i went to start home bridge it failed with the following:

Load homebridge-bluetooth.Bluetooth
/usr/local/lib/node_modules/homebridge-bluetooth/source/platform.js:16
  if (!config.accessories || !(config.accessories instanceof Array)) {
             ^
TypeError: Cannot read property 'accessories' of null
    at new BluetoothPlatform (/usr/local/lib/node_modules/homebridge-bluetooth/source/platform.js:16:14)
    at Server._loadDynamicPlatforms (/usr/local/lib/node_modules/homebridge/lib/server.js:315:30)
    at Server.run (/usr/local/lib/node_modules/homebridge/lib/server.js:82:8)
    at module.exports (/usr/local/lib/node_modules/homebridge/lib/cli.js:40:10)
    at Object.<anonymous> (/usr/local/lib/node_modules/homebridge/bin/homebridge:17:22)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
  1. How can i get home bridge started (maybe disabling bluetooth as and when)
  2. How do i go about adding my lock to home bridge? I managed to get my thermostat connected with a lot of copy past in the config file but i would know what i need to add for the lock.

Phil

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.