• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import deviceManager from '@ohos.distributedDeviceManager'
17import { logger } from './Logger'
18
19let SUBSCRIBE_ID = 100
20let TAG = 'RemoteDeviceModel'
21
22export default class RemoteDeviceModel {
23  deviceList = []
24  discoverList = []
25  callback
26  authCallback
27  deviceManager = undefined
28
29  registerDeviceListCallback(callback) {
30    logger.info(TAG, `deviceManager type =${typeof (this.deviceManager)} ,${JSON.stringify(this.deviceManager)} ,${JSON.stringify(this.deviceManager) === '{}'}`)
31    if (typeof (this.deviceManager) !== 'undefined') {
32      this.registerDeviceListCallback_(callback)
33      return
34    }
35    logger.info(TAG, `deviceManager is null begin`)
36    logger.info(TAG, `deviceManager.createDeviceManager begin`)
37    try {
38      this.deviceManager = deviceManager.createDeviceManager("ohos.samples.distributedcalc")
39      this.registerDeviceListCallback_(callback)
40      logger.info(TAG, `createDeviceManager callback returned, value=${JSON.stringify(this.deviceManager)}`)
41    } catch (error) {
42      logger.error(TAG, `createDeviceManager throw error,  error.code=${JSON.stringify(error.code)} , errorMessage=${error.message}`)
43    }
44    logger.info(TAG, `deviceManager.createDeviceManager end`)
45  }
46
47  changeState(device, state) {
48    if (this.deviceList.length <= 0) {
49      this.callback()
50      return
51    }
52    if (state === deviceManager.DeviceStateChange.AVAILABLE) {
53      let list = new Array()
54      for (let i = 0;i < this.deviceList.length; i++) {
55        if (this.deviceList[i].deviceId !== device.deviceId) {
56          list[i] = device
57        }
58      }
59      this.deviceList = list
60      logger.debug(TAG, `ready, device list = ${JSON.stringify(device)}`)
61      this.callback()
62    } else {
63      for (let j = 0; j < this.deviceList.length; j++) {
64        if (this.deviceList[j].deviceId === device.deviceId) {
65          this.deviceList[j] = device
66          break
67        }
68      }
69      logger.debug(TAG, `offline, device list= ${JSON.stringify(this.deviceList)}`)
70      this.callback()
71    }
72  }
73
74  changeStateOnline(device) {
75    this.deviceList[this.deviceList.length] = device
76    logger.debug(TAG, `online, device list= ${JSON.stringify(this.deviceList)}`)
77    this.callback()
78    if (this.authCallback !== null) {
79      this.authCallback()
80      this.authCallback = null
81    }
82  }
83
84  changeStateOffline(device) {
85    if (this.deviceList.length > 0) {
86      let list = []
87      for (let j = 0; j < this.deviceList.length; j++) {
88        if (this.deviceList[j].deviceId !== device.deviceId) {
89          list[j] = device
90        }
91      }
92      this.deviceList = list
93    }
94    logger.info(TAG, `offline, updated device list=${JSON.stringify(device)}`)
95    this.callback()
96  }
97
98  registerDeviceListCallback_(callback) {
99    logger.info(TAG, `registerDeviceListCallback`)
100    this.callback = callback
101    if (this.deviceManager === undefined) {
102      logger.error(TAG, `deviceManager has not initialized`)
103      this.callback()
104      return
105    }
106
107    logger.info(TAG, `getTrustedDeviceListSync begin`)
108    try {
109      let list = this.deviceManager.getAvailableDeviceListSync()
110      logger.info(TAG, `getTrustedDeviceListSync end, list=${JSON.stringify(list)}`)
111      if (typeof (list) !== 'undefined' && JSON.stringify(list) !== '[]') {
112        this.deviceList = list
113      }
114      logger.info(TAG, `getTrustedDeviceListSync end, deviceList=${JSON.stringify(list)}`)
115    } catch (error) {
116      logger.error(TAG, `getTrustedDeviceListSync throw error,  error.code=${JSON.stringify(error.code)} , errorMessage=${error.message}`)
117    }
118    this.callback()
119    logger.info(TAG, `getTrustedDeviceListSync end, callback finished`)
120    try {
121      this.deviceManager.on('deviceStateChange', (data) => {
122        logger.info(TAG, `deviceStateChange data=${JSON.stringify(data)}`)
123        switch (data.action) {
124          case deviceManager.DeviceStateChange.AVAILABLE:
125            this.changeState(data.device, deviceManager.DeviceStateChange.AVAILABLE)
126            break
127          case deviceManager.DeviceStateChange.UNKNOWN:
128            this.changeStateOnline(data.device)
129            break
130          case deviceManager.DeviceStateChange.UNKNOWN:
131            this.changeStateOffline(data.device)
132            break
133          default:
134            break
135        }
136      })
137      this.deviceManager.on('discoverSuccess', (data) => {
138        if (data === null) {
139          return
140        }
141        this.discoverList = [];
142        logger.info(TAG, `deviceFound data=${JSON.stringify(data)}`)
143        logger.info(TAG, `deviceFound this.discoverList=${JSON.stringify(this.discoverList)}`)
144        this.deviceFound(data)
145      })
146      this.deviceManager.on('discoverFailure', (data) => {
147        logger.info(TAG, `discoverFail data=${JSON.stringify(data)}`)
148      })
149      this.deviceManager.on('serviceDie', () => {
150        logger.error(TAG, `serviceDie`)
151      })
152    } catch (error) {
153      logger.error(TAG, `on throw error,  error.code=${JSON.stringify(error)}`)
154    }
155    this.startDeviceDiscovery()
156  }
157
158  deviceFound(data) {
159    for (let i = 0; i < this.discoverList.length; i++) {
160      if (this.discoverList[i].deviceId === data.device.deviceId) {
161        logger.info(TAG, `device founded ignored`)
162        return
163      }
164    }
165    this.discoverList[this.discoverList.length] = data.device
166    logger.info(TAG, `deviceFound this.discoverList=${JSON.stringify(this.discoverList)}`)
167    this.callback()
168  }
169
170  /**
171   * 通过SUBSCRIBE_ID搜索分布式组网内的设备
172   */
173  startDeviceDiscovery() {
174    SUBSCRIBE_ID = Math.floor(65536 * Math.random()) // Generate a random number
175    let discoverParam = {
176      'discoverTargetType': 1
177    }
178    let filterOptions = {
179      availableStatus: 0
180    }
181    logger.debug(TAG, `startDeviceDiscovery ${SUBSCRIBE_ID}`)
182    try {
183      this.deviceManager.startDiscovering(discoverParam, filterOptions)
184    } catch (error) {
185      logger.error(TAG, `startDeviceDiscovery throw error,  error.code=${JSON.stringify(error.code)} , errorMessage=${error.message}`)
186    }
187  }
188
189  unregisterDeviceListCallback() {
190    logger.debug(TAG, `stopDeviceDiscovery ${SUBSCRIBE_ID}`)
191    if (this.deviceManager === undefined) {
192      return
193    }
194    try {
195      this.deviceManager.stopDiscovering()
196      this.deviceManager.off('deviceStateChange')
197      this.deviceManager.off('discoverSuccess')
198      this.deviceManager.off('discoverFailure')
199      this.deviceManager.off('serviceDie')
200      this.deviceList = []
201    } catch (error) {
202      logger.error(TAG, `throw error, error.code=${JSON.stringify(error.code)} , errorMessage=${error.message}`)
203    }
204  }
205
206  authenticateDevice(device, callBack) {
207    logger.debug(TAG, `authenticateDevice ${JSON.stringify(device)}`)
208    for (let i = 0; i < this.discoverList.length; i++) {
209      if (this.discoverList[i].deviceId === device.deviceId) {
210        let extraInfo = {
211          'targetPkgName': 'ohos.samples.distributedcalc',
212          'appName': 'Distributed Calc',
213          'appDescription': 'Distributed Calc',
214          'business': '0'
215        }
216        let authParam = {
217          'authType': 1,
218          'extraInfo': extraInfo
219        }
220        let bindParam = {
221          "bindLevel": 3,
222          "bindType": 1,
223          "appName": 'Distributed Calc',
224          "targetPkgName": 'ohos.samples.distributedcalc',
225        }
226        if (this.deviceManager === undefined) {
227          return
228        }
229        try {
230          this.deviceManager.bindTarget(device.deviceId, bindParam, (err, data) => {
231            if (err) {
232              logger.error(TAG, `authenticateDevice error.code=${JSON.stringify(err.code)} , errorMessage=${err.message}`)
233              this.authCallback = null
234              return
235            }
236            logger.info(TAG, `authenticateDevice succeed:${JSON.stringify(data)}`)
237            this.authCallback = callBack
238          })
239        } catch (error) {
240          logger.error(TAG, `authenticateDevice throw error.code=${JSON.stringify(error.code)} , errorMessage=${error.message}`)
241        }
242      }
243    }
244  }
245}