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 { NativeApi } from '@ohos/ippprint'; 21 22const parentPort = worker.workerPort; 23const nativeApi = NativeApi.getInstance(); 24const TAG = 'PrintWorker'; 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 let requestCode = message.requestCode; 34 let requestData = undefined; 35 if (message !== undefined && message !== null && Object.prototype.hasOwnProperty.call(message, "data")) { 36 requestData = message.data; 37 } 38 let responseMessage = undefined; 39 Log.info(TAG, `request code is ${WorkerUtil.getStringByWorkerCode(requestCode)}`); 40 switch (requestCode) { 41 case RequestCode.GET_CAPS: 42 getCapabilities(requestData); 43 break; 44 default: 45 Log.error(TAG, 'onMessage. error code'); 46 } 47}; 48 49function getCapabilities(data) { 50 Log.debug(TAG, 'data: ' + JSON.stringify(data)); 51 nativeApi.getCapabilities(data.uri, data.printerName, (result) => { 52 let response; 53 if (typeof result === 'number') { 54 response = new WorkerResponse(RequestCode.GET_CAPS, ResponseCode.ERROR); 55 } else { 56 Log.info(TAG, 'getCapabilities success'); 57 response = new WorkerResponse(RequestCode.GET_CAPS, ResponseCode.OK); 58 response.data = result; 59 } 60 postMessageToMainThread(parentPort, response); 61 }); 62} 63 64function parseMessage(event) { 65 if (event === null || event.data === null) { 66 Log.error(TAG, 'worker receive an event but null'); 67 return undefined; 68 } 69 return event.data; 70} 71 72function postMessageToMainThread(parentPort, data) { 73 if (parentPort === undefined || parentPort === null) { 74 Log.error(TAG, 'parentPort is null, cannot post message'); 75 } 76 parentPort.postMessage(data); 77} 78 79