nd_qxz_data.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. from datetime import datetime
  2. import pymongo
  3. import pandas as pd
  4. from urllib import parse
  5. import requests
  6. import os
  7. import sys
  8. import django
  9. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  10. sys.path.append(BASE_DIR)
  11. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bigdataAPI.settings')
  12. django.setup()
  13. from apps.PestAnalysis.models import EnvTempHum, HeNanAddr
  14. def bigata_mongo():
  15. user = parse.quote_plus("root")
  16. passwd = parse.quote_plus("yfkj@6020")
  17. myclient = pymongo.MongoClient("mongodb://{0}:{1}@8.136.98.49:57017/".format(user,passwd))
  18. return myclient
  19. def device_aggrate():
  20. myclient = bigata_mongo()
  21. mydb = myclient.smartfarming
  22. mycol = mydb.sa_device
  23. query = [
  24. {
  25. "$match": {
  26. "province": "河南省",
  27. "device_type_id": 15
  28. }
  29. },
  30. {
  31. "$group": {
  32. "_id": {
  33. "province": "$province",
  34. "city": "$city",
  35. "district": "$district"
  36. },
  37. "device_ids": { "$addToSet": "$device_id" },
  38. "unique_count": { "$sum": 1 }
  39. }
  40. },
  41. {
  42. "$project": {
  43. "location": "$_id",
  44. "device_ids": 1,
  45. "unique_count": 1,
  46. "_id": 0
  47. }
  48. }
  49. ]
  50. result = mycol.aggregate(query)
  51. # for i in list(result):
  52. # device_ids = i.get("device_ids")
  53. # count = i.get("unique_count")
  54. # location = i.get("location")
  55. # print("地址:", location, "数量", count)
  56. myclient.close()
  57. return list(result)
  58. def nd_qxz_data(device_ids, start, end):
  59. myclient = bigata_mongo()
  60. mydb = myclient.smartfarming
  61. mycol = mydb.sa_nd_qxz_data
  62. query = {
  63. "upl_time": {
  64. "$gte": start,
  65. "$lte": end
  66. },
  67. "device_id": {
  68. "$in": device_ids
  69. }
  70. }
  71. project = {
  72. "_id": 0,
  73. "temp": 1,
  74. "swc": 1
  75. }
  76. nd_data = mycol.find(query,project)
  77. myclient.close()
  78. nd_data = list(nd_data)
  79. tmp_list = {}
  80. if nd_data:
  81. for k in nd_data:
  82. temp = k.get("temp")
  83. swc = k.get("swc")
  84. if temp:
  85. temp = temp.split(",")
  86. for index, ti in enumerate(temp):
  87. try:
  88. ti = float(ti)
  89. except:
  90. ti = 0
  91. if "temp_" + str(index) in tmp_list:
  92. tmp_list["temp_" + str(index)].append(ti)
  93. else:
  94. tmp_list["temp_" + str(index)] = [ti]
  95. if swc:
  96. swc = swc.split(",")
  97. for index, si in enumerate(swc):
  98. try:
  99. si = float(si)
  100. except:
  101. si = 0
  102. if "swc_" + str(index) in tmp_list:
  103. tmp_list["swc_" + str(index)].append(si)
  104. else:
  105. tmp_list["swc_" + str(index)] = [si]
  106. avg_data = {}
  107. for k, v in tmp_list.items():
  108. avg_data[k] = round(sum(v) / len(v), 2)
  109. return avg_data
  110. def main(start_y, end_y):
  111. start_year = datetime(start_y, 1, 1, 0, 0, 0).timestamp()
  112. end_year = datetime(end_y, 1, 1, 0, 0, 0).timestamp()
  113. device_addr = device_aggrate()
  114. for i in device_addr:
  115. device_ids = i.get("device_ids")
  116. location = i.get("location")
  117. province = location.get("province")
  118. city = location.get("city")
  119. district = location.get("district")
  120. print(district)
  121. henan = HeNanAddr.objects.filter(province=province, city=city, district=district)
  122. if henan.exists():
  123. henan = henan.first()
  124. addr_code = henan.code
  125. if addr_code:
  126. # 时间
  127. for r in range(int(start_year), int(end_year), 86400):
  128. data = nd_qxz_data(device_ids, r, r + 86400)
  129. format_date = datetime.fromtimestamp(r).strftime("%Y-%m-%d")
  130. for k, v in data.items():
  131. if k.startswith("temp"):
  132. k_lst = k.split("_")
  133. if len(k_lst) == 2:
  134. title = f"{(int(k_lst[1]) + 1) * 10}cm土壤温度"
  135. EnvTempHum.objects.create(
  136. title = title,
  137. value = v,
  138. unit = "℃",
  139. type = "1",
  140. date = r,
  141. format_date = format_date,
  142. province = province,
  143. city = city,
  144. district = district,
  145. addr_code = addr_code
  146. )
  147. elif k.startswith("swc"):
  148. k_lst = k.split("_")
  149. if len(k_lst) == 2:
  150. title = f"{(int(k_lst[1]) + 1) * 10}cm土壤湿度"
  151. EnvTempHum.objects.create(
  152. title = title,
  153. value = v,
  154. unit = "%",
  155. type = "2",
  156. date = r,
  157. format_date = format_date,
  158. province = province,
  159. city = city,
  160. district = district,
  161. addr_code = addr_code
  162. )
  163. if __name__ == '__main__':
  164. main(2024, 2025)