l17.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "os"
  8. "strconv"
  9. "strings"
  10. "time"
  11. mqtt "github.com/eclipse/paho.mqtt.golang"
  12. "github.com/joho/godotenv"
  13. )
  14. type OpenWeather struct {
  15. City string `json:"name"`
  16. Main struct {
  17. Temp float64 `json:"temp"`
  18. FeelLike float64 `json:"feels_like"`
  19. } `json:"main"`
  20. Weather []struct {
  21. MainWeather string `json:"main"`
  22. Description string `json:"description"`
  23. } `json:"weather"`
  24. Wind struct {
  25. Speed float64 `json:"speed"`
  26. } `json:"wind"`
  27. }
  28. func WeatherReq() (string, float64, string, float64, float64, string) {
  29. err := godotenv.Load()
  30. if err != nil {
  31. log.Fatalf("upload your .env file %v\n", err)
  32. }
  33. api := os.Getenv("openweathermap")
  34. if api == "" {
  35. log.Fatalf("add your openweathermap api in .env file\n")
  36. }
  37. city := os.Getenv("city_openweather")
  38. if city == "" {
  39. log.Fatalf("add your city for openweathermap in .env file\n")
  40. }
  41. client := &http.Client{
  42. Timeout: 20 * time.Second,
  43. }
  44. lin := "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&appid=" + api
  45. url := strings.ReplaceAll(lin, " ", "%20")
  46. req, err := http.NewRequest("GET", url, nil)
  47. if err != nil {
  48. log.Fatalf("%v\n", err)
  49. }
  50. resp, err := client.Do(req)
  51. if err != nil {
  52. log.Fatalf("%v\n", err)
  53. }
  54. if resp.StatusCode != 200 {
  55. log.Fatalf("openweathermap return %d\n", resp.StatusCode)
  56. }
  57. defer resp.Body.Close()
  58. var WeatherData OpenWeather
  59. err = json.NewDecoder(resp.Body).Decode(&WeatherData)
  60. if err != nil {
  61. log.Fatalf("%v\n", err)
  62. }
  63. return WeatherData.City, WeatherData.Main.Temp, WeatherData.Weather[0].MainWeather, WeatherData.Wind.Speed, WeatherData.Main.FeelLike, WeatherData.Weather[0].Description
  64. }
  65. func Send(client mqtt.Client, topic string) {
  66. city, temp, main, speed, feel, description := WeatherReq()
  67. payload := fmt.Sprintf("City: %s, Temperature: %.2f°C, Feel like %.2f°C\nWeather: %s, %s, Wind %.2fm/s", city, temp, feel, main, description, speed)
  68. token := client.Publish(topic, 1, false, payload)
  69. token.Wait()
  70. if err := token.Error(); err != nil {
  71. log.Fatalf("%v\n", token.Error())
  72. } else {
  73. fmt.Println("Sent in", topic)
  74. }
  75. }
  76. func main() {
  77. opts := mqtt.NewClientOptions()
  78. err := godotenv.Load()
  79. if err != nil {
  80. log.Fatalf("%v\n", err)
  81. }
  82. broker := os.Getenv("broker_mqtt")
  83. if broker == "" {
  84. log.Fatalf("add yout broker in .env file\n")
  85. }
  86. ClientID := os.Getenv("clientid_mqtt")
  87. if ClientID == "" {
  88. log.Fatalf("add your client id in .env file")
  89. }
  90. topic := os.Getenv("topic_mqtt")
  91. if topic == "" {
  92. log.Fatalf("add your topic in .env file")
  93. }
  94. username := os.Getenv("login_mqtt")
  95. if username != "" {
  96. opts.SetUsername(username)
  97. }
  98. password := os.Getenv("password_mqtt")
  99. if password != "" {
  100. opts.SetPassword(password)
  101. }
  102. TimeHour := os.Getenv("TimeHourSendMQTT")
  103. opts.AddBroker(broker)
  104. opts.SetClientID(ClientID)
  105. opts.SetConnectTimeout(5 * time.Second)
  106. client := mqtt.NewClient(opts)
  107. if token := client.Connect(); token.Wait() && token.Error() != nil {
  108. log.Fatalf("%v\n", token.Error())
  109. }
  110. defer client.Disconnect(250)
  111. fmt.Println("Connect to a broker")
  112. var ticker *time.Ticker
  113. if TimeHour != "" {
  114. ReallyTimeHour, err := strconv.Atoi(TimeHour)
  115. if err != nil {
  116. log.Fatalf("%s\n", err)
  117. }
  118. ticker = time.NewTicker(time.Duration(ReallyTimeHour) * time.Hour)
  119. } else {
  120. ticker = time.NewTicker(2 * time.Hour)
  121. }
  122. defer ticker.Stop()
  123. Send(client, topic)
  124. for range ticker.C {
  125. Send(client, topic)
  126. }
  127. }