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 {WorkerUtil} from '@ohos/ippprint'; 17import worker from '@ohos.worker'; 18import { Log } from '@ohos/common'; 19import {WorkerResponse, RequestCode, ResponseCode } from '@ohos/ippprint'; 20import {P2PDiscoveryChannel} from '@ohos/ippprint'; 21 22const parentPort = worker.workerPort; 23const p2pDiscoveryChannel = P2PDiscoveryChannel.getInstance(); 24const TAG = 'DiscoveryWorker'; 25 26parentPort.onerror = function (e) { 27 Log.error(TAG, 'worker on error ' + JSON.stringify(e)); 28}; 29 30parentPort.onmessage = function (messageEvent) { 31 Log.info(TAG, 'parent port on message enter'); 32 let message = parseMessage(messageEvent); 33 if (!Object.prototype.hasOwnProperty.call(message, "requestCode")) { 34 Log.error(TAG, 'requestCode is not in message'); 35 return; 36 } 37 let requestCode = message.requestCode; 38 Log.info(TAG, `request code is ${WorkerUtil.getStringByWorkerCode(requestCode)}`); 39 switch (requestCode) { 40 case RequestCode.P2P_START_DISCOVERY: 41 startP2pDiscovery(); 42 break; 43 case RequestCode.P2P_CANCEL_DISCOVERY: 44 stopP2pDiscovery(); 45 break; 46 default: 47 Log.error(TAG, 'onMessage. error code'); 48 } 49}; 50 51function startP2pDiscovery() { 52 p2pDiscoveryChannel.startDiscovery(p2pDiscoveryResult); 53} 54 55function p2pDiscoveryResult(found, p2pDevice) { 56 Log.info(TAG, 'p2pDiscoveryResult enter '); 57 let p2pDiscoveryResponse = new WorkerResponse(RequestCode.P2P_START_DISCOVERY, ResponseCode.OK); 58 p2pDiscoveryResponse.data = { 'found': found, 'p2pDevice': p2pDevice }; 59 postMessageToMainThread(parentPort, p2pDiscoveryResponse); 60} 61 62function stopP2pDiscovery() { 63 p2pDiscoveryChannel.cancel(); 64} 65 66 67function parseMessage(event) { 68 if (event === null || event.data === null) { 69 Log.error(TAG, 'worker receive an event but null'); 70 return undefined; 71 } 72 return event.data; 73} 74 75function postMessageToMainThread(parentPort, data) { 76 if (parentPort === undefined || parentPort === null) { 77 Log.error(TAG, 'parentPort is null, cannot post message'); 78 } 79 parentPort.postMessage(data); 80} 81 82