1 /*
2 * Copyright (c) 2025 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
16 #include "mc_set_mech_hid_preemptive_cmd.h"
17
18 #include "mechbody_controller_log.h"
19
20 namespace OHOS {
21 namespace MechBodyController {
22 namespace {
23 const std::string TAG = "SetMechHidPreemptiveCmd";
24 constexpr uint8_t CMD_SET_HID_PREEMPTIVE_TYPE = 0x04;
25 constexpr uint8_t CMD_SET_HID_PREEMPTIVE_LENGTH = 1;
26 }
27
SetMechHidPreemptiveCmd(bool isPreemptive)28 SetMechHidPreemptiveCmd::SetMechHidPreemptiveCmd(bool isPreemptive)
29 {
30 cmdSet_ = CMD_SET;
31 cmdId_ = CMD_ID;
32 reqSize_ = REQ_SIZE;
33 rspSize_ = RSP_SIZE;
34 needResponse_ = (RSP_SIZE > 0);
35 timeoutMs_ = MECHBODY_MSG_TIMEOUT;
36 isPreemptive_ = isPreemptive;
37 retryTimes_ = CMD_PRIORITY_HIGH;
38 }
39
Marshal() const40 std::shared_ptr<MechDataBuffer> SetMechHidPreemptiveCmd::Marshal() const
41 {
42 HILOGD("start.");
43 auto buffer = std::make_shared<MechDataBuffer>(reqSize_ + BIT_OFFSET_2);
44 if (buffer == nullptr) {
45 HILOGE("Failed to allocate memory for Marshal buffer");
46 return nullptr;
47 }
48
49 CHECK_ERR_RETURN_VALUE(buffer->AppendUint8(cmdSet_), nullptr, "append cmdSet_");
50 CHECK_ERR_RETURN_VALUE(buffer->AppendUint8(cmdId_), nullptr, "append cmdId_");
51
52 CHECK_ERR_RETURN_VALUE(buffer->AppendUint8(CMD_SET_HID_PREEMPTIVE_TYPE), nullptr, "append control type");
53 CHECK_ERR_RETURN_VALUE(buffer->AppendUint8(CMD_SET_HID_PREEMPTIVE_LENGTH), nullptr, "append control len");
54 CHECK_ERR_RETURN_VALUE(buffer->AppendUint8(static_cast<uint8_t>(isPreemptive_)), nullptr, "append isPreemptive_");
55
56 HILOGD("end.");
57 return buffer;
58 }
59
TriggerResponse(std::shared_ptr<MechDataBuffer> data)60 void SetMechHidPreemptiveCmd::TriggerResponse(std::shared_ptr<MechDataBuffer> data)
61 {
62 if (data == nullptr || data->Size() < RSP_SIZE + BIT_OFFSET_2) {
63 HILOGE("Invalid input data for response");
64 return;
65 }
66
67 CHECK_ERR_RETURN(data->ReadUint8(BIT_OFFSET_2, result_), "read result_");
68 HILOGI("response code: %{public}u", result_);
69
70 if (responseCb_) {
71 HILOGI("trigger response callback.");
72 responseCb_();
73 }
74 }
75
GetResult() const76 uint8_t SetMechHidPreemptiveCmd::GetResult() const
77 {
78 return result_;
79 }
80 } // namespace MechBodyController
81 } // namespace OHOS
82