• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/**
2 * Copyright (c) 2025 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 promptAction from '@ohos.promptAction';
17import hilog from '../model/Logger';
18import wifi from '@ohos.wifiManager';
19import { P2pView } from '../component/P2pView';
20
21const TAG = 'availableP2p';
22
23/**
24 * available p2p page of WiFi test
25 */
26@Entry
27@Component
28struct WifiConnect {
29  @State p2pList: Array<wifi.WifiP2pDevice> = []
30  @State p2pLinkedInfo: wifi.WifiP2pLinkedInfo | null = null;
31  private selectIndex: number = - 1
32  @State isSwitchOn: boolean = false;
33
34  addListener() {
35    // 连接状态改变时,修改连接信息
36    hilog.info(TAG, 'addListener');
37    wifi.on('p2pConnectionChange', async wifiP2pLinkedInfo => {
38      hilog.info('p2p connection change receive event: ' + JSON.stringify(wifiP2pLinkedInfo));
39      this.p2pLinkedInfo = wifiP2pLinkedInfo
40      let connectState = wifiP2pLinkedInfo.connectState
41      let p2pConnectionMessage = ''
42      switch ( connectState ) {
43        case 0:
44          p2pConnectionMessage = 'DISCONNECTED!';
45          this.p2pLinkedInfo = null
46          promptAction.showToast({ message : 'connect disabled' })
47          break;
48        case 1:
49          p2pConnectionMessage = 'CONNECTED!';
50          promptAction.showToast({ message : 'connect success' })
51          let curGp = await wifi.getCurrentGroup()
52          AppStorage.setOrCreate('p2pLinkedDeviceName', curGp.groupName)
53          break;
54        default:
55          p2pConnectionMessage = '未知状态';
56          break;
57      }
58      AppStorage.setOrCreate('p2pConnectState', connectState)
59    })
60
61      wifi.on('p2pPeerDeviceChange', async (_: wifi.WifiP2pDevice[]) => {
62      hilog.info(TAG, 'p2pPeerDeviceChange:', JSON.stringify(_))
63      try {
64        let devices = await wifi.getP2pPeerDevices()
65        this.p2pList = devices
66      } catch (e) {
67        hilog.info(JSON.stringify(e))
68      }
69    })
70  }
71
72  aboutToAppear() {
73    // 如果wifi是开的,就记录下状态,然后扫描p2p设备,并获取连接信息
74    if (!wifi.isWifiActive()) {
75      promptAction.showToast({ message : 'place active wifi' })
76      return
77    }
78    this.isSwitchOn = true;
79    wifi.startDiscoverDevices()
80    this.addListener();
81  }
82
83  aboutToDisappear() {
84    wifi.off('p2pPeerDeviceChange')
85    wifi.off('p2pConnectionChange')
86  }
87
88
89  connectP2p(p2pScanInfo: wifi.WifiP2pDevice) {
90    promptAction.showToast({ message : 'connect to device' })
91    hilog.info(TAG , `connect deviceAddress=${ p2pScanInfo.deviceAddress }`)
92    hilog.info(TAG , `p2pScanInfo:` + JSON.stringify(p2pScanInfo))
93    let config: wifi.WifiP2PConfig = {
94      deviceAddress : p2pScanInfo.deviceAddress,
95      netId : - 2 ,
96      deviceAddressType: 1,
97      passphrase : '' ,
98      groupName : '' ,
99      goBand : 0
100    }
101    wifi.p2pConnect(config)
102  }
103
104
105  build() {
106    Column() {
107      Row() {
108        Text($r('app.string.p2p_available'))
109          .fontSize(22)
110          .fontWeight(FontWeight.Bold)
111          .height(40)
112      }
113      .width('100%')
114      .padding({ left: 16, right: 16 })
115
116      List({ space: 5 }) {
117        ForEach(this.p2pList , (item: wifi.WifiP2pDevice , index: number) => {
118          ListItem() {
119            P2pView({ p2p : item })
120          }
121          .onClick(() => {
122            hilog.info(TAG , 'p2p click')
123            this.selectIndex = index
124            if ( this.p2pLinkedInfo !== null && this.p2pLinkedInfo.connectState == 1 ) {
125              promptAction.showToast({ message : 'this p2p is connected' })
126              return
127            }
128            this.connectP2p(item)
129          })
130        } , (item: wifi.WifiP2pDevice) => JSON.stringify(item));
131      }
132      .layoutWeight(1)
133      .divider({ strokeWidth : 1 , color : Color.Gray , startMargin : 10 , endMargin : 10 })
134      .margin(10)
135    }
136    .margin({ top : 15 , bottom : 100 })
137  }
138}