l17.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  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. 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. link := "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&appid=" + api
  45. url := strings.ReplaceAll(link, " ", "%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 { log.Fatalf("%v\n", err) }
  80. broker := os.Getenv("broker_mqtt")
  81. if broker == "" { log.Fatalf("add yout broker in .env file\n") }
  82. ClientID := os.Getenv("clientid_mqtt")
  83. if ClientID == "" { log.Fatalf("add your client id in .env file") }
  84. topic := os.Getenv("topic_mqtt")
  85. if topic == "" { log.Fatalf("add your topic in .env file") }
  86. username := os.Getenv("login_mqtt")
  87. if username != "" { opts.SetUsername(username) }
  88. password := os.Getenv("password_mqtt")
  89. if password != "" { opts.SetPassword(password) }
  90. TimeHour := os.Getenv("TimeHourSendMQTT")
  91. opts.AddBroker(broker)
  92. opts.SetClientID(ClientID)
  93. opts.SetConnectTimeout(5 * time.Second)
  94. client := mqtt.NewClient(opts)
  95. if token := client.Connect(); token.Wait() && token.Error() != nil { log.Fatalf("%v\n", token.Error()) }
  96. defer client.Disconnect(250)
  97. fmt.Println("Connect to a broker")
  98. var ticker *time.Ticker
  99. if TimeHour != "" {
  100. ReallyTimeHour, err := strconv.Atoi(TimeHour)
  101. if err != nil { log.Fatalf("%s\n", err) }
  102. ticker = time.NewTicker(time.Duration(ReallyTimeHour) * time.Hour)
  103. } else {
  104. ticker = time.NewTicker(2 * time.Hour)
  105. }
  106. defer ticker.Stop()
  107. Send(client, topic)
  108. for range ticker.C {
  109. Send(client, topic)
  110. }
  111. }