xref: /openbmc/pldm/common/utils.cpp (revision 549e4bc8bf5504b407ffc1976ab557dcad6c6028)
1 #include "utils.hpp"
2 
3 #include <libpldm/pdr.h>
4 #include <libpldm/pldm_types.h>
5 #include <linux/mctp.h>
6 
7 #include <phosphor-logging/lg2.hpp>
8 #include <xyz/openbmc_project/Common/error.hpp>
9 #include <xyz/openbmc_project/Logging/Create/client.hpp>
10 #include <xyz/openbmc_project/ObjectMapper/client.hpp>
11 
12 #include <algorithm>
13 #include <array>
14 #include <cctype>
15 #include <ctime>
16 #include <fstream>
17 #include <iostream>
18 #include <map>
19 #include <stdexcept>
20 #include <string>
21 #include <vector>
22 
23 PHOSPHOR_LOG2_USING;
24 
25 namespace pldm
26 {
27 namespace utils
28 {
29 
findStateEffecterPDR(uint8_t,uint16_t entityID,uint16_t stateSetId,const pldm_pdr * repo)30 std::vector<std::vector<uint8_t>> findStateEffecterPDR(
31     uint8_t /*tid*/, uint16_t entityID, uint16_t stateSetId,
32     const pldm_pdr* repo)
33 {
34     uint8_t* outData = nullptr;
35     uint32_t size{};
36     const pldm_pdr_record* record{};
37     std::vector<std::vector<uint8_t>> pdrs;
38     try
39     {
40         do
41         {
42             record = pldm_pdr_find_record_by_type(repo, PLDM_STATE_EFFECTER_PDR,
43                                                   record, &outData, &size);
44             if (record)
45             {
46                 auto pdr = reinterpret_cast<pldm_state_effecter_pdr*>(outData);
47                 auto compositeEffecterCount = pdr->composite_effecter_count;
48                 auto possible_states_start = pdr->possible_states;
49 
50                 for (auto effecters = 0x00; effecters < compositeEffecterCount;
51                      effecters++)
52                 {
53                     auto possibleStates =
54                         reinterpret_cast<state_effecter_possible_states*>(
55                             possible_states_start);
56                     auto setId = possibleStates->state_set_id;
57                     auto possibleStateSize =
58                         possibleStates->possible_states_size;
59 
60                     if (pdr->entity_type == entityID && setId == stateSetId)
61                     {
62                         std::vector<uint8_t> effecter_pdr(&outData[0],
63                                                           &outData[size]);
64                         pdrs.emplace_back(std::move(effecter_pdr));
65                         break;
66                     }
67                     possible_states_start += possibleStateSize + sizeof(setId) +
68                                              sizeof(possibleStateSize);
69                 }
70             }
71 
72         } while (record);
73     }
74     catch (const std::exception& e)
75     {
76         error("Failed to obtain a record, error - {ERROR}", "ERROR", e);
77     }
78 
79     return pdrs;
80 }
81 
findStateSensorPDR(uint8_t,uint16_t entityID,uint16_t stateSetId,const pldm_pdr * repo)82 std::vector<std::vector<uint8_t>> findStateSensorPDR(
83     uint8_t /*tid*/, uint16_t entityID, uint16_t stateSetId,
84     const pldm_pdr* repo)
85 {
86     uint8_t* outData = nullptr;
87     uint32_t size{};
88     const pldm_pdr_record* record{};
89     std::vector<std::vector<uint8_t>> pdrs;
90     try
91     {
92         do
93         {
94             record = pldm_pdr_find_record_by_type(repo, PLDM_STATE_SENSOR_PDR,
95                                                   record, &outData, &size);
96             if (record)
97             {
98                 auto pdr = reinterpret_cast<pldm_state_sensor_pdr*>(outData);
99                 auto compositeSensorCount = pdr->composite_sensor_count;
100                 auto possible_states_start = pdr->possible_states;
101 
102                 for (auto sensors = 0x00; sensors < compositeSensorCount;
103                      sensors++)
104                 {
105                     auto possibleStates =
106                         reinterpret_cast<state_sensor_possible_states*>(
107                             possible_states_start);
108                     auto setId = possibleStates->state_set_id;
109                     auto possibleStateSize =
110                         possibleStates->possible_states_size;
111 
112                     if (pdr->entity_type == entityID && setId == stateSetId)
113                     {
114                         std::vector<uint8_t> sensor_pdr(&outData[0],
115                                                         &outData[size]);
116                         pdrs.emplace_back(std::move(sensor_pdr));
117                         break;
118                     }
119                     possible_states_start += possibleStateSize + sizeof(setId) +
120                                              sizeof(possibleStateSize);
121                 }
122             }
123 
124         } while (record);
125     }
126     catch (const std::exception& e)
127     {
128         error(
129             "Failed to obtain a record with entity ID '{ENTITYID}', error - {ERROR}",
130             "ENTITYID", entityID, "ERROR", e);
131     }
132 
133     return pdrs;
134 }
135 
readHostEID()136 uint8_t readHostEID()
137 {
138     uint8_t eid{};
139     std::ifstream eidFile{HOST_EID_PATH};
140     if (!eidFile.good())
141     {
142         error("Failed to open remote terminus EID file at path '{PATH}'",
143               "PATH", static_cast<std::string>(HOST_EID_PATH));
144     }
145     else
146     {
147         std::string eidStr;
148         eidFile >> eidStr;
149         if (!eidStr.empty())
150         {
151             eid = atoi(eidStr.c_str());
152         }
153         else
154         {
155             error("Remote terminus EID file was empty");
156         }
157     }
158 
159     return eid;
160 }
161 
isValidEID(eid mctpEid)162 bool isValidEID(eid mctpEid)
163 {
164     if (mctpEid == MCTP_ADDR_NULL || mctpEid < MCTP_START_VALID_EID ||
165         mctpEid == MCTP_ADDR_ANY)
166     {
167         return false;
168     }
169 
170     return true;
171 }
172 
getNumPadBytes(uint32_t data)173 uint8_t getNumPadBytes(uint32_t data)
174 {
175     uint8_t pad;
176     pad = ((data % 4) ? (4 - data % 4) : 0);
177     return pad;
178 } // end getNumPadBytes
179 
uintToDate(uint64_t data,uint16_t * year,uint8_t * month,uint8_t * day,uint8_t * hour,uint8_t * min,uint8_t * sec)180 bool uintToDate(uint64_t data, uint16_t* year, uint8_t* month, uint8_t* day,
181                 uint8_t* hour, uint8_t* min, uint8_t* sec)
182 {
183     constexpr uint64_t max_data = 29991231115959;
184     constexpr uint64_t min_data = 19700101000000;
185     if (data < min_data || data > max_data)
186     {
187         return false;
188     }
189 
190     *year = data / 10000000000;
191     data = data % 10000000000;
192     *month = data / 100000000;
193     data = data % 100000000;
194     *day = data / 1000000;
195     data = data % 1000000;
196     *hour = data / 10000;
197     data = data % 10000;
198     *min = data / 100;
199     *sec = data % 100;
200 
201     return true;
202 }
203 
parseEffecterData(const std::vector<uint8_t> & effecterData,uint8_t effecterCount)204 std::optional<std::vector<set_effecter_state_field>> parseEffecterData(
205     const std::vector<uint8_t>& effecterData, uint8_t effecterCount)
206 {
207     std::vector<set_effecter_state_field> stateField;
208 
209     if (effecterData.size() != effecterCount * 2)
210     {
211         return std::nullopt;
212     }
213 
214     for (uint8_t i = 0; i < effecterCount; ++i)
215     {
216         uint8_t set_request = effecterData[i * 2] == PLDM_REQUEST_SET
217                                   ? PLDM_REQUEST_SET
218                                   : PLDM_NO_CHANGE;
219         set_effecter_state_field filed{set_request, effecterData[i * 2 + 1]};
220         stateField.emplace_back(std::move(filed));
221     }
222 
223     return std::make_optional(std::move(stateField));
224 }
225 
getService(const char * path,const char * interface) const226 std::string DBusHandler::getService(const char* path,
227                                     const char* interface) const
228 {
229     using DbusInterfaceList = std::vector<std::string>;
230     std::map<std::string, std::vector<std::string>> mapperResponse;
231     auto& bus = DBusHandler::getBus();
232 
233     auto mapper = bus.new_method_call(ObjectMapper::default_service,
234                                       ObjectMapper::instance_path,
235                                       ObjectMapper::interface, "GetObject");
236 
237     if (interface)
238     {
239         mapper.append(path, DbusInterfaceList({interface}));
240     }
241     else
242     {
243         mapper.append(path, DbusInterfaceList({}));
244     }
245 
246     auto mapperResponseMsg = bus.call(mapper, dbusTimeout);
247     mapperResponseMsg.read(mapperResponse);
248     return mapperResponse.begin()->first;
249 }
250 
getSubtree(const std::string & searchPath,int depth,const std::vector<std::string> & ifaceList) const251 GetSubTreeResponse DBusHandler::getSubtree(
252     const std::string& searchPath, int depth,
253     const std::vector<std::string>& ifaceList) const
254 {
255     auto& bus = pldm::utils::DBusHandler::getBus();
256     auto method = bus.new_method_call(ObjectMapper::default_service,
257                                       ObjectMapper::instance_path,
258                                       ObjectMapper::interface, "GetSubTree");
259     method.append(searchPath, depth, ifaceList);
260     auto reply = bus.call(method, dbusTimeout);
261     GetSubTreeResponse response;
262     reply.read(response);
263     return response;
264 }
265 
getSubTreePaths(const std::string & objectPath,int depth,const std::vector<std::string> & ifaceList) const266 GetSubTreePathsResponse DBusHandler::getSubTreePaths(
267     const std::string& objectPath, int depth,
268     const std::vector<std::string>& ifaceList) const
269 {
270     std::vector<std::string> paths;
271     auto& bus = pldm::utils::DBusHandler::getBus();
272     auto method = bus.new_method_call(
273         ObjectMapper::default_service, ObjectMapper::instance_path,
274         ObjectMapper::interface, "GetSubTreePaths");
275     method.append(objectPath, depth, ifaceList);
276     auto reply = bus.call(method, dbusTimeout);
277 
278     reply.read(paths);
279     return paths;
280 }
281 
getAncestors(const std::string & path,const std::vector<std::string> & ifaceList) const282 GetAncestorsResponse DBusHandler::getAncestors(
283     const std::string& path, const std::vector<std::string>& ifaceList) const
284 {
285     auto& bus = pldm::utils::DBusHandler::getBus();
286     auto method = bus.new_method_call(ObjectMapper::default_service,
287                                       ObjectMapper::instance_path,
288                                       ObjectMapper::interface, "GetAncestors");
289     method.append(path, ifaceList);
290     auto reply = bus.call(method, dbusTimeout);
291     GetAncestorsResponse response;
292     reply.read(response);
293     return response;
294 }
295 
reportError(const char * errorMsg)296 void reportError(const char* errorMsg)
297 {
298     auto& bus = pldm::utils::DBusHandler::getBus();
299     using LoggingCreate =
300         sdbusplus::client::xyz::openbmc_project::logging::Create<>;
301     try
302     {
303         using namespace sdbusplus::xyz::openbmc_project::Logging::server;
304         auto severity =
305             sdbusplus::xyz::openbmc_project::Logging::server::convertForMessage(
306                 sdbusplus::xyz::openbmc_project::Logging::server::Entry::Level::
307                     Error);
308         auto method = bus.new_method_call(LoggingCreate::default_service,
309                                           LoggingCreate::instance_path,
310                                           LoggingCreate::interface, "Create");
311 
312         std::map<std::string, std::string> addlData{};
313         method.append(errorMsg, severity, addlData);
314         bus.call_noreply(method, dbusTimeout);
315     }
316     catch (const std::exception& e)
317     {
318         error(
319             "Failed to do dbus call for creating error log for '{ERRMSG}' at path '{PATH}' and interface '{INTERFACE}', error - {ERROR}",
320             "ERRMSG", errorMsg, "PATH", LoggingCreate::instance_path,
321             "INTERFACE", LoggingCreate::interface, "ERROR", e);
322     }
323 }
324 
setDbusProperty(const DBusMapping & dBusMap,const PropertyValue & value) const325 void DBusHandler::setDbusProperty(const DBusMapping& dBusMap,
326                                   const PropertyValue& value) const
327 {
328     auto setDbusValue = [&dBusMap, this](const auto& variant) {
329         auto& bus = getBus();
330         auto service =
331             getService(dBusMap.objectPath.c_str(), dBusMap.interface.c_str());
332         auto method = bus.new_method_call(
333             service.c_str(), dBusMap.objectPath.c_str(), dbusProperties, "Set");
334         method.append(dBusMap.interface.c_str(), dBusMap.propertyName.c_str(),
335                       variant);
336         bus.call_noreply(method, dbusTimeout);
337     };
338 
339     if (dBusMap.propertyType == "uint8_t")
340     {
341         std::variant<uint8_t> v = std::get<uint8_t>(value);
342         setDbusValue(v);
343     }
344     else if (dBusMap.propertyType == "bool")
345     {
346         std::variant<bool> v = std::get<bool>(value);
347         setDbusValue(v);
348     }
349     else if (dBusMap.propertyType == "int16_t")
350     {
351         std::variant<int16_t> v = std::get<int16_t>(value);
352         setDbusValue(v);
353     }
354     else if (dBusMap.propertyType == "uint16_t")
355     {
356         std::variant<uint16_t> v = std::get<uint16_t>(value);
357         setDbusValue(v);
358     }
359     else if (dBusMap.propertyType == "int32_t")
360     {
361         std::variant<int32_t> v = std::get<int32_t>(value);
362         setDbusValue(v);
363     }
364     else if (dBusMap.propertyType == "uint32_t")
365     {
366         std::variant<uint32_t> v = std::get<uint32_t>(value);
367         setDbusValue(v);
368     }
369     else if (dBusMap.propertyType == "int64_t")
370     {
371         std::variant<int64_t> v = std::get<int64_t>(value);
372         setDbusValue(v);
373     }
374     else if (dBusMap.propertyType == "uint64_t")
375     {
376         std::variant<uint64_t> v = std::get<uint64_t>(value);
377         setDbusValue(v);
378     }
379     else if (dBusMap.propertyType == "double")
380     {
381         std::variant<double> v = std::get<double>(value);
382         setDbusValue(v);
383     }
384     else if (dBusMap.propertyType == "string")
385     {
386         std::variant<std::string> v = std::get<std::string>(value);
387         setDbusValue(v);
388     }
389     else
390     {
391         error("Unsupported property type '{TYPE}'", "TYPE",
392               dBusMap.propertyType);
393         throw std::invalid_argument("UnSupported Dbus Type");
394     }
395 }
396 
getDbusPropertyVariant(const char * objPath,const char * dbusProp,const char * dbusInterface) const397 PropertyValue DBusHandler::getDbusPropertyVariant(
398     const char* objPath, const char* dbusProp, const char* dbusInterface) const
399 {
400     auto& bus = DBusHandler::getBus();
401     auto service = getService(objPath, dbusInterface);
402     auto method =
403         bus.new_method_call(service.c_str(), objPath, dbusProperties, "Get");
404     method.append(dbusInterface, dbusProp);
405     return bus.call(method, dbusTimeout).unpack<PropertyValue>();
406 }
407 
getManagedObj(const char * service,const char * rootPath)408 ObjectValueTree DBusHandler::getManagedObj(const char* service,
409                                            const char* rootPath)
410 {
411     auto& bus = DBusHandler::getBus();
412     auto method = bus.new_method_call(service, rootPath,
413                                       "org.freedesktop.DBus.ObjectManager",
414                                       "GetManagedObjects");
415     return bus.call(method).unpack<ObjectValueTree>();
416 }
417 
getDbusPropertiesVariant(const char * serviceName,const char * objPath,const char * dbusInterface) const418 PropertyMap DBusHandler::getDbusPropertiesVariant(
419     const char* serviceName, const char* objPath,
420     const char* dbusInterface) const
421 {
422     auto& bus = DBusHandler::getBus();
423     auto method =
424         bus.new_method_call(serviceName, objPath, dbusProperties, "GetAll");
425     method.append(dbusInterface);
426     return bus.call(method, dbusTimeout).unpack<PropertyMap>();
427 }
428 
jsonEntryToDbusVal(std::string_view type,const nlohmann::json & value)429 PropertyValue jsonEntryToDbusVal(std::string_view type,
430                                  const nlohmann::json& value)
431 {
432     PropertyValue propValue{};
433     if (type == "uint8_t")
434     {
435         propValue = static_cast<uint8_t>(value);
436     }
437     else if (type == "uint16_t")
438     {
439         propValue = static_cast<uint16_t>(value);
440     }
441     else if (type == "uint32_t")
442     {
443         propValue = static_cast<uint32_t>(value);
444     }
445     else if (type == "uint64_t")
446     {
447         propValue = static_cast<uint64_t>(value);
448     }
449     else if (type == "int16_t")
450     {
451         propValue = static_cast<int16_t>(value);
452     }
453     else if (type == "int32_t")
454     {
455         propValue = static_cast<int32_t>(value);
456     }
457     else if (type == "int64_t")
458     {
459         propValue = static_cast<int64_t>(value);
460     }
461     else if (type == "bool")
462     {
463         propValue = static_cast<bool>(value);
464     }
465     else if (type == "double")
466     {
467         propValue = static_cast<double>(value);
468     }
469     else if (type == "string")
470     {
471         propValue = static_cast<std::string>(value);
472     }
473     else
474     {
475         error("Unknown D-Bus property type '{TYPE}'", "TYPE", type);
476     }
477 
478     return propValue;
479 }
480 
findStateEffecterId(const pldm_pdr * pdrRepo,uint16_t entityType,uint16_t entityInstance,uint16_t containerId,uint16_t stateSetId,bool localOrRemote)481 uint16_t findStateEffecterId(const pldm_pdr* pdrRepo, uint16_t entityType,
482                              uint16_t entityInstance, uint16_t containerId,
483                              uint16_t stateSetId, bool localOrRemote)
484 {
485     uint8_t* pdrData = nullptr;
486     uint32_t pdrSize{};
487     const pldm_pdr_record* record{};
488     do
489     {
490         record = pldm_pdr_find_record_by_type(pdrRepo, PLDM_STATE_EFFECTER_PDR,
491                                               record, &pdrData, &pdrSize);
492         if (record && (localOrRemote ^ pldm_pdr_record_is_remote(record)))
493         {
494             auto pdr = reinterpret_cast<pldm_state_effecter_pdr*>(pdrData);
495             auto compositeEffecterCount = pdr->composite_effecter_count;
496             auto possible_states_start = pdr->possible_states;
497 
498             for (auto effecters = 0x00; effecters < compositeEffecterCount;
499                  effecters++)
500             {
501                 auto possibleStates =
502                     reinterpret_cast<state_effecter_possible_states*>(
503                         possible_states_start);
504                 auto setId = possibleStates->state_set_id;
505                 auto possibleStateSize = possibleStates->possible_states_size;
506 
507                 if (entityType == pdr->entity_type &&
508                     entityInstance == pdr->entity_instance &&
509                     containerId == pdr->container_id && stateSetId == setId)
510                 {
511                     return pdr->effecter_id;
512                 }
513                 possible_states_start += possibleStateSize + sizeof(setId) +
514                                          sizeof(possibleStateSize);
515             }
516         }
517     } while (record);
518 
519     return PLDM_INVALID_EFFECTER_ID;
520 }
521 
emitStateSensorEventSignal(uint8_t tid,uint16_t sensorId,uint8_t sensorOffset,uint8_t eventState,uint8_t previousEventState)522 int emitStateSensorEventSignal(uint8_t tid, uint16_t sensorId,
523                                uint8_t sensorOffset, uint8_t eventState,
524                                uint8_t previousEventState)
525 {
526     try
527     {
528         auto& bus = DBusHandler::getBus();
529         auto msg = bus.new_signal("/xyz/openbmc_project/pldm",
530                                   "xyz.openbmc_project.PLDM.Event",
531                                   "StateSensorEvent");
532         msg.append(tid, sensorId, sensorOffset, eventState, previousEventState);
533 
534         msg.signal_send();
535     }
536     catch (const std::exception& e)
537     {
538         error("Failed to emit pldm event signal, error - {ERROR}", "ERROR", e);
539         return PLDM_ERROR;
540     }
541 
542     return PLDM_SUCCESS;
543 }
544 
findStateSensorId(const pldm_pdr * pdrRepo,uint8_t tid,uint16_t entityType,uint16_t entityInstance,uint16_t containerId,uint16_t stateSetId)545 uint16_t findStateSensorId(const pldm_pdr* pdrRepo, uint8_t tid,
546                            uint16_t entityType, uint16_t entityInstance,
547                            uint16_t containerId, uint16_t stateSetId)
548 {
549     auto pdrs = findStateSensorPDR(tid, entityType, stateSetId, pdrRepo);
550     for (auto pdr : pdrs)
551     {
552         auto sensorPdr = reinterpret_cast<pldm_state_sensor_pdr*>(pdr.data());
553         auto compositeSensorCount = sensorPdr->composite_sensor_count;
554         auto possible_states_start = sensorPdr->possible_states;
555 
556         for (auto sensors = 0x00; sensors < compositeSensorCount; sensors++)
557         {
558             auto possibleStates =
559                 reinterpret_cast<state_sensor_possible_states*>(
560                     possible_states_start);
561             auto setId = possibleStates->state_set_id;
562             auto possibleStateSize = possibleStates->possible_states_size;
563             if (entityType == sensorPdr->entity_type &&
564                 entityInstance == sensorPdr->entity_instance &&
565                 stateSetId == setId && containerId == sensorPdr->container_id)
566             {
567                 return sensorPdr->sensor_id;
568             }
569             possible_states_start +=
570                 possibleStateSize + sizeof(setId) + sizeof(possibleStateSize);
571         }
572     }
573     return PLDM_INVALID_EFFECTER_ID;
574 }
575 
printBuffer(bool isTx,const std::vector<uint8_t> & buffer)576 void printBuffer(bool isTx, const std::vector<uint8_t>& buffer)
577 {
578     if (buffer.empty())
579     {
580         return;
581     }
582 
583     std::cout << (isTx ? "Tx: " : "Rx: ");
584 
585     std::ranges::for_each(buffer, [](uint8_t byte) {
586         std::cout << std::format("{:02x} ", byte);
587     });
588 
589     std::cout << std::endl;
590 }
591 
toString(const struct variable_field & var)592 std::string toString(const struct variable_field& var)
593 {
594     if (var.ptr == nullptr || !var.length)
595     {
596         return "";
597     }
598 
599     std::string str(reinterpret_cast<const char*>(var.ptr), var.length);
600     std::replace_if(
601         str.begin(), str.end(), [](const char& c) { return !isprint(c); }, ' ');
602     return str;
603 }
604 
split(std::string_view srcStr,std::string_view delim,std::string_view trimStr)605 std::vector<std::string> split(std::string_view srcStr, std::string_view delim,
606                                std::string_view trimStr)
607 {
608     std::vector<std::string> out;
609     size_t start;
610     size_t end = 0;
611 
612     while ((start = srcStr.find_first_not_of(delim, end)) != std::string::npos)
613     {
614         end = srcStr.find(delim, start);
615         std::string_view dstStr = srcStr.substr(start, end - start);
616         if (!trimStr.empty())
617         {
618             dstStr.remove_prefix(dstStr.find_first_not_of(trimStr));
619             dstStr.remove_suffix(
620                 dstStr.size() - 1 - dstStr.find_last_not_of(trimStr));
621         }
622 
623         if (!dstStr.empty())
624         {
625             out.push_back(std::string(dstStr));
626         }
627     }
628 
629     return out;
630 }
631 
getCurrentSystemTime()632 std::string getCurrentSystemTime()
633 {
634     const auto zonedTime{std::chrono::zoned_time{
635         std::chrono::current_zone(), std::chrono::system_clock::now()}};
636     return std::format("{:%F %Z %T}", zonedTime);
637 }
638 
checkForFruPresence(const std::string & objPath)639 bool checkForFruPresence(const std::string& objPath)
640 {
641     bool isPresent = false;
642     static constexpr auto presentInterface =
643         "xyz.openbmc_project.Inventory.Item";
644     static constexpr auto presentProperty = "Present";
645     try
646     {
647         auto propVal = pldm::utils::DBusHandler().getDbusPropertyVariant(
648             objPath.c_str(), presentProperty, presentInterface);
649         isPresent = std::get<bool>(propVal);
650     }
651     catch (const sdbusplus::exception::SdBusError& e)
652     {
653         error("Failed to check for FRU presence at {PATH}, error - {ERROR}",
654               "PATH", objPath, "ERROR", e);
655     }
656     return isPresent;
657 }
658 
checkIfLogicalBitSet(const uint16_t & containerId)659 bool checkIfLogicalBitSet(const uint16_t& containerId)
660 {
661     return !(containerId & 0x8000);
662 }
663 
setFruPresence(const std::string & fruObjPath,bool present)664 void setFruPresence(const std::string& fruObjPath, bool present)
665 {
666     pldm::utils::PropertyValue value{present};
667     pldm::utils::DBusMapping dbusMapping;
668     dbusMapping.objectPath = fruObjPath;
669     dbusMapping.interface = "xyz.openbmc_project.Inventory.Item";
670     dbusMapping.propertyName = "Present";
671     dbusMapping.propertyType = "bool";
672     try
673     {
674         pldm::utils::DBusHandler().setDbusProperty(dbusMapping, value);
675     }
676     catch (const std::exception& e)
677     {
678         error(
679             "Failed to set the present property on path '{PATH}', error - {ERROR}.",
680             "PATH", fruObjPath, "ERROR", e);
681     }
682 }
683 
trimNameForDbus(std::string & name)684 std::string_view trimNameForDbus(std::string& name)
685 {
686     std::replace(name.begin(), name.end(), ' ', '_');
687     auto nullTerminatorPos = name.find('\0');
688     if (nullTerminatorPos != std::string::npos)
689     {
690         name.erase(nullTerminatorPos);
691     }
692     return name;
693 }
694 
dbusPropValuesToDouble(const std::string_view & type,const pldm::utils::PropertyValue & value,double * doubleValue)695 bool dbusPropValuesToDouble(const std::string_view& type,
696                             const pldm::utils::PropertyValue& value,
697                             double* doubleValue)
698 {
699     if (!dbusValueNumericTypeNames.contains(type))
700     {
701         return false;
702     }
703 
704     if (!doubleValue)
705     {
706         return false;
707     }
708 
709     try
710     {
711         if (type == "uint8_t")
712         {
713             *doubleValue = static_cast<double>(std::get<uint8_t>(value));
714         }
715         else if (type == "int16_t")
716         {
717             *doubleValue = static_cast<double>(std::get<int16_t>(value));
718         }
719         else if (type == "uint16_t")
720         {
721             *doubleValue = static_cast<double>(std::get<uint16_t>(value));
722         }
723         else if (type == "int32_t")
724         {
725             *doubleValue = static_cast<double>(std::get<int32_t>(value));
726         }
727         else if (type == "uint32_t")
728         {
729             *doubleValue = static_cast<double>(std::get<uint32_t>(value));
730         }
731         else if (type == "int64_t")
732         {
733             *doubleValue = static_cast<double>(std::get<int64_t>(value));
734         }
735         else if (type == "uint64_t")
736         {
737             *doubleValue = static_cast<double>(std::get<uint64_t>(value));
738         }
739         else if (type == "double")
740         {
741             *doubleValue = static_cast<double>(std::get<double>(value));
742         }
743         else
744         {
745             return false;
746         }
747     }
748     catch (const std::exception& e)
749     {
750         return false;
751     }
752 
753     return true;
754 }
755 
fruFieldValuestring(const uint8_t * value,const uint8_t & length)756 std::optional<std::string> fruFieldValuestring(const uint8_t* value,
757                                                const uint8_t& length)
758 {
759     if (!value || !length)
760     {
761         lg2::error("Fru data to string invalid data.");
762         return std::nullopt;
763     }
764 
765     return std::string(reinterpret_cast<const char*>(value), length);
766 }
767 
fruFieldParserU32(const uint8_t * value,const uint8_t & length)768 std::optional<uint32_t> fruFieldParserU32(const uint8_t* value,
769                                           const uint8_t& length)
770 {
771     if (!value || length != sizeof(uint32_t))
772     {
773         lg2::error("Fru data to u32 invalid data.");
774         return std::nullopt;
775     }
776 
777     uint32_t ret;
778     std::memcpy(&ret, value, length);
779     return ret;
780 }
781 
782 } // namespace utils
783 } // namespace pldm
784