Skip to content

Commit

Permalink
feat: added hooks and context
Browse files Browse the repository at this point in the history
Signed-off-by: Berend Sliedrecht <[email protected]>
  • Loading branch information
berendsliedrecht committed Aug 8, 2023
1 parent b75b7d7 commit c1abff6
Show file tree
Hide file tree
Showing 22 changed files with 297 additions and 91 deletions.
1 change: 0 additions & 1 deletion example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
"start": "react-native start"
},
"dependencies": {
"@animo-id/react-native-ble-didcomm": "../",
"babel-plugin-module-resolver": "4.1.0",
"react": "18.1.0",
"react-native": "0.70.3"
Expand Down
74 changes: 36 additions & 38 deletions example/src/Central.tsx
Original file line number Diff line number Diff line change
@@ -1,54 +1,52 @@
import React, { useEffect, useState } from 'react'
import React, { PropsWithChildren, useEffect, useMemo, useState } from 'react'
import { Button } from 'react-native'
import {
Central as BleCentral,
DEFAULT_DIDCOMM_SERVICE_UUID,
DEFAULT_DIDCOMM_MESSAGE_CHARACTERISTIC_UUID,
DEFAULT_DIDCOMM_INDICATE_CHARACTERISTIC_UUID,
useCentral,
useCentralOnDiscovered,
useCentralOnConnected,
useCentralOnDisconnected,
useCentralOnReceivedMessage,
useCentralShutdownOnUnmount,
} from '@animo-id/react-native-ble-didcomm'
import { Spacer } from './App'

const msg = 'Hello from Central!'

export const Central = () => {
const central = new BleCentral()
const [isConnected, setIsConnected] = useState(false)
export const Central: React.FC<PropsWithChildren> = ({ children }) => {
const central = useMemo(() => new BleCentral(), [])

return <CentralProvider value={central}>{children}</CentralProvider>
}

const CentralChildren = () => {
useCentralShutdownOnUnmount()

const [peripheralId, setPeripheralId] = useState<string>()
const [isConnected, setIsConnected] = useState<boolean>(false)

const { central } = useCentral()

useCentralOnDiscovered((identifier: string) => {
console.log(`[CENTRAL]: Discovered: ${identifier}`)
setPeripheralId(identifier)
})

useCentralOnConnected((identifier: string) => {
console.log(`[CENTRAL]: Connected to: ${identifier}`)
setIsConnected(true)
})

useCentralOnReceivedMessage((message: string) => {
console.log(`[CENTRAL]: Received indication: ${message}`)
})

useEffect(() => {
const onDiscoverPeripheralListener = central.registerOnDiscoveredListener(
({ identifier }: { identifier: string }) => {
console.log(`[CENTRAL]: Discovered: ${identifier}`)
setPeripheralId(identifier)
}
)

const onConnectedPeripheralListener = central.registerOnConnectedListener(
({ identifier }: { identifier: string }) => {
console.log(`[CENTRAL]: Connected to: ${identifier}`)
setIsConnected(true)
}
)

const onDisconnectedPeripheralListener =
central.registerOnDisconnectedListener(
({ identifier }: { identifier: string }) =>
console.log(`[CENTRAL]: Disconnected from ${identifier}`)
)

const onReceivedNotificationListener = central.registerMessageListener(
({ message }: { message: string }) =>
console.log(`[CENTRAL]: Received indication: ${message}`)
)

return () => {
void shutdown()
onDiscoverPeripheralListener.remove()
onConnectedPeripheralListener.remove()
onReceivedNotificationListener.remove()
onDisconnectedPeripheralListener.remove()
}
}, [])
useCentralOnDisconnected((identifier: string) => {
console.log(`[CENTRAL]: Disconnected from ${identifier}`)
})

const start = central.start

Expand Down
55 changes: 26 additions & 29 deletions example/src/Peripheral.tsx
Original file line number Diff line number Diff line change
@@ -1,47 +1,44 @@
import React, { useEffect, useState } from 'react'
import React, { PropsWithChildren, useEffect, useMemo, useState } from 'react'
import { Button } from 'react-native'
import {
Peripheral as BlePeripheral,
DEFAULT_DIDCOMM_SERVICE_UUID,
DEFAULT_DIDCOMM_MESSAGE_CHARACTERISTIC_UUID,
DEFAULT_DIDCOMM_INDICATE_CHARACTERISTIC_UUID,
PeripheralProvider,
usePeripheralOnConnected,
usePeripheralOnDisconnected,
usePeripheralOnReceiveMessage,
usePeripheralShutdownOnUnmount,
} from '@animo-id/react-native-ble-didcomm'
import { Spacer } from './App'

const msg = 'Hello from peripheral!'

export const Peripheral = () => {
const peripheral = new BlePeripheral()
const [isConnected, setIsConnected] = useState(false)
export const Peripheral: React.FC<PropsWithChildren> = ({ children }) => {
const peripeheral = useMemo(() => new BlePeripheral(), [])

return <PeripheralProvider value={peripheral}>{children}</PeripheralProvider>
}

useEffect(() => {
const onConnectedCentralListener = peripheral.registerOnConnectedListener(
({ identifier }: { identifier: string }) => {
console.log(`[PERIPHERAL]: Connected to ${identifier}`)
setIsConnected(true)
}
)
const PeripheralChildren = () => {
usePeripheralShutdownOnUnmount()

const [isConnected, setIsConnected] = useState(false)

const onDisconnectedCentralListener =
peripheral.registerOnDisconnectedListener(
({ identifier }: { identifier: string }) => {
console.log(`[PERIPHERAL]: Disconnected from ${identifier}`)
setIsConnected(false)
}
)
usePeripheralOnConnected((identifier: string) => {
console.log(`[PERIPHERAL]: Connected to ${identifier}`)
setIsConnected(true)
})

const onReceivedWriteWithoutResponseListener =
peripheral.registerMessageListener(({ message }: { message: string }) =>
console.log(`[PERIPHERAL]: Received message: ${message}`)
)
usePeripheralOnDisconnected((identifier: string) => {
console.log(`[PERIPHERAL]: Connected to ${identifier}`)
setIsConnected(true)
})

return () => {
void shutdown()
onConnectedCentralListener.remove()
onReceivedWriteWithoutResponseListener.remove()
onDisconnectedCentralListener.remove()
}
}, [])
usePeripheralOnReceiveMessage((message: string) => {
console.log(`[PERIPHERAL]: Received message: ${message}`)
})

const start = peripheral.start

Expand Down
15 changes: 1 addition & 14 deletions example/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,6 @@
"@jridgewell/gen-mapping" "^0.1.0"
"@jridgewell/trace-mapping" "^0.3.9"

"@animo-id/react-native-ble-didcomm@../":
version "0.0.0"
dependencies:
buffer "6.0.3"

"@babel/code-frame@^7.0.0", "@babel/code-frame@^7.10.4", "@babel/code-frame@^7.18.6":
version "7.18.6"
resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.18.6.tgz#3b25d38c89600baa2dcc219edfa88a74eb2c427a"
Expand Down Expand Up @@ -1481,14 +1476,6 @@ buffer-from@^1.0.0:
resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.2.tgz#2b146a6fd72e80b4f55d255f35ed59a3a9a41bd5"
integrity sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==

[email protected]:
version "6.0.3"
resolved "https://registry.yarnpkg.com/buffer/-/buffer-6.0.3.tgz#2ace578459cc8fbe2a70aaa8f52ee63b6a74c6c6"
integrity sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==
dependencies:
base64-js "^1.3.1"
ieee754 "^1.2.1"

buffer@^5.5.0:
version "5.7.1"
resolved "https://registry.yarnpkg.com/buffer/-/buffer-5.7.1.tgz#ba62e7c13133053582197160851a8f648e99eed0"
Expand Down Expand Up @@ -2286,7 +2273,7 @@ [email protected]:
statuses "2.0.1"
toidentifier "1.0.1"

ieee754@^1.1.13, ieee754@^1.2.1:
ieee754@^1.1.13:
version "1.2.1"
resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.2.1.tgz#8eb7a10a63fff25d15a57b001586d177d1b0d352"
integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==
Expand Down
30 changes: 30 additions & 0 deletions src/central/CentralProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import type { Central } from './central'
import type { PropsWithChildren } from 'react'
import { useContext } from 'react'
import * as React from 'react'

interface CentralContextItems {
central: Central
}

const CentralContext = React.createContext<CentralContextItems | undefined>(
undefined
)

export const useCentral = () => {
const centralContext = useContext(CentralContext)
if (!centralContext) {
throw new Error('Central hook is not called within the CentralProvider')
}
return centralContext
}

export const CentralProvider: React.FC<
PropsWithChildren<{ central: Central }>
> = ({ central, children }) => {
return (
<CentralContext.Provider value={{ central }}>
{children}
</CentralContext.Provider>
)
}
4 changes: 2 additions & 2 deletions src/central.ts → src/central/central.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { NativeEventEmitter, NativeModules } from 'react-native'
import type { Ble, ServiceOptions } from './ble'
import { sdk } from './register'
import type { Ble, ServiceOptions } from '../ble'
import { sdk } from '../register'

export class Central implements Ble {
bleDidcommEmitter = new NativeEventEmitter(NativeModules.BleDidcomm)
Expand Down
5 changes: 5 additions & 0 deletions src/central/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export * from './useCentralOnConnected'
export * from './useCentralOnDisconnected'
export * from './useCentralOnDiscovered'
export * from './useCentralOnReceivedMessage'
export * from './useCentralShutdownOnUnmount'
18 changes: 18 additions & 0 deletions src/central/hooks/useCentralOnConnected.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { useEffect } from 'react'
import { useCentral } from '../CentralProvider'

export const useCentralOnConnected = (
cb: (identifier: string) => void | Promise<void>
) => {
const { central } = useCentral()

useEffect(() => {
const listener = central.registerOnConnectedListener(({ identifier }) =>
cb(identifier)
)

return () => {
listener.remove()
}
}, [])
}
18 changes: 18 additions & 0 deletions src/central/hooks/useCentralOnDisconnected.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { useEffect } from 'react'
import { useCentral } from '../CentralProvider'

export const useCentralOnDisconnected = (
cb: (identifier: string) => void | Promise<void>
) => {
const { central } = useCentral()

useEffect(() => {
const listener = central.registerOnDisconnectedListener(({ identifier }) =>
cb(identifier)
)

return () => {
listener.remove()
}
}, [])
}
18 changes: 18 additions & 0 deletions src/central/hooks/useCentralOnDiscovered.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { useEffect } from 'react'
import { useCentral } from '../CentralProvider'

export const useCentralOnDiscovered = (
cb: (identifier: string) => void | Promise<void>
) => {
const { central } = useCentral()

useEffect(() => {
const listener = central.registerOnDiscoveredListener(({ identifier }) =>
cb(identifier)
)

return () => {
listener.remove()
}
}, [])
}
18 changes: 18 additions & 0 deletions src/central/hooks/useCentralOnReceivedMessage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { useEffect } from 'react'
import { useCentral } from '../CentralProvider'

export const useCentralOnReceivedMessage = (
cb: (message: string) => void | Promise<void>
) => {
const { central } = useCentral()

useEffect(() => {
const listener = central.registerMessageListener(({ message }) =>
cb(message)
)

return () => {
listener.remove()
}
}, [])
}
12 changes: 12 additions & 0 deletions src/central/hooks/useCentralShutdownOnUnmount.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { useEffect } from 'react'
import { useCentral } from '../CentralProvider'

export const useCentralShutdownOnUnmount = () => {
const { central } = useCentral()

useEffect(() => {
return () => {
void central.shutdown()
}
}, [])
}
3 changes: 3 additions & 0 deletions src/central/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './hooks'
export * from './central'
export * from './CentralProvider'
32 changes: 32 additions & 0 deletions src/peripheral/PeripheralProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type { Peripheral } from './peripheral'
import type { PropsWithChildren } from 'react'
import { useContext } from 'react'
import * as React from 'react'

interface PeripheralContextItems {
peripheral: Peripheral
}

const PeripheralContext = React.createContext<
PeripheralContextItems | undefined
>(undefined)

export const usePeripheral = () => {
const peripheralContext = useContext(PeripheralContext)
if (!peripheralContext) {
throw new Error(
'Peripheral hook is not called within the PeripheralProvider'
)
}
return peripheralContext
}

export const PeripheralProvider: React.FC<
PropsWithChildren<{ peripheral: Peripheral }>
> = ({ peripheral, children }) => {
return (
<PeripheralContext.Provider value={{ peripheral }}>
{children}
</PeripheralContext.Provider>
)
}
4 changes: 4 additions & 0 deletions src/peripheral/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export * from './usePeripheralOnReceivedMessage'
export * from './usePeripheralOnDisconnected'
export * from './usePeripheralOnConnected'
export * from './usePeripheralShutdownOnUnmount'
Loading

0 comments on commit c1abff6

Please sign in to comment.