npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@movusoz/react-native-ble

v2.6.12

Published

React Native wrapper for FitMachine BLE comms

Downloads

12

Readme

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.

prop | type | description | default ---- | ---- | ----------- | ------- autoScan | bool | start with automatic scanning enabled | false autoScanInterval | int | time between scans | 12000 scanTime | int | how long to scan for | 3000 onScanBegin | func | called when a scan is started | undefined onScanComplete | func | called with an array of devices each time a scan is completed | undefined onBluetoothStateChange | func | called with a bool that tells you if bluetooth is on or off | undefined logger | logger | a custom logger object | consoleLogger requestTimeoutMs | int | how long a request should timeout after in milliseconds | 15000 connectionTimeoutMs | int | how long a connection should timeout after in milliseconds | 15000

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

prop | type | description | notes ---- | ---- | ----------- | ----- id | string | the UDID (iOS) or BLE MAC Address (Android) of the FitMachine | try not to use as it's different across platforms name | string | the advertising name of the FitMachine | this includes the fm prefix (e.g. "fm11:22:33:44:55:66") serial | string | the WiFi MAC Address of the FitMachine | same as name but sans fm (e.g. "11:22:33:44:55:66")

Request

prop | type | description | notes ---- | ---- | ----------- | ----- command | string | the command code / name, e.g. V for list firmware version | dataObject | object | the request parameter object, e.g. a WiFi Profile | dump this with JSON.stringify(request.dataObject, null, 2)

Response

prop | type | description | notes ---- | ---- | ----------- | ----- responseCode | string | the response code / name, e.g. V for list firmware version | length | int | the length of the message data in bytes | data | string | the data content of the message |

WiFi Profile

prop | type | description | notes ---- | ---- | ----------- | ------- ssid | string | the SSID of the network profile | strictly 1-32 chars; can be non printable securityType | int | the type of security available on this endpoint | see the securityType enum index | int | the position of this network in the CC3200's internal list | used for the deleteWifiProfile command priority | int | the priority of this network in the CC3200's internal list | decides the order in which network connections are attempted rssi | int | the received signal strength indicator of this network | roughly how strong the WiFi signal is apMacAddress | string | the MAC Address of the wireless Access Point | not used connected | bool | whether this network is the currently connected network | only available with the N command password | string | the PSK to be used with this network | write-only for the addWifiProfile command

securityType

value | description ----- | ----------- 0x00 | Unsecured network 0x02 | WPA2 Personal 0x05 | WPA2 Enterprise