my/go/l17.go

96 lines
2.2 KiB
Go
Raw Normal View History

package main
import (
"log"
"github.com/joho/godotenv"
"os"
"strings"
"net/http"
"time"
"encoding/json"
2026-06-16 22:21:43 +03:00
mqtt "github.com/eclipse/paho.mqtt.golang"
"fmt"
"strconv"
)
type OpenWeather struct{
City string `json:"name"`
Main struct {
Temp float64 `json:"temp"`
} `json:"main"`
}
2026-06-16 22:21:43 +03:00
func WeatherReq() (string, float64) {
err := godotenv.Load()
if err != nil {
log.Fatalf("%v\n", err)
}
api := os.Getenv("openweathermap")
city := os.Getenv("city_openweather")
client := &http.Client{
Timeout: 20 * time.Second,
}
link := "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&appid=" + api
url := strings.ReplaceAll(link, " ", "%20")
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Fatalf("%v\n", err)
}
resp, err := client.Do(req)
if err != nil {
log.Fatalf("%v\n", err)
}
2026-06-16 22:21:43 +03:00
defer resp.Body.Close()
var WeatherData OpenWeather
err = json.NewDecoder(resp.Body).Decode(&WeatherData)
if err != nil {
log.Fatalf("%v\n", err)
}
2026-06-16 22:21:43 +03:00
return WeatherData.City, WeatherData.Main.Temp
}
func Send(client mqtt.Client, topic string) {
city, temp := WeatherReq()
payload := fmt.Sprintf("City: %s, Temperature: %.2f°C", city, temp)
token := client.Publish(topic, 1, false, payload)
token.Wait()
if err := token.Error(); err != nil {
log.Fatalf("%v\n", token.Error)
} else {
fmt.Println("Sent in", topic)
}
}
2026-06-16 22:21:43 +03:00
func main() {
err := godotenv.Load()
if err != nil { log.Fatalf("%v\n", err) }
broker := os.Getenv("broker_mqtt")
ClientID := os.Getenv("clientid_mqtt")
topic := os.Getenv("topic_mqtt")
2026-06-17 22:25:34 +03:00
username := os.Getenv("login_mqtt")
password := os.Getenv("password_mqtt")
TimeHour := os.Getenv("TimeHourSendMQTT")
ReallyTimeHour, err := strconv.Atoi(TimeHour)
2026-06-16 22:21:43 +03:00
opts := mqtt.NewClientOptions()
opts.AddBroker(broker)
opts.SetClientID(ClientID)
opts.SetConnectTimeout(5 * time.Second)
2026-06-17 22:25:34 +03:00
opts.SetUsername(username)
opts.SetPassword(password)
2026-06-16 22:21:43 +03:00
client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil { log.Fatalf("%v\n", token.Error()) }
defer client.Disconnect(250)
fmt.Println("Connect to a broker")
ticker := time.NewTicker(time.Duration(ReallyTimeHour) * time.Hour)
defer ticker.Stop()
Send(client, topic)
2026-06-16 22:21:43 +03:00
for range ticker.C {
Send(client, topic)
2026-06-16 22:21:43 +03:00
}
}