All Projects â†’ mrousavy â†’ react-native-google-nearby-messages

mrousavy / react-native-google-nearby-messages

Licence: MIT license
📲 Communicate with nearby devices using Bluetooth, BLE, WiFi and near-ultrasonic audio. Broadcast and receive small payloads (like strings) using the easy-to-use React Native API!

Programming Languages

kotlin
9241 projects
typescript
32286 projects
swift
15916 projects
objective c
16641 projects - #2 most used programming language
javascript
184084 projects - #8 most used programming language
java
68154 projects - #9 most used programming language

Projects that are alternatives of or similar to react-native-google-nearby-messages

ESP32BleAdvertise
Simple library for BLE advertise using ESP32 in Arduino
Stars: ✭ 39 (-72.73%)
Mutual labels:  bluetooth, ble
GoFIT SDK Android
GoFIT SDK for Android — GOLiFE 手環 App 介接 SDK
Stars: ✭ 32 (-77.62%)
Mutual labels:  bluetooth, ble
ESP32 IMU BARO GPS VARIO
GPS altimeter/variometer with LCD display, routes with waypoints, data/gps track logging, bluetooth NMEA sentence transmission, wifi AP + webpage configuration
Stars: ✭ 72 (-49.65%)
Mutual labels:  wifi, bluetooth
deneyapkart-arduino-core
Arduino Core for Deneyap DevKits
Stars: ✭ 39 (-72.73%)
Mutual labels:  wifi, ble
theheraldproject.github.io
Herald - Proximity Detection Protocol and research documentation, including the Fair Efficacy Formula
Stars: ✭ 17 (-88.11%)
Mutual labels:  bluetooth, ble
Gesture-Detecting-Macro-Keyboard
Glorified Bluetooth macro keyboard with machine learning (TensorFlow Lite for Microcontrollers) running on an ESP32.
Stars: ✭ 68 (-52.45%)
Mutual labels:  bluetooth, ble
Gormsson
Harald "Bluetooth" Gormsson was a king of Denmark and Norway.
Stars: ✭ 25 (-82.52%)
Mutual labels:  bluetooth, ble
app-xyo-nodejs
XYO Archivist/Diviner CLI
Stars: ✭ 41 (-71.33%)
Mutual labels:  bluetooth, ble
SmartSpin2k
Transform your spin bike into a Smart Trainer!
Stars: ✭ 88 (-38.46%)
Mutual labels:  bluetooth, ble
daydream-node
Quick Node.js module to connect to the Daydream controller and receive all the data
Stars: ✭ 17 (-88.11%)
Mutual labels:  bluetooth, ble
mi-lamp-re
💡 Reverse Engineering Notes for the Yeelight Bedside Lamp (BLE)
Stars: ✭ 35 (-75.52%)
Mutual labels:  bluetooth, ble
ChromeBluetooth
Demo of a "Stress Display" using Chrome Bluetooth. Reads Heart-rate data, and displays "stress" colors to a smart bulb. (Uses a SBT5007 smart bulb)
Stars: ✭ 14 (-90.21%)
Mutual labels:  bluetooth, ble
spherov2.py
Unofficial Python API for all Sphero toys
Stars: ✭ 36 (-74.83%)
Mutual labels:  bluetooth, ble
easyble
A simple framework for Android Bluetooth Low Energy (BLE)
Stars: ✭ 43 (-69.93%)
Mutual labels:  bluetooth, ble
ioBroker.ble
Monitor Bluetooth Low Energy beacons
Stars: ✭ 39 (-72.73%)
Mutual labels:  bluetooth, ble
ble2mqtt
Bluetooth to MQTT bridge, add your bluetooth-capable (including controllable) devices to your smart home
Stars: ✭ 46 (-67.83%)
Mutual labels:  bluetooth, ble
rpi3-wifi-conf
A simple Python script to configure wifi over bluetooth for a Raspberry Pi 3
Stars: ✭ 112 (-21.68%)
Mutual labels:  wifi, bluetooth
coBlue
Use Bluetooth Low Energy for remote commands, file transfer, Based on bluez Bluetooth protocol stack (BLE Terminal)
Stars: ✭ 41 (-71.33%)
Mutual labels:  bluetooth, ble
sblendid
A JavaScript Bluetooth Low Energy (BLE) Library
Stars: ✭ 60 (-58.04%)
Mutual labels:  bluetooth, ble
ble2mqtt
A BLE to MQTT bridge
Stars: ✭ 60 (-58.04%)
Mutual labels:  bluetooth, ble

react-native-google-nearby-messages

An async Google Nearby Messages API Wrapper for React Native (Android & iOS), supporting autolinking, custom discovery modes (broadcast, scan, ..), custom discovery mediums (bluetooth, audio, ..), awaitable native invokations and React hooks!

Also, this is a good example on how to use Swift in a React Native - Native Module.

react-native-google-nearby-messages GitHub stars GitHub followers

Buy Me a Coffee at ko-fi.com

Install

This packages uses React Native autolinking (> 0.60)

npm i react-native-google-nearby-messages
# for iOS
cd ios && pod install && cd ..

Note (iOS): Everytime you run pod install an entry called Assets.car is created in your Build Phases -> [CP] Copy Pods Resources which causes the build to fail. This is a known bug in the Google NearbyMessages pod. A workaround is to manually remove this file everytime you run pod install. See #4 (comment) for an automatic fix. Please create a PR here if you found a better solution for this!

Usage

See the example app.

iOS Setup

