@chargespot/spjs
v0.23.0
Published
Spot App JS SDK
Downloads
75
Readme
Spot JS SDK
Usage
ESM (recommanded)
Install from npm:
npm i @chargespot/spjs
Use it as a normal dependency:
import { showToast } from '@chargespot/spjs'
showToast({ title: 'Hello SPOT' })
Or you want to use it in a scope:
import * as sp from '@chargespot/spjs'
sp.showToast({ title: 'Hello SPOT' })
We write the SDK with TypeScript so all definations are out-of-box.
UMD
The Global module name is sp
(window.sp
).
You can find a basic UMD example here: https://3ji4i.csb.app/.
<script src="https://unpkg.com/@chargespot/spjs@latest/umd/index.min.js"></script>
<script>
sp.showToast({ title: 'Hello SPOT' })
</script>
API
There are two styles of API:
- Promise style: Post a message and wait / not wait for the Payload Response.
- Event style: Listening to an event and unlistening with the same callback function.
Promise Style
Resolve with SuccesssPayload and reject with ErrorPayload.
getLocation().then(
(payload: SuccessPayload) => {
console.log(payload)
},
(error: ErrorPayload) => {
console.log(error)
}
)
ErrorPayload
Especially, the type of ErrorPayload is:
| Key | Value Type | Value Example | Comment | | ------- | ---------- | ------------- | ------------------------ | | errCode | number | 10002 | | | errMsg | string | 'no device' | duraction in millisecond |
Event Style
Pass a callback function which will be called with the SuccessPayload.
Event style API name will always start with on
like onFoo
.
onLocationChange((payload: SuccessPayload) => {
console.log(payload)
})
You can cancel the listening by passing same function later.
const handleLocationChange = (payload: SuccessPayload) => {
console.log(payload)
}
onLocationChange(handleLocationChange)
setTimeout(() => {
offLocationChange(handleLocationChange)
}, 1000)
Permission
There are many permision scopes related to API call.
SpotApp will show a pop-up asking for user permission for the first time, and return an error message if user deny.
Notice that you will not get the real reason behind the deny response from three of:
- SpotApp does not have the permission from the native OS.
- User deny the first time pop-up.
- The pop-up will be only shown once, and the request will be auto rejected after first time.
| Scope Value | Scene Enum (for TypeScript) | Related API | Comment | | -------------------- | --------------------------- | ---------------------- | -------------------------------------------------------------- | | 'scope.userProfile' | Scope.UserProfile | getUserProfile() | - | | 'scope.userLocation' | Scope.UserLocation | getLocation() | - | | 'scope.bluetooth' | Scope.Bluetooth | openBluetoothAdapter() | - | | 'scope.camera' | Scope.Camera | scanCode() | Always given, and can not switch on/off in miniapp openSetting |
Permission Deny ErrorPayload
| errCode | errMsg | Value Example | Comment | | ------- | ------ | -------------------------------------- | ----------------------------- | | errCode | number | -2 | Always -2 for permission deny | | errMsg | string | 'no permission for scope.userLocation' | May vary |
permit
Pre-asking the specific scope permission, without really calling relatede API
Param
| Key | Value Type | Value Example | Required | Default | Comment | | ----- | ---------- | ----------------- | -------- | ------- | -------------- | | scope | Scope | 'scope.bluetooth' | true | - | only one scope |
Setting
getSetting
Get the current mini-app scope setting.
SuccessPayload
| Key | Value Type | Value Example | Comment |
| ----------------- | ------------------------ | ----------------------- | ------- |
| permissionSetting | Record<Scope, boolean>
| {'scope.camera': false} | - |
openSetting
Open mini-app scope setting page, and get the result of setting.
SuccessPayload
| Key | Value Type | Value Example | Comment |
| ----------------- | ------------------------ | ---------------------------- | ------- |
| permissionSetting | Record<Scope, boolean>
| {'scope.userLocation': true} | - |
import { getLocation, openSetting } from '@chargespot/spjs'
getLocation().catch((e) => {
if (e.errCode === -2) {
confirm('the mini-app needs location permission').then(() => {
openSetting().then(({ permissionSetting }) => {
if (permissionSetting['scope.userLocation']) {
toast('thanks!')
// re-execuate location flow
// getLocation()
}
})
})
}
})
Base
canIUse
Check if a function or message name is available.
Both function name or message name are accpeted, JS SDK will convert the function name to the related message name
- function name:
chooseCoupon
- message name (with scope):
coupon/chooseCoupon
import { canIUse, chooseCoupon } from '@chargespot/spjs'
async function useCoupon() {
const { available } = await canIUse('chooseCoupon')
if (!available) return
// continue
const { couponId } = await chooseCoupon()
}
Param
| Key | Value Type | Value Example | Required | Default | Comment | | ---- | ---------- | -------------- | -------- | -------------------------------------- | ------- | | name | string | 'chooseCoupon' | true | spjs sdk function name or message name | |
SuccessPayload
| Key | Value Type | Value Example | Comment | | --------- | ---------- | ------------- | ------- | | available | boolean | true | - |
getSystemInfo
Get the current enviroment information
SuccessPayload
| Key | Value Type | Value Example | Comment | | ---------- | --------------------------- | ------------- | -------------------------------------------------------- | | version | string | '1.23.4' | - | | language | Language | 'ja_JP' | - | | enviroment | 'sharespot' | 'chargespot' | 'chargespot' | 'chargespot' means current miniapp running in ChargeSPOT |
Language will be one of:
enum Language {
EnUS = 'en_US',
JaJP = 'ja_JP',
ThTH = 'th_TH',
ZhCN = 'zh_CN',
ZhHK = 'zh_HK',
ZhTW = 'zh_TW',
}
getLaunchOptions
Get the environment information of how the mini-app launched.
The example below shows a scenario that the mini-app launched by a SpotApp camera scan result:
import { getLaunchOptions } from '@chargespot/spjs'
getLaunchOptions().then((launchOptions) => {
if (launchOptions.scene === 1011) {
// https://api.charge-spot.com/device?type=3&uuid=foo
const launchUrl = launchOptions.query.result
// uuid === 'foo'
const { uuid } = parseDeviceUrl(launchUrl)
window.location.href = `/devicePage/${uuid}`
}
})
with TypeScript:
import { getLaunchOptions, Scene, ScanSceneQuery } from '@chargespot/spjs'
getLaunchOptions().then((launchOptions) => {
if (launchOptions.scene === Scene.Scan) {
const query = launchOptions.query as ScanSceneQuery
// https://api.charge-spot.com/device?type=3&uuid=foo
const launchUrl = launchOptions.query.result
// uuid === 'foo'
const { uuid } = parseDeviceUrl(launchUrl)
window.location.href = `/devicePage/${uuid}`
}
})
SuccessPayload
| Key | Value Type | Value Example | Comment | | ----- | ----------- | ------------- | ------- | | scene | Scene | 1001 | - | | query | SceneQuery? | - | - |
Scene and SceneQuery
| Scene Value | Scene Enum (for TypeScript) | SceneQuery Type | Comment |
| ----------- | --------------------------- | ---------------------- | ------------------------------------------------------------------------------------- |
| 1001 | Scene.Home | - | Top of the Home Page |
| 1011 | Scene.Scan | ScanSceneQuery | SpotApp Scan Result |
| 1029 | Scene.CouponDetail | CouponSceneQuery? | Spot Coupon Page (with Spot Coupon ID) |
| 1065 | Scene.UrlScheme | UrlSchemeSceneQuery? | SpotApp Launched by URL Scheme (Universal Links or spotapp://miniApp
custom scheme) |
| 1146 | Scene.Map | MapSceneQuery | POI information |
| 1151 | Scene.OrderDetail | OrderSceneQuery | Order information |
| 2000 | Scene.UsingOrder | OrderSceneQuery | Order information, without status |
| 2001 | Scene.Reservation | ReservationSceneQuery? | Reservation information, optional |
| 2002 | Scene.PayDetail | - | Payment Detail Page |
| 2003 | Scene.MapInstantLaunch | MapSceneQuery? | Instant Launch (すぐ利用する) Button in Map Page, within or outside POI panel |
| 2004 | Scene.Help | - | Help Page in ShareSPOT My Page |
ScanSceneQuery
Notice: You have to register the QR code format (e.g URL prefix) to SpotApp first
| Key | Value Type | Value Example | Comment | | ------ | ---------- | ---------------------------------------------------- | ------------------------ | | result | string | 'https://api.charge-spot.com/device?type=3&uuid=foo' | Value of the Scan Result |
CouponSceneQuery
You could use the coupon ID here as the defaultValue of chooseCoupon()
| Key | Value Type | Value Example | Comment | | -------- | ---------- | --------------------- | ----------------------------------------------- | | couponId | string | '1517390046445137921' | The Spot Coupon ID, it is a number style string |
UrlSchemeSceneQuery
You will get the whole url scheme and should parse its query by yourself.
You could launch your mini app by two ways:
- Universal Links:
https://sharespot.jp/miniapp?appId=${YOUR_MINI_APP_ID}
- Spot App URL Scheme:
spotapp://miniapp?appId=${YOUR_MINI_APP_ID}
Add the launch query on the launchData
url query parameter like:
- Universal Links:
https://sharespot.jp/miniapp?appId=${YOUR_MINI_APP_ID}&launchData=${encodeURIComponent('fooBar?')}
- Spot App URL Scheme:
spotapp://miniapp?appId=${YOUR_MINI_APP_ID}&launchData=${encodeURIComponent('fooBar?')}
And you will obtain the whole value of launchData.
Note: only the value on launchData
will be accpeted.
| Key | Value Type | Value Example | Comment | | ---------- | ---------- | ------------- | ------------------------ | | launchData | string | 'fooBar?' | Value of the launch Data |
MapSceneQuery
| Key | Value Type | Value Example | Comment | | ------------- | ------------ | ------------- | -------------- | | merchantPoiId | MiniAppPoiId | '123' | MiniApp POI Id |
OrderSceneQuery
| Key | Value Type | Value Example | Comment | | --------------- | -------------- | ------------- | ------------------------------ | | merchantOrderId | MiniAppOrderId | - | MiniApp Order Id | | orderNo | OrderNo | - | MiniApp Order No (for display) | | status | OrderStatus? | 0 | SpotApp Order Status |
OrderStatus
| Value | Enum (for TypeScript) | Comment | | ----- | --------------------- | ------- | | 0 | OrderStatus.Complete | - | | 1 | OrderStatus.Unpaid | - | | 2 | OrderStatus.Canceled | - |
ReservationSceneQuery
| Key | Value Type | Value Example | Comment | | --------------------- | -------------------- | ------------- | ---------------------- | | merchantReservationId | MiniAppReservationId | - | MiniApp Reservation Id |
openAction
Redirect to ShareSPOT Native Page with url and related launch options.
URL provided in other documents.
Param
| Key | Value Type | Value Example | Required | Default | Comment | | ------------- | ---------- | ---------------------------- | -------- | ------- | -------------------- | | url | string | 'spotapp://usagelist?type=3' | true | - | ShareSPOT Action Url | | launchOptions | object | - | false | - | |
ErrorPayload
| ErrCode | ErrMessage | | ------- | ------------------------------------ | | -1 | URL is not supported, with no action |
UI
showToast
Show a native toast.
Param
| Key | Value Type | Value Example | Required | Default | Comment | | -------- | ---------- | ------------- | -------- | ------- | ------------------------ | | duration | Number | 300 | false | 1500 | duraction in millisecond | | title | String | 'Hello SPOT' | true | - | |
setNavigationBarColor
Change color of the Top Navigation Bar.
Param
| Key | Value Type | Value Example | Required | Default | Comment | | --------------- | ---------- | ------------- | -------- | ------- | ------------ | | frontColor | String | '#000000' | false | - | color in HEX | | backgroundColor | String | '#ffffff' | false | - | |
Auth
login
Get the code
for the auth flow. A basic auth flow is like:
- Your Web Application: When the miniapp launching, call the
login()
and send thecode
to your backend. - Your Backend Service: Send the
code
with other information to the SPOT Open API. - Your Backend Service: Get the SPOT User Identity for your service. Register or obtain the User in your service.
- Your Web Application: Get your user information.
Check the SPOT Open API Document for more detailed information.
// Call the login() when the miniapp launched
async function getUser() {
const localUserString = window.localStorage.getItem('user')
if (localUserString) return JSON.parse(localUserString)
const {code} = await login()
// pass the code to your back-end
const user = fetch(`/user/login?spot_login_code=${code}`)
// save to the local
window.localStorage.setItem('user', JSON.stringify(user))
return user
}
Code Expired
The code
you recevied:
- Could only be used one time.
- Should be used in 5 minutes.
Therefore, the code will be expired (You will get 401
from our SPOT Open API) when:
- The code has been used once time.
- The code is issued 5 miniutes ago.
SuccessPayload
| Key | Value Type | Value Example | Comment | | ---- | ---------- | ------------- | ------- | | code | string | - | - |
getUserProfile
Get non-sensitive user info in the Spot App.
SuccessPayload
| Key | Value Type | Value Example | Comment | | -------- | ---------- | ------------- | ------- | | userInfo | UserInfo | - | - |
UserInfo
| Key | Value Type | Value Example | Comment | | ------ | ---------- | ------------- | ------------------------------------- | | name | string | - | User name in the Spot App | | avatar | string | - | User avatar image URL in the Spot App |
Device
scanCode
Call a native QR code reader and get the result
SuccessPayload
| Key | Value Type | Value Example | Comment | | -------- | --------------------- | ----------------------- | ---------- | | scanType | 'barCode' | 'qrCode' | - | code type | | result | string | 'https://chargespot.jp' | code value |
setClipboardData
Set string data into the clipboard
Param
| Key | Value Type | Value Example | Comment | | ---- | ---------- | ------------- | ----------------------------- | | data | string | - | string value set to clipboard |
makePhoneCall
Make a phone call like tel:
URI in <a>
tag.
Param
| Key | Value Type | Value Example | Comment |
| ----------- | ---------- | ------------- | ------------------------------------------------------------------------- |
| phoneNumber | string | - | phone number value after tel:
URI, hyphens or country code may included |
makePhoneCall({ phoneNumber: '+81-90-0000-0000' })
sendMail
Send email like mailto:
in <a>
tag, but only few fields (in https://datatracker.ietf.org/doc/html/rfc6068) are supported.
Only one recipent is supported, separators like ,
or ;
in to
field are not working.
Param
| Key | Value Type | Value Example | Required | Comment | | ------- | ---------- | ------------------------------------- | -------- | ----------------------------------------- | | to | string | '[email protected]' | true | Multiple recipients are not supported | | subject | string | - | false | Mail Subject | | body | string | - | false | Mail Body |
SuccessPayload
| Key | Value Type | Value Example | Comment | | ------ | ---------------------- | ------------- | -------------------------- | | result | 'success' | 'unknown' | - | Check result section below |
result
'success'
means'sent'
in iOS but does not guarantee success, though you could display a success message afterwards.'unknown'
means the email client has been successfully launched in Android, but due to limitations, the error payload could not be caught.
ErrorPayload
| ErrCode | ErrMessage | | ------- | ---------------------------------------------------------------------------------------------------------- | | -1 | 'cancelled': user canceled operation; 'failed': sending email failed; or 'saved': email saved to draft box |
All 3 reasons use same error code -1
Share
setShareInfo
Set the information for twitter / facebook share.
Param
| Key | Value Type | Value Example | Required | Default | Comment | | ----------- | ---------- | -------------------------------- | -------- | -------------------------- | --------- | | title | string | 'Campaign Title' | true | current Web cocument title | | | url | string? | 'https://chargespot.jp/campaign' | false | current Web Page URL | | | description | string? | - | false | - | | | image | string? | - | false | - | Image URL |
showShareMenu
Show Share Bottom Menu, value from setShareInfo
shareTo
Directly call the native share method, it behaviours equivalent to call showShareMenu()
and click the platform
setShareInfo({ title: 'my mini app' })
function onTwitterButtonClick() {
shareTo({ platform: 'twitter' })
}
function onShareButtonClick() {
showShareMenu()
}
Param
| Key | Value Type | Value Example | Required | Default | Comment | | -------- | ------------- | ------------- | -------- | ------- | ------- | | platform | SharePlatform | 'twitter' | true | - | |
SharePlatform will be one of:
type SharePlatform =
| 'line'
| 'twitter'
| 'facebook'
| 'messenger'
| 'mail'
| 'wechatMessage'
| 'wechatMoments'
| 'copyLink'
| 'system'
Coupon
chooseCoupon
Open a native dialog to guide user choose their coupon.
There are 4 scenes of calling the method:
- SuccessPayload with
couponId
: User has coupon and select a coupon. - SuccessPayload with no
couponId
: User has coupon and decide not using. - ErrorPayload with
-1
ErrCode: User close the native dialog with exit current flow. - SuccessPayload with no
couponId
: User has no coupon. native dialog will not be shown.
A typical code example will be:
async function makePayment() {
const { couponId } = await chooseCoupon({ defaultCouponId: 'foo' })
// if an cancel error occur, the flow will not continue
await request('/make-my-mini-app-payment', { data: { couponId } })
}
Param
| Key | Type | Example | Required | Default | Comment | | --------------- | ------- | --------------------- | -------- | ------- | ------------------------------------------------------------------------------- | | defaultCouponId | string? | "1517390046445137921" | false | - | If user has the coupon when calling the method, it will be selected by default. |
SuccessPayload
| Key | Type | Example | Comment | | -------- | ------- | ------- | ------- | | couponId | string? | - | - |
ErrorPayload
| ErrCode | ErrMessage | | ------- | ------------------------------------------------------------ | | -1 | user cancel choosing coupon, not continue with no coupon |
Payment
requestBindPayment
Call a native Popover to help user add / bind or update a legal payment method.
You should call this method after your back-end request SPOT payment failed, and:
- Re-call your back-end after this method successed
- Show error message after this method failed
ErrorPayload
| ErrCode | ErrMessage | | ------- | ------------------------ | | -1 | user cancel this payment |
Location
getLocation
Get current location.
SuccessPayload
| Key | Value Type | Value Example | Comment | | --------- | ---------- | ------------- | ------- | | latitude | number | - | - | | longitude | number | - | - |
ErrorPayload
| ErrCode | ErrMessage | | ------- | ------------------------------------------- | | -2 | Permission deny, check "Permission" Section |
startLocationUpdate
Enable location real-time updating feature
stopLocationUpdate
Disable location real-time updating feature
onLocationChange
Get the real-time location result
SuccessPayload
As same as getLocation
offLocationChange
Stop listening location change event
navigateLocation
Navigate to specific location, from current location.
Param
| Key | Value Type | Value Example | Required | Default | Comment | | --------- | ---------- | ------------- | -------- | ------- | ------------------------- | | latitude | number | 35.680323 | true | - | Destination latitude | | longitude | number | 139.764582 | true | - | Destination longitude | | name | string? | 'Yurakucho' | false | - | Optional destination name |
navigateLocation({
latitude: 35.680323,
longitude 139.764582,
name: 'Yurakucho',
})
Bluetooth
A simplest Bluetooth flow is:
- openBluetoothAdapter()
- startBluetoothDevicesDiscovery()
- getBluetoothDevices()
- createBLEConnection()
- getBLEDeviceServices()
- getBLEDeviceCharacteristics()
- readBLECharacteristicValue()
- writeBLECharacteristicValue()
openBluetoothAdapter
Open Bluetooth adpater.
closeBluetoothAdapter
Close Bluetooth adapter
getBluetoothAdapterState
Get current bluetooth adapter state
SuccessPayload
| Key | Value Type | Value Example | Comment | | ----- | ------------ | ------------- | ------- | | state | AdapterState | - | - |
AdapterState
| Key | Value Type | Value Example | Comment | | ----------- | ---------- | ------------- | ------- | | discovering | boolean | - | - | | available | boolean | - | - |
onBluetoothAdapterStateChange
Listen Bluetooth adapter state change event
SuccessPayload
| Key | Value Type | Value Example | Comment | | ----- | ------------ | ------------- | ------- | | state | AdapterState | - | - |
offBluetoothAdapterStateChange
Unlisten Bluetooth adapter state change event
startBluetoothDevicesDiscovery
Start discovering devices
Param
| Key | Value Type | Value Example | Required | Default | Comment | | ------------------ | ---------- | ------------- | -------- | ------- | ----------------------- | | allowDuplicatesKey | boolean | false | false | false | - | | interval | number | 1000 | false | 0 | interval in millseconds |
startBluetoothDevicesDiscovery({
allowDuplicatesKey: false,
interval: 300,
}).catch((error: ErrorPayload) => {
console.log(error)
})
stopBluetoothDevicesDiscovery
Stop discv
Error Payload
TBD.
| Code | Message | Comment | | ----- | --------------- | ------- | | 10001 | 'not available' | - |
getBluetoothDevices
Get discovered devices during start and end
SuccessPayload
| Key | Value Type | Value Example | Comment | | ------- | ---------- | ------------- | ----------- | | devices | Device[] | - | device list |
Device
| Key | Value Type | Value Example | Comment | | -------------------- | ---------- | ---------------- | ------- | | name | string | 'My MacBook Pro' | - | | deviceId | string | - | - | | RSSI | number | - | - | | advertisData | string | - | - | | advertisServiceUUIDs | string[] | - | - | | localName | string[] | - | - | | serviceData | string[] | - | - |
Example
async function getDevices() {
await startBluetoothDevicesDiscovery()
const { devices } = await getBluetoothDevices()
devices.map((device) => {
console.log(device.name) // 'My MacBook Pro'
})
}
onBluetoothDeviceFound
New devices found event
SuccessPayload
| Key | Value Type | Value Example | Comment | | ------- | ---------- | ------------- | ----------- | | devices | Device[] | - | device list |
offBluetoothDeviceFound
Pair with onBluetoothDeviceFound
createBLEConnection
Create BLE Connection with device
Param
| Key | Value Type | Value Example | Required | Default | Comment | | -------- | ---------- | -------------------------------------- | -------- | ------- | --------- | | deviceId | string | '629FA080-FACC-8DEB-8C57-40985EC4A153' | true | - | device id |
Example
createBLEConnection({ deviceId: '629FA080-FACC-8DEB-8C57-40985EC4A153' })
closeBLEConnection
close connection with the specific device.
Param
| Key | Value Type | Value Example | Required | Default | Comment | | -------- | ---------- | -------------------------------------- | -------- | ------- | --------- | | deviceId | string | '629FA080-FACC-8DEB-8C57-40985EC4A153' | true | - | device id |
onBLEConnectionStateChange
Listen to the connection state change event
SuccessPayload
| Key | Value Type | Value Example | Comment | | --------- | ---------- | -------------------------------------- | --------- | | deviceId | string | '629FA080-FACC-8DEB-8C57-40985EC4A153' | device id | | connected | boolean | true | - |
Example
createBLEConnection({ deviceId: '629FA080-FACC-8DEB-8C57-40985EC4A153' })
onBLEConnectionStateChange((payload) => {
console.log(payload.deviceId) // '629FA080-FACC-8DEB-8C57-40985EC4A153'
console.log(payload.connected) // true
})
offBLEConnectionStateChange
Pair with onBLEConnectionStateChange
getBLEDeviceRSSI
Get device RSSI
Param
| Key | Value Type | Value Example | Required | Default | Comment | | -------- | ---------- | -------------------------------------- | -------- | ------- | --------- | | deviceId | string | '629FA080-FACC-8DEB-8C57-40985EC4A153' | true | - | device id |
SuccessPayload
| Key | Value Type | Value Example | Comment | | ---- | ---------- | ------------- | ---------------------------------- | | RSSI | number | - | Received Signal Strength Indicator |
getBLEDeviceServices
Get device service list
Param
| Key | Value Type | Value Example | Required | Default | Comment | | -------- | ---------- | -------------------------------------- | -------- | ------- | --------- | | deviceId | string | '629FA080-FACC-8DEB-8C57-40985EC4A153' | true | - | device id |
SuccessPayload
| Key | Value Type | Value Example | Comment | | -------- | --------------- | ------------- | ------------ | | services | DeviceService[] | - | service list |
DeviceService
| Key | Value Type | Value Example | Comment | | --------- | ---------- | ------------- | ------- | | uuid | string | - | - | | isPrimary | boolean | - | - |
getBLEDeviceCharacteristics
Get device service list
Param
| Key | Value Type | Value Example | Required | Default | Comment | | --------- | ---------- | ------------- | -------- | ------- | ---------- | | deviceId | string | - | true | - | device id | | serviceId | string | - | true | - | service id |
SuccessPayload
| Key | Value Type | Value Example | Comment | | --------------- | ---------------------- | ------------- | -------------------- | | characteristics | DeviceCharacteristic[] | - | characteristics list |
DeviceCharacteristic
| Key | Value Type | Value Example | Comment | | ---------- | ---------------------------- | ------------- | ------- | | uuid | string | - | - | | properties | DeviceCharacteristicProperty | - | - |
DeviceCharacteristicProperty
| Key | Value Type | Value Example | Comment | | -------- | ---------- | ------------- | ------- | | read | boolean | - | - | | write | boolean | - | - | | notify | boolean | - | - | | indicate | boolean | - | - |
readBLECharacteristicValue
Read characteristic value.
Notice: You will get response on onBLECharacteristicValueChange
event
Param
| Key | Value Type | Value Example | Required | Default | Comment | | ---------------- | ---------- | ------------- | -------- | ------- | ----------------- | | deviceId | string | - | true | - | device id | | serviceId | string | - | true | - | service id | | characteristicId | string | - | true | - | characteristic id |
onBLECharacteristicValueChange
Listen characteristic changing.
SuccessPayload
| Key | Value Type | Value Example | Comment | | ---------------- | ---------- | ---------------------- | ----------------------------------------------- | | deviceId | string | - | device id | | serviceId | string | - | service id | | characteristicId | string | - | characteristic id | | value | string | 'YmFzZTY0IGRlY29kZXI=' | Bytecode dharacteristic value encoded in Base64 |
Example
readBLECharacteristicValue({
deviceId: 'foo',
serviceId: 'bar',
characteristicId: 'baz',
})
// get the read result from the event
onBLECharacteristicValueChange(
({ deviceId, serviceId, characteristicId, value }) => {
console.log(deviceId) // 'foo'
console.log(serviceId) // 'bar'
console.log(characteristicId) // 'baz'
console.log(value) // 'YmFzZTY0IGRlY29kZXI='
}
)
offBLECharacteristicValueChange
Pair with onBLECharacteristicValueChange
writeBLECharacteristicValue
Param
| Key | Value Type | Value Example | Required | Default | Comment | | ---------------- | ---------- | ---------------------- | -------- | ------- | ----------------------------------------------- | | deviceId | string | - | true | - | device id | | serviceId | string | - | true | - | service id | | characteristicId | string | - | true | - | characteristic id | | value | string | 'YmFzZTY0IGRlY29kZXI=' | true | - | Bytecode dharacteristic value encoded in Base64 |
notifyBLECharacteristicValueChange
| Key | Value Type | Value Example | Comment | | ---------------- | ---------- | ------------- | ------------------------------------------------ | | deviceId | string | - | device id | | serviceId | string | - | service id | | characteristicId | string | - | characteristic id | | state | boolean | true | start characteristic notify event (if supported) |