MDNSService.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include "MDNSService.h"
  2. #include <arpa/inet.h>
  3. #include <vector>
  4. #include "mdns.h"
  5. using namespace bell;
  6. class implMDNSService : public MDNSService {
  7. private:
  8. const std::string type;
  9. const std::string proto;
  10. void unregisterService() { mdns_service_remove(type.c_str(), proto.c_str()); }
  11. public:
  12. implMDNSService(std::string type, std::string proto)
  13. : type(type), proto(proto){};
  14. };
  15. /**
  16. * ESP32 implementation of MDNSService
  17. * @see https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/protocols/mdns.html
  18. **/
  19. std::unique_ptr<MDNSService> MDNSService::registerService(
  20. const std::string& serviceName, const std::string& serviceType,
  21. const std::string& serviceProto, const std::string& serviceHost,
  22. int servicePort, const std::map<std::string, std::string> txtData) {
  23. std::vector<mdns_txt_item_t> txtItems;
  24. txtItems.reserve(txtData.size());
  25. for (auto& data : txtData) {
  26. mdns_txt_item_t item;
  27. item.key = data.first.c_str();
  28. item.value = data.second.c_str();
  29. txtItems.push_back(item);
  30. }
  31. mdns_service_add(serviceName.c_str(), /* instance_name */
  32. serviceType.c_str(), /* service_type */
  33. serviceProto.c_str(), /* proto */
  34. servicePort, /* port */
  35. txtItems.data(), /* txt */
  36. txtItems.size() /* num_items */
  37. );
  38. return std::make_unique<implMDNSService>(serviceType, serviceProto);
  39. }