1 /*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <libprotocan/MessageDef.h>
18
19 #include <android-base/logging.h>
20
21 namespace android::hardware::automotive::protocan {
22
23 using can::V1_0::CanMessage;
24 using can::V1_0::CanMessageId;
25
MessageDef(CanMessageId id,uint16_t len,std::map<std::string,Signal> signals,std::optional<Signal> counter,std::optional<Checksum> checksum)26 MessageDef::MessageDef(CanMessageId id, uint16_t len, std::map<std::string, Signal> signals,
27 std::optional<Signal> counter, std::optional<Checksum> checksum)
28 : id(id), kLen(len), kSignals(std::move(signals)), kCounter(counter), kChecksum(checksum) {}
29
operator [](const std::string & signalName) const30 const Signal& MessageDef::operator[](const std::string& signalName) const {
31 auto it = kSignals.find(signalName);
32 CHECK(it != kSignals.end()) << "Signal " << signalName << " doesn't exist";
33 return it->second;
34 }
35
makeDefault() const36 CanMessage MessageDef::makeDefault() const {
37 CanMessage msg = {};
38 msg.id = id;
39 msg.payload.resize(kLen);
40
41 for (auto const& [name, signal] : kSignals) {
42 signal.setDefault(msg);
43 }
44
45 return msg;
46 }
47
makeCounter() const48 MessageCounter MessageDef::makeCounter() const {
49 CHECK(kCounter.has_value()) << "Can't build a counter for message without such signal";
50 return MessageCounter(*kCounter);
51 }
52
updateChecksum(can::V1_0::CanMessage & msg) const53 void MessageDef::updateChecksum(can::V1_0::CanMessage& msg) const {
54 if (!kChecksum.has_value()) return;
55 kChecksum->update(msg);
56 }
57
validate(const can::V1_0::CanMessage & msg) const58 bool MessageDef::validate(const can::V1_0::CanMessage& msg) const {
59 return msg.payload.size() >= kLen;
60 }
61
62 } // namespace android::hardware::automotive::protocan
63