2.6.12 • Published 1 year ago

@movusoz/react-native-ble v2.6.12

Weekly downloads
-
License
ISC
Repository
github
Last release
1 year ago

react-native-ble

This library provides React Native interfaces for talking to FitMachine via BLE.

Usage

Import this library in your package.json using the git flavour by just adding this line to the dependencies section:

  "dependencies": {
    "@movusoz/react-native-ble": "git+https://github.com/movusoz/react-native-ble.git#1.2.0"
  }

Then simply run yarn to install.

Upgrading is the same, just change the version tag after the # and run yarn again.

Using a dev FitMachine

To search connected USB FitMachines on a dev board

ls dev

look for a tty. device

To connect to a USB FitMachine on a dev board

screen /dev/tty.usbserial-A600KQZN 230400

To exit: Ctrl+A -> : -> quit -> Enter

To remove previous screen sessions

screen -rd

Reference

Table of Contents:

ApiClient - Promise-based requests to the FitMachine

BluetoothProvider - high-level provider of Bluetooth related functionality

withBluetooth - HoC that pipes BluetoothProvider context into a Component

Logging - implement custom logging integration

Data Types - data type reference

ApiClient

ApiClient.fetchWifiProfiles(device)

This function returns a Promise which will resolve to a list of WiFi Profiles:

  import { ApiClient } from '@movusoz/react-native-ble';

  class MyScreen extends Component {
    componentDidMount () {
      // use findDevice (see below) to get the device
      ApiClient.fetchWifiProfiles(device).then(profiles => {
        /* ... */
      });
    }
  }

ApiClient.addWifiProfile(device, profile)

This function will send two commands in succession: add then list. It will return you a Promise that will resolve to the updated list of WiFi Profiles:

  import { ApiClient } from '@movusoz/react-native-ble';

  class MyScreen extends Component {
    componentDidMount () {
      // use findDevice (see below) to get the device
      const profile = {
        ssid: 'Movus',
        password: 'pass123',
        securityType: 0x02
      };
      ApiClient.addWifiProfile(device, profile).then(profiles => {
        /* ... */
      });
    }
  }

ApiClient.deleteWifiProfile(device, profileIndex)

This function will send two commands in succession: delete then list. It will return you a Promise that will resolve to the updated list of WiFi Profiles:

  import { ApiClient } from '@movusoz/react-native-ble';

  class MyScreen extends Component {
    componentDidMount () {
      // use findDevice (see below) to get the device
      // delete the device at index 1
      ApiClient.deleteWifiProfile(device, 1).then(profiles => {
        /* ... */
      });
    }
  }

BluetoothProvider

This is an application-level wrapper that provides Bluetooth help functionality, as well as an "auto scan" function that will periodically deliver you a list of nearby devices. You can also configure custom logging here.

proptypedescriptiondefault
autoScanboolstart with automatic scanning enabledfalse
autoScanIntervalinttime between scans12000
scanTimeinthow long to scan for3000
onScanBeginfunccalled when a scan is startedundefined
onScanCompletefunccalled with an array of devices each time a scan is completedundefined
onBluetoothStateChangefunccalled with a bool that tells you if bluetooth is on or offundefined
loggerloggera custom logger objectconsoleLogger
requestTimeoutMsinthow long a request should timeout after in milliseconds15000
connectionTimeoutMsinthow long a connection should timeout after in milliseconds15000

Example usage:

import { BluetoothProvider } from '@movusoz/react-native-ble';

class App extends Component {
  handleScanBegin () {
    this.setState({ scanning: true });
  }

  handleScanComplete (devices) {
    const [ device1, device2, ...rest ] = devices;

    // the serial prop is the FitMachine's WiFi MAC
    expect(device1.serial).toBe('60:10:20:30:40:50');
    this.setState({ scanning: false });
  }

  handleBluetoothStateChange (bluetoothIsPoweredOn) {
    if (bluetoothIsPoweredOn) {
      alert('bluetooth was switched on :)');
    } else {
      alert('bluetooth was switched off :(');
    }
  }

  render () {
    // scan for 2s every 10s
    const scanTime = 2000;
    const autoScanInterval = 10000;

    return (
      <BluetoothProvider
        scanTime={scanTime}
        autoScanInterval={autoScanInterval}
        onScanBegin={this.handleScanBegin}
        onScanComplete={this.handleScanComplete}
        onBluetoothStateChange={this.handleBluetoothStateChange}
      >
        {/* the rest of the app */}
      </BluetoothProvider>
    )
  }
}

withBluetooth

Provided via the BluetoothProvider is a HoC called withBluetooth. This will pass down a bluetooth object to the props of your connected component that provides methods for interacting with device.

bluetooth.setAutoScan(autoScan, { autoScanTime, autoScanInterval })

Asks Bluetooth to continually scan in the background for devices.

import { withBluetooth } from '@movusoz/react-native-ble';

@withBluetooth()
class Screen extends Component {
  /* ... */

  componentDidMount () {
    const { bluetooth } = this.props;
    // while this component is mounted, scan in the background
    // for 2 seconds every 10 seconds
    bluetooth.setAutoScan(true, { autoScanTime: 2000, 10000 });
  }

