1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- package controller
- import (
- "bigdata_archives/app/e"
- "bigdata_archives/global"
- "bigdata_archives/utils"
- "github.com/gin-gonic/gin"
- "github.com/gorilla/websocket"
- "log"
- "time"
- )
- // GetTemperatureHumidity 获取近一周内所有温湿度情况
- func GetTemperatureHumidity(c *gin.Context) {
- var temperatureHumidity []utils.Temperature
- // 获取当前时间
- now := time.Now()
- // 计算一周前的时间
- oneWeekAgo := now.AddDate(0, 0, -7)
- // 格式化时间
- formattedTime := oneWeekAgo.Format("2006-01-02 15:04:05")
- // 查询最近一周的数据
- tx := global.DBLink.Where("upload_time >= ?", formattedTime).Find(&temperatureHumidity)
- if tx.Error == nil && tx.RowsAffected >= 0 {
- e.ResponseSuccess(c, temperatureHumidity)
- return
- }
- e.ResponseWithMsg(c, e.FIndFail, e.FIndFail.GetMsg())
- }
- var upgrader = websocket.Upgrader{
- ReadBufferSize: 1024,
- WriteBufferSize: 1024,
- }
- func WebSocketHandler(c *gin.Context) {
- conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
- if err != nil {
- log.Println(err)
- return
- }
- defer conn.Close()
- for {
- // 发送最新一周内的温度湿度数据
- if len(utils.LatestData) > 0 {
- err := conn.WriteJSON(utils.LatestData)
- if err != nil {
- log.Println(err)
- break
- }
- }
- time.Sleep(1 * time.Second) // 每分钟发送一次数据
- }
- }
- // GetTemperatureHumidityInRange 获取指定时间范围内温湿度情况
- func GetTemperatureHumidityInRange(c *gin.Context, startTime, endTime string) {
- var temperatureHumidity []utils.Temperature
- // 使用传入的起始时间和结束时间查询数据
- global.DBLink.Where("upload_time BETWEEN ? AND ?", startTime, endTime).Find(&temperatureHumidity)
- // 可以进一步处理temperatureHumidity数据或者直接返回给客户端
- }
|