temperature.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package controller
  2. import (
  3. "bigdata_archives/app/e"
  4. "bigdata_archives/global"
  5. "bigdata_archives/utils"
  6. "github.com/gin-gonic/gin"
  7. "github.com/gorilla/websocket"
  8. "log"
  9. "time"
  10. )
  11. // GetTemperatureHumidity 获取近一周内所有温湿度情况
  12. func GetTemperatureHumidity(c *gin.Context) {
  13. var temperatureHumidity []utils.Temperature
  14. // 获取当前时间
  15. now := time.Now()
  16. // 计算一周前的时间
  17. oneWeekAgo := now.AddDate(0, 0, -7)
  18. // 格式化时间
  19. formattedTime := oneWeekAgo.Format("2006-01-02 15:04:05")
  20. // 查询最近一周的数据
  21. tx := global.DBLink.Where("upload_time >= ?", formattedTime).Find(&temperatureHumidity)
  22. if tx.Error == nil && tx.RowsAffected >= 0 {
  23. e.ResponseSuccess(c, temperatureHumidity)
  24. return
  25. }
  26. e.ResponseWithMsg(c, e.FIndFail, e.FIndFail.GetMsg())
  27. }
  28. var upgrader = websocket.Upgrader{
  29. ReadBufferSize: 1024,
  30. WriteBufferSize: 1024,
  31. }
  32. func WebSocketHandler(c *gin.Context) {
  33. conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
  34. if err != nil {
  35. log.Println(err)
  36. return
  37. }
  38. defer conn.Close()
  39. for {
  40. // 发送最新一周内的温度湿度数据
  41. if len(utils.LatestData) > 0 {
  42. err := conn.WriteJSON(utils.LatestData)
  43. if err != nil {
  44. log.Println(err)
  45. break
  46. }
  47. }
  48. time.Sleep(1 * time.Second) // 每分钟发送一次数据
  49. }
  50. }
  51. // GetTemperatureHumidityInRange 获取指定时间范围内温湿度情况
  52. func GetTemperatureHumidityInRange(c *gin.Context, startTime, endTime string) {
  53. var temperatureHumidity []utils.Temperature
  54. // 使用传入的起始时间和结束时间查询数据
  55. global.DBLink.Where("upload_time BETWEEN ? AND ?", startTime, endTime).Find(&temperatureHumidity)
  56. // 可以进一步处理temperatureHumidity数据或者直接返回给客户端
  57. }