l17.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package main
  2. import (
  3. "log"
  4. "github.com/joho/godotenv"
  5. "os"
  6. "strings"
  7. "net/http"
  8. "time"
  9. "encoding/json"
  10. mqtt "github.com/eclipse/paho.mqtt.golang"
  11. "fmt"
  12. "strconv"
  13. )
  14. type OpenWeather struct{
  15. City string `json:"name"`
  16. Main struct {
  17. Temp float64 `json:"temp"`
  18. } `json:"main"`
  19. }
  20. func WeatherReq() (string, float64) {
  21. err := godotenv.Load()
  22. if err != nil {
  23. log.Fatalf("%v\n", err)
  24. }
  25. api := os.Getenv("openweathermap")
  26. city := os.Getenv("city_openweather")
  27. client := &http.Client{
  28. Timeout: 20 * time.Second,
  29. }
  30. link := "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&appid=" + api
  31. url := strings.ReplaceAll(link, " ", "%20")
  32. req, err := http.NewRequest("GET", url, nil)
  33. if err != nil {
  34. log.Fatalf("%v\n", err)
  35. }
  36. resp, err := client.Do(req)
  37. if err != nil {
  38. log.Fatalf("%v\n", err)
  39. }
  40. defer resp.Body.Close()
  41. var WeatherData OpenWeather
  42. err = json.NewDecoder(resp.Body).Decode(&WeatherData)
  43. if err != nil {
  44. log.Fatalf("%v\n", err)
  45. }
  46. return WeatherData.City, WeatherData.Main.Temp
  47. }
  48. func Send(client mqtt.Client, topic string) {
  49. city, temp := WeatherReq()
  50. payload := fmt.Sprintf("City: %s, Temperature: %.2f°C", city, temp)
  51. token := client.Publish(topic, 1, false, payload)
  52. token.Wait()
  53. if err := token.Error(); err != nil {
  54. log.Fatalf("%v\n", token.Error)
  55. } else {
  56. fmt.Println("Sent in", topic)
  57. }
  58. }
  59. func main() {
  60. err := godotenv.Load()
  61. if err != nil { log.Fatalf("%v\n", err) }
  62. broker := os.Getenv("broker_mqtt")
  63. ClientID := os.Getenv("clientid_mqtt")
  64. topic := os.Getenv("topic_mqtt")
  65. username := os.Getenv("login_mqtt")
  66. password := os.Getenv("password_mqtt")
  67. TimeHour := os.Getenv("TimeHourSendMQTT")
  68. ReallyTimeHour, err := strconv.Atoi(TimeHour)
  69. opts := mqtt.NewClientOptions()
  70. opts.AddBroker(broker)
  71. opts.SetClientID(ClientID)
  72. opts.SetConnectTimeout(5 * time.Second)
  73. opts.SetUsername(username)
  74. opts.SetPassword(password)
  75. client := mqtt.NewClient(opts)
  76. if token := client.Connect(); token.Wait() && token.Error() != nil { log.Fatalf("%v\n", token.Error()) }
  77. defer client.Disconnect(250)
  78. fmt.Println("Connect to a broker")
  79. ticker := time.NewTicker(time.Duration(ReallyTimeHour) * time.Hour)
  80. defer ticker.Stop()
  81. Send(client, topic)
  82. for range ticker.C {
  83. Send(client, topic)
  84. }
  85. }