@eohjsc/react-native-smart-city 0.7.3-rc24 → 0.7.3-rc25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,300 @@
1
+ import React from 'react';
2
+ import { Alert } from 'react-native';
3
+ import { act } from 'react-test-renderer';
4
+ import MockAdapter from 'axios-mock-adapter';
5
+ import { NavigationContext } from '@react-navigation/native';
6
+
7
+ import DeviceDetail from '../detail';
8
+ import { API } from '../../../configs';
9
+ import { AccessibilityLabel } from '../../../configs/Constants';
10
+ import { SCProvider } from '../../../context';
11
+ import { mockSCStore } from '../../../context/mockStore';
12
+ import api from '../../../utils/Apis/axios';
13
+ import { useWatchConfigs } from '../../../hooks/IoT';
14
+ import { render } from '../../../../jest/render';
15
+ import { BleManager } from 'react-native-ble-plx';
16
+ import { v4 as uuidv4 } from 'uuid';
17
+ import base64 from 'react-native-base64';
18
+
19
+ const mock = new MockAdapter(api.axiosInstance);
20
+
21
+ jest.mock('../../../hooks/IoT', () => {
22
+ return {
23
+ ...jest.requireActual('../../../hooks/IoT'),
24
+ useWatchConfigs: jest.fn(),
25
+ };
26
+ });
27
+
28
+ jest.mock('../../../hooks/Common', () => {
29
+ return {
30
+ ...jest.requireActual('../../../hooks/Common'),
31
+ useHomeAssistantDeviceConnected: () => ({ isConnected: true }),
32
+ };
33
+ });
34
+
35
+ let store = mockSCStore({});
36
+
37
+ const navContextValue = {
38
+ isFocused: () => false,
39
+ addListener: jest.fn(() => jest.fn()),
40
+ };
41
+
42
+ const wrapComponent = (state, account, route) => (
43
+ <SCProvider initState={state}>
44
+ <NavigationContext.Provider
45
+ value={{
46
+ ...navContextValue,
47
+ isFocused: () => true,
48
+ }}
49
+ >
50
+ <DeviceDetail account={account} route={route} />
51
+ </NavigationContext.Provider>
52
+ </SCProvider>
53
+ );
54
+
55
+ const mockAlertShow = jest.fn();
56
+ Alert.alert = mockAlertShow;
57
+
58
+ describe('test DeviceDetail', () => {
59
+ let route;
60
+ let account;
61
+ const address = uuidv4();
62
+ const password = uuidv4();
63
+ const device = {
64
+ connect: jest.fn(() => Promise.resolve(device)),
65
+ discoverAllServicesAndCharacteristics: jest.fn(() =>
66
+ Promise.resolve(device)
67
+ ),
68
+ writeCharacteristicWithoutResponseForService: jest.fn(),
69
+ writeCharacteristicWithResponseForService: jest.fn(),
70
+ cancelConnection: jest.fn(),
71
+ readCharacteristicForService: jest.fn((service, characteristic) => ({
72
+ value: base64.encode('confirmed'),
73
+ })),
74
+ };
75
+ const bleManager = new BleManager();
76
+ bleManager.startDeviceScan.mockImplementation((uuids, options, handler) =>
77
+ handler(null, device)
78
+ );
79
+
80
+ beforeEach(() => {
81
+ device.connect.mockClear();
82
+ device.cancelConnection.mockClear();
83
+ device.discoverAllServicesAndCharacteristics.mockClear();
84
+ device.writeCharacteristicWithoutResponseForService.mockClear();
85
+ device.writeCharacteristicWithResponseForService.mockClear();
86
+ device.readCharacteristicForService.mockClear();
87
+
88
+ mock.onGet(API.DEVICE.DEVICE_DETAIL(1)).reply(200, {
89
+ id: 1,
90
+ is_enable_bluetooth: true,
91
+ remote_control_options: {
92
+ bluetooth: {
93
+ address,
94
+ password,
95
+ },
96
+ },
97
+ });
98
+
99
+ mock.onGet(API.DEVICE.DISPLAY(1)).reply(200, {
100
+ items: [
101
+ {
102
+ configuration: {
103
+ action1: '2b949045-8e03-4c07-a855-7794ade2e69c',
104
+ action1_data: {
105
+ color: '#00979D',
106
+ command_prefer_over_bluetooth: true,
107
+ command_prefer_over_googlehome: false,
108
+ command_prefer_over_internet: false,
109
+ googlehome_actions: [],
110
+ icon: 'caretup',
111
+ id: 9,
112
+ key: '2b949045-8e03-4c07-a855-7794ade2e69c',
113
+ arduino_action: {
114
+ value: 1,
115
+ pin: {
116
+ pin_number: 2,
117
+ },
118
+ },
119
+ },
120
+ action2: '38347d5e-4418-4ab0-978c-c82f4c034897',
121
+ action2_data: {
122
+ color: '#00979D',
123
+ command_prefer_over_bluetooth: false,
124
+ command_prefer_over_googlehome: false,
125
+ command_prefer_over_internet: true,
126
+ googlehome_actions: [],
127
+ icon: 'stop',
128
+ id: 11,
129
+ key: '38347d5e-4418-4ab0-978c-c82f4c034897',
130
+ },
131
+ action3: 'a492e08c-8cb1-44ee-8ea0-46aaca4e5141',
132
+ action3_data: {
133
+ color: '#00979D',
134
+ command_prefer_over_bluetooth: false,
135
+ command_prefer_over_googlehome: false,
136
+ command_prefer_over_internet: true,
137
+ googlehome_actions: [],
138
+ icon: 'caretdown',
139
+ id: 10,
140
+ key: 'a492e08c-8cb1-44ee-8ea0-46aaca4e5141',
141
+ },
142
+ icon1: 'caretup',
143
+ icon2: 'stop',
144
+ icon3: 'caretdown',
145
+ text1: 'UP',
146
+ text2: 'STOP/UNLOCK',
147
+ text3: 'DOWN',
148
+ },
149
+ id: 19,
150
+ order: 2,
151
+ template: 'three_button_action_template',
152
+ type: 'action',
153
+ },
154
+ ],
155
+ side_menu_items: [{ id: 1, order: 1, name: 'Setup generate passcode' }],
156
+ });
157
+ route = {
158
+ params: {
159
+ unitData: {
160
+ id: 1,
161
+ name: 'Unit name',
162
+ address: '298 Dien Bien Phu',
163
+ remote_control_options: {
164
+ googlehome: [
165
+ {
166
+ config_maps: [],
167
+ auth: {},
168
+ chip_id: 1,
169
+ },
170
+ ],
171
+ },
172
+ },
173
+ station: {
174
+ id: 2,
175
+ name: 'Station name',
176
+ },
177
+ sensorData: {
178
+ id: 1,
179
+ is_managed_by_backend: true,
180
+ station: { id: 2, name: 'Station name' },
181
+ name: 'Sensor name',
182
+ chip_id: 1,
183
+ },
184
+ title: 'Button',
185
+ },
186
+ };
187
+ account = {
188
+ token: 'abc',
189
+ };
190
+ jest.useFakeTimers();
191
+
192
+ const setState = jest.fn();
193
+ const useLayoutEffectSpy = jest.spyOn(React, 'useLayoutEffect');
194
+ useLayoutEffectSpy.mockImplementation(() => setState);
195
+ useWatchConfigs.mockReset();
196
+ });
197
+
198
+ it('scan bluetooth if available', async () => {
199
+ await render(wrapComponent(store, account, route));
200
+ jest.runAllTimers();
201
+ expect(bleManager.stopDeviceScan).toHaveBeenCalledTimes(2);
202
+ expect(bleManager.startDeviceScan).toHaveBeenCalledTimes(1);
203
+ expect(bleManager.startDeviceScan.mock.calls[0][0]).toEqual([address]);
204
+ });
205
+
206
+ it('connect to first device', async () => {
207
+ await render(wrapComponent(store, account, route));
208
+ jest.runAllTimers();
209
+ expect(bleManager.stopDeviceScan).toHaveBeenCalledTimes(2);
210
+ expect(device.connect).toHaveBeenCalledTimes(1);
211
+ expect(device.discoverAllServicesAndCharacteristics).toHaveBeenCalledTimes(
212
+ 1
213
+ );
214
+ expect(
215
+ device.writeCharacteristicWithoutResponseForService
216
+ ).toHaveBeenCalledTimes(1);
217
+ expect(
218
+ device.writeCharacteristicWithResponseForService
219
+ ).toHaveBeenCalledTimes(1);
220
+ expect(
221
+ base64.decode(
222
+ device.writeCharacteristicWithoutResponseForService.mock.calls[0][2]
223
+ )
224
+ ).toEqual('start');
225
+ const confirmMessage =
226
+ device.writeCharacteristicWithResponseForService.mock.calls[0][2];
227
+ expect(base64.decode(confirmMessage).substring(0, 7)).toEqual('confirm');
228
+ });
229
+
230
+ it('disconnect when leave screen', async () => {
231
+ const { unmount } = await render(wrapComponent(store, account, route));
232
+ jest.runAllTimers();
233
+ await act(async () => {
234
+ unmount();
235
+ });
236
+ expect(device.cancelConnection).toHaveBeenCalledTimes(1);
237
+ });
238
+
239
+ it('fail scan', async () => {
240
+ bleManager.startDeviceScan.mockImplementationOnce(
241
+ (uuids, options, handler) => handler('error', device)
242
+ );
243
+ await render(wrapComponent(store, account, route));
244
+ jest.runAllTimers();
245
+ expect(bleManager.stopDeviceScan).toHaveBeenCalledTimes(1);
246
+ expect(device.connect).toHaveBeenCalledTimes(0);
247
+ });
248
+
249
+ it('control arduino pin device', async () => {
250
+ const { root } = await render(wrapComponent(store, account, route));
251
+ jest.runAllTimers();
252
+ const button = root.findByProps({
253
+ accessibilityLabel: AccessibilityLabel.BUTTON_TEMPLATE_1,
254
+ });
255
+ device.writeCharacteristicWithResponseForService.mockClear();
256
+ device.writeCharacteristicWithoutResponseForService.mockClear();
257
+ await act(async () => {
258
+ await button.props.onPress();
259
+ });
260
+ expect(
261
+ device.writeCharacteristicWithResponseForService
262
+ ).toHaveBeenCalledTimes(1);
263
+ });
264
+
265
+ it('control arduino pin fail', async () => {
266
+ device.readCharacteristicForService.mockReturnValue({ value: 'wrong' });
267
+ const { root } = await render(wrapComponent(store, account, route));
268
+ jest.runAllTimers();
269
+ const button = root.findByProps({
270
+ accessibilityLabel: AccessibilityLabel.BUTTON_TEMPLATE_1,
271
+ });
272
+ device.writeCharacteristicWithResponseForService.mockClear();
273
+ device.writeCharacteristicWithoutResponseForService.mockClear();
274
+ await act(async () => {
275
+ await button.props.onPress();
276
+ });
277
+ expect(
278
+ device.writeCharacteristicWithResponseForService
279
+ ).toHaveBeenCalledTimes(0);
280
+ });
281
+
282
+ it('control after fail scan', async () => {
283
+ bleManager.startDeviceScan.mockImplementationOnce(
284
+ (uuids, options, handler) => handler('error', device)
285
+ );
286
+ const { root } = await render(wrapComponent(store, account, route));
287
+ jest.runAllTimers();
288
+ const button = root.findByProps({
289
+ accessibilityLabel: AccessibilityLabel.BUTTON_TEMPLATE_1,
290
+ });
291
+ device.writeCharacteristicWithResponseForService.mockClear();
292
+ device.writeCharacteristicWithoutResponseForService.mockClear();
293
+ await act(async () => {
294
+ await button.props.onPress();
295
+ });
296
+ expect(
297
+ device.writeCharacteristicWithResponseForService
298
+ ).toHaveBeenCalledTimes(0);
299
+ });
300
+ });
@@ -0,0 +1,135 @@
1
+ /* eslint-disable no-console */
2
+ // console log is required for debug, this feature has a lot of debugging
3
+ import { useCallback, useEffect, useRef, useState } from 'react';
4
+ import base64 from 'react-native-base64';
5
+ import { ScanMode } from 'react-native-ble-plx';
6
+ import md5 from 'md5';
7
+ import { bleManager } from '../../../utils/bluetooth';
8
+
9
+ const CHARACTERISTIC_CONFIRM_CODE_UUID = '6ee26cfb-b42f-43ae-9ecf-f70d84bbd64f';
10
+ const CHARACTERISTIC_CONTROL_UUID = 'f0e7aa38-e466-42af-b4c7-5e6ec5c9a614';
11
+
12
+ export const useBluetoothDevice = (device) => {
13
+ const serviceUuid = device?.remote_control_options?.bluetooth?.address;
14
+ const password = device?.remote_control_options?.bluetooth?.password;
15
+ const deviceRef = useRef(null);
16
+ const [isConnected, setIsConnected] = useState(false);
17
+
18
+ useEffect(() => {
19
+ // on unmount, disconnect bluetooth, so it can be reused again
20
+ return () => {
21
+ if (isConnected) {
22
+ deviceRef.current.cancelConnection();
23
+ }
24
+ };
25
+ }, [isConnected]);
26
+
27
+ const control = useCallback(
28
+ (action, data) => {
29
+ if (!isConnected) {
30
+ return;
31
+ }
32
+
33
+ const value =
34
+ data?.value === undefined ? action.arduino_action.value : data?.value;
35
+ const message = `${action.arduino_action.pin.pin_number};${value}`;
36
+
37
+ console.log('control', message);
38
+
39
+ deviceRef.current.writeCharacteristicWithResponseForService(
40
+ serviceUuid,
41
+ CHARACTERISTIC_CONTROL_UUID,
42
+ base64.encode(message)
43
+ );
44
+ },
45
+ [isConnected, serviceUuid]
46
+ );
47
+
48
+ const sendConfirmCode = useCallback(
49
+ async (instanceCode) => {
50
+ console.log(`sendConfirmCode ${instanceCode}`);
51
+ const confirmCode = md5(`${password}${instanceCode}`);
52
+
53
+ await deviceRef.current.writeCharacteristicWithResponseForService(
54
+ serviceUuid,
55
+ CHARACTERISTIC_CONFIRM_CODE_UUID,
56
+ base64.encode('confirm' + confirmCode)
57
+ );
58
+ const result = await deviceRef.current.readCharacteristicForService(
59
+ serviceUuid,
60
+ CHARACTERISTIC_CONFIRM_CODE_UUID
61
+ );
62
+ const resultText = base64.decode(result.value);
63
+ console.log(resultText);
64
+ if (resultText.includes('confirmed')) {
65
+ setIsConnected(true);
66
+ return true;
67
+ }
68
+ return false;
69
+ },
70
+ [password, serviceUuid]
71
+ );
72
+
73
+ const askInstanceCode = useCallback(async () => {
74
+ console.log('askInstanceCode');
75
+
76
+ await deviceRef.current.writeCharacteristicWithoutResponseForService(
77
+ serviceUuid,
78
+ CHARACTERISTIC_CONFIRM_CODE_UUID,
79
+ base64.encode('start')
80
+ );
81
+ const response = await deviceRef.current.readCharacteristicForService(
82
+ serviceUuid,
83
+ CHARACTERISTIC_CONFIRM_CODE_UUID
84
+ );
85
+ return base64.decode(response.value);
86
+ }, [serviceUuid]);
87
+
88
+ const realConnect = useCallback(async () => {
89
+ // return await new Promise((resolve) => {
90
+ if (!serviceUuid || !password) {
91
+ console.log('Bluetooth is not enabled for this device');
92
+ return false;
93
+ }
94
+ console.log('start real connect');
95
+ try {
96
+ bleManager.stopDeviceScan();
97
+ } catch (e) {
98
+ /* istanbul ignore next */
99
+ console.log('Failed to stop scan');
100
+ }
101
+ bleManager.startDeviceScan(
102
+ [serviceUuid],
103
+ { scanMode: ScanMode?.LowLatency },
104
+ // eslint-disable-next-line promise/prefer-await-to-callbacks
105
+ async (error, bleDevice) => {
106
+ if (error) {
107
+ console.log(error);
108
+ return false;
109
+ }
110
+ console.log(bleDevice?.name, bleDevice?.localName);
111
+
112
+ console.log('bleManager.stopDeviceScan');
113
+ bleManager.stopDeviceScan();
114
+ console.log('device.connect');
115
+ const connectedDevice = await bleDevice.connect({ timeout: 5000 });
116
+
117
+ console.log('device.discoverAllServicesAndCharacteristics');
118
+ const fullInfoDevice =
119
+ await connectedDevice.discoverAllServicesAndCharacteristics();
120
+ console.log('device.publicCodeCharacteristic');
121
+ deviceRef.current = fullInfoDevice;
122
+
123
+ const instanceCode = await askInstanceCode();
124
+ return await sendConfirmCode(instanceCode);
125
+ }
126
+ );
127
+ // });
128
+ }, [askInstanceCode, password, sendConfirmCode, serviceUuid]);
129
+
130
+ useEffect(() => {
131
+ realConnect();
132
+ }, [realConnect]);
133
+
134
+ return { control, isConnected };
135
+ };
@@ -33,6 +33,7 @@ const { standardizeWidth, standardizeHeight } = standardizeCameraScreenSize(
33
33
  export const SensorDisplayItem = ({
34
34
  item = {},
35
35
  sensor,
36
+ bluetoothDevice,
36
37
  emergency,
37
38
  offsetTitle,
38
39
  setOffsetTitle,
@@ -46,7 +47,7 @@ export const SensorDisplayItem = ({
46
47
  const { type, template, uri, id, name, title, value_evaluation } =
47
48
  configuration;
48
49
 
49
- const sendRemoteCommand = useRemoteControl();
50
+ const sendRemoteCommand = useRemoteControl(bluetoothDevice);
50
51
  const [processing, setProcessing] = useState(false);
51
52
  // eslint-disable-next-line no-unused-vars
52
53
  const [configValues, setConfigValues] = useConfigGlobalState('configValues');
@@ -114,12 +115,12 @@ export const SensorDisplayItem = ({
114
115
  }, [configValues, evaluate, evaluateValue, configuration, value_evaluation]);
115
116
 
116
117
  const doAction = useCallback(
117
- async (action, data, interrupted = false) => {
118
+ async (action, data, interrupted = false, silent = false) => {
118
119
  if (processing && !interrupted) {
119
120
  return;
120
121
  }
121
122
  setProcessing(true);
122
- await sendRemoteCommand(sensor, action, data, userId);
123
+ await sendRemoteCommand(sensor, action, data, userId, silent);
123
124
  setProcessing(false);
124
125
  },
125
126
  [processing, sendRemoteCommand, sensor, userId]