l17.go 2.9 KB

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