mdns.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Module for access to the nodemcu_mdns functions
  2. #include "module.h"
  3. #include "lauxlib.h"
  4. #include <string.h>
  5. #include <stdlib.h>
  6. #include <alloca.h>
  7. #include <stdint.h>
  8. #include "lwip/ip_addr.h"
  9. #include "nodemcu_mdns.h"
  10. #include "user_interface.h"
  11. //
  12. // mdns.close()
  13. //
  14. static int mdns_close(lua_State *L)
  15. {
  16. nodemcu_mdns_close();
  17. return 0;
  18. }
  19. //
  20. // mdns.register(hostname [, { attributes} ])
  21. //
  22. static int mdns_register(lua_State *L)
  23. {
  24. struct nodemcu_mdns_info info;
  25. memset(&info, 0, sizeof(info));
  26. info.host_name = luaL_checkstring(L, 1);
  27. info.service_name = "http";
  28. info.service_port = 80;
  29. info.host_desc = info.host_name;
  30. if (lua_gettop(L) >= 2) {
  31. luaL_checktype(L, 2, LUA_TTABLE);
  32. lua_pushnil(L); // first key
  33. int slot = 0;
  34. while (lua_next(L, 2) != 0 && slot < sizeof(info.txt_data) / sizeof(info.txt_data[0])) {
  35. luaL_checktype(L, -2, LUA_TSTRING);
  36. const char *key = luaL_checkstring(L, -2);
  37. if (strcmp(key, "port") == 0) {
  38. info.service_port = luaL_checkinteger(L, -1);
  39. } else if (strcmp(key, "service") == 0) {
  40. info.service_name = luaL_checkstring(L, -1);
  41. } else if (strcmp(key, "description") == 0) {
  42. info.host_desc = luaL_checkstring(L, -1);
  43. } else {
  44. int len = strlen(key) + 1;
  45. const char *value = luaL_checkstring(L, -1);
  46. char *p = alloca(len + strlen(value) + 1);
  47. strcpy(p, key);
  48. strcat(p, "=");
  49. strcat(p, value);
  50. info.txt_data[slot++] = p;
  51. }
  52. lua_pop(L, 1);
  53. }
  54. }
  55. struct ip_info ipconfig;
  56. uint8_t mode = wifi_get_opmode();
  57. if (!wifi_get_ip_info((mode == 2) ? SOFTAP_IF : STATION_IF, &ipconfig) || !ipconfig.ip.addr) {
  58. return luaL_error(L, "No network connection");
  59. }
  60. // Close up the old session (if any). This cannot fail
  61. // so no chance of losing the memory in 'result'
  62. mdns_close(L);
  63. // Save the result as it appears that nodemcu_mdns_init needs
  64. // to have the data valid while it is running.
  65. if (!nodemcu_mdns_init(&info)) {
  66. mdns_close(L);
  67. return luaL_error(L, "Unable to start mDns daemon");
  68. }
  69. return 0;
  70. }
  71. // Module function map
  72. LROT_BEGIN(mdns, NULL, 0)
  73. LROT_FUNCENTRY( register, mdns_register )
  74. LROT_FUNCENTRY( close, mdns_close )
  75. LROT_END(mdns, NULL, 0)
  76. NODEMCU_MODULE(MDNS, "mdns", mdns, NULL);