l17.go 3.2 KB

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