• 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 hilog from '../model/Logger'
17import promptAction from '@ohos.promptAction'
18import wifi from '@ohos.wifiManager'
19import router from '@ohos.router'
20
21const TAG = 'WifiConnect'
22@Entry
23@Component
24struct WifiConnect {
25  ssid: string = ''
26  password: string = ''
27  selectedSecurityType: wifi.WifiSecurityType = wifi.WifiSecurityType.WIFI_SEC_TYPE_INVALID
28  private linkedInfo: wifi.WifiLinkedInfo | null = null;
29  @State isLinked: boolean = false;
30  @State isSwitchOn: boolean = false;
31  @State wifiCandidateConfig: wifi.WifiDeviceConfig = {
32    ssid: '',
33    bssid: '',
34    preSharedKey: '',
35    isHiddenSsid: false,
36    securityType: 0
37  }
38  private controller: CustomDialogController | null = null;
39
40  async connectwifi(deviceConfig: wifi.WifiDeviceConfig) {
41    try {
42      promptAction.showToast({ message : 'connect to wifi' })
43      hilog.info(`connectwifi failed err is ${JSON.stringify(deviceConfig)}`);
44      wifi.addCandidateConfig(deviceConfig).then(result => {
45        // 连接指定网络
46        wifi.connectToCandidateConfig(result);
47        this.getLinkedInfo()
48      });
49    }catch(error){
50      hilog.error('sun failed:' + JSON.stringify(error));
51    }
52  }
53
54  async getLinkedInfo() {
55    try {
56      let wifiLinkedInfo = await wifi.getLinkedInfo();
57      if (wifiLinkedInfo === null || wifiLinkedInfo.bssid === '') {
58        this.isLinked = false;
59        this.linkedInfo = null;
60        return;
61      }
62      this.isLinked = true;
63      this.linkedInfo = wifiLinkedInfo;
64    } catch (err) {
65      hilog.info(`getLinkedInfo failed err is ${JSON.stringify(err)}`);
66    }
67  }
68
69  addListener() {
70    // 连接状态改变时,修改连接信息
71    wifi.on('wifiConnectionChange', async state => {
72      hilog.info(TAG, `wifiConnectionChange: ${state}`);
73      await this.getLinkedInfo();
74    })
75  }
76
77  aboutToAppear() {
78    // 如果wifi是开的,就记录下状态,然后扫描wifi,并获取连接信息
79    if (wifi.isWifiActive()) {
80      hilog.info(TAG, 'wifi is active');
81      this.isSwitchOn = true;
82    }
83    hilog.info(TAG, 'wifi is disabled');
84    // 启动监听
85    this.addListener();
86  }
87
88  build() {
89    Column() {
90          Column() {
91            Row() {
92              Text('ssid').fontSize('16fp').width('18%')
93              TextInput({ placeholder: $r('app.string.input_candidate_wifi_ssid') })
94                .placeholderColor(Color.Grey)
95                .placeholderFont({ size: '16fp' })
96                .caretColor(Color.Blue)
97                .width('80%')
98                .fontSize('16fp')
99                .fontColor($r('app.color.title_black_color'))
100                .onChange((value: string) => {
101                  this.wifiCandidateConfig.ssid = value;
102                })
103            }
104            .width('100%')
105            .margin({ top: '3%' })
106
107            // .height( CommonConstants.TEXT_INPUT_HEIGHT )
108            // .backgroundColor( $r( 'app.color.input_background' ) )
109            Row() {
110              Text('bssid').fontSize('16fp').width('18%')
111              TextInput({ placeholder: $r('app.string.input_candidate_wifi_bssid') })
112                .placeholderColor(Color.Grey)
113                .placeholderFont({ size: '16fp' })
114                .caretColor(Color.Blue)
115                .width('80%')
116                .fontSize('16fp')
117                .fontColor($r('app.color.title_black_color'))
118                .onChange((value: string) => {
119                  this.wifiCandidateConfig.bssid = value;
120                })
121            }
122            .width('100%')
123            .margin({ top: '3%' })
124
125            Row() {
126              Text('preSharedKey').fontSize('16fp').width('28%')
127              TextInput({ placeholder: $r('app.string.input_candidate_wifi_preSharedKey') })
128                .placeholderColor(Color.Grey)
129                .placeholderFont({ size: '16fp' })
130                .caretColor(Color.Blue)
131                .width('70%')
132                .fontSize('16fp')
133                .fontColor($r('app.color.title_black_color'))
134                .onChange((value: string) => {
135                  this.wifiCandidateConfig.preSharedKey = value;
136                })
137            }
138            .width('100%')
139            .margin({ top: '3%' })
140
141
142            Row() {
143              Text('isHiddenSsid').fontSize('16fp').width('28%')
144              TextInput({ placeholder: $r('app.string.input_candidate_wifi_isHiddenSsid') })
145                .placeholderColor(Color.Grey)
146                .placeholderFont({ size: '16fp' })
147                .caretColor(Color.Blue)
148                .width('70%')
149                .fontSize('16fp')
150                .fontColor($r('app.color.title_black_color'))
151                .onChange((value: string) => {
152                  this.wifiCandidateConfig.isHiddenSsid = parseInt(value, 10) === 1;
153                })
154            }
155            .width('100%')
156            .margin({ top: '3%' })
157
158            Row() {
159              Text('securityType').fontSize('16fp').width('28%')
160              Column() {
161                Select([
162                  { value: 'WIFI_SEC_TYPE_INVALID' },
163                  { value: 'WIFI_SEC_TYPE_OPEN' },
164                  { value: 'WIFI_SEC_TYPE_PSK' },
165                  { value: 'WIFI_SEC_TYPE_SAE' }
166                ])
167                  .fontColor($r('app.color.title_black_color'))
168                  .optionBgColor($r('app.color.input_background'))
169                  .selectedOptionBgColor($r('app.color.input_background'))
170                  .selectedOptionFontColor($r('app.color.input_background'))
171                  .selected(0)
172                  .value('WIFI_SEC_TYPE_INVALID')
173                  .font({ size: 16 })
174                  .selectedOptionFont({ size: 17 })
175                  .optionFont({ size: 15 })
176                  .width('100%')
177                  .onSelect((index: number) => {
178                    this.wifiCandidateConfig.securityType = index;
179                  })
180              }
181              .width('70%')
182              .borderRadius(1)
183            }
184            .justifyContent(FlexAlign.Start)
185            .alignItems(VerticalAlign.Center)
186            .width('100%')
187            .margin({ top: '3%' })
188
189            Row() {
190              Button($r('app.string.confirm_button'))// .dialogButtonStyle()
191                .onClick(() => {
192                  if(this.wifiCandidateConfig.ssid === '' || this.wifiCandidateConfig.preSharedKey === '') {
193                    hilog.info(TAG, 'ssid || preSharedKey is null');
194                    promptAction.showToast({ message : 'ssid or preSharedKey is null' })
195                    return;
196                  }
197                  this.connectwifi(this.wifiCandidateConfig);
198                })
199                .height('100%')
200            }
201            .width('70')
202            .height('6%')
203            .justifyContent(FlexAlign.SpaceBetween)
204          }
205        }
206      }
207  }