• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
19 namespace Hdc {
20 class HdcFileDescriptor;
21 struct CtxFileIO {
22     uv_fs_t fs;
23     uint8_t *bufIO;
24     size_t size;
25     HdcFileDescriptor *thisClass;
26 };
27 
28 class HdcFileDescriptor {
29 public:
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);
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 
44 protected:
45 private:
46     static void FileIOOnThread(CtxFileIO *ctxIO, int bufSize, bool isWrite);
47     int LoopReadOnThread();
48 
49     std::function<void()> callbackCloseFd;
50     CmdResultCallback callbackFinish;
51     CallBackWhenRead callbackRead;
52     uv_loop_t *loop;
53     void *callerContext;
54     bool workContinue;
55     int fdIO;
56     int refIO;
57     std::thread ioReadThread;
58     std::thread ioWriteThread;
59 
60     static void IOWriteThread(void *object);
61     std::queue<CtxFileIO *> writeQueue;
62     std::mutex writeMutex;
63     std::condition_variable writeCond;
64     void PushWrite(CtxFileIO *cfio);
65     CtxFileIO *PopWrite();
66     void NotifyWrite();
67     void HandleWrite();
68     void WaitWrite();
69     void CtxFileIOWrite(CtxFileIO *cfio);
70 };
71 }  // namespace Hdc
72 
73 #endif  // HDC_FILE_DESCRIPTOR_H
74