• 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 '../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        let dmInstance = deviceManager.createDeviceManager('ohos.samples.distributedmusicplayer');
37        logger.info(TAG, `dmInstance= ${JSON.stringify (dmInstance)}`)
38        this.#deviceManager = dmInstance
39        this.registerDeviceListCallback_(callback)
40        logger.info(TAG, `createDeviceManager callback returned, value= ${JSON.stringify(this.#deviceManager)}`)
41      } catch (error) {
42        logger.info(TAG, `createDeviceManager throw error, error=${error} message=${error.message}`)
43      }
44      logger.info(TAG, `deviceManager.createDeviceManager end`)
45    } else {
46      this.registerDeviceListCallback_(callback)
47    }
48  }
49
50  registerDeviceListCallback_(callback) {
51    logger.info(TAG, `registerDeviceListCallback`)
52    this.callback = callback
53    if (this.#deviceManager == undefined) {
54      logger.error(TAG, `deviceManager has not initialized`)
55      this.callback()
56      return
57    }
58
59    logger.info(TAG, `getTrustedDeviceListSync begin`)
60    try {
61      var list = this.#deviceManager.getAvailableDeviceListSync()
62      logger.debug(TAG, `getTrustedDeviceListSync end, deviceList=${JSON.stringify(list)}`)
63      if (typeof (list) != 'undefined' && typeof (list.length) != 'undefined') {
64        this.deviceList = list
65      }
66    } catch (error) {
67      logger.info(TAG, `getTrustedDeviceListSync throw error, error=${error} message=${error.message}`)
68    }
69
70    this.callback()
71    logger.info(TAG, `callback finished`)
72    try {
73      this.#deviceManager.on('deviceStateChange', (data) => {
74        logger.debug(TAG, `deviceStateChange data=${JSON.stringify(data)}`)
75        switch (data.action) {
76          case deviceManager.DeviceStateChange.AVAILABLE:
77            this.discoverList = []
78            this.deviceList.push(data.device)
79            logger.debug(TAG, `ready, updated device list=${JSON.stringify(this.deviceList)}`)
80            try {
81              let list = this.deviceManager.getAvailableDeviceListSync()
82              logger.debug(TAG, `getTrustedDeviceListSync end, deviceList=${JSON.stringify(list)}`)
83              if (typeof (list) !== 'undefined' && typeof (list.length) !== 'undefined') {
84                this.deviceList = list
85              }
86            } catch (error) {
87              logger.error(TAG, `getTrustedDeviceListSync throw error,  error.code=${JSON.stringify(error)}`)
88            }
89            this.callback()
90            break
91          case deviceManager.DeviceStateChange.UNAVAILABLE:
92            if (this.deviceList.length > 0) {
93              let list = []
94              for (let j = 0; j < this.deviceList.length; j++) {
95                if (this.deviceList[j].deviceId !== data.device.deviceId) {
96                  list[j] = data.device
97                }
98              }
99              this.deviceList = list
100            }
101            logger.debug(TAG, `offline, updated device list=${JSON.stringify(data.device)}`)
102            this.callback()
103            break
104          default:
105            break
106        }
107      })
108      this.#deviceManager.on('discoverSuccess', (data) => {
109        this.discoverList = [];
110        logger.debug(TAG, `discoverSuccess data=${JSON.stringify(data)} deviceList=${this.deviceList} length=${this.deviceList.length}`)
111        for (var i = 0; i < this.discoverList.length; i++) {
112          if (this.discoverList[i].deviceId === data.device.deviceId) {
113            logger.info(TAG, `device founded, ignored`)
114            return
115          }
116        }
117        this.discoverList[this.discoverList.length] = data.device
118        this.callback()
119      })
120      this.#deviceManager.on('discoverFailure', (data) => {
121        logger.debug(TAG, `discoverFailure data=${JSON.stringify(data)}`)
122      })
123      this.#deviceManager.on('serviceDie', () => {
124        logger.error(TAG, `serviceDie`)
125      })
126    } catch (error) {
127      logger.info(TAG, `on throw error, error=${error} message=${error.message}`)
128    }
129
130
131    let discoverParam = {
132      'discoverTargetType': 1
133    };
134    let filterOptions = {
135      'availableStatus': 0
136    };
137    logger.info(TAG, `startDiscovering${SUBSCRIBE_ID}`)
138    try {
139      if (this.deviceManager !== null) {
140        this.#deviceManager.startDiscovering(discoverParam, filterOptions)
141      }
142    } catch (error) {
143      logger.error(TAG, `startDiscovering throw code:${error.code} message:${error.message}`)
144    }
145  }
146
147  authDevice(deviceId, callback) {
148    logger.debug(TAG, `authDevice ${deviceId}`)
149    for (let i = 0; i < this.discoverList.length; i++) {
150      if (this.discoverList[i].deviceId !== deviceId) {
151        continue
152      }
153      if (this.#deviceManager === undefined) {
154        logger.info(TAG, 'this.#deviceManager is undefinded')
155        return
156      }
157      logger.debug(TAG, `authenticateDevice ${JSON.stringify(this.discoverList[i])}`)
158      try {
159        if (this.deviceManager !== null) {
160          this.#deviceManager.bindTarget(deviceId, {
161            bindLevel: 3,
162            bindType: 1,
163            targetPkgName: 'ohos.samples.distributedmusicplayer',
164            appName: 'Music',
165          }, (err, data) => {
166            if (err) {
167              logger.error(TAG, `authenticateDevice error: ${JSON.stringify(err)}`)
168              this.authCallback = () => {
169              }
170              return
171            }
172            logger.debug(TAG, `authenticateDevice succeed: ${JSON.stringify(data)}`)
173            this.authCallback = callback
174          })
175        }
176      } catch (error) {
177        logger.error(TAG, `authenticateDevice throw throw code:${error.code} message:${error.message}`)
178      }
179    }
180  }
181
182  unregisterDeviceListCallback() {
183    logger.debug(TAG, `stopDeviceDiscovery ${SUBSCRIBE_ID}`)
184    if (typeof (this.#deviceManager) === 'undefined') {
185      return
186    }
187    try {
188      this.#deviceManager.stopDiscovering(SUBSCRIBE_ID)
189      this.#deviceManager.off('deviceStateChange')
190      this.#deviceManager.off('discoverSuccess')
191      this.#deviceManager.off('discoverFailure')
192      this.#deviceManager.off('serviceDie')
193      this.deviceList = []
194    } catch (error) {
195      logger.info(TAG, `stopDeviceDiscovery throw error, error=${error} message=${error.message}`)
196    }
197  }
198}