See: https://developers.google.com/nearby/messages/ios/get-started

  1. Add bluetooth permissions (NSBluetoothPeripheralUsageDescription, NSBluetoothAlwaysUsageDescription for 'ble', and NSMicrophoneUsageDescription for 'audio') to Info.plist
  2. Create your API Key at the Google Developer Console.
  3. (Optionally): Add the react-native-permissions library to check if Bluetooth is available on the device (it's 'unavailable' on iOS Simulators!) If it's 'unavailable', calls to subscribe or publish might crash the app (EXC_BAD_ACCESS) so only call if Bluetooth permission is denied, granted or blocked. This library will handle the permission checking for you when you call publish() or subscribe() for the first time.
  4. Pass the generated API Key as a parameter using the connect function

Android Setup

See: https://developers.google.com/nearby/messages/android/get-started

  1. Create your API Key at the Google Developer Console.

  2. Add your generated API Key and Permissions to your AndroidManifest.xml:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.google.sample.app" >
        <!-- For BLE/Bluetooth -->
        <uses-permission android:name="android.permission.BLUETOOTH" />
        <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
        <!-- For Audio -->
        <uses-permission android:name="android.permission.RECORD_AUDIO" />
    
        <application ...>
            <meta-data
                android:name="com.google.android.nearby.messages.API_KEY"
                android:value="API_KEY" />
            <activity>
            ...
            </activity>
        </application>
    </manifest>
  3. (Optionally): Call checkBluetoothAvailability() to ensure that Bluetooth capabilities are available on the current device.

  4. Call connect without any key.

Publishing

import { connect, publish, addOnErrorListener } from 'react-native-google-nearby-messages';

const removeListener = addOnErrorListener((kind, message) => console.error(`${kind}: ${message}`));
const disconnect = await connect({ apiKey: GOOGLE_API_KEY });
const unpublish = await publish('hello !');

// later, e.g. in componentWillUnmount()
removeListener();
unpublish();
disconnect();

Make sure to unpublish, disconnect and remove any listeners as they won't be removed automatically! I don't know if that's possible, if so, please create a Pull Request.

Subscribing

import { connect, subscribe, addOnErrorListener } from 'react-native-google-nearby-messages';

const removeListener = addOnErrorListener((kind, message) => console.error(`${kind}: ${message}`));
const disconnect = await connect({ apiKey: GOOGLE_API_KEY });
const unsubscribe = await subscribe(
  (m) => {
    console.log(`new message found: ${m}`);
  },
  (m) => {
    console.log(`message lost: ${m}`);
  });

// later, e.g. in componentWillUnmount()
removeListener();
unsubscribe();
disconnect();

Make sure to unpublish, disconnect and remove any listeners as they won't be removed automatically! I don't know if that's possible, if so, please create a Pull Request.

Bluetooth Availability

Check if the user has granted Bluetooth Permissions. This feature is experimental, and strongly differs between iOS and Android.

import { checkBluetoothPermission } from 'react-native-google-nearby-messages';

const hasPermission = await checkBluetoothPermission();

Check if bluetooth is available on this device. This feature is experimental, and strongly differs between iOS and Android. Make sure to use a library like react-native-permissions to check if Bluetooth is really available, otherwise your Application might crash with a EXEC_BAD_ACCESS error. See troubleshooting

import { checkBluetoothAvailability } from 'react-native-google-nearby-messages';

const isBluetoothAvailable = await checkBluetoothAvailability();

React Hooks

This library also provides react hooks for common use cases. In case you're not familiar with hooks, please read the hooks documentation. When the component unmounts, the hooks automatically stop publishing, subscribing, remove error listeners and disconnect for you. You can also look into the hooks source code and tweak them for your use case.

Make sure to memoize the NearbyConfig object using useMemo, otherwise the hooks will fall into an infinite loop of re-renders because the config object gets re-created each time and therefore has changed. (See: react useEffect's deps)

useNearbyPublication

Publishes a message and returns a state which describes the Nearby API status. (e.g.: connecting, published, error, ...)

export default function App() {
  const nearbyConfig = useMemo<NearbyConfig>(() => ({ apiKey: GOOGLE_API_KEY }), []);
  const nearbyStatus = useNearbyPublication(nearbyConfig, 'Hello from Nearby!');
  // ...
}

useNearbySubscription

Subscribe to nearby messages and return a state for all messages in an array, as well as a state describing the Nearby API Status. (e.g.: connecting, published, error, ...)

export default function App() {
  const nearbyConfig = useMemo<NearbyConfig>(() => ({ apiKey: GOOGLE_API_KEY }), []);
  const { nearbyMessages, nearbyStatus } = useNearbySubscription(nearbyConfig);
  return (
    <FlatList
      data={nearbyMessages}
      renderItem={({ item }) => <Text>{item}</Text>}
      />
  );
}

useNearbySearch

Search for a specific message using nearby messages. The isNearby local specifies whether the string iPhone 11 could be found using the Nearby API, and the nearbyStatus local describes the current status of the Nearby API. (e.g.: connecting, published, error, ...)

export default function App() {
  const nearbyConfig = useMemo<NearbyConfig>(() => ({ apiKey: GOOGLE_API_KEY }), []);
  const { isNearby, nearbyStatus } = useNearbySearch(nearbyConfig, 'iPhone 11');
  return (
    <Text>{isNearby ? 'iPhone 11 is nearby!' : 'iPhone 11 is far, far away.'}</Text>
  );
}

useNearbyErrorCallback

Subscribe to any errors emitted from the Nearby API.

export default function App() {
  useNearbyErrorCallback((kind, message) => {
    console.log(`Nearby API Error: ${kind}: ${message}`)
  });
}

Troubleshooting

If you're having any trouble getting the Nearby API working, please make sure you've read the Troubleshooting Page.

If that doesn't help either, create an issue.

Buy Me a Coffee at ko-fi.com

Resources

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].