series_service.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. """PKS 原始采样曲线:按设备与时间窗口读取 YSJ_5 / YSJ_10 / YSJ_11。
  2. 只取运行样本(``YSJ_41 > 0``);停机造成的长时间空档插入空点,让曲线断开。
  3. """
  4. from datetime import timedelta
  5. from typing import Any
  6. from db import connect
  7. GAP = timedelta(seconds=60)
  8. def _num(value: Any) -> float | None:
  9. """0(传感器掉点/停机残留)视为无效,置空以断开曲线。"""
  10. try:
  11. number = float(value) if value is not None else None
  12. except (TypeError, ValueError):
  13. return None
  14. if number is None or number <= 0:
  15. return None
  16. return number
  17. def query_series(device_code: str, start: str, end: str) -> dict[str, Any]:
  18. connection = connect()
  19. try:
  20. with connection.cursor() as cursor:
  21. cursor.execute(
  22. """
  23. SELECT sample_time, YSJ_5, YSJ_10, YSJ_11
  24. FROM pks_long_sample
  25. WHERE device_code = %s AND sample_time >= %s AND sample_time <= %s
  26. AND YSJ_41 > 0
  27. ORDER BY sample_time
  28. """,
  29. (device_code, start, end),
  30. )
  31. rows = cursor.fetchall()
  32. finally:
  33. connection.close()
  34. times: list[str] = []
  35. oil: list[float | None] = []
  36. coupling: list[float | None] = []
  37. chain: list[float | None] = []
  38. previous = None
  39. for row in rows:
  40. moment = row["sample_time"]
  41. if previous is not None and (moment - previous) > GAP:
  42. middle = previous + (moment - previous) / 2
  43. times.append(middle.strftime("%Y-%m-%d %H:%M:%S"))
  44. oil.append(None)
  45. coupling.append(None)
  46. chain.append(None)
  47. times.append(moment.strftime("%Y-%m-%d %H:%M:%S"))
  48. oil.append(_num(row["YSJ_5"]))
  49. coupling.append(_num(row["YSJ_10"]))
  50. chain.append(_num(row["YSJ_11"]))
  51. previous = moment
  52. return {
  53. "device_code": device_code,
  54. "start": start,
  55. "end": end,
  56. "count": len(times),
  57. "times": times,
  58. "oil": oil,
  59. "coupling": coupling,
  60. "chain": chain,
  61. }