• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023-2023 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 wifi from '@ohos.wifi';
17import { Log } from '@ohos/common';
18import { print } from '@kit.BasicServicesKit';
19import { P2P_SERVICE_ERROR } from '@ohos/common';
20import CommonEventManager from '@ohos.commonEventManager';
21import ArrayList from '@ohos.util.ArrayList';
22
23const TAG = 'WifiModel';
24
25export class WifiModel {
26  public static readonly p2pPeerDeviceChange: string = 'p2pPeerDeviceChange';
27  public static readonly p2pConnectionChange: string = 'p2pConnectionChange';
28  public static readonly p2pStateChange: string = 'p2pStateChange';
29  private wifiListener: ArrayList<WifiListener> = new ArrayList<WifiListener>();
30  private wifiSubscriber;
31
32  constructor() {
33    this.registerWifiCommonEvent();
34  }
35
36  public addListener(listener: WifiListener): void {
37    if (!this.wifiListener.has(listener)) {
38      this.wifiListener.add(listener);
39    } else {
40      Log.error(TAG, 'listener is exist');
41    }
42  }
43
44  public removeListener(listener: WifiListener): void {
45    if (this.wifiListener.has(listener)) {
46      this.wifiListener.remove(listener);
47    } else {
48      Log.error(TAG, 'listener is not exist');
49    }
50  }
51
52  /**
53   *  register wifi common event;
54   */
55  private async registerWifiCommonEvent(): Promise<void> {
56    try {
57      this.wifiSubscriber = await CommonEventManager.createSubscriber({events:
58      [CommonEventManager.Support.COMMON_EVENT_WIFI_POWER_STATE, CommonEventManager.Support.COMMON_EVENT_WIFI_CONN_STATE,
59        CommonEventManager.Support.COMMON_EVENT_WIFI_P2P_CONN_STATE]});
60      CommonEventManager.subscribe(this.wifiSubscriber, (err, data) => {
61        if (err) {
62          Log.error(TAG, `subscribe failed, code is ${err.code}, message is ${err.message}`);
63        } else {
64          for (let wifiListener of this.wifiListener) {
65            wifiListener.onConnectionStateChanged(data);
66          }
67        }
68      });
69    } catch (error) {
70      Log.error(TAG, 'create subscriber fail: ' + JSON.stringify(error));
71    }
72  }
73
74  /**
75   * 获取当前设备连接信息
76   */
77  async getP2pLinkInfo(): Promise<wifi.WifiP2pLinkedInfo> {
78    return wifi.getP2pLinkedInfo() as Promise<wifi.WifiP2pLinkedInfo>;
79  }
80
81
82  registerWifiP2pEvent(event, callback): void {
83    wifi.on(event, callback);
84  }
85
86  unregisterWifiP2pEvent(event: string, callback?: (data) => void): void {
87    switch (event) {
88      case WifiModel.p2pPeerDeviceChange:
89        wifi.off('p2pPeerDeviceChange', callback);
90        break;
91      case WifiModel.p2pConnectionChange:
92        wifi.off('p2pConnectionChange', callback);
93        break;
94      case WifiModel.p2pStateChange:
95        wifi.off('p2pStateChange');
96        break;
97      default:
98        Log.error(TAG, 'error event: ' + event);
99    }
100  }
101
102  /**
103   * 开始发现p2p设备
104   */
105  discoveryP2pDevices(): boolean {
106    let result: boolean = <boolean>wifi.startDiscoverDevices();
107    if (!result) {
108      Log.error(TAG, `discoveryStatus is ${result}`);
109      //底层p2p服务未启动, 上报错误
110      print.updateExtensionInfo(JSON.stringify(P2P_SERVICE_ERROR));
111    }
112    return result;
113  }
114
115  stopDiscoveryP2pDevices(): boolean {
116    return wifi.stopDiscoverDevices() as boolean;
117  }
118
119  getP2pDevices(callback: (p2pDevices: wifi.WifiP2pDevice[]) => void): void {
120    wifi.getP2pPeerDevices().then((p2pDevices: wifi.WifiP2pDevice[]) => {
121      callback(p2pDevices);
122    }).catch((error) => {
123      Log.error(TAG, 'get p2p device failed: ' + JSON.stringify(error));
124    });
125  }
126
127  /**
128   * 连接打印机
129   *
130   * @param config
131   * @param callback
132   */
133  connectToPrinter(config): boolean {
134    Log.info(TAG, 'start to connect');
135    return <boolean>wifi.p2pConnect(config);
136  }
137
138  /**
139   * 断开打印机连接
140   *
141   * @param callback
142   */
143  disconnectToPrinter(): boolean {
144    Log.info(TAG, 'start to disconnect');
145    return <boolean>wifi.removeGroup();
146  }
147
148  stopConnection(): void {
149    Log.debug(TAG, 'stop Connection');
150    this.unregisterWifiP2pEvent(WifiModel.p2pConnectionChange);
151    wifi.p2pCancelConnect();
152  }
153
154  close(): void {
155    this.unregisterWifiP2pEvent(WifiModel.p2pPeerDeviceChange);
156    this.stopConnection();
157    if (this.wifiSubscriber !== undefined) {
158      CommonEventManager.unsubscribe(this.wifiSubscriber);
159    }
160  }
161}
162
163
164export interface WifiListener {
165  onConnectionStateChanged(data): void;
166}