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 #include "stream_plugin.h"
16 #include "securec.h"
17
18 #include <sys/syscall.h>
19 #include <sys/types.h>
20 #include <unistd.h>
21
StreamPlugin()22 StreamPlugin::StreamPlugin() {}
23
~StreamPlugin()24 StreamPlugin::~StreamPlugin() {}
25
Start(const uint8_t * configData,uint32_t configSize)26 int StreamPlugin::Start(const uint8_t* configData, uint32_t configSize)
27 {
28 // 反序列化
29 CHECK_TRUE(protoConfig_.ParseFromArray(configData, configSize) > 0, -1, "%s:parseFromArray failed!", __func__);
30 // 启动线程写数据
31 std::unique_lock<std::mutex> locker(mutex_);
32 running_ = true;
33 writeThread_ = std::thread(&StreamPlugin::Loop, this);
34
35 return 0;
36 }
37
Stop()38 int StreamPlugin::Stop()
39 {
40 std::unique_lock<std::mutex> locker(mutex_);
41 running_ = false;
42 locker.unlock();
43 if (writeThread_.joinable()) {
44 writeThread_.join();
45 }
46 HILOG_INFO(LOG_CORE, "%s:stop success!", __func__);
47 return 0;
48 }
49
SetWriter(WriterStruct * writer)50 int StreamPlugin::SetWriter(WriterStruct* writer)
51 {
52 resultWriter_ = writer;
53 return 0;
54 }
55
GetTimeMS()56 uint64_t StreamPlugin::GetTimeMS()
57 {
58 const int MS_PER_S = 1000;
59 const int NS_PER_MS = 1000000;
60 struct timespec ts;
61 clock_gettime(CLOCK_BOOTTIME, &ts);
62 return ts.tv_sec * MS_PER_S + ts.tv_nsec / NS_PER_MS;
63 }
64
Loop(void)65 void StreamPlugin::Loop(void)
66 {
67 HILOG_INFO(LOG_CORE, "%s:transporter thread %d start !!!!!", __func__, gettid());
68 uint32_t index = 0;
69 while (running_) {
70 StreamData dataProto;
71 dataProto.set_intdata(index);
72 dataProto.set_stringdata(std::to_string(index));
73 buffer_.resize(dataProto.ByteSizeLong());
74 dataProto.SerializeToArray(buffer_.data(), buffer_.size());
75
76 if (index < 50) { // 50: count of loop
77 if (resultWriter_->write != nullptr) {
78 resultWriter_->write(resultWriter_, buffer_.data(), buffer_.size());
79 resultWriter_->flush(resultWriter_);
80 }
81 }
82 index++;
83 }
84 resultWriter_->flush(resultWriter_);
85 HILOG_INFO(LOG_CORE, "%s:transporter thread %d exit !!!!!", __func__, gettid());
86 }