1/* 2 * Copyright (C) 2021 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#ifndef HDC_FILE_DESCRIPTOR_H 16#define HDC_FILE_DESCRIPTOR_H 17#include "common.h" 18 19namespace Hdc { 20class HdcFileDescriptor; 21struct CtxFileIO { 22 uv_fs_t fs; 23 uint8_t *bufIO; 24 size_t size; 25 HdcFileDescriptor *thisClass; 26}; 27 28class HdcFileDescriptor { 29public: 30 // callerContext, normalFinish, errorString 31 using CmdResultCallback = std::function<bool(const void *, const bool, const string)>; 32 // callerContext, readBuf, readIOByes 33 using CallBackWhenRead = std::function<bool(const void *, uint8_t *, const int)>; 34 HdcFileDescriptor(uv_loop_t *loopIn, int fdToRead, void *callerContextIn, CallBackWhenRead callbackReadIn, 35 CmdResultCallback callbackFinishIn, bool interactiveShell); 36 virtual ~HdcFileDescriptor(); 37 int Write(uint8_t *data, int size); 38 int WriteWithMem(uint8_t *data, int size); 39 40 bool ReadyForRelease(); 41 bool StartWorkOnThread(); 42 void StopWorkOnThread(bool tryCloseFdIo, std::function<void()> closeFdCallback); 43 44protected: 45private: 46 static void FileIOOnThread(CtxFileIO *ctxIO, int bufSize); 47 int LoopReadOnThread(); 48 49 std::function<void()> callbackCloseFd; 50 CmdResultCallback callbackFinish; 51 CallBackWhenRead callbackRead; 52 uv_loop_t *loop; 53 void *callerContext; 54 std::atomic<bool> workContinue; 55 int fdIO; 56 int refIO; 57 bool isInteractive; 58 std::thread ioReadThread; 59 std::thread ioWriteThread; 60 61 static void IOWriteThread(void *object); 62 std::queue<CtxFileIO *> writeQueue; 63 std::mutex writeMutex; 64 std::condition_variable writeCond; 65 void PushWrite(CtxFileIO *cfio); 66 CtxFileIO *PopWrite(); 67 void NotifyWrite(); 68 void HandleWrite(); 69 void WaitWrite(); 70 void CtxFileIOWrite(CtxFileIO *cfio); 71}; 72} // namespace Hdc 73 74#endif // HDC_FILE_DESCRIPTOR_H 75