1 /*
2  * Copyright (C) 2021-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 
16 #include "p2p_enabled_state.h"
17 #include <string>
18 #include "wifi_logger.h"
19 #include "wifi_p2p_hal_interface.h"
20 #include "wifi_settings.h"
21 #include "p2p_state_machine.h"
22 #include "wifi_logger.h"
23 
24 DEFINE_WIFILOG_P2P_LABEL("P2pEnabledState");
25 
26 namespace OHOS {
27 namespace Wifi {
28 const int CHANNEL_INDEX_OF_DISCOVER = 16;
29 const int TIMEOUT_MASK_OF_DISCOVER = 0x00FF;
30 const int DISCOVER_TIMEOUT_S = 120;
31 // miracast
32 const int CMD_TYPE_SET = 2;
33 const int DATA_TYPE_SET_LISTEN_MODE = 4;
34 const std::string ONEHOP_LISTEN_MODE = "1";
35 
P2pEnabledState(P2pStateMachine & stateMachine,WifiP2pGroupManager & groupMgr,WifiP2pDeviceManager & deviceMgr)36 P2pEnabledState::P2pEnabledState(P2pStateMachine &stateMachine, WifiP2pGroupManager &groupMgr,
37     WifiP2pDeviceManager &deviceMgr)
38     : State("P2pEnabledState"),
39       mProcessFunMap(),
40       p2pStateMachine(stateMachine),
41       groupManager(groupMgr),
42       deviceManager(deviceMgr)
43 {}
GoInState()44 void P2pEnabledState::GoInState()
45 {
46     WIFI_LOGI("             GoInState");
47     Init();
48     constexpr int defaultPeriodTime = 500;
49     constexpr int defaultIntervalTime = 1000;
50     p2pStateMachine.BroadcastP2pConnectionChanged();
51     if (P2pSettingsInitialization()) {
52         p2pStateMachine.BroadcastP2pStatusChanged(P2pState::P2P_STATE_STARTED);
53         P2pVendorConfig config;
54         WifiSettings::GetInstance().GetP2pVendorConfig(config);
55         if (config.GetIsAutoListen()) {
56             WIFI_LOGI("Auto start P2P listen!");
57             p2pStateMachine.SendMessage(
58                 static_cast<int>(P2P_STATE_MACHINE_CMD::CMD_START_LISTEN), defaultPeriodTime, defaultIntervalTime);
59         }
60     } else {
61         WIFI_LOGE("P2pSettingsInitialization Failed, Start Disable P2P!");
62         p2pStateMachine.SendMessage(static_cast<int>(P2P_STATE_MACHINE_CMD::CMD_P2P_DISABLE));
63     }
64 }
65 
GoOutState()66 void P2pEnabledState::GoOutState()
67 {
68     WIFI_LOGI("             GoOutState");
69 }
70 
Init()71 void P2pEnabledState::Init()
72 {
73     mProcessFunMap.insert(std::make_pair(P2P_STATE_MACHINE_CMD::CMD_P2P_DISABLE, &P2pEnabledState::ProcessCmdDisable));
74     mProcessFunMap.insert(
75         std::make_pair(P2P_STATE_MACHINE_CMD::CMD_START_LISTEN, &P2pEnabledState::ProcessCmdStartListen));
76     mProcessFunMap.insert(
77         std::make_pair(P2P_STATE_MACHINE_CMD::CMD_STOP_LISTEN, &P2pEnabledState::ProcessCmdStopListen));
78     mProcessFunMap.insert(
79         std::make_pair(P2P_STATE_MACHINE_CMD::CMD_DEVICE_DISCOVERS, &P2pEnabledState::ProcessCmdDiscPeer));
80     mProcessFunMap.insert(
81         std::make_pair(P2P_STATE_MACHINE_CMD::CMD_STOP_DEVICE_DISCOVERS, &P2pEnabledState::ProcessCmdStopDiscPeer));
82     mProcessFunMap.insert(
83         std::make_pair(P2P_STATE_MACHINE_CMD::P2P_EVENT_DEVICE_FOUND, &P2pEnabledState::ProcessDeviceFoundEvt));
84     mProcessFunMap.insert(
85         std::make_pair(P2P_STATE_MACHINE_CMD::P2P_EVENT_PRI_DEVICE_FOUND, &P2pEnabledState::ProcessPriDeviceFoundEvt));
86     mProcessFunMap.insert(
87         std::make_pair(P2P_STATE_MACHINE_CMD::P2P_EVENT_DEVICE_LOST, &P2pEnabledState::ProcessDeviceLostEvt));
88     mProcessFunMap.insert(
89         std::make_pair(P2P_STATE_MACHINE_CMD::P2P_EVENT_FIND_STOPPED, &P2pEnabledState::ProcessFindStoppedEvt));
90     mProcessFunMap.insert(
91         std::make_pair(P2P_STATE_MACHINE_CMD::CMD_DELETE_GROUP, &P2pEnabledState::ProcessCmdDeleteGroup));
92     mProcessFunMap.insert(
93         std::make_pair(P2P_STATE_MACHINE_CMD::CMD_PUT_LOCAL_SERVICE, &P2pEnabledState::ProcessCmdAddLocalService));
94     mProcessFunMap.insert(
95         std::make_pair(P2P_STATE_MACHINE_CMD::CMD_DEL_LOCAL_SERVICE, &P2pEnabledState::ProcessCmdDelLocalService));
96     mProcessFunMap.insert(
97         std::make_pair(P2P_STATE_MACHINE_CMD::CMD_DISCOVER_SERVICES, &P2pEnabledState::ProcessCmdDiscServices));
98     mProcessFunMap.insert(std::make_pair(
99         P2P_STATE_MACHINE_CMD::CMD_STOP_DISCOVER_SERVICES, &P2pEnabledState::ProcessCmdStopDiscServices));
100     mProcessFunMap.insert(
101         std::make_pair(P2P_STATE_MACHINE_CMD::CMD_REQUEST_SERVICE, &P2pEnabledState::ProcessCmdRequestService));
102     mProcessFunMap.insert(
103         std::make_pair(P2P_STATE_MACHINE_CMD::P2P_EVENT_SERV_DISC_REQ, &P2pEnabledState::ProcessServiceDiscReqEvt));
104     mProcessFunMap.insert(
105         std::make_pair(P2P_STATE_MACHINE_CMD::P2P_EVENT_SERV_DISC_RESP, &P2pEnabledState::ProcessServiceDiscRspEvt));
106     mProcessFunMap.insert(
107         std::make_pair(P2P_STATE_MACHINE_CMD::EXCEPTION_TIMED_OUT, &P2pEnabledState::ProcessExceptionTimeOut));
108     mProcessFunMap.insert(
109         std::make_pair(P2P_STATE_MACHINE_CMD::CMD_SET_DEVICE_NAME, &P2pEnabledState::ProcessCmdSetDeviceName));
110     mProcessFunMap.insert(
111         std::make_pair(P2P_STATE_MACHINE_CMD::CMD_SET_WFD_INFO, &P2pEnabledState::ProcessCmdSetWfdInfo));
112     mProcessFunMap.insert(
113         std::make_pair(P2P_STATE_MACHINE_CMD::CMD_CANCEL_CONNECT, &P2pEnabledState::ProcessCmdCancelConnect));
114     mProcessFunMap.insert(
115         std::make_pair(P2P_STATE_MACHINE_CMD::P2P_CONNECT_FAILED, &P2pEnabledState::ProcessCmdConnectFailed));
116     mProcessFunMap.insert(
117         std::make_pair(P2P_STATE_MACHINE_CMD::CMD_DISCOVER_PEERS, &P2pEnabledState::ProcessCmdDiscoverPeers));
118     InitProcessMsg();
119 }
120 
InitProcessMsg()121 void P2pEnabledState::InitProcessMsg()
122 {
123     mProcessFunMap.insert(
124         std::make_pair(P2P_STATE_MACHINE_CMD::CMD_INCREASE_SHARE_LINK, &P2pEnabledState::ProcessCmdIncreaseSharedLink));
125     mProcessFunMap.insert(
126         std::make_pair(P2P_STATE_MACHINE_CMD::CMD_DECREASE_SHARE_LINK, &P2pEnabledState::ProcessCmdDecreaseSharedLink));
127     mProcessFunMap.insert(
128         std::make_pair(P2P_STATE_MACHINE_CMD::P2P_EVENT_CHR_REPORT, &P2pEnabledState::ProcessChrReport));
129 }
130 
ProcessCmdDisable(InternalMessagePtr msg) const131 bool P2pEnabledState::ProcessCmdDisable(InternalMessagePtr msg) const
132 {
133     WIFI_LOGI("P2P ProcessCmdDisable recv CMD: %{public}d", msg->GetMessageName());
134     p2pStateMachine.BroadcastP2pStatusChanged(P2pState::P2P_STATE_CLOSING);
135     p2pStateMachine.BroadcastP2pDiscoveryChanged(false);
136     WifiP2PHalInterface::GetInstance().StopP2p();
137     p2pStateMachine.SwitchState(&p2pStateMachine.p2pDisablingState);
138     return EXECUTED;
139 }
ProcessCmdStartListen(InternalMessagePtr msg) const140 bool P2pEnabledState::ProcessCmdStartListen(InternalMessagePtr msg) const
141 {
142     p2pStateMachine.StopTimer(static_cast<int>(P2P_STATE_MACHINE_CMD::P2P_REMOVE_DEVICE));
143 
144     if (WifiP2PHalInterface::GetInstance().P2pFlush()) {
145         WIFI_LOGW("Unexpected results in p2p flush.");
146     }
147 
148     constexpr int defaultOpClass = 81;
149     constexpr int defaultChannel = 6;
150     if (WifiP2PHalInterface::GetInstance().SetListenChannel(defaultChannel, defaultOpClass)) {
151         WIFI_LOGI("p2p set listen channel failed. channel:%{public}d, opclass:%{public}d", defaultChannel,
152             defaultOpClass);
153         p2pStateMachine.BroadcastActionResult(P2pActionCallback::StartP2pListen, WIFI_OPT_FAILED);
154         return EXECUTED;
155     }
156 
157     size_t period = static_cast<size_t>(msg->GetParam1());
158     size_t interval = static_cast<size_t>(msg->GetParam2());
159     if (WifiP2PHalInterface::GetInstance().P2pConfigureListen(true, period, interval)) {
160         WIFI_LOGE("p2p configure to start listen failed.");
161         p2pStateMachine.BroadcastActionResult(P2pActionCallback::StartP2pListen, WIFI_OPT_FAILED);
162     } else {
163         WIFI_LOGI("p2p configure to start listen successful.");
164         p2pStateMachine.BroadcastActionResult(P2pActionCallback::StartP2pListen, WIFI_OPT_SUCCESS);
165     }
166     return EXECUTED;
167 }
ProcessCmdStopListen(InternalMessagePtr msg) const168 bool P2pEnabledState::ProcessCmdStopListen(InternalMessagePtr msg) const
169 {
170     WIFI_LOGI("P2P ProcessCmdStopListen recv CMD: %{public}d", msg->GetMessageName());
171     if (WifiP2PHalInterface::GetInstance().P2pConfigureListen(false, 0, 0)) {
172         WIFI_LOGE("p2p configure to stop listen failed.");
173         p2pStateMachine.BroadcastActionResult(P2pActionCallback::StopP2pListen, WIFI_OPT_FAILED);
174     } else {
175         WIFI_LOGI("p2p configure to stop listen successful.");
176         p2pStateMachine.BroadcastActionResult(P2pActionCallback::StopP2pListen, WIFI_OPT_SUCCESS);
177     }
178 
179     if (!WifiP2PHalInterface::GetInstance().P2pFlush()) {
180         WIFI_LOGW("Unexpected results in p2p flush.");
181     }
182     return EXECUTED;
183 }
ProcessCmdDiscPeer(InternalMessagePtr msg) const184 bool P2pEnabledState::ProcessCmdDiscPeer(InternalMessagePtr msg) const
185 {
186     p2pStateMachine.StopTimer(static_cast<int>(P2P_STATE_MACHINE_CMD::P2P_REMOVE_DEVICE));
187     WIFI_LOGI("P2P ProcessCmdDiscPeer recv CMD: %{public}d", msg->GetMessageName());
188     p2pStateMachine.HandlerDiscoverPeers();
189     return EXECUTED;
190 }
ProcessCmdStopDiscPeer(InternalMessagePtr msg) const191 bool P2pEnabledState::ProcessCmdStopDiscPeer(InternalMessagePtr msg) const
192 {
193     WIFI_LOGI("P2P ProcessCmdStopDiscPeer recv CMD: %{public}d", msg->GetMessageName());
194     WifiErrorNo retCode = WifiP2PHalInterface::GetInstance().P2pStopFind();
195     if (retCode == WifiErrorNo::WIFI_HAL_OPT_OK) {
196         p2pStateMachine.BroadcastActionResult(P2pActionCallback::StopDiscoverDevices, ErrCode::WIFI_OPT_SUCCESS);
197     } else {
198         p2pStateMachine.BroadcastActionResult(P2pActionCallback::StopDiscoverDevices, ErrCode::WIFI_OPT_FAILED);
199     }
200     return EXECUTED;
201 }
ProcessDeviceFoundEvt(InternalMessagePtr msg) const202 bool P2pEnabledState::ProcessDeviceFoundEvt(InternalMessagePtr msg) const
203 {
204     WIFI_LOGI("p2p_enabled_state recv P2P_EVENT_DEVICE_FOUND");
205     WifiP2pDevice device;
206     if (!msg->GetMessageObj(device)) {
207         WIFI_LOGE("Failed to obtain device information.");
208         return EXECUTED;
209     }
210 
211     if (deviceManager.GetThisDevice() == device) {
212         return EXECUTED;
213     }
214     WIFI_LOGI("ProcessDeviceFoundEvt, address:%{private}s, addressType:%{public}d",
215         device.GetDeviceAddress().c_str(), device.GetDeviceAddressType());
216     deviceManager.UpdateDeviceSupplicantInf(device);
217     p2pStateMachine.BroadcastP2pPeersChanged();
218     return EXECUTED;
219 }
ProcessPriDeviceFoundEvt(InternalMessagePtr msg) const220 bool P2pEnabledState::ProcessPriDeviceFoundEvt(InternalMessagePtr msg) const
221 {
222     WIFI_LOGI("p2p_enabled_state recv P2P_EVENT_PRI_DEVICE_FOUND");
223     std::string privateInfo;
224     if (!msg->GetMessageObj(privateInfo)) {
225         WIFI_LOGE("Failed to obtain device information.");
226         return EXECUTED;
227     }
228     p2pStateMachine.BroadcastP2pPrivatePeersChanged(privateInfo);
229     return EXECUTED;
230 }
ProcessDeviceLostEvt(InternalMessagePtr msg) const231 bool P2pEnabledState::ProcessDeviceLostEvt(InternalMessagePtr msg) const
232 {
233     WIFI_LOGI("p2p_enabled_state recv P2P_EVENT_DEVICE_LOST");
234     WifiP2pDevice device;
235     if (!msg->GetMessageObj(device)) {
236         WIFI_LOGE("Failed to obtain device information.");
237         return EXECUTED;
238     }
239     WIFI_LOGI("ProcessDeviceLostEvt, address:%{private}s, addressType:%{public}d",
240         device.GetDeviceAddress().c_str(), device.GetDeviceAddressType());
241     if (deviceManager.RemoveDevice(device.GetDeviceAddress())) {
242         p2pStateMachine.BroadcastP2pPeersChanged();
243     }
244 
245     if (p2pStateMachine.serviceManager.DelServicesFormAddress(device.GetDeviceAddress())) {
246         p2pStateMachine.BroadcastP2pServicesChanged();
247     }
248 
249     if (p2pStateMachine.serviceManager.RemoveServiceResponse(device.GetDeviceAddress())) {
250         WIFI_LOGI("device: %{private}s , Delete a response record.", device.GetDeviceAddress().c_str());
251     }
252     return EXECUTED;
253 }
ProcessFindStoppedEvt(InternalMessagePtr msg) const254 bool P2pEnabledState::ProcessFindStoppedEvt(InternalMessagePtr msg) const
255 {
256     WIFI_LOGI("P2P ProcessFindStoppedEvt recv event: %{public}d", msg->GetMessageName());
257     p2pStateMachine.BroadcastP2pDiscoveryChanged(false);
258     return EXECUTED;
259 }
ProcessCmdDeleteGroup(InternalMessagePtr msg) const260 bool P2pEnabledState::ProcessCmdDeleteGroup(InternalMessagePtr msg) const
261 {
262     p2pStateMachine.DelayMessage(msg);
263     p2pStateMachine.SwitchState(&p2pStateMachine.p2pGroupOperatingState);
264     return EXECUTED;
265 }
266 
ExecuteStateMsg(InternalMessagePtr msg)267 bool P2pEnabledState::ExecuteStateMsg(InternalMessagePtr msg)
268 {
269     if (msg == nullptr) {
270         WIFI_LOGE("fatal error!");
271         return NOT_EXECUTED;
272     }
273     int msgName = msg->GetMessageName();
274     auto iter = mProcessFunMap.find(static_cast<P2P_STATE_MACHINE_CMD>(msgName));
275     if (iter == mProcessFunMap.end()) {
276         return NOT_EXECUTED;
277     }
278     if ((this->*(iter->second))(msg)) {
279         return EXECUTED;
280     } else {
281         return NOT_EXECUTED;
282     }
283 }
284 
P2pConfigInitialization()285 bool P2pEnabledState::P2pConfigInitialization()
286 {
287     bool result = true;
288 
289     p2pStateMachine.InitializeThisDevice();
290     const std::string &deviceName = deviceManager.GetThisDevice().GetDeviceName();
291     const std::string ssidPostfixName = std::string("-") + deviceName;
292 
293     WifiErrorNo retCode = WifiP2PHalInterface::GetInstance().SetP2pDeviceName(deviceName);
294     if (retCode == WifiErrorNo::WIFI_HAL_OPT_FAILED) {
295         WIFI_LOGE("Failed to set the device name.");
296         result = false;
297     }
298 
299     retCode = WifiP2PHalInterface::GetInstance().SetP2pSsidPostfix(ssidPostfixName);
300     if (retCode == WifiErrorNo::WIFI_HAL_OPT_FAILED) {
301         WIFI_LOGE("Failed to set the SSID prefix");
302     }
303 
304     std::string primaryDeviceType = deviceManager.GetThisDevice().GetPrimaryDeviceType();
305     if (!primaryDeviceType.empty()) {
306         retCode = WifiP2PHalInterface::GetInstance().SetP2pDeviceType(primaryDeviceType);
307         if (retCode == WifiErrorNo::WIFI_HAL_OPT_FAILED) {
308             WIFI_LOGE("Failed to set the device type.");
309             result = false;
310         }
311     } else {
312         WIFI_LOGE("Primary device type is empty!!!");
313     }
314 
315     std::string secDeviceType = deviceManager.GetThisDevice().GetSecondaryDeviceType();
316     if (!secDeviceType.empty()) {
317         retCode = WifiP2PHalInterface::GetInstance().SetP2pSecondaryDeviceType(secDeviceType);
318         if (retCode == WifiErrorNo::WIFI_HAL_OPT_FAILED) {
319             WIFI_LOGE("Failed to set the secondary device type.");
320         }
321     }
322 
323     retCode = WifiP2PHalInterface::GetInstance().SetP2pConfigMethods(
324         std::string("virtual_push_button physical_display keypad"));
325     if (retCode == WifiErrorNo::WIFI_HAL_OPT_FAILED) {
326         WIFI_LOGE("Failed to set the wps config methods.");
327         result = false;
328     }
329 
330     retCode = WifiP2PHalInterface::GetInstance().SetPersistentReconnect(1);
331     if (retCode == WifiErrorNo::WIFI_HAL_OPT_FAILED) {
332         WIFI_LOGE("Failed to set persistent reconnect.");
333         result = false;
334     }
335 
336     std::string deviceAddr;
337     WifiP2PHalInterface::GetInstance().GetDeviceAddress(deviceAddr);
338     if (retCode == WifiErrorNo::WIFI_HAL_OPT_FAILED) {
339         WIFI_LOGE("Failed to obtain the device address.");
340         result = false;
341     }
342 
343     deviceManager.GetThisDevice().SetDeviceAddress(deviceAddr);
344     p2pStateMachine.UpdateGroupInfoToWpa();
345     return result;
346 }
347 
P2pSettingsInitialization()348 bool P2pEnabledState::P2pSettingsInitialization()
349 {
350     WIFI_LOGI("Start P2pSettingsInitialization");
351 
352     bool result = P2pConfigInitialization();
353     p2pStateMachine.UpdateOwnDevice(P2pDeviceStatus::PDS_AVAILABLE);
354 
355     WifiErrorNo retCode = WifiP2PHalInterface::GetInstance().P2pFlush();
356     if (retCode == WifiErrorNo::WIFI_HAL_OPT_FAILED) {
357         WIFI_LOGE("Failed to flush p2p.");
358         result = false;
359     }
360 
361     retCode = WifiP2PHalInterface::GetInstance().FlushService();
362     if (retCode == WifiErrorNo::WIFI_HAL_OPT_FAILED) {
363         WIFI_LOGE("Failed to flush p2p service.");
364         result = false;
365     }
366 
367     WIFI_LOGI("service discovery external is default.");
368     retCode = WifiP2PHalInterface::GetInstance().SetServiceDiscoveryExternal(false);
369     if (retCode == WifiErrorNo::WIFI_HAL_OPT_FAILED) {
370         WIFI_LOGE("Failed to set service discovery external.");
371         result = false;
372     }
373 
374     p2pStateMachine.UpdateGroupManager();
375     p2pStateMachine.UpdatePersistentGroups();
376     return result;
377 }
378 
ProcessCmdAddLocalService(InternalMessagePtr msg) const379 bool P2pEnabledState::ProcessCmdAddLocalService(InternalMessagePtr msg) const
380 {
381     WIFI_LOGI("p2p_enabled_state recv CMD_PUT_LOCAL_SERVICE");
382     WifiP2pServiceInfo service;
383     if (!msg->GetMessageObj(service)) {
384         WIFI_LOGE("Failed to obtain WifiP2pServiceInfo information.");
385         return EXECUTED;
386     }
387     if (!p2pStateMachine.serviceManager.AddLocalService(service)) {
388         p2pStateMachine.BroadcastActionResult(P2pActionCallback::PutLocalP2pService, ErrCode::WIFI_OPT_FAILED);
389         return EXECUTED;
390     }
391     WifiErrorNo retCode = WifiP2PHalInterface::GetInstance().P2pServiceAdd(service);
392     if (retCode != WifiErrorNo::WIFI_HAL_OPT_OK) {
393         p2pStateMachine.serviceManager.RemoveLocalService(service);
394         p2pStateMachine.BroadcastActionResult(P2pActionCallback::PutLocalP2pService, ErrCode::WIFI_OPT_FAILED);
395     } else {
396         p2pStateMachine.BroadcastActionResult(P2pActionCallback::PutLocalP2pService, ErrCode::WIFI_OPT_SUCCESS);
397     }
398     return EXECUTED;
399 }
ProcessCmdDelLocalService(InternalMessagePtr msg) const400 bool P2pEnabledState::ProcessCmdDelLocalService(InternalMessagePtr msg) const
401 {
402     WIFI_LOGI("recv CMD: %{public}d", msg->GetMessageName());
403     WifiP2pServiceInfo service;
404     if (!msg->GetMessageObj(service)) {
405         WIFI_LOGE("Failed to obtain WifiP2pServiceInfo information.");
406         return EXECUTED;
407     }
408     p2pStateMachine.serviceManager.RemoveLocalService(service);
409 
410     WifiErrorNo retCode = WifiP2PHalInterface::GetInstance().P2pServiceRemove(service);
411     if (retCode == WifiErrorNo::WIFI_HAL_OPT_OK) {
412         p2pStateMachine.BroadcastActionResult(P2pActionCallback::DeleteLocalP2pService, ErrCode::WIFI_OPT_SUCCESS);
413     } else {
414         p2pStateMachine.BroadcastActionResult(P2pActionCallback::DeleteLocalP2pService, ErrCode::WIFI_OPT_FAILED);
415     }
416     return EXECUTED;
417 }
418 
ProcessCmdDiscServices(InternalMessagePtr msg) const419 bool P2pEnabledState::ProcessCmdDiscServices(InternalMessagePtr msg) const
420 {
421     WIFI_LOGI("P2P ProcessCmdDiscServices recv CMD: %{public}d", msg->GetMessageName());
422     p2pStateMachine.CancelSupplicantSrvDiscReq();
423     std::string reqId;
424     WifiP2pServiceRequest request;
425     WifiP2pDevice device;
426     device.SetDeviceAddress(std::string("00:00:00:00:00:00"));
427     request.SetProtocolType(P2pServicerProtocolType::SERVICE_TYPE_ALL);
428     request.SetTransactionId(p2pStateMachine.serviceManager.GetTransId());
429 
430     p2pStateMachine.StopTimer(static_cast<int>(P2P_STATE_MACHINE_CMD::P2P_REMOVE_DEVICE));
431     WifiErrorNo retCode =
432         WifiP2PHalInterface::GetInstance().ReqServiceDiscovery(device.GetDeviceAddress(), request.GetTlv(), reqId);
433     if (WifiErrorNo::WIFI_HAL_OPT_OK != retCode) {
434         WIFI_LOGI("Failed to schedule the P2P service discovery request.");
435         p2pStateMachine.BroadcastActionResult(P2pActionCallback::DiscoverServices, ErrCode::WIFI_OPT_FAILED);
436         return EXECUTED;
437     }
438     p2pStateMachine.serviceManager.SetQueryId(reqId);
439 
440     retCode = WifiP2PHalInterface::GetInstance().P2pFind(DISC_TIMEOUT_S);
441     if (retCode != WifiErrorNo::WIFI_HAL_OPT_OK) {
442         WIFI_LOGE("call P2pFind failed, ErrorCode: %{public}d", static_cast<int>(retCode));
443         p2pStateMachine.BroadcastActionResult(P2pActionCallback::DiscoverServices, ErrCode::WIFI_OPT_FAILED);
444         return EXECUTED;
445     }
446 
447     WIFI_LOGI("CMD_DISCOVER_SERVICES successful.");
448     p2pStateMachine.BroadcastActionResult(P2pActionCallback::DiscoverServices, ErrCode::WIFI_OPT_SUCCESS);
449     p2pStateMachine.BroadcastP2pDiscoveryChanged(true);
450     return EXECUTED;
451 }
452 
ProcessCmdStopDiscServices(InternalMessagePtr msg) const453 bool P2pEnabledState::ProcessCmdStopDiscServices(InternalMessagePtr msg) const
454 {
455     WIFI_LOGI("P2P ProcessCmdStopDiscServices recv CMD: %{public}d", msg->GetMessageName());
456     WifiErrorNo retCode = WifiP2PHalInterface::GetInstance().P2pStopFind();
457     if (retCode == WifiErrorNo::WIFI_HAL_OPT_OK) {
458         p2pStateMachine.BroadcastActionResult(P2pActionCallback::StopDiscoverServices, ErrCode::WIFI_OPT_SUCCESS);
459     } else {
460         p2pStateMachine.BroadcastActionResult(P2pActionCallback::StopDiscoverServices, ErrCode::WIFI_OPT_FAILED);
461     }
462     return EXECUTED;
463 }
464 
ProcessCmdRequestService(InternalMessagePtr msg) const465 bool P2pEnabledState::ProcessCmdRequestService(InternalMessagePtr msg) const
466 {
467     std::pair<WifiP2pDevice, WifiP2pServiceRequest> info;
468     if (!msg->GetMessageObj(info)) {
469         WIFI_LOGE("Failed to obtain WifiP2pServiceRequest information.");
470         return EXECUTED;
471     }
472     const WifiP2pDevice &device = info.first;
473     const WifiP2pServiceRequest &request = info.second;
474 
475     p2pStateMachine.CancelSupplicantSrvDiscReq();
476 
477     std::string reqId;
478     WifiErrorNo retCode =
479         WifiP2PHalInterface::GetInstance().ReqServiceDiscovery(device.GetDeviceAddress(), request.GetTlv(), reqId);
480     if (WifiErrorNo::WIFI_HAL_OPT_OK != retCode) {
481         WIFI_LOGI("Failed to schedule the P2P service discovery request.");
482         p2pStateMachine.BroadcastActionResult(P2pActionCallback::RequestService, ErrCode::WIFI_OPT_FAILED);
483         return EXECUTED;
484     }
485     p2pStateMachine.serviceManager.SetQueryId(reqId);
486 
487     retCode = WifiP2PHalInterface::GetInstance().P2pFind(DISC_TIMEOUT_S);
488     if (retCode != WifiErrorNo::WIFI_HAL_OPT_OK) {
489         WIFI_LOGE("call P2pFind failed, ErrorCode: %{public}d", static_cast<int>(retCode));
490         p2pStateMachine.BroadcastActionResult(P2pActionCallback::RequestService, ErrCode::WIFI_OPT_FAILED);
491         return EXECUTED;
492     }
493 
494     p2pStateMachine.BroadcastActionResult(P2pActionCallback::RequestService, ErrCode::WIFI_OPT_SUCCESS);
495     return EXECUTED;
496 }
497 
ProcessServiceDiscReqEvt(InternalMessagePtr msg) const498 bool P2pEnabledState::ProcessServiceDiscReqEvt(InternalMessagePtr msg) const
499 {
500     WIFI_LOGI("p2p_enabled_state recv P2P_EVENT_SERV_DISC_REQ");
501     WifiP2pServiceRequestList reqList;
502     if (!msg->GetMessageObj(reqList)) {
503         WIFI_LOGE("Failed to obtain WifiP2pServiceRequestList information.");
504         return EXECUTED;
505     }
506 
507     const std::string deviceAddress = reqList.GetDevice().GetDeviceAddress();
508     int dialogToken = reqList.GetDialogToken();
509     if (p2pStateMachine.serviceManager.IsRecordedRequest(deviceAddress, dialogToken)) {
510         return EXECUTED;
511     } else {
512         p2pStateMachine.serviceManager.AddRequestRecord(deviceAddress, dialogToken);
513     }
514 
515     WifiP2pServiceResponseList respList = p2pStateMachine.serviceManager.ProcessServiceRequestList(reqList);
516     if (respList.GetServiceResponseList().size() > 0) {
517         if (WifiErrorNo::WIFI_HAL_OPT_OK != WifiP2PHalInterface::GetInstance().RespServiceDiscovery(
518             respList.GetDevice(), respList.GetFrequency(), respList.GetDialogToken(), respList.GetTlvs())) {
519             WIFI_LOGE("Failed to reply to the service response. deviceAddress: %{private}s, frequency "
520                 "%{public}d,dialogToken %{public}d",
521                 respList.GetDevice().GetDeviceAddress().c_str(), respList.GetFrequency(), respList.GetDialogToken());
522         }
523     } else {
524         WIFI_LOGI("p2p service:Failed to reply to the message.");
525     }
526 
527     std::any info = deviceAddress;
528     p2pStateMachine.MessageExecutedLater(static_cast<int>(P2P_STATE_MACHINE_CMD::REMOVE_SERVICE_REQUEST_RECORD),
529         dialogToken,
530         0,
531         info,
532         REMOVE_SERVICE_REQUEST_RECORD);
533 
534     return EXECUTED;
535 }
536 
ProcessServiceDiscRspEvt(InternalMessagePtr msg) const537 bool P2pEnabledState::ProcessServiceDiscRspEvt(InternalMessagePtr msg) const
538 {
539     WIFI_LOGI("p2p_enabled_state recv P2P_EVENT_SERV_DISC_RESP");
540     WifiP2pServiceResponseList respList;
541     if (!msg->GetMessageObj(respList)) {
542         WIFI_LOGE("Failed to obtain WifiP2pServiceResponseList information.");
543         return EXECUTED;
544     }
545 
546     const std::vector<WifiP2pServiceResponse> list = respList.GetServiceResponseList();
547 
548     WifiP2pDevice dev = deviceManager.GetDevices(respList.GetDevice().GetDeviceAddress());
549     for (auto iter = list.begin(); iter != list.end(); ++iter) {
550         p2pStateMachine.HandleP2pServiceResp(*iter, dev);
551     }
552     return EXECUTED;
553 }
ProcessExceptionTimeOut(InternalMessagePtr msg) const554 bool P2pEnabledState::ProcessExceptionTimeOut(InternalMessagePtr msg) const
555 {
556     WIFI_LOGI("recv exception timeout event: %{public}d", msg->GetMessageName());
557     p2pStateMachine.SwitchState(&p2pStateMachine.p2pIdleState);
558     return EXECUTED;
559 }
560 
ProcessCmdSetDeviceName(InternalMessagePtr msg) const561 bool P2pEnabledState::ProcessCmdSetDeviceName(InternalMessagePtr msg) const
562 {
563     WIFI_LOGI("p2p_enabled_state CMD: set device name.");
564     std::string deviceName;
565     if (!msg->GetMessageObj(deviceName)) {
566         LOGE("Failed to obtain string information.");
567         return EXECUTED;
568     }
569 
570     WifiErrorNo retCode = WifiP2PHalInterface::GetInstance().SetP2pDeviceName(deviceName);
571     if (retCode == WifiErrorNo::WIFI_HAL_OPT_FAILED) {
572         WIFI_LOGE("Failed to set the device name.");
573         p2pStateMachine.BroadcastActionResult(P2pActionCallback::P2pSetDeviceName, WIFI_OPT_FAILED);
574         return EXECUTED;
575     } else {
576         WIFI_LOGE("Successfully set the device name.");
577         deviceManager.GetThisDevice().SetDeviceName(deviceName);
578         p2pStateMachine.BroadcastThisDeviceChanaged(deviceManager.GetThisDevice());
579         p2pStateMachine.BroadcastActionResult(P2pActionCallback::P2pSetDeviceName, WIFI_OPT_SUCCESS);
580     }
581 
582     const std::string ssidPostfixName = std::string("-") + deviceName;
583     retCode = WifiP2PHalInterface::GetInstance().SetP2pSsidPostfix(ssidPostfixName);
584     if (retCode == WifiErrorNo::WIFI_HAL_OPT_FAILED) {
585         WIFI_LOGE("Failed to set the SSID prefix");
586     }
587     return EXECUTED;
588 }
ProcessCmdSetWfdInfo(InternalMessagePtr msg) const589 bool P2pEnabledState::ProcessCmdSetWfdInfo(InternalMessagePtr msg) const
590 {
591     WIFI_LOGI("P2P ProcessCmdSetWfdInfo recv CMD: %{public}d", msg->GetMessageName());
592     WifiP2pWfdInfo wfdInfo;
593     if (!msg->GetMessageObj(wfdInfo)) {
594         WIFI_LOGE("Failed to obtain wfd information.");
595         return EXECUTED;
596     }
597 
598     std::string subelement;
599     wfdInfo.GetDeviceInfoElement(subelement);
600     subelement = "0 " + subelement;
601     if (WifiP2PHalInterface::GetInstance().SetWfdDeviceConfig(subelement) != WifiErrorNo::WIFI_HAL_OPT_OK) {
602         WIFI_LOGE("Failed to set wfd config:%{public}s.", subelement.c_str());
603         return EXECUTED;
604     }
605     if (WifiP2PHalInterface::GetInstance().SetWfdEnable(wfdInfo.GetWfdEnabled()) != WifiErrorNo::WIFI_HAL_OPT_OK) {
606         WIFI_LOGE("Set wifidisplay enabled failed.");
607         return EXECUTED;
608     }
609     return EXECUTED;
610 }
611 
ProcessCmdCancelConnect(InternalMessagePtr msg) const612 bool P2pEnabledState::ProcessCmdCancelConnect(InternalMessagePtr msg) const
613 {
614     WIFI_LOGI("P2P ProcessCmdCancelConnect recv CMD: %{public}d", msg->GetMessageName());
615     p2pStateMachine.BroadcastActionResult(P2pActionCallback::P2pCancelConnect, ErrCode::WIFI_OPT_FAILED);
616     return EXECUTED;
617 }
ProcessCmdConnectFailed(InternalMessagePtr msg) const618 bool P2pEnabledState::ProcessCmdConnectFailed(InternalMessagePtr msg) const
619 {
620     WIFI_LOGI("P2P ProcessCmdConnectFailed recv CMD: %{public}d", msg->GetMessageName());
621     constexpr int connectFailed = 2;
622     constexpr int connectTimeout = 15;
623     WifiP2pDevice device;
624     if (!msg->GetMessageObj(device)) {
625         WIFI_LOGE("Failed to obtain device information.");
626         return EXECUTED;
627     }
628     if (msg->GetParam1() == connectFailed || msg->GetParam1() == connectTimeout) {
629         WIFI_LOGD("P2P ProcessCmdConnectFailed: filed reason = %{public}d", msg->GetParam1());
630         p2pStateMachine.RemoveGroupByDevice(device);
631     }
632     return EXECUTED;
633 }
634 
AddScanChannelInTimeout(uint32_t channelid,uint32_t timeout)635 static int AddScanChannelInTimeout(uint32_t channelid, uint32_t timeout)
636 {
637     int ret = (channelid << CHANNEL_INDEX_OF_DISCOVER) + (timeout & TIMEOUT_MASK_OF_DISCOVER);
638     WIFI_LOGD("AddScanChannelInTimeout result = %{public}d", ret);
639     return ret;
640 }
641 
ProcessCmdDiscoverPeers(InternalMessagePtr msg) const642 bool P2pEnabledState::ProcessCmdDiscoverPeers(InternalMessagePtr msg) const
643 {
644     WIFI_LOGI("P2P ProcessCmdDiscoverPeers recv CMD: %{public}d", msg->GetMessageName());
645     const int channelid = msg->GetParam1();
646     WifiP2PHalInterface::GetInstance().DeliverP2pData(CMD_TYPE_SET, DATA_TYPE_SET_LISTEN_MODE, ONEHOP_LISTEN_MODE);
647     p2pStateMachine.CancelSupplicantSrvDiscReq();
648     int ret = AddScanChannelInTimeout(channelid, DISCOVER_TIMEOUT_S);
649     int retCode = WifiP2PHalInterface::GetInstance().P2pFind(ret);
650     if (retCode != WifiErrorNo::WIFI_HAL_OPT_OK) {
651         WIFI_LOGE("call ProcessCmdDiscoverPeers failed, ErrorCode: %{public}d", static_cast<int>(retCode));
652         WifiP2PHalInterface::GetInstance().P2pStopFind();
653         return NOT_EXECUTED;
654     } else {
655         p2pStateMachine.BroadcastActionResult(P2pActionCallback::DiscoverPeers, ErrCode::WIFI_OPT_SUCCESS);
656         p2pStateMachine.BroadcastP2pDiscoveryChanged(true);
657         return EXECUTED;
658     }
659     return EXECUTED;
660 }
661 
ProcessCmdIncreaseSharedLink(InternalMessagePtr msg) const662 bool P2pEnabledState::ProcessCmdIncreaseSharedLink(InternalMessagePtr msg) const
663 {
664     int callingUid = msg->GetParam1();
665     WIFI_LOGI("Uid %{public}d increaseSharedLink", callingUid);
666     SharedLinkManager::IncreaseSharedLink(callingUid);
667     return EXECUTED;
668 }
669 
ProcessCmdDecreaseSharedLink(InternalMessagePtr msg) const670 bool P2pEnabledState::ProcessCmdDecreaseSharedLink(InternalMessagePtr msg) const
671 {
672     int callingUid = msg->GetParam1();
673     WIFI_LOGI("Uid %{public}d decreaseSharedLink", callingUid);
674     SharedLinkManager::DecreaseSharedLink(callingUid);
675     if (SharedLinkManager::GetSharedLinkCount() == 0) {
676         p2pStateMachine.SendMessage(static_cast<int>(P2P_STATE_MACHINE_CMD::CMD_REMOVE_GROUP));
677     }
678     return EXECUTED;
679 }
680 
ProcessChrReport(InternalMessagePtr msg) const681 bool P2pEnabledState::ProcessChrReport(InternalMessagePtr msg) const
682 {
683     int errCode = msg->GetParam1();
684     WIFI_LOGI("P2pEnabledState receive chr error code %{public}d", errCode);
685     WifiP2pDevice device = deviceManager.GetThisDevice();
686     device.SetChrErrCode(static_cast<P2pChrEvent>(errCode));
687     p2pStateMachine.BroadcastThisDeviceChanaged(device);
688     return EXECUTED;
689 }
690 } // namespace Wifi
691 } // namespace OHOS
692