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