1 #include "dbus_to_event_handler.hpp"
2 
3 #include "libpldmresponder/pdr.hpp"
4 
5 #include <phosphor-logging/lg2.hpp>
6 
7 PHOSPHOR_LOG2_USING;
8 
9 namespace pldm
10 {
11 using namespace pldm::responder;
12 using namespace pldm::responder::pdr;
13 using namespace pldm::responder::pdr_utils;
14 using namespace pldm::utils;
15 using namespace sdbusplus::bus::match::rules;
16 
17 namespace state_sensor
18 {
19 const std::vector<uint8_t> pdrTypes{PLDM_STATE_SENSOR_PDR};
20 
21 DbusToPLDMEvent::DbusToPLDMEvent(
22     int /* mctp_fd */, uint8_t mctp_eid, pldm::InstanceIdDb& instanceIdDb,
23     pldm::requester::Handler<pldm::requester::Request>* handler) :
24     mctp_eid(mctp_eid), instanceIdDb(instanceIdDb), handler(handler)
25 {}
26 
27 void DbusToPLDMEvent::sendEventMsg(uint8_t eventType,
28                                    const std::vector<uint8_t>& eventDataVec)
29 {
30     auto instanceId = instanceIdDb.next(mctp_eid);
31     std::vector<uint8_t> requestMsg(
32         sizeof(pldm_msg_hdr) + PLDM_PLATFORM_EVENT_MESSAGE_MIN_REQ_BYTES +
33         eventDataVec.size());
34     auto request = reinterpret_cast<pldm_msg*>(requestMsg.data());
35 
36     auto rc = encode_platform_event_message_req(
37         instanceId, 1 /*formatVersion*/, TERMINUS_ID /*tId*/, eventType,
38         eventDataVec.data(), eventDataVec.size(), request,
39         eventDataVec.size() + PLDM_PLATFORM_EVENT_MESSAGE_MIN_REQ_BYTES);
40     if (rc != PLDM_SUCCESS)
41     {
42         instanceIdDb.free(mctp_eid, instanceId);
43         error(
44             "Failed to encode platform event message request, response code '{RC}'",
45             "RC", rc);
46         return;
47     }
48 
49     auto platformEventMessageResponseHandler = [](mctp_eid_t /*eid*/,
50                                                   const pldm_msg* response,
51                                                   size_t respMsgLen) {
52         if (response == nullptr || !respMsgLen)
53         {
54             error("Failed to receive response for platform event message");
55             return;
56         }
57         uint8_t completionCode{};
58         uint8_t status{};
59         auto rc = decode_platform_event_message_resp(response, respMsgLen,
60                                                      &completionCode, &status);
61         if (rc || completionCode)
62         {
63             error(
64                 "Failed to decode response of platform event message, response code '{RC}' and completion code '{CC}'",
65                 "RC", rc, "CC", completionCode);
66         }
67     };
68 
69     rc = handler->registerRequest(
70         mctp_eid, instanceId, PLDM_PLATFORM, PLDM_PLATFORM_EVENT_MESSAGE,
71         std::move(requestMsg), std::move(platformEventMessageResponseHandler));
72     if (rc)
73     {
74         error("Failed to send the platform event message, response code '{RC}'",
75               "RC", rc);
76     }
77 }
78 
79 void DbusToPLDMEvent::sendStateSensorEvent(SensorId sensorId,
80                                            const DbusObjMaps& dbusMaps)
81 {
82     // Encode PLDM platform event msg to indicate a state sensor change.
83     // DSP0248_1.2.0 Table 19
84     if (!dbusMaps.contains(sensorId))
85     {
86         // this is not an error condition, if we end up here
87         // that means that the sensor with the sensor id has
88         // custom behaviour(or probably an oem sensor) in
89         // sending events that cannot be captured via standard
90         // dbus-json infastructure
91         return;
92     }
93 
94     size_t sensorEventSize = PLDM_SENSOR_EVENT_DATA_MIN_LENGTH + 1;
95     const auto& [dbusMappings, dbusValMaps] = dbusMaps.at(sensorId);
96     for (size_t offset = 0; offset < dbusMappings.size(); ++offset)
97     {
98         std::vector<uint8_t> sensorEventDataVec{};
99         sensorEventDataVec.resize(sensorEventSize);
100         auto eventData = reinterpret_cast<struct pldm_sensor_event_data*>(
101             sensorEventDataVec.data());
102         eventData->sensor_id = sensorId;
103         eventData->sensor_event_class_type = PLDM_STATE_SENSOR_STATE;
104         eventData->event_class[0] = static_cast<uint8_t>(offset);
105         eventData->event_class[1] = PLDM_SENSOR_UNKNOWN;
106         eventData->event_class[2] = PLDM_SENSOR_UNKNOWN;
107 
108         const auto& dbusMapping = dbusMappings[offset];
109         const auto& dbusValueMapping = dbusValMaps[offset];
110         auto stateSensorMatch = std::make_unique<sdbusplus::bus::match_t>(
111             pldm::utils::DBusHandler::getBus(),
112             propertiesChanged(dbusMapping.objectPath.c_str(),
113                               dbusMapping.interface.c_str()),
114             [this, sensorEventDataVec, dbusValueMapping, dbusMapping, sensorId,
115              offset](auto& msg) mutable {
116                 DbusChangedProps props{};
117                 std::string intf;
118                 uint8_t previousState = PLDM_SENSOR_UNKNOWN;
119                 msg.read(intf, props);
120                 if (!props.contains(dbusMapping.propertyName))
121                 {
122                     return;
123                 }
124                 for (const auto& itr : dbusValueMapping)
125                 {
126                     bool findValue = false;
127                     if (dbusMapping.propertyType == "string")
128                     {
129                         std::string src = std::get<std::string>(itr.second);
130                         std::string dst = std::get<std::string>(
131                             props.at(dbusMapping.propertyName));
132 
133                         auto values = pldm::utils::split(src, "||", " ");
134                         for (const auto& value : values)
135                         {
136                             if (value == dst)
137                             {
138                                 findValue = true;
139                                 break;
140                             }
141                         }
142                     }
143                     else
144                     {
145                         findValue =
146                             itr.second == props.at(dbusMapping.propertyName)
147                                 ? true
148                                 : false;
149                     }
150 
151                     if (findValue)
152                     {
153                         auto eventData =
154                             reinterpret_cast<struct pldm_sensor_event_data*>(
155                                 sensorEventDataVec.data());
156                         eventData->event_class[1] = itr.first;
157                         if (sensorCacheMap.contains(sensorId) &&
158                             sensorCacheMap[sensorId][offset] !=
159                                 PLDM_SENSOR_UNKNOWN)
160                         {
161                             previousState = sensorCacheMap[sensorId][offset];
162                         }
163                         else
164                         {
165                             previousState = itr.first;
166                         }
167                         eventData->event_class[2] = previousState;
168                         this->sendEventMsg(PLDM_SENSOR_EVENT,
169                                            sensorEventDataVec);
170                         updateSensorCacheMaps(sensorId, offset, previousState);
171                         break;
172                     }
173                 }
174             });
175         stateSensorMatchs.emplace_back(std::move(stateSensorMatch));
176     }
177 }
178 
179 void DbusToPLDMEvent::listenSensorEvent(const pdr_utils::Repo& repo,
180                                         const DbusObjMaps& dbusMaps)
181 {
182     const std::map<Type, sensorEvent> sensorHandlers = {
183         {PLDM_STATE_SENSOR_PDR,
184          [this](SensorId sensorId, const DbusObjMaps& dbusMaps) {
185              this->sendStateSensorEvent(sensorId, dbusMaps);
186          }}};
187 
188     pldm_state_sensor_pdr* pdr = nullptr;
189     std::unique_ptr<pldm_pdr, decltype(&pldm_pdr_destroy)> sensorPdrRepo(
190         pldm_pdr_init(), pldm_pdr_destroy);
191     if (!sensorPdrRepo)
192     {
193         throw std::runtime_error("Unable to instantiate sensor PDR repository");
194     }
195 
196     for (auto pdrType : pdrTypes)
197     {
198         Repo sensorPDRs(sensorPdrRepo.get());
199         getRepoByType(repo, sensorPDRs, pdrType);
200         if (sensorPDRs.empty())
201         {
202             return;
203         }
204 
205         PdrEntry pdrEntry{};
206         auto pdrRecord = sensorPDRs.getFirstRecord(pdrEntry);
207         while (pdrRecord)
208         {
209             pdr = reinterpret_cast<pldm_state_sensor_pdr*>(pdrEntry.data);
210             SensorId sensorId = LE16TOH(pdr->sensor_id);
211             if (sensorHandlers.contains(pdrType))
212             {
213                 sensorHandlers.at(pdrType)(sensorId, dbusMaps);
214             }
215 
216             pdrRecord = sensorPDRs.getNextRecord(pdrRecord, pdrEntry);
217         }
218     }
219 }
220 
221 } // namespace state_sensor
222 } // namespace pldm
223