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