  componentWillUnmount () {
    const { bluetooth } = this.props;
    bluetooth.setAutoScan(false);
  }

  /* ... */
}

bluetooth.findDevice(serial)

If the requested serial is in the most recent auto-scan list, it will be returned immediately. Otherwise, the auto-scan will be triggered in-place and if the device is then found after that auto-scan it will be returned, otherwise you'll get undefined.

import { withBluetooth } from '@movusoz/react-native-ble';

@withBluetooth()
class Screen extends Component {  
  /* ... */

  componentDidMount () {
    const { bluetooth } = this.props;
    bluetooth
      .findDevice('60:10:20:30:40:50')
      .then(device => {
        if (device) {
          /* do stuff with the device now */
        } else {
          alert('the device was not found');
        }
      });
  }

  /* ... */
}

bluetooth.connect(device)

Forces Bluetooth to connect to the device (as opposed to letting it happen automatically when you send a message).

import { withBluetooth } from '@movusoz/react-native-ble';

@withBluetooth()
class Screen extends Component {  
  /* ... */

  componentDidMount () {
    const { bluetooth } = this.props;
    bluetooth
      .findDevice('60:10:20:30:40:50')
      .then(device => {
        /* connect to it */
        !!device && bluetooth.connect(device);
      });
  }

  /* ... */
}

bluetooth.getConnectedDevice()

Returns the currently connected device, or null.

import { withBluetooth } from '@movusoz/react-native-ble';

@withBluetooth()
class Screen extends Component {  
  /* ... */

  componentDidMount () {
    const { bluetooth } = this.props;
    const device = bluetooth.getConnectedDevice();
    if (device) {
      /* do stuff with the device now */
    } else {
      /* we aren't connected to anything right now */
    }
  }

  /* ... */
}

bluetooth.disconnect()

Forces the Bluetooth layer to disconnect.

import { withBluetooth } from '@movusoz/react-native-ble';

@withBluetooth()
class Screen extends Component {  
  /* ... */

  componentWillUnmount () {
    const { bluetooth } = this.props;
    bluetooth.disconnect();
  }

  /* ... */
}

Logging

This library has logging hooks and provides a default console logger. If you don't want to use the logger and would prefer to send the logs somewhere else (API, Bluetooth, a screen, whatever), you simply have to implement a logger object (described below) and pass it to the logger prop of the BluetoothProvider.

This logger object is optional, and will default to consoleLogger provided in this repository (which serves as a convenient sample implementation!).

startConnecting(device)

Called when the library initiates a connection to the device.

connectionFailed(device, error)

Called when a connection attempt fails to the given device. The error is a string.

finishConnecting(device)

Called when a given device is successfully connected to.

localDisconnect(device)

Called when a given device is disconnected from locally (i.e. we initiated the disconnect).

remoteDisconnect(device)

Called when a given device is disconnected remotely (i.e. they initiated the disconnect).

startRequest(device, request)

Called when a given request is sent to a device.

requestFailed(error)

Called when the last request failed. The error is a string.

finishRequest(response)

Called when a request finishes successfully. The response is the response data object. Dump it with JSON.stringify(response, null, 2).

otherMessageReceived(response)

Called when any message is received that we're not expecting or not currently waiting for.

dataReceived(data)

Called when any data is received on the characteristic monitor. consoleLogger does not log this by default.

errorReceived(error)

Called when an error is received on the characteristic monitor outside of a request.

Data Types

Device

proptypedescriptionnotes
idstringthe UDID (iOS) or BLE MAC Address (Android) of the FitMachinetry not to use as it's different across platforms
namestringthe advertising name of the FitMachinethis includes the fm prefix (e.g. "fm11:22:33:44:55:66")
serialstringthe WiFi MAC Address of the FitMachinesame as name but sans fm (e.g. "11:22:33:44:55:66")

Request

proptypedescriptionnotes
commandstringthe command code / name, e.g. V for list firmware version
dataObjectobjectthe request parameter object, e.g. a WiFi Profiledump this with JSON.stringify(request.dataObject, null, 2)

Response

proptypedescriptionnotes
responseCodestringthe response code / name, e.g. V for list firmware version
lengthintthe length of the message data in bytes
datastringthe data content of the message

WiFi Profile

proptypedescriptionnotes
ssidstringthe SSID of the network profilestrictly 1-32 chars; can be non printable
securityTypeintthe type of security available on this endpointsee the securityType enum
indexintthe position of this network in the CC3200's internal listused for the deleteWifiProfile command
priorityintthe priority of this network in the CC3200's internal listdecides the order in which network connections are attempted
rssiintthe received signal strength indicator of this networkroughly how strong the WiFi signal is
apMacAddressstringthe MAC Address of the wireless Access Pointnot used
connectedboolwhether this network is the currently connected networkonly available with the N command
passwordstringthe PSK to be used with this networkwrite-only for the addWifiProfile command

securityType

valuedescription
0x00Unsecured network
0x02WPA2 Personal
0x05WPA2 Enterprise
2.6.12

1 year ago

2.6.11

2 years ago

2.6.10

2 years ago

2.6.7

2 years ago

2.6.9

2 years ago

2.6.8

2 years ago

2.6.6

2 years ago

2.6.5

2 years ago