1/* 2 * Copyright (c) 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 worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker'; 17import { offsetMomentum, energy, advance } from '../model/NBody_ETS_6'; 18import Logger from '../utils/Logger'; 19 20const workerPort: ThreadWorkerGlobalScope = worker.workerPort; 21const TAG: string = 'CalculateWorker'; 22 23/** 24 * Defines the event handler to be called when the worker thread receives a message sent by the host thread. 25 * The event handler is executed in the worker thread. 26 * 27 * @param e message data 28 */ 29workerPort.onmessage = function (e: MessageEvents): void { 30 Logger.info(TAG, 'CalculateWorker: start calculating...'); 31 let data = e.data; 32 console.info(TAG, 'message from main thread' + JSON.stringify(data)); 33 let res: number = computeTask(data.timeSteps); 34 workerPort.postMessage({ result: res }); 35}; 36 37/** 38 * Defines the event handler to be called when the worker receives a message that cannot be deserialized. 39 * The event handler is executed in the worker thread. 40 * 41 * @param e message data 42 */ 43workerPort.onmessageerror = function (e: MessageEvents): void { 44 Logger.error(TAG, 'CalculateWorker: onmessageerror = ' + e.data); 45}; 46 47/** 48 * Defines the event handler to be called when an exception occurs during worker execution. 49 * The event handler is executed in the worker thread. 50 * 51 * @param e error message 52 */ 53workerPort.onerror = function (e: ErrorEvent): void { 54 Logger.error(TAG, 'CalculateWorker: onerror = ' + e.message); 55}; 56 57/** 58 * 运行天体轨道计算程序 59 * @param totalTimeSteps 时间推移量 60 * @returns 计算时间 61 */ 62function computeTask(totalTimeSteps: number): number { 63 const tagInTask: string = 'computeTask'; 64 const timeStep: number = 0.01; // 单位:hour 65 const fractionDigits: number = 9; // 机械能数值小数位 66 let start: number = new Date().getTime(); 67 68 // 建立孤立系统的动量守恒 69 offsetMomentum(); 70 Logger.info(tagInTask, energy().toFixed(fractionDigits)); 71 72 // 更新天体在按指定的时间变化后的位置信息 73 for (let i: number = 0; i < totalTimeSteps; i++) { 74 advance(timeStep); 75 } 76 77 // 判断系统计算前后机械能守恒 78 Logger.info(tagInTask, energy().toFixed(fractionDigits)); 79 let end: number = new Date().getTime(); 80 return end - start; 81}