app.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import eventlet
  2. import json
  3. from flask import Flask, render_template
  4. from flask_mqtt import Mqtt
  5. from flask_socketio import SocketIO
  6. from flask_bootstrap import Bootstrap
  7. from flask_sqlalchemy import SQLAlchemy
  8. import pymysql
  9. from models import *
  10. from sqlalchemy import text
  11. from datetime import datetime as dt
  12. import json
  13. #綠化(綠色線程)所有系統模組,實現IO多路複用
  14. eventlet.monkey_patch()
  15. pymysql.install_as_MySQLdb()
  16. app = Flask(__name__)
  17. app.config['SECRET'] = 'my secret key'
  18. app.config['TEMPLATES_AUTO_RELOAD'] = True
  19. app.config['MQTT_BROKER_URL'] = '54.248.68.32'
  20. app.config['MQTT_BROKER_PORT'] = 1883
  21. app.config['MQTT_USERNAME'] = 'aisky-client'
  22. app.config['MQTT_PASSWORD'] = 'aiskyc'
  23. app.config['MQTT_KEEPALIVE'] = 60
  24. app.config['MQTT_TLS_ENABLED'] = False
  25. db = SQLAlchemy(app)
  26. # 配置數據庫的連接字符串
  27. app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://land:skyeye@13.113.114.87:3306/LandGreen'
  28. # 配置數據庫內容再更新時自動提交
  29. app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
  30. # 如果設置成True(默認情況),Flask-SQLAlchemy 將會追蹤對象的修改並且發送信號
  31. app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
  32. # 配置session所需要的秘鑰
  33. app.config['SECRET_KEY'] = 'you guess'
  34. # template 有修改後,會自動去更新
  35. app.config['TEMPLATES_AUTO_RELOAD'] = True
  36. # Parameters for SSL enabled
  37. # app.config['MQTT_BROKER_PORT'] = 8883
  38. # app.config['MQTT_TLS_ENABLED'] = True
  39. # app.config['MQTT_TLS_INSECURE'] = True
  40. # app.config['MQTT_TLS_CA_CERTS'] = 'ca.crt'
  41. mqtt = Mqtt(app)
  42. socketio = SocketIO(app)
  43. bootstrap = Bootstrap(app)
  44. sw1_status = 0
  45. sw2_status = 0
  46. response_status = 0
  47. @app.route('/')
  48. def index():
  49. global response_status
  50. return render_template('index.html', params=locals())
  51. #監聽來自publish事件
  52. @socketio.on('publish')
  53. def handle_publish(json_str):
  54. data = json.loads(json_str)
  55. topic = data['topic']
  56. del data['topic']
  57. del data['qos']
  58. #switch開關
  59. command_dict = {"sw1":0, "sw2":0, "sw3":0, "sw4":0, "sw5":0, "sw6":0, "sw7":0,
  60. "sw8":0, "sw9":0, "sw10":0, "sw11":0, "sw12":0}
  61. data['command'] = "sw"
  62. for command in command_dict:
  63. data[command] = command_dict[command]
  64. stem = StemSystem.query.order_by(text('datetime desc')).first()
  65. root = RootSystem.query.order_by(text('datetime desc')).first()
  66. liquid = LiquidTank.query.order_by(text('datetime desc')).first()
  67. fitolab1 = Fitolab1Sensor.query.order_by(text('datetime desc')).first()
  68. current_time = dt.now()
  69. current_str_time = str(dt.now())[:16]
  70. global sw1_status
  71. global sw2_status
  72. global response_status
  73. try:
  74. tem_tem1 = stem.tem_tem1[:-2]
  75. tem_start1 = dt.strptime(current_str_time[:11] + stem.tem_start1, "%Y-%m-%d %H:%M")
  76. tem_end1 = dt.strptime(current_str_time[:11] + stem.tem_end1, "%Y-%m-%d %H:%M")
  77. print(tem_tem1, fitolab1.s_air_tem1, tem_start1, tem_end1, current_time, sep="\n")
  78. if str(fitolab1.s_air_tem1) > tem_tem1 and tem_start1 <= current_time < tem_end1:
  79. if response_status == 0:
  80. json_data = json.dumps(data)
  81. mqtt.publish(topic=topic, payload=json_data)
  82. else:
  83. if sw1_status == 0:
  84. data["sw1"] = 1
  85. sw1_status = 1
  86. json_data = json.dumps(data)
  87. mqtt.publish(topic=topic, payload=json_data)
  88. elif str(fitolab1.s_air_tem1) == tem_tem1 and tem_start1 <= current_time < tem_end1:
  89. if response_status == 0:
  90. json_data = json.dumps(data)
  91. mqtt.publish(topic=topic, payload=json_data)
  92. else:
  93. if sw1_status == 1:
  94. data["sw1"] = 0
  95. sw1_status = 0
  96. json_data = json.dumps(data)
  97. mqtt.publish(topic=topic, payload=json_data)
  98. if sw2_status == 1:
  99. data["sw2"] = 0
  100. sw2_status = 0
  101. json_data = json.dumps(data)
  102. mqtt.publish(topic=topic, payload=json_data)
  103. elif str(fitolab1.s_air_tem1) < tem_tem1 and tem_start1 <= current_time < tem_end1:
  104. if response_status == 0:
  105. json_data = json.dumps(data)
  106. mqtt.publish(topic=topic, payload=json_data)
  107. else:
  108. if sw2_status == 0:
  109. data["sw2"] = 1
  110. sw2_status = 1
  111. json_data = json.dumps(data)
  112. mqtt.publish(topic=topic, payload=json_data)
  113. elif current_time >= tem_end1:
  114. if sw1_status == 1:
  115. data["sw1"] = 0
  116. sw1_status = 0
  117. if sw2_status == 1:
  118. data["sw2"] = 0
  119. sw2_status = 0
  120. json_data = json.dumps(data)
  121. mqtt.publish(topic=topic, payload=json_data)
  122. except Exception:
  123. pass
  124. try:
  125. tem_tem2 = stem.tem_tem2[:-2]
  126. tem_start2 = dt.strptime(current_str_time[:11] + stem.tem_start2, "%Y-%m-%d %H:%M")
  127. tem_end2 = dt.strptime(current_str_time[:11] + stem.tem_end2, "%Y-%m-%d %H:%M")
  128. print(tem_tem2, fitolab1.s_air_tem1, tem_start2, tem_end2, current_time, sep="\n")
  129. if str(fitolab1.s_air_tem1) > tem_tem2 and tem_start2 <= current_time < tem_end2:
  130. if response_status == 0:
  131. json_data = json.dumps(data)
  132. mqtt.publish(topic=topic, payload=json_data)
  133. else:
  134. if sw1_status == 0:
  135. data["sw1"] = 1
  136. sw1_status = 1
  137. json_data = json.dumps(data)
  138. mqtt.publish(topic=topic, payload=json_data)
  139. elif str(fitolab1.s_air_tem1) == tem_tem2 and tem_start2 <= current_time < tem_end2:
  140. if response_status == 0:
  141. json_data = json.dumps(data)
  142. mqtt.publish(topic=topic, payload=json_data)
  143. else:
  144. if sw1_status == 1:
  145. data["sw1"] = 0
  146. sw1_status = 0
  147. json_data = json.dumps(data)
  148. mqtt.publish(topic=topic, payload=json_data)
  149. if sw2_status == 1:
  150. data["sw2"] = 0
  151. sw2_status = 0
  152. json_data = json.dumps(data)
  153. mqtt.publish(topic=topic, payload=json_data)
  154. elif str(fitolab1.s_air_tem1) < tem_tem2 and tem_start2 <= current_time < tem_end2:
  155. if response_status == 0:
  156. json_data = json.dumps(data)
  157. mqtt.publish(topic=topic, payload=json_data)
  158. else:
  159. if sw2_status == 0:
  160. data["sw2"] = 1
  161. sw2_status = 1
  162. json_data = json.dumps(data)
  163. mqtt.publish(topic=topic, payload=json_data)
  164. elif current_time >= tem_end2:
  165. if sw1_status == 1:
  166. data["sw1"] = 0
  167. sw1_status = 0
  168. if sw2_status == 1:
  169. data["sw2"] = 0
  170. sw2_status = 0
  171. json_data = json.dumps(data)
  172. mqtt.publish(topic=topic, payload=json_data)
  173. except Exception:
  174. pass
  175. try:
  176. tem_tem3 = stem.tem_tem3[:-2]
  177. tem_start3 = dt.strptime(current_str_time[:11] + stem.tem_start3, "%Y-%m-%d %H:%M")
  178. tem_end3 = dt.strptime(current_str_time[:11] + stem.tem_end3, "%Y-%m-%d %H:%M")
  179. print(tem_tem3, fitolab1.s_air_tem1, tem_start3, tem_end3, current_time, sep="\n")
  180. if str(fitolab1.s_air_tem1) > tem_tem3 and tem_start3 <= current_time < tem_end3:
  181. if response_status == 0:
  182. json_data = json.dumps(data)
  183. mqtt.publish(topic=topic, payload=json_data)
  184. else:
  185. if sw1_status == 0:
  186. data["sw1"] = 1
  187. sw1_status = 1
  188. json_data = json.dumps(data)
  189. mqtt.publish(topic=topic, payload=json_data)
  190. elif str(fitolab1.s_air_tem1) == tem_tem3 and tem_start3 <= current_time < tem_end3:
  191. if response_status == 0:
  192. json_data = json.dumps(data)
  193. mqtt.publish(topic=topic, payload=json_data)
  194. else:
  195. if sw1_status == 1:
  196. data["sw1"] = 0
  197. sw1_status = 0
  198. json_data = json.dumps(data)
  199. mqtt.publish(topic=topic, payload=json_data)
  200. if sw2_status == 1:
  201. data["sw2"] = 0
  202. sw2_status = 0
  203. json_data = json.dumps(data)
  204. mqtt.publish(topic=topic, payload=json_data)
  205. elif str(fitolab1.s_air_tem1) < tem_tem3 and tem_start3 <= current_time < tem_end3:
  206. if response_status == 0:
  207. json_data = json.dumps(data)
  208. mqtt.publish(topic=topic, payload=json_data)
  209. else:
  210. if sw2_status == 0:
  211. data["sw2"] = 1
  212. sw2_status = 1
  213. json_data = json.dumps(data)
  214. mqtt.publish(topic=topic, payload=json_data)
  215. elif current_time >= tem_end3:
  216. if sw1_status == 1:
  217. data["sw1"] = 0
  218. sw1_status = 0
  219. if sw2_status == 1:
  220. data["sw2"] = 0
  221. sw2_status = 0
  222. json_data = json.dumps(data)
  223. mqtt.publish(topic=topic, payload=json_data)
  224. except Exception:
  225. pass
  226. print("end")
  227. #mqtt訂閱
  228. @mqtt.on_connect()
  229. def handle_connect(client, userdata, flags, rc):
  230. # mqtt.subscribe('AISKY/AppleFarm/MK-G/9c:65:f9:1e:66:b3/Log')
  231. mqtt.subscribe('AISKY/AppleFarm/MK-G/b8:27:eb:f8:24:92/Log')
  232. #處理mqtt訂閱訊息
  233. @mqtt.on_message()
  234. def handle_mqtt_message(client, userdata, message):
  235. global response_status
  236. payload = message.payload.decode()
  237. print(payload)
  238. json_payload = json.loads(payload)
  239. data = dict(
  240. payload=message.payload.decode()
  241. )
  242. error_num = 0
  243. if json_payload['response'] == '0':
  244. error_num += 1
  245. #如果回傳的response為0到達3次,則在前端通知警示
  246. if error_num == 3:
  247. data['error'] = True
  248. if json_payload['response'] == '1':
  249. response_status = 1
  250. socketio.emit('mqtt_message', data=data)
  251. #調用日誌訊息
  252. @mqtt.on_log()
  253. def handle_logging(client, userdata, level, buf):
  254. print(level, buf)
  255. if __name__ == '__main__':
  256. socketio.run(app, host='0.0.0.0', port=5002, use_reloader=True, debug=False)