• 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.distributedHardware.deviceManager'
17import { logger } from '../model/Logger'
18
19var SUBSCRIBE_ID = 100
20const TAG = 'RemoteDeviceModel'
21
22export default class RemoteDeviceModel {
23  deviceList = []
24  discoverList = []
25  callback
26  authCallback = null
27  #deviceManager
28
29  constructor() {
30  }
31
32  registerDeviceListCallback(callback) {
33    if (typeof (this.#deviceManager) === 'undefined') {
34      logger.info(TAG, `deviceManager.createDeviceManager begin`)
35      try {
36        deviceManager.createDeviceManager('ohos.samples.distributedmusicplayer', (error, value) => {
37          if (error) {
38            logger.error(TAG, `createDeviceManager failed.`)
39            return
40          }
41          this.#deviceManager = value
42          this.registerDeviceListCallback_(callback)
43          logger.info(TAG, `createDeviceManager callback returned, error=${error} value=${value}`)
44        })
45      } catch (error) {
46        logger.info(TAG, `createDeviceManager throw error, error=${error} message=${error.message}`)
47      }
48      logger.info(TAG, `deviceManager.createDeviceManager end`)
49    } else {
50      this.registerDeviceListCallback_(callback)
51    }
52  }
53
54  registerDeviceListCallback_(callback) {
55    logger.info(TAG, `registerDeviceListCallback`)
56    this.callback = callback
57    if (this.#deviceManager == undefined) {
58      logger.error(TAG, `deviceManager has not initialized`)
59      this.callback()
60      return
61    }
62
63    logger.info(TAG, `getTrustedDeviceListSync begin`)
64    try {
65      var list = this.#deviceManager.getTrustedDeviceListSync()
66      logger.debug(TAG, `getTrustedDeviceListSync end, deviceList=${JSON.stringify(list)}`)
67      if (typeof (list) != 'undefined' && typeof (list.length) != 'undefined') {
68        this.deviceList = list
69      }
70    } catch (error) {
71      logger.info(TAG, `getTrustedDeviceListSync throw error, error=${error} message=${error.message}`)
72    }
73
74    this.callback()
75    logger.info(TAG, `callback finished`)
76    try {
77      this.#deviceManager.on('deviceStateChange', (data) => {
78        logger.debug(TAG, `deviceStateChange data=${JSON.stringify(data)}`)
79        switch (data.action) {
80          case deviceManager.DeviceStateChangeAction.READY:
81            this.discoverList = []
82            this.deviceList.push(data.device)
83            logger.debug(TAG, `ready, updated device list=${JSON.stringify(this.deviceList)}`)
84            try {
85              let list = this.deviceManager.getTrustedDeviceListSync()
86              logger.debug(TAG, `getTrustedDeviceListSync end, deviceList=${JSON.stringify(list)}`)
87              if (typeof (list) !== 'undefined' && typeof (list.length) !== 'undefined') {
88                this.deviceList = list
89              }
90            } catch (error) {
91              logger.error(TAG, `getTrustedDeviceListSync throw error,  error.code=${JSON.stringify(error)}`)
92            }
93            this.callback()
94            break
95          case deviceManager.DeviceStateChangeAction.OFFLINE:
96            if (this.deviceList.length > 0) {
97              let list = []
98              for (let j = 0; j < this.deviceList.length; j++) {
99                if (this.deviceList[j].deviceId !== data.device.deviceId) {
100                  list[j] = data.device
101                }
102              }
103              this.deviceList = list
104            }
105            logger.debug(TAG, `offline, updated device list=${JSON.stringify(data.device)}`)
106            this.callback()
107            break
108          default:
109            break
110        }
111      })
112      this.#deviceManager.on('deviceFound', (data) => {
113        this.discoverList = [];
114        logger.debug(TAG, `deviceFound data=${JSON.stringify(data)} deviceList=${this.deviceList} length=${this.deviceList.length}`)
115        for (var i = 0; i < this.discoverList.length; i++) {
116          if (this.discoverList[i].deviceId === data.device.deviceId) {
117            logger.info(TAG, `device founded, ignored`)
118            return
119          }
120        }
121        this.discoverList[this.discoverList.length] = data.device
122        this.callback()
123      })
124      this.#deviceManager.on('discoverFail', (data) => {
125        logger.debug(TAG, `discoverFail data=${JSON.stringify(data)}`)
126      })
127      this.#deviceManager.on('serviceDie', () => {
128        logger.error(TAG, `serviceDie`)
129      })
130    } catch (error) {
131      logger.info(TAG, `on throw error, error=${error} message=${error.message}`)
132    }
133
134
135    SUBSCRIBE_ID = Math.floor(65536 * Math.random())
136    var info = {
137      subscribeId: SUBSCRIBE_ID,
138      mode: 0xAA,
139      medium: 2,
140      freq: 2,
141      isSameAccount: false,
142      isWakeRemote: true,
143      capability: 0
144    }
145    logger.debug(`startDeviceDiscovery ${SUBSCRIBE_ID}`)
146    try {
147      this.#deviceManager.startDeviceDiscovery(info)
148    } catch (error) {
149      logger.info(TAG, `startDeviceDiscovery throw error, error=${error} message=${error.message}`)
150    }
151  }
152
153  authDevice(deviceId, callback) {
154    logger.debug(TAG, `authDevice ${deviceId}`)
155    for (var i = 0; i < this.discoverList.length; i++) {
156      if (this.discoverList[i].deviceId === deviceId) {
157        logger.info(TAG, `device founded, ignored`)
158        let extraInfo = {
159          "targetPkgName": 'ohos.samples.distributedmusicplayer',
160          "appName": 'Music',
161          "appDescription": 'Music player application',
162          "business": '0'
163        }
164        let authParam = {
165          "authType": 1,
166          "appIcon": '',
167          "appThumbnail": '',
168          "extraInfo": extraInfo
169        }
170        logger.debug(TAG, `authenticateDevice ${JSON.stringify(this.discoverList[i])}`)
171        try {
172          this.#deviceManager.authenticateDevice(this.discoverList[i], authParam, (err, data) => {
173            if (err) {
174              logger.error(TAG, `authenticateDevice failed, err=${JSON.stringify(err)}`)
175              this.authCallback = null
176            } else {
177              logger.debug(TAG, `authenticateDevice succeed, data=${JSON.stringify(data)}`)
178              this.authCallback = callback
179            }
180          })
181        } catch (error) {
182          logger.info(TAG, `authenticateDevice throw error, error=${error} message=${error.message}`)
183        }
184      }
185    }
186  }
187
188  unregisterDeviceListCallback() {
189    logger.debug(TAG, `stopDeviceDiscovery ${SUBSCRIBE_ID}`)
190    if (typeof (this.#deviceManager) === 'undefined') {
191      return
192    }
193    try {
194      this.#deviceManager.stopDeviceDiscovery(SUBSCRIBE_ID)
195      this.#deviceManager.off('deviceStateChange')
196      this.#deviceManager.off('deviceFound')
197      this.#deviceManager.off('discoverFail')
198      this.#deviceManager.off('serviceDie')
199      this.deviceList = []
200    } catch (error) {
201      logger.info(TAG, `stopDeviceDiscovery throw error, error=${error} message=${error.message}`)
202    }
203  }
204}