123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290 |
- import eventlet
- import json
- from flask import Flask, render_template
- from flask_mqtt import Mqtt
- from flask_socketio import SocketIO
- from flask_bootstrap import Bootstrap
- from flask_sqlalchemy import SQLAlchemy
- import pymysql
- from models import *
- from sqlalchemy import text
- from datetime import datetime as dt
- import json
- #綠化(綠色線程)所有系統模組,實現IO多路複用
- eventlet.monkey_patch()
- pymysql.install_as_MySQLdb()
- app = Flask(__name__)
- app.config['SECRET'] = 'my secret key'
- app.config['TEMPLATES_AUTO_RELOAD'] = True
- app.config['MQTT_BROKER_URL'] = '54.248.68.32'
- app.config['MQTT_BROKER_PORT'] = 1883
- app.config['MQTT_USERNAME'] = 'aisky-client'
- app.config['MQTT_PASSWORD'] = 'aiskyc'
- app.config['MQTT_KEEPALIVE'] = 60
- app.config['MQTT_TLS_ENABLED'] = False
- db = SQLAlchemy(app)
- # 配置數據庫的連接字符串
- app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://land:skyeye@13.113.114.87:3306/LandGreen'
- # 配置數據庫內容再更新時自動提交
- app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
- # 如果設置成True(默認情況),Flask-SQLAlchemy 將會追蹤對象的修改並且發送信號
- app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
- # 配置session所需要的秘鑰
- app.config['SECRET_KEY'] = 'you guess'
- # template 有修改後,會自動去更新
- app.config['TEMPLATES_AUTO_RELOAD'] = True
- # Parameters for SSL enabled
- # app.config['MQTT_BROKER_PORT'] = 8883
- # app.config['MQTT_TLS_ENABLED'] = True
- # app.config['MQTT_TLS_INSECURE'] = True
- # app.config['MQTT_TLS_CA_CERTS'] = 'ca.crt'
- mqtt = Mqtt(app)
- socketio = SocketIO(app)
- bootstrap = Bootstrap(app)
- sw1_status = 0
- sw2_status = 0
- response_status = 0
- @app.route('/')
- def index():
- global response_status
- return render_template('index.html', params=locals())
- #監聽來自publish事件
- @socketio.on('publish')
- def handle_publish(json_str):
- data = json.loads(json_str)
- topic = data['topic']
- del data['topic']
- del data['qos']
- #switch開關
- command_dict = {"sw1":0, "sw2":0, "sw3":0, "sw4":0, "sw5":0, "sw6":0, "sw7":0,
- "sw8":0, "sw9":0, "sw10":0, "sw11":0, "sw12":0}
- data['command'] = "sw"
- for command in command_dict:
- data[command] = command_dict[command]
- stem = StemSystem.query.order_by(text('datetime desc')).first()
- root = RootSystem.query.order_by(text('datetime desc')).first()
- liquid = LiquidTank.query.order_by(text('datetime desc')).first()
- fitolab1 = Fitolab1Sensor.query.order_by(text('datetime desc')).first()
- current_time = dt.now()
- current_str_time = str(dt.now())[:16]
- global sw1_status
- global sw2_status
- global response_status
- try:
- tem_tem1 = stem.tem_tem1[:-2]
- tem_start1 = dt.strptime(current_str_time[:11] + stem.tem_start1, "%Y-%m-%d %H:%M")
- tem_end1 = dt.strptime(current_str_time[:11] + stem.tem_end1, "%Y-%m-%d %H:%M")
- print(tem_tem1, fitolab1.s_air_tem1, tem_start1, tem_end1, current_time, sep="\n")
- if str(fitolab1.s_air_tem1) > tem_tem1 and tem_start1 <= current_time < tem_end1:
- if response_status == 0:
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- else:
- if sw1_status == 0:
- data["sw1"] = 1
- sw1_status = 1
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- elif str(fitolab1.s_air_tem1) == tem_tem1 and tem_start1 <= current_time < tem_end1:
- if response_status == 0:
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- else:
- if sw1_status == 1:
- data["sw1"] = 0
- sw1_status = 0
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- if sw2_status == 1:
- data["sw2"] = 0
- sw2_status = 0
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- elif str(fitolab1.s_air_tem1) < tem_tem1 and tem_start1 <= current_time < tem_end1:
- if response_status == 0:
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- else:
- if sw2_status == 0:
- data["sw2"] = 1
- sw2_status = 1
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- elif current_time >= tem_end1:
- if sw1_status == 1:
- data["sw1"] = 0
- sw1_status = 0
- if sw2_status == 1:
- data["sw2"] = 0
- sw2_status = 0
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- except Exception:
- pass
- try:
- tem_tem2 = stem.tem_tem2[:-2]
- tem_start2 = dt.strptime(current_str_time[:11] + stem.tem_start2, "%Y-%m-%d %H:%M")
- tem_end2 = dt.strptime(current_str_time[:11] + stem.tem_end2, "%Y-%m-%d %H:%M")
- print(tem_tem2, fitolab1.s_air_tem1, tem_start2, tem_end2, current_time, sep="\n")
- if str(fitolab1.s_air_tem1) > tem_tem2 and tem_start2 <= current_time < tem_end2:
- if response_status == 0:
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- else:
- if sw1_status == 0:
- data["sw1"] = 1
- sw1_status = 1
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- elif str(fitolab1.s_air_tem1) == tem_tem2 and tem_start2 <= current_time < tem_end2:
- if response_status == 0:
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- else:
- if sw1_status == 1:
- data["sw1"] = 0
- sw1_status = 0
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- if sw2_status == 1:
- data["sw2"] = 0
- sw2_status = 0
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- elif str(fitolab1.s_air_tem1) < tem_tem2 and tem_start2 <= current_time < tem_end2:
- if response_status == 0:
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- else:
- if sw2_status == 0:
- data["sw2"] = 1
- sw2_status = 1
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- elif current_time >= tem_end2:
- if sw1_status == 1:
- data["sw1"] = 0
- sw1_status = 0
- if sw2_status == 1:
- data["sw2"] = 0
- sw2_status = 0
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- except Exception:
- pass
- try:
- tem_tem3 = stem.tem_tem3[:-2]
- tem_start3 = dt.strptime(current_str_time[:11] + stem.tem_start3, "%Y-%m-%d %H:%M")
- tem_end3 = dt.strptime(current_str_time[:11] + stem.tem_end3, "%Y-%m-%d %H:%M")
- print(tem_tem3, fitolab1.s_air_tem1, tem_start3, tem_end3, current_time, sep="\n")
- if str(fitolab1.s_air_tem1) > tem_tem3 and tem_start3 <= current_time < tem_end3:
- if response_status == 0:
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- else:
- if sw1_status == 0:
- data["sw1"] = 1
- sw1_status = 1
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- elif str(fitolab1.s_air_tem1) == tem_tem3 and tem_start3 <= current_time < tem_end3:
- if response_status == 0:
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- else:
- if sw1_status == 1:
- data["sw1"] = 0
- sw1_status = 0
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- if sw2_status == 1:
- data["sw2"] = 0
- sw2_status = 0
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- elif str(fitolab1.s_air_tem1) < tem_tem3 and tem_start3 <= current_time < tem_end3:
- if response_status == 0:
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- else:
- if sw2_status == 0:
- data["sw2"] = 1
- sw2_status = 1
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- elif current_time >= tem_end3:
- if sw1_status == 1:
- data["sw1"] = 0
- sw1_status = 0
- if sw2_status == 1:
- data["sw2"] = 0
- sw2_status = 0
- json_data = json.dumps(data)
- mqtt.publish(topic=topic, payload=json_data)
- except Exception:
- pass
- print("end")
- #mqtt訂閱
- @mqtt.on_connect()
- def handle_connect(client, userdata, flags, rc):
- # mqtt.subscribe('AISKY/AppleFarm/MK-G/9c:65:f9:1e:66:b3/Log')
- mqtt.subscribe('AISKY/AppleFarm/MK-G/b8:27:eb:f8:24:92/Log')
- #處理mqtt訂閱訊息
- @mqtt.on_message()
- def handle_mqtt_message(client, userdata, message):
- global response_status
- payload = message.payload.decode()
- print(payload)
- json_payload = json.loads(payload)
- data = dict(
- payload=message.payload.decode()
- )
- error_num = 0
- if json_payload['response'] == '0':
- error_num += 1
- #如果回傳的response為0到達3次,則在前端通知警示
- if error_num == 3:
- data['error'] = True
- if json_payload['response'] == '1':
- response_status = 1
- socketio.emit('mqtt_message', data=data)
- #調用日誌訊息
- @mqtt.on_log()
- def handle_logging(client, userdata, level, buf):
- print(level, buf)
- if __name__ == '__main__':
- socketio.run(app, host='0.0.0.0', port=5002, use_reloader=True, debug=False)
|