# 主業務邏輯中的視圖和路由的定義
import os
import datetime
from flask import Flask, redirect, render_template, request, session, Response, jsonify
from sqlalchemy.sql.expression import desc
# 導入藍圖程序，用於構建路由
from werkzeug.utils import redirect
from . import main
from coffee_manage import mqtt
# 導入db，用於操作數據庫
from coffee_manage import db
# 導入實體類，用於操作數據庫
from ..models import *
import json
from datetime import datetime as dt
from sqlalchemy import text
import pymysql
import pandas as pd
from concurrent.futures import ThreadPoolExecutor
import cv2
import pickle
import socket
import time
import threading
import numpy as np
import math
from .mqtt import MQTT
from matplotlib import pyplot as plt
import random
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg as FigureCanvas
import io
from flask import make_response

pool = ThreadPoolExecutor(25)
s_sock = 0
lock = threading.Lock()
'''
mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffee',
                       password='skyeye', database='Coffee', charset='utf8')
mycursor = mydb.cursor()
'''

# 主頁的訪問路徑
@main.route('/')
def main_index():
    # 獲取登入信息
    if 'id' in session and 'uname' in session:
        username = session['uname']

        # Rita 參數 params 是用來取得參數的 locals=() 所有參數
        return render_template('index.html', params=locals())
    else:
        # Rita 是否應改為 registration 註冊, 沒有會員資料就導到註冊去
        return render_template('sign_in.html')

# Rita 測試
# 使用者名稱測試

# !!! AttributeError: 'NoneType' object has no attribute 'vacuum'

@main.route('/loading/S<stid>', methods=['GET', 'POST'])
def S_loading(stid):
    if request.method == 'GET':
        # 色選機
        return
    else:
        pass

@main.route('/loading/P<ptid>', methods=['GET', 'POST'])
def P_loading(ptid):
    if request.method == 'GET':
        # 脫皮機
        return
        
    else:
        pass


@main.route('/loading/C<ctid>', methods=['GET', 'POST'])
def C_loading(ctid):
    if request.method == 'GET':
        tank_actuator = clean_tank_actuator.query.filter_by(tank_num='C'+ctid).order_by(text('datetime desc')).first()
        tank_vacuum = tank_actuator.vacuum
        tank_pump_waterFloat = tank_actuator.pump_waterFloat
        tank_pump_waterL2 = tank_actuator.pump_waterL2
        tank_pump_waterL4 = tank_actuator.pump_waterL4
        tank_solenoid_waterL3 = tank_actuator.solenoid_waterL3
        tank_solenoid_waterL5 = tank_actuator.solenoid_waterL5
        tank_stepping_motor = tank_actuator.stepping_motor
        print('tank_stepping_motor:', tank_stepping_motor)

        # 感測器_浮選清洗_超音波感測器
        tank_UltraSonic = clean_tank_UltraSonic.query.filter_by(tank_num='C'+ctid).order_by(text('datetime desc')).first()
        UltraSonic= tank_UltraSonic.UltraSonic

        return jsonify({"UltraSonic":UltraSonic,
                        "tank_vacuum":tank_vacuum, 
                        "tank_pump_waterFloat":tank_pump_waterFloat, 
                        "tank_pump_waterL2":tank_pump_waterL2, 
                        "tank_pump_waterL4":tank_pump_waterL4, 
                        "tank_solenoid_waterL3":tank_solenoid_waterL3, 
                        "tank_solenoid_waterL5":tank_solenoid_waterL5, 
                        "tank_stepping_motor":tank_stepping_motor
                        })
    else:
        pass


@main.route('/loading/F<ftid>', methods=['GET', 'POST'])
def F_loading(ftid):
    if request.method == 'GET':
        # 制動器_發酵槽_ALL
        tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
        tank_vacuum = tank_actuator.vacuum
        tank_threewayvalve_input = tank_actuator.threewayvalve_input
        tank_diskvalve = tank_actuator.diskvalve
        tank_solenoid_water_total = tank_actuator.solenoid_tank_water_total
        tank_solenoid_disinfect = tank_actuator.solenoid_tank_disinfect
        outer_solenoid_water = tank_actuator.solenoid_outer_water
        tank_solenoid_water_in = tank_actuator.solenoid_tank_water_in
        tank_pump_sensor = tank_actuator.pump_sensor
        tank_threewayvalve_bean = tank_actuator.threewayvalve_bean
        outer_threewayvalve_float = tank_actuator.threewayvalve_outer_float

        tank_motor = tank_actuator.motor
        tank_heater1 = tank_actuator.heater1
        tank_heater2 = tank_actuator.heater2
        tank_temp_enable = tank_actuator.temp_enable
        tank_temp = tank_actuator.temp

        # 感測器_發酵桶_SHT11
        tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
        SHT11_Temp = float(tank_SHT11.SHT11_Temp)
        SHT11_Humidity = float(tank_SHT11.SHT11_Humidity)
        # 感測器_發酵桶_二氧化碳
        tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
        CO2 = float(tank_CO2.CO2)
        # 感測器_發酵桶_酸鹼值
        tank_PH = ferment_tank_PH.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
        tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
        tank_DO = ferment_tank_DO.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
        tank_EC = ferment_tank_EC.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
        PH = float(tank_PH.PH)
        ORP = float(tank_ORP.ORP)
        DO = float(tank_DO.DO)
        EC = float(tank_EC.EC)
        # 感測器_發酵桶_氣壓
        tank_PA = ferment_tank_PA.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
        PA = float(tank_PA.PA)
        # 感測器_發酵桶_超音波感測器
        tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
        UltraSonic= int(tank_UltraSonic.UltraSonic)
        # 感測器_發酵桶_水位計
        tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
        WaterLevel = tank_WaterLevel.WaterLevel

        return jsonify({"UltraSonic":UltraSonic,
                        "SHT11_Temp": SHT11_Temp,
                        "SHT11_Humidity":SHT11_Humidity,
                        "CO2":CO2,
                        "PH":PH,
                        "ORP":ORP,
                        "DO":DO,
                        "EC":EC,
                        "PA":PA,
                        "WaterLevel":WaterLevel,
                        
                        "tank_vacuum":tank_vacuum,
                        "tank_threewayvalve_input":tank_threewayvalve_input,
                        "tank_diskvalve":tank_diskvalve,
                        "tank_solenoid_water_total":tank_solenoid_water_total,
                        "tank_solenoid_disinfect":tank_solenoid_disinfect,
                        "outer_solenoid_water":outer_solenoid_water,
                        "tank_solenoid_water_in":tank_solenoid_water_in,
                        "tank_pump_sensor":tank_pump_sensor,
                        "tank_threewayvalve_bean":tank_threewayvalve_bean,
                        "outer_threewayvalve_float":outer_threewayvalve_float,
                        "tank_motor":tank_motor,
                        "tank_heater1":tank_heater1,
                        "tank_heater2":tank_heater2,
                        "tank_temp_enable":tank_temp_enable,
                        "tank_temp":tank_temp
                        })

    else:
        pass

@main.route('/loading/D<dtid>', methods=['GET', 'POST'])
def D_loading(dtid):
    if request.method == 'GET':
        # 感測器_乾燥桶_超音波感測器
        tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
        UltraSonic = tank_UltraSonic.UltraSonic
        # 感測器_乾燥桶_SHT11
        tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
        SHT11_Temp = tank_SHT11.SHT11_Temp
        SHT11_Humidity = tank_SHT11.SHT11_Humidity
        # 感測器_乾燥桶_土壤三合一
        tank_Soil = dry_tank_Soil.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
        soil_Temp = tank_Soil.soil_Temp
        soil_Humidity = tank_Soil.soil_Humidity
        soil_EC = tank_Soil.soil_EC
        # 感測器_乾燥桶_氣壓
        tank_PA = dry_tank_PA.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
        PA = tank_PA.PA
        # 制動器_乾燥桶_ALL
        tank_brake = dry_tank_brake.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
        #      tank_vacuum = 'ON' if i<100 else 2 if i>100 else 0
        tank_vacuum = tank_brake.vacuum
        tank_threewayvalve = tank_brake.threewayvalve
        tank_diskvalve = tank_brake.diskvalve
        tank_solenoid_disinfect = tank_brake.solenoid_disinfect
        tank_solenoid_water = tank_brake.solenoid_water
        tank_motor = tank_brake.motor
        tank_blower = tank_brake.blower
        tank_heater1 = tank_brake.heater1
        tank_heater2 = tank_brake.heater2
        tank_temp1_enable = tank_brake.temp1_enable
        tank_temp1 = tank_brake.temp1

        #return jsonify({"peeling": peeling_rpm})
        
        return jsonify({"UltraSonic":UltraSonic,
                        "SHT11_Temp": SHT11_Temp,
                        "SHT11_Humidity":SHT11_Humidity,
                        "soil_Temp":soil_Temp,
                        "soil_Humidity":soil_Humidity,
                        "soil_EC":soil_EC,
                        "PA":PA,
                        
                        "tank_vacuum":tank_vacuum,
                        "tank_threewayvalve":tank_threewayvalve,
                        "tank_diskvalve":tank_diskvalve,
                        "tank_solenoid_disinfect":tank_solenoid_disinfect,
                        "tank_solenoid_water":tank_solenoid_water,
                        "tank_motor":tank_motor,
                        "tank_blower":tank_blower,
                        "tank_heater1":tank_heater1,
                        "tank_heater2":tank_heater2,
                        "tank_temp1_enable":tank_temp1_enable,
                        "tank_temp1":tank_temp1
                        })

    else:
        pass

@main.route('/index_new')
def index_new():
    return render_template('index_new.html', params=locals())

@main.route('/user/<name>')
def user(name):
    return render_template('hello.html', name=name)
'''
@main.route('/plot.png')
def plot():
    # 重新整理會有問題
    # 圖的寬和高
    fig = plt.figure()
    # 在圖中新增子圖, 通常多個圖才會用到？
    axis = fig.add_subplot(1, 1, 1)
    # x、 軸資料
    xs = range(100)
    ys = [random.randint(1, 50) for x in xs]
    axis.plot(xs, ys)
    canvas = FigureCanvas(fig)
    output = io.BytesIO()
    canvas.print_png(output)
    response = make_response(output.getvalue())
    response.mimetype = 'image/png'
    return response
'''

@main.route('/chart/<sensor_name>/<tid>', methods=['GET', 'POST'])
def chart(sensor_name, tid):
    if request.method == 'GET':

        return render_template('sensor_chart.html', **locals())

    elif request.method == 'POST':
        
        starttime = request.values['sensor_starttime']      # 2021-07-19T09:00
        endtime = request.values['sensor_endtime']          # 2021-07-19T12:00
        sensor_name = request.values['sensors']
        print('sensor_name:', sensor_name)


        # 判斷資料索取區間 起<迄 
        if starttime < endtime :
            # print('starttime endtime:', starttime, endtime)
            #　print('TF:', starttime<endtime )                    # 可以比較 起<迄
            # [html]2021-07-19T09:00 轉換成 [python]datetime.datetime(2021, 7, 19, 9, 0, 0) 
            start_YY = starttime[:4]                                                            # '2021'
            start_MM = starttime[6:7] if starttime[5:7][:1] == '0' else starttime[5:7]          # '07'
            start_DD = starttime[9:10] if starttime[8:10][:1] == '0' else starttime[8:10]       # '19'
            start_hh = starttime[12:13] if starttime[11:13][:1] == '0' else starttime[11:13]    # '09'
            start_mm = starttime[15:] if starttime[14:][:1] == '0' else starttime[14:]          # '00'
            start_ss = 0

            end_YY = endtime[:4]                                                            # '2021'
            end_MM = endtime[6:7] if endtime[5:7][:1] == '0' else endtime[5:7]              # '07'
            end_DD = endtime[9:10] if endtime[8:10][:1] == '0' else endtime[8:10]           # '19'
            end_hh = endtime[12:13] if endtime[11:13][:1] == '0' else endtime[11:13]        # '09'
            end_mm = endtime[15:] if endtime[14:][:1] == '0' else endtime[14:]              # '00'
            end_ss = 0

            time_range = []
            temp_range = []

            # 拿掉會 Error, 要使用沒有 GUI 的 matplotlib
            plt.switch_backend('agg')
            plt.figure()

            if sensor_name == 'SHT11_Temp':
                for d in db.session.query(dry_tank_SHT11) \
                    .filter_by(tank_num='D' + tid) \
                    .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_SHT11.datetime) \
                    .filter(dry_tank_SHT11.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
                    .order_by(dry_tank_SHT11.datetime):
                    # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
                
                    time_range.append(str(d.datetime))
                    temp_range.append(float(d.SHT11_Temp))
                # 畫出 x 軸基準線
                plt.axhline(28.5, color= 'r')
            
            elif sensor_name == 'SHT11_Humidity':
                for d in db.session.query(dry_tank_SHT11) \
                    .filter_by(tank_num='D' + tid) \
                    .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_SHT11.datetime) \
                    .filter(dry_tank_SHT11.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
                    .order_by(dry_tank_SHT11.datetime):
                    # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
                
                    time_range.append(str(d.datetime))
                    temp_range.append(float(d.SHT11_Humidity))
            
            elif sensor_name == 'UltraSonic':
                for d in db.session.query(dry_tank_UltraSonic) \
                    .filter_by(tank_num='D' + tid) \
                    .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_UltraSonic.datetime) \
                    .filter(dry_tank_UltraSonic.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
                    .order_by(dry_tank_UltraSonic.datetime):
                    # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
                
                    time_range.append(str(d.datetime))
                    temp_range.append(float(d.UltraSonic))
            
            elif sensor_name == 'PA':
                for d in db.session.query(dry_tank_PA) \
                    .filter_by(tank_num='D' + tid) \
                    .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_PA.datetime) \
                    .filter(dry_tank_PA.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
                    .order_by(dry_tank_PA.datetime):
                    # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
                
                    time_range.append(str(d.datetime))
                    temp_range.append(float(d.PA))
            
            elif sensor_name == 'soil_Temp':
                for d in db.session.query(dry_tank_Soil) \
                    .filter_by(tank_num='D' + tid) \
                    .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_Soil.datetime) \
                    .filter(dry_tank_Soil.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
                    .order_by(dry_tank_Soil.datetime):
                    # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
                
                    time_range.append(str(d.datetime))
                    temp_range.append(float(d.soil_Temp))
                # 畫出 x 軸基準線
                plt.axhline(28.5, color= 'r')

            elif sensor_name == 'soil_Humidity':
                for d in db.session.query(dry_tank_Soil) \
                    .filter_by(tank_num='D' + tid) \
                    .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_Soil.datetime) \
                    .filter(dry_tank_Soil.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
                    .order_by(dry_tank_Soil.datetime):
                    # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
                
                    time_range.append(str(d.datetime))
                    temp_range.append(float(d.soil_Humidity))
            
            elif sensor_name == 'soil_EC':
                for d in db.session.query(dry_tank_Soil) \
                    .filter_by(tank_num='D' + tid) \
                    .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_Soil.datetime) \
                    .filter(dry_tank_Soil.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
                    .order_by(dry_tank_Soil.datetime):
                    # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
                
                    time_range.append(str(d.datetime))
                    temp_range.append(float(d.soil_EC))

            print('time_range:', time_range)
            print('temp_range:', temp_range)
           
            # 設定 x 軸資料、y 軸資料、折線顏色
            plt.plot(time_range, temp_range, 'bo')
            # x 軸標題 (中文無法顯示)
            # plt.xlabel('time')
            # plt.ylabel(sensor_name)
            # x 軸 label 和垂直顯示, rotation='vertical'
            plt.xticks(time_range, rotation='vertical' )
            # 設定圖表標題
            plt.title(sensor_name) 
            # 調整圖片與周圍的間距
            plt.tight_layout()
            # plt.show()
            # 儲存圖片 應改為相對路徑 
            plt.savefig('C:/Users/USER/Rita/Coffee/CoffeeProject/app/static/img/new_plot.png')
            
            return render_template('sensor_chart.html', url ="../../static/img/new_plot.png", **locals())

        # 判斷資料索取區間 起>迄 
        else:
            return render_template('sensor_chart.html', **locals())
            
# Rita 測試
# 乾燥桶感測器/制動器測試
# Rita 須加上 <tid> 區分桶號 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

@main.route('/dry_tank/1', methods=['GET'])
def dry_tank():
    if request.method == 'GET':
        
        return render_template('dry_tank.html')

@main.route('/clean', methods=['GET'])
def clean():
    # 制動器_浮選清洗_ALL
    tank_actuator = clean_tank_actuator.query.filter_by(tank_num='C1').order_by(text('datetime desc')).first()
    tank_vacuum = 'ON' if tank_actuator.vacuum == 1 else 'OFF'
    tank_pump_waterFloat = 'ON' if tank_actuator.pump_waterFloat == 1 else 'OFF'
    tank_pump_waterL2 = 'ON' if tank_actuator.pump_waterL2 == 1 else 'OFF'
    tank_pump_waterL4 = 'ON' if tank_actuator.pump_waterL4 == 1 else 'OFF'
    tank_solenoid_waterL3 = 'ON' if tank_actuator.solenoid_waterL3 == 1 else 'OFF'
    tank_solenoid_waterL5 = 'ON' if tank_actuator.solenoid_waterL5 == 1 else 'OFF'
    tank_stepping_motor = tank_actuator.stepping_motor
    print('tank_stepping_motor:', tank_stepping_motor)

    # 感測器_浮選清洗_超音波感測器
    tank_UltraSonic = clean_tank_UltraSonic.query.filter_by(tank_num='C1').order_by(text('datetime desc')).first()
        
    return render_template('clean.html', **locals())

@main.route('/ferment', methods=['GET'])
def ferment():
        '''
        # 制動器_入料儲豆槽_真空吸料機
        input_vacuum = ferment_input_actuator.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
        #　print('input_vacuum.vacuum:', input_vacuum.vacuum)
        input_vacuum = 'ON' if (input_vacuum.vacuum == 1) else 'OFF'
        # print('input_vacuum:', input_vacuum)

        # 制動器_發酵槽_ALL
        tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
        tank_vacuum = 'ON' if tank_actuator.vacuum == 1 else 'OFF'
        tank_threewayvalve_input = 'ON' if tank_actuator.threewayvalve_input == 1 else 'OFF'
        tank_diskvalve = 'ON' if tank_actuator.diskvalve == 1 else 'OFF'
        tank_solenoid_water_total = 'ON' if tank_actuator.solenoid_tank_water_total == 1 else 'OFF'
        tank_solenoid_disinfect = 'ON' if tank_actuator.solenoid_tank_disinfect == 1 else 'OFF'
        outer_solenoid_water = 'ON' if tank_actuator.solenoid_outer_water == 1 else 'OFF'
        tank_solenoid_water_in = 'ON' if tank_actuator.solenoid_tank_water_in == 1 else 'OFF'
        tank_pump_sensor = 'ON' if tank_actuator.pump_sensor == 1 else 'OFF'
        tank_threewayvalve_bean = 'ON' if tank_actuator.threewayvalve_bean == 1 else 'OFF'
        outer_threewayvalve_float = 'ON' if tank_actuator.threewayvalve_outer_float == 1 else 'OFF'

        tank_motor = tank_actuator.motor
        tank_heater1 = 'ON' if tank_actuator.heater1 == 1 else 'OFF'
        tank_heater2 = 'ON' if tank_actuator.heater2 == 1 else 'OFF'
        tank_temp_enable = 'ON' if tank_actuator.temp_enable == 1 else 'OFF'
        tank_temp = tank_actuator.temp

        # 制動器_出料儲豆槽_真空吸引機
        output_vacuum = ferment_output_actuator.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
        #print('output_vacuum.vacuum: ', output_vacuum.vacuum)
        output_vacuum = 'ON' if (output_vacuum.vacuum == 1) else 'OFF'
        #print('output_vacuum: ', output_vacuum)

        # 感測器_入料儲豆槽_超音波感測器
        input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
        # 感測器_發酵桶_SHT11
        tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
        # 感測器_發酵桶_二氧化碳
        tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
        # 感測器_發酵桶_酸鹼值
        tank_PH = ferment_tank_PH.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
        tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
        tank_DO = ferment_tank_DO.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
        tank_EC = ferment_tank_EC.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
        # 感測器_發酵桶_氣壓
        tank_PA = ferment_tank_PA.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
        # 感測器_發酵桶_超音波感測器
        tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
        # 感測器_發酵桶_水位計
        tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
        # 感測器_出料儲豆槽_超音波感測器
        output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
        '''
        return render_template('ferment.html', **locals())

@main.route('/dry', methods=['GET'])
def dry():
    if request.method == 'GET':
        '''
        # 感測器_入料儲豆槽_超音波感測器
        input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()
        # 感測器_乾燥桶_SHT11
        tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()
        # 感測器_乾燥桶_土壤三合一
        tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()
        # 感測器_乾燥桶_氣壓
        tank_PA = dry_tank_PA.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()
        # 感測器_乾燥桶_超音波感測器
        tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()
        # 感測器_出料儲豆槽_超音波感測器
        output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()

        tank_brake = dry_tank_brake.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()
        tank_vacuum = 'ON' if tank_brake.vacuum == 1 else 'OFF'
        tank_threewayvalve = 'ON' if tank_brake.threewayvalve == 1 else 'OFF'
        tank_diskvalve = 'ON' if tank_brake.diskvalve == 1 else 'OFF'
        tank_solenoid_disinfect = 'ON' if tank_brake.solenoid_disinfect == 1 else 'OFF'
        tank_solenoid_water = 'ON' if tank_brake.solenoid_water == 1 else 'OFF'
        tank_motor = tank_brake.motor
        tank_blower = 'ON' if tank_brake.blower == 1 else 'OFF'
        tank_heater1 = 'ON' if tank_brake.heater1 == 1 else 'OFF'
        tank_heater2 = 'ON' if tank_brake.heater2 == 1 else 'OFF'
        tank_temp1_enable = 'ON' if tank_brake.temp1_enable == 1 else 'OFF'
        tank_temp1 = tank_brake.temp1        
        '''
        return render_template('dry.html', **locals())

@main.route('/clean_container/<tid>', methods=['GET', 'POST'])
def clean_container(tid):
    if request.method == 'GET':

        # 制動器_入料儲豆槽_真空吸料機
        input_vacuum = clean_input_actuator.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
        input_vacuum = 'ON' if (input_vacuum.vacuum == 1) else 'OFF'

        # 制動器_浮選清洗_ALL
        tank_actuator = clean_tank_actuator.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
        tank_vacuum = 'ON' if tank_actuator.vacuum == 1 else 'OFF'
        tank_pump_waterFloat = 'ON' if tank_actuator.pump_waterFloat == 1 else 'OFF'
        tank_pump_waterL2 = 'ON' if tank_actuator.pump_waterL2 == 1 else 'OFF'
        tank_pump_waterL4 = 'ON' if tank_actuator.pump_waterL4 == 1 else 'OFF'
        tank_solenoid_waterL3 = 'ON' if tank_actuator.solenoid_waterL3 == 1 else 'OFF'
        tank_solenoid_waterL5 = 'ON' if tank_actuator.solenoid_waterL5 == 1 else 'OFF'
        tank_stepping_motor = tank_actuator.stepping_motor
        
        # 制動器_出料儲豆槽_真空吸料機
        output_vacuum = clean_output_actuator.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
        output_vacuum = 'ON' if (output_vacuum.vacuum == 1) else 'OFF'

        # 感測器_浮選清洗_超音波感測器
        tank_UltraSonic = clean_tank_UltraSonic.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
        
        
        return render_template('clean_container.html', title='clean_container', **locals())

    elif request.method == 'POST':
        pass

@main.route('/ferment_container/<tid>', methods=['GET', 'POST'])
def ferment_container(tid):
    if request.method == 'GET':

        # 制動器_入料儲豆槽_真空吸料機
        input_vacuum = ferment_input_actuator.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
        #　print('input_vacuum.vacuum:', input_vacuum.vacuum)
        input_vacuum = 'ON' if (input_vacuum.vacuum == 1) else 'OFF'
        # print('input_vacuum:', input_vacuum)

        # 制動器_發酵槽_ALL
        tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
        tank_vacuum = 'ON' if tank_actuator.vacuum == 1 else 'OFF'
        tank_threewayvalve_input = 'ON' if tank_actuator.threewayvalve_input == 1 else 'OFF'
        tank_diskvalve = 'ON' if tank_actuator.diskvalve == 1 else 'OFF'
        tank_solenoid_water_total = 'ON' if tank_actuator.solenoid_tank_water_total == 1 else 'OFF'
        tank_solenoid_disinfect = 'ON' if tank_actuator.solenoid_tank_disinfect == 1 else 'OFF'
        outer_solenoid_water = 'ON' if tank_actuator.solenoid_outer_water == 1 else 'OFF'
        tank_solenoid_water_in = 'ON' if tank_actuator.solenoid_tank_water_in == 1 else 'OFF'
        tank_pump_sensor = 'ON' if tank_actuator.pump_sensor == 1 else 'OFF'
        tank_threewayvalve_bean = 'ON' if tank_actuator.threewayvalve_bean == 1 else 'OFF'
        outer_threewayvalve_float = 'ON' if tank_actuator.threewayvalve_outer_float == 1 else 'OFF'

        tank_motor = tank_actuator.motor
        tank_heater1 = 'ON' if tank_actuator.heater1 == 1 else 'OFF'
        tank_heater2 = 'ON' if tank_actuator.heater2 == 1 else 'OFF'
        tank_temp_enable = 'ON' if tank_actuator.temp_enable == 1 else 'OFF'
        tank_temp = tank_actuator.temp

        # 制動器_出料儲豆槽_真空吸引機
        output_vacuum = ferment_output_actuator.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
        #print('output_vacuum.vacuum: ', output_vacuum.vacuum)
        output_vacuum = 'ON' if (output_vacuum.vacuum == 1) else 'OFF'
        #print('output_vacuum: ', output_vacuum)

        # 感測器_入料儲豆槽_超音波感測器
        input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
        # 感測器_發酵桶_SHT11
        tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
        # 感測器_發酵桶_二氧化碳
        tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
        # 感測器_發酵桶_酸鹼值
        tank_PH = ferment_tank_PH.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
        tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
        tank_DO = ferment_tank_DO.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
        tank_EC = ferment_tank_EC.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
        # 感測器_發酵桶_氣壓
        tank_PA = ferment_tank_PA.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
        # 感測器_發酵桶_超音波感測器
        tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
        # 感測器_發酵桶_水位計
        tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
        num_tank_WaterLevel = float(tank_WaterLevel.WaterLevel)
        # 感測器_出料儲豆槽_超音波感測器
        output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
        
        return render_template('ferment_container.html', title='ferment_container', **locals())

    elif request.method == 'POST':
        pass

@main.route('/dry_container_schedule', methods=['GET', 'POST'])
def dry_container_schedule():
    if request.method == 'GET':
        if 'id' in session and 'uname' in session:
            username = session['uname']
        
        # 感測器_入料儲豆槽_超音波感測器
        input_UltraSonic = dry_input_sensor.query.order_by(text('datetime desc')).first()
        # 感測器_乾燥桶_超音波感測器
        tank_UltraSonic = dry_tank_UltraSonic.query.order_by(text('datetime desc')).first()
        
        return render_template('dry_container_schedule.html', title='dry_container_schedule', **locals())
    
    elif request.method == 'POST':
        pass



@main.route('/dry_container/<tid>', methods=['GET', 'POST'])
def dry_container(tid):
    if request.method == 'GET':
        if 'id' in session and 'uname' in session:
            username = session['uname']

        # Rita 參數 params 是用來取得參數的 locals=() 所有參數
        '''     
        # 開啟本機 coffeetest 資料庫
        # mydb = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='g53743001', database='coffeetest', charset='utf8')
        mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffee',
                               password='skyeye', database='Coffee', charset='utf8')
        mycursor = mydb.cursor()
        '''

        # 感測器_入料儲豆槽_超音波感測器
        input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
        # 感測器_乾燥桶_SHT11
        tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
        num_SHT11_temp = float(tank_SHT11.SHT11_Temp)
        # 感測器_乾燥桶_土壤三合一
        tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
        num_Soil_temp = float(tank_Soil.soil_Temp)
        # 感測器_乾燥桶_氣壓
        tank_PA = dry_tank_PA.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
        # 感測器_乾燥桶_超音波感測器
        tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
        # 感測器_出料儲豆槽_超音波感測器
        output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()

        # 制動器_入料儲豆槽_真空吸引機
        input_vacuum = dry_input_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
        # print("input_vacuum:", input_vacuum)
        input_vacuum = input_vacuum.vacuum
        #print('input_vacuum:', input_vacuum.vacuum)
        # 制動器_乾燥桶_ALL
        tank_brake = dry_tank_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
        tank_vacuum = tank_brake.vacuum
        tank_threewayvalve = tank_brake.threewayvalve
        tank_diskvalve = tank_brake.diskvalve
        tank_solenoid_disinfect = tank_brake.solenoid_disinfect
        tank_solenoid_water = tank_brake.solenoid_water
        tank_motor = tank_brake.motor
        tank_blower = tank_brake.blower
        tank_heater1 = tank_brake.heater1
        tank_heater2 = tank_brake.heater2
        tank_temp1_enable = tank_brake.temp1_enable
        tank_temp1 = tank_brake.temp1
        '''
        tank_vacuum = 'ON' if tank_brake.vacuum == 1 else 'OFF'
        tank_threewayvalve = 'ON' if tank_brake.threewayvalve == 1 else 'OFF'
        tank_diskvalve = 'ON' if tank_brake.diskvalve == 1 else 'OFF'
        tank_solenoid_disinfect = 'ON' if tank_brake.solenoid_disinfect == 1 else 'OFF'
        tank_solenoid_water = 'ON' if tank_brake.solenoid_water == 1 else 'OFF'
        tank_motor = tank_brake.motor
        tank_blower = 'ON' if tank_brake.blower == 1 else 'OFF'
        tank_heater1 = 'ON' if tank_brake.heater1 == 1 else 'OFF'
        tank_heater2 = 'ON' if tank_brake.heater2 == 1 else 'OFF'
        tank_temp1_enable = 'ON' if tank_brake.temp1_enable == 1 else 'OFF'
        tank_temp1 = tank_brake.temp1
        '''
        
        '''
        data = mycursor.execute(
            'SELECT * FROM dry_tank_brake ORDER BY datetime DESC;')
        data = mycursor.fetchone()
        '''
        # 制動器_出料儲豆槽_真空吸引機
        output_vacuum = dry_output_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
        #print('output_vacuum.vacuum: ', output_vacuum.vacuum)
        output_vacuum = 'ON' if (output_vacuum.vacuum == 1) else 'OFF'
        #print('output_vacuum: ', output_vacuum)


        # 傳 MQTT 給阿超, 阿超讓硬體動作, 將資料儲存到資料庫

        input_data = set_dry_input.query.order_by(text('datetime desc')).first()
        schedule_input_height = input_data.input_height
        schedule_input_entertime = input_data.input_entertime
        schedule_input_exittime = input_data.input_exittime
        schedule_tank_height = input_data.tank_height

        return render_template('dry_container.html', title='dry_container', **locals())

    elif request.method == 'POST':
        # 表單輸入處
        print('/dry_input_setting POST')
        set = set_dry_input()
        set.input_height = request.form['schedule_input_height']
        set.input_entertime = request.form['schedule_input_entertime']
        set.input_exittime = request.form['schedule_input_exittime']
        set.tank_height = request.form['schedule_tank_height']

        #將數據保存進資料庫  - 註冊
        db.session.add(set)
        # 手動提交，目的是為了獲取提交後的user的id
        db.session.commit()
        # 當user成功插入進資料庫之後，程序會自動將所有信息取出來在賦值給user
        # 完成登入的操作

        # setting = Set_dry_input.query.order_by(text('datetime desc')).first()

        #session['id'] = set.userID
        #session['uname'] = set.username
        return redirect('/dry_container')

# 登入頁面的訪問路徑
@main.route('/login', methods=['GET', 'POST'])
def login_views():
    if request.method == 'GET':
        if 'id' in session and 'uname' in session:
            return redirect('/')
        else:
            return render_template('sign_in.html')
    else:
        # 接收前端傳過來的資料
        username = request.form['username']
        password = request.form['password']
        # 使用接收的用戶和密碼到資料庫中查詢
        # Rita first() 避免欄位中的 null 值 ???
        user = User.query.filter_by(
            username=username, password=password).first()
        # 如果用戶存在，將信息保存置session並重定向回首頁，否則重定向回登入頁
        if user:
            resp = redirect('/')
            # 判斷是否有記住密碼
            if 'rem' in request.form:
                userID = str(user.userID)
                max_age = 60*60*24*365  # Rita max_age???
                resp.set_cookie("username", username, max_age=max_age)
                resp.set_cookie("userID", userID, max_age=max_age)

            session['uname'] = user.username
            session['id'] = user.userID
            return resp
        else:
            errMsg = "Wrong login or password"
            return render_template('sign_in.html', errMsg=errMsg)

# 登入重設密碼的頁面
# Rita reset_pwd1 - Email
# Rita reset_pwd2 - New password / Confirm password


@main.route('/reset_password', methods=['POST', 'GET'])
def reset_password_views():
    if request.method == 'GET':
        if 'mail' in session:
            del session['mail']
        return render_template('reset_pwd1.html')
    else:
        # 如果有id在session裡，代表從reset_pwd2過來的 ???????????????
        if "mail" in session:
            new_pwd = request.form['new_pwd']
            confirm_pwd = request.form['confirm_pwd']
            # 判斷密碼是否一致
            if new_pwd == confirm_pwd:
                mail = session['mail']
                user = User.query.filter_by(mail=mail).first()
                user.password = new_pwd
                db.session.add(user)
                del session['mail']
                # 修改完後回登入頁
                return redirect('/login')
            else:
                errMsg = "Passwords does not match"
                # Rita 前面的 errMsg 是指網頁上的 {{errMsg}} 位置
                return render_template('reset_pwd2.html', errMsg=errMsg)

        email = request.form['email']
        user = User.query.filter_by(mail=email).first()
        if user:  # Rita 有找到對應 email
            session['mail'] = user.mail
            return render_template('reset_pwd2.html')
        else:
            errMsg = "Wrong email.Please try again"
            return render_template('reset_pwd1.html', errMsg=errMsg)

# 註冊頁面的訪問路徑


@main.route('/register', methods=['POST', "GET"])
def register_views():
    if request.method == 'GET':
        return render_template('registration.html')
    else:
        # 獲取文本框的值並賦值給user實體對象
        user = User()
        user.firstname = request.form['firstname']
        user.lastname = request.form['lastname']
        user.mail = request.form['email']
        user.phone = request.form['phone']
        user.username = request.form['username']
        user.password = request.form['password']
        user.status = 1     # Rita app\models.py 設定 0:admin;1:new;9:disable
        #將數據保存進資料庫  - 註冊
        db.session.add(user)
        # 手動提交，目的是為了獲取提交後的user的id
        db.session.commit()
        # 當user成功插入進資料庫之後，程序會自動將所有信息取出來在賦值給user
        # 完成登入的操作
        user = User.query.filter_by(username=user.username).first()
        session['id'] = user.userID
        session['uname'] = user.username
        return redirect('/')

# 驗證email訪問路徑


@main.route('/check_email')
def check_email_views():
    email = request.args['email']
    user = User.query.filter_by(mail=email).first()
    if user:
        # Rita email 錯誤時會顯示 Incorrect email address
        result = {"errMsg": " "}
    else:
        result = {"pass": " "}
    return json.dumps(result)       # ??? 輸出 result 意義???

# 驗證username訪問路徑


@main.route('/check_username')
def check_username_views():
    username = request.args['username']
    user = User.query.filter_by(username=username).first()
    if user:
        result = {"errMsg": " "}
    else:
        result = {"pass": " "}
    return json.dumps(result)


# 咖啡貨櫃的訪問路徑
@main.route('/cargo_list', methods=['GET', 'POST'])
def cargo_list_views():
    username = session['uname']
    if request.method == 'GET':
        return render_template('cargo_list.html', params=locals())
    else:
        pass


# 貨櫃1的訪問路徑
@main.route('/cargo1', methods=['GET', 'POST'])
def cargo1_views():
    username = session['uname']
    if request.method == 'GET':
        return render_template('cargo1.html', params=locals())
    else:
        pass

# 貨櫃1排程的訪問路徑


@main.route('/cargo1_schedule', methods=['GET', 'POST'])
def cargo1_schedule_views():
    username = session['uname']
    if request.method == 'GET':
        # 將已儲存的排程資料傳給前端
        # 進豆閥
        try:
            bean = BeanValve.query.order_by(text('datetime desc')).first()
            datetime = bean.datetime
            beans = BeanValve.query.filter_by(
                datetime=datetime).all()
        except Exception as e:
            pass

        # 清洗機
        try:
            wash = WashMachine.query.order_by(text('datetime desc')).first()
            datetime = wash.datetime
            washes = WashMachine.query.filter_by(datetime=datetime).all()
        except Exception as e:
            pass

        # 輸送帶1
        try:
            belt1 = ConveyorBelt1.query.order_by(text('datetime desc')).first()
            datetime = belt1.datetime
            belts1 = ConveyorBelt1.query.filter_by(datetime=datetime).all()
        except Exception as e:
            pass

# ///////////////////////////////////////////////////////////////////////////////////////////

        # 消毒機
        try:
            disinfect = Cargo1Disinfect.query.order_by(
                text('datetime desc')).first()
            datetime = disinfect.datetime
            disinfects = Cargo1Disinfect.query.filter_by(
                datetime=datetime).all()
        except Exception as e:
            pass

        # 色選機
        try:
            color = ColorMachine.query.order_by(text('datetime desc')).first()
            datetime = color.datetime
            colors = ColorMachine.query.filter_by(datetime=datetime).all()
        except Exception as e:
            pass

        # 輸送帶2
        try:
            belt2 = ConveyorBelt2.query.order_by(text('datetime desc')).first()
            datetime = belt2.datetime
            belts2 = ConveyorBelt2.query.filter_by(datetime=datetime).all()
        except Exception as e:
            pass

        # 去皮機
        try:
            peeling = PeelingMachine.query.order_by(
                text('datetime desc')).first()
            datetime = peeling.datetime
            peelings = PeelingMachine.query.filter_by(datetime=datetime).all()
        except Exception as e:
            pass

        # 輸送帶3
        try:
            belt3 = ConveyorBelt3.query.order_by(text('datetime desc')).first()
            datetime = belt3.datetime
            belts3 = ConveyorBelt3.query.filter_by(datetime=datetime).all()
        except Exception as e:
            pass

        return render_template('cargo1_schedule.html', params=locals())
    else:
        current_time = dt.now()

        # 循環從前端提交過來的資料
        for i in request.form:
            # 進豆閥
            if i[:10] == 'inletValve':
                if i[:19] == 'inletValve_duration':
                    bean = BeanValve()
                    bean.duration = request.form[i]

                elif i[:18] == 'inletValve_from_hr':
                    iv_from_hr = request.form[i]

                elif i[:19] == 'inletValve_from_min':
                    iv_from_min = request.form[i]
                    bean.start = iv_from_hr + ":" + iv_from_min

                elif i[:16] == 'inletValve_to_hr':
                    iv_to_hr = request.form[i]

                elif i[:17] == 'inletValve_to_min':
                    iv_to_min = request.form[i]
                    bean.end = iv_to_hr + ":" + iv_to_min

                    bean.datetime = current_time
                    db.session.add(bean)
                    db.session.commit()

            # 清洗機
            elif i[:4] == 'wash':
                if i[:13] == 'wash_duration':
                    wash = WashMachine()
                    wash.duration = request.form[i]

                elif i[:12] == 'wash_from_hr':
                    wash_from_hr = request.form[i]

                elif i[:13] == 'wash_from_min':
                    wash_from_min = request.form[i]
                    wash.start = wash_from_hr + ":" + wash_from_min

                elif i[:10] == 'wash_to_hr':
                    wash_to_hr = request.form[i]

                elif i[:11] == 'wash_to_min':
                    wash_to_min = request.form[i]
                    wash.end = wash_to_hr + ":" + wash_to_min

                    wash.datetime = current_time
                    db.session.add(wash)
                    db.session.commit()

            # 輸送帶1
            elif i[:5] == 'belt1':
                if i[:14] == 'belt1_duration':
                    belt1 = ConveyorBelt1()
                    belt1.duration = request.form[i]

                elif i[:13] == 'belt1_from_hr':
                    belt1_from_hr = request.form[i]

                elif i[:14] == 'belt1_from_min':
                    belt1_from_min = request.form[i]
                    belt1.start = belt1_from_hr + ":" + belt1_from_min

                elif i[:11] == 'belt1_to_hr':
                    belt1_to_hr = request.form[i]

                elif i[:12] == 'belt1_to_min':
                    belt1_to_min = request.form[i]
                    belt1.end = belt1_to_hr + ":" + belt1_to_min

                    belt1.datetime = current_time
                    db.session.add(belt1)
                    db.session.commit()

            # 消毒
            elif i[:9] == 'disinfect':
                if i[:18] == 'disinfect_duration':
                    disinfect = Cargo1Disinfect()
                    disinfect.duration = request.form[i]

                elif i[:17] == 'disinfect_from_hr':
                    di_from_hr = request.form[i]

                elif i[:18] == 'disinfect_from_min':
                    di_from_min = request.form[i]
                    disinfect.start = di_from_hr + ":" + di_from_min

                elif i[:15] == 'disinfect_to_hr':
                    di_to_hr = request.form[i]

                elif i[:16] == 'disinfect_to_min':
                    di_to_min = request.form[i]
                    disinfect.end = di_to_hr + ":" + di_to_min

                    disinfect.datetime = current_time
                    db.session.add(disinfect)
                    db.session.commit()

            # 色選機
            elif i[:5] == 'color':
                if i[:14] == 'color_duration':
                    color = ColorMachine()
                    color.duration = request.form[i]

                elif i[:13] == 'color_from_hr':
                    color_from_hr = request.form[i]

                elif i[:14] == 'color_from_min':
                    color_from_min = request.form[i]
                    color.start = color_from_hr + ":" + color_from_min

                elif i[:11] == 'color_to_hr':
                    color_to_hr = request.form[i]

                elif i[:12] == 'color_to_min':
                    color_to_min = request.form[i]
                    color.end = color_to_hr + ":" + color_to_min

                    color.datetime = current_time
                    db.session.add(color)
                    db.session.commit()

            # 輸送帶2
            elif i[:5] == 'belt2':
                if i[:14] == 'belt2_duration':
                    belt2 = ConveyorBelt2()
                    belt2.duration = request.form[i]

                elif i[:13] == 'belt2_from_hr':
                    belt2_from_hr = request.form[i]

                elif i[:14] == 'belt2_from_min':
                    belt2_from_min = request.form[i]
                    belt2.start = belt2_from_hr + ":" + belt2_from_min

                elif i[:11] == 'belt2_to_hr':
                    belt2_to_hr = request.form[i]

                elif i[:12] == 'belt2_to_min':
                    belt2_to_min = request.form[i]
                    belt2.end = belt2_to_hr + ":" + belt2_to_min

                    belt2.datetime = current_time
                    db.session.add(belt2)
                    db.session.commit()

            # 去皮機
            elif i[:6] == 'peeled':
                if i[:15] == 'peeled_duration':
                    peeling = PeelingMachine()
                    peeling.duration = request.form[i]

                elif i[:14] == 'peeled_from_hr':
                    peeled_from_hr = request.form[i]

                elif i[:15] == 'peeled_from_min':
                    peeled_from_min = request.form[i]
                    peeling.start = peeled_from_hr + ":" + peeled_from_min

                elif i[:12] == 'peeled_to_hr':
                    peeled_to_hr = request.form[i]

                elif i[:13] == 'peeled_to_min':
                    peeled_to_min = request.form[i]
                    peeling.end = peeled_to_hr + ":" + peeled_to_min

                    peeling.datetime = current_time
                    db.session.add(peeling)
                    db.session.commit()

            # 輸送帶3
            elif i[:5] == 'belt3':
                if i[:14] == 'belt3_duration':
                    belt3 = ConveyorBelt3()
                    belt3.duration = request.form[i]

                elif i[:13] == 'belt3_from_hr':
                    belt3_from_hr = request.form[i]

                elif i[:14] == 'belt3_from_min':
                    belt3_from_min = request.form[i]
                    belt3.start = belt3_from_hr + ":" + belt3_from_min

                elif i[:11] == 'belt3_to_hr':
                    belt3_to_hr = request.form[i]

                elif i[:12] == 'belt3_to_min':
                    belt3_to_min = request.form[i]
                    belt3.end = belt3_to_hr + ":" + belt3_to_min

                    belt3.datetime = current_time
                    db.session.add(belt3)
                    db.session.commit()

        return render_template('cargo1.html', params=locals())


# 貨櫃2的訪問路徑
@main.route('/cargo2', methods=['GET', 'POST'])
def cargo2_views():
    username = session['uname']
    if request.method == 'GET':
        return render_template('cargo2.html', params=locals())
    else:
        pass

# 貨櫃2排程的發酵槽訪問路徑


@main.route('/cargo2_schedule_tanks', methods=['GET', 'POST'])
def cargo2_schedule_tanks_views():
    username = session['uname']
    if request.method == 'GET':
        return render_template('cargo2_schedule_tanks.html', params=locals())
    else:
        pass

# 貨櫃2排程發酵槽的清單訪問路徑


@main.route('/cargo2_schedule/<tid>', methods=['GET', 'POST'])
def cargo2_schedule_views(tid):
    username = session['uname']
    if request.method == 'GET':
        # 將已儲存的排程資料傳給前端
        # 打菌
        try:
            bacteria = Bacteria.query.filter_by(tank_num=int(
                tid)).order_by(text('datetime desc')).first()
            datetime = bacteria.datetime
            bacterias = Bacteria.query.filter_by(datetime=datetime).all()
        except Exception as e:
            pass

        # 消毒
        try:
            disinfect = Cargo2Disinfect.query.filter_by(
                tank_num=int(tid)).order_by(text('datetime desc')).first()
            datetime = disinfect.datetime
            disinfects = Cargo2Disinfect.query.filter_by(
                datetime=datetime).all()
        except Exception as e:
            pass

        # 加熱
        try:
            heating = Heating.query.filter_by(tank_num=int(
                tid)).order_by(text('datetime desc')).first()
            datetime = heating.datetime
            heatings = Heating.query.filter_by(datetime=datetime).all()
        except Exception as e:
            pass

        # 攪拌
        try:
            stir = Stir.query.filter_by(tank_num=int(tid)).order_by(
                text('datetime desc')).first()
            datetime = stir.datetime
            stirs = Stir.query.filter_by(datetime=datetime).all()
        except Exception as e:
            pass

        # 注水
        try:
            water = WaterInjection.query.filter_by(
                tank_num=int(tid)).order_by(text('datetime desc')).first()
            datetime = water.datetime
            waters = WaterInjection.query.filter_by(datetime=datetime).all()
        except Exception as e:
            pass

        # 開上閥
        try:
            top = TopValve.query.filter_by(tank_num=int(
                tid)).order_by(text('datetime desc')).first()
            datetime = top.datetime
            tops = TopValve.query.filter_by(datetime=datetime).all()
        except Exception as e:
            pass

        # 開下閥
        try:
            bottom = BottomValve.query.filter_by(tank_num=int(
                tid)).order_by(text('datetime desc')).first()
            datetime = bottom.datetime
            bottoms = BottomValve.query.filter_by(datetime=datetime).all()
        except Exception as e:
            pass

        # 溫度
        try:
            tem = Temperature.query.filter_by(tank_num=int(
                tid)).order_by(text('datetime desc')).first()
            datetime = tem.datetime
            tems = Temperature.query.filter_by(datetime=datetime).all()
        except Exception as e:
            pass

        return render_template('cargo2_schedule.html', params=locals())
    else:
        current_time = dt.now()

        # 循環從前端提交過來的資料
        for i in request.form:
            # 打菌
            if i[:8] == 'bacteria':
                if i[:17] == 'bacteria_duration':
                    bacteria = Bacteria()
                    bacteria.duration = request.form[i]

                elif i[:16] == 'bacteria_from_hr':
                    bac_from_hr = request.form[i]

                elif i[:17] == 'bacteria_from_min':
                    bac_from_min = request.form[i]
                    bacteria.start = bac_from_hr + ":" + bac_from_min

                elif i[:14] == 'bacteria_to_hr':
                    bac_to_hr = request.form[i]

                elif i[:15] == 'bacteria_to_min':
                    bac_to_min = request.form[i]
                    bacteria.end = bac_to_hr + ":" + bac_to_min

                    bacteria.datetime = current_time
                    bacteria.tank_num = int(tid)
                    db.session.add(bacteria)
                    db.session.commit()

            # 消毒
            elif i[:9] == 'disinfect':
                if i[:18] == 'disinfect_duration':
                    disinfect = Cargo2Disinfect()
                    disinfect.duration = request.form[i]

                elif i[:17] == 'disinfect_from_hr':
                    di_from_hr = request.form[i]

                elif i[:18] == 'disinfect_from_min':
                    di_from_min = request.form[i]
                    disinfect.start = di_from_hr + ":" + di_from_min

                elif i[:15] == 'disinfect_to_hr':
                    di_to_hr = request.form[i]

                elif i[:16] == 'disinfect_to_min':
                    di_to_min = request.form[i]
                    disinfect.end = di_to_hr + ":" + di_to_min

                    disinfect.datetime = current_time
                    disinfect.tank_num = int(tid)
                    db.session.add(disinfect)
                    db.session.commit()

            # 加熱
            elif i[:7] == 'heating':
                if i[:16] == 'heating_duration':
                    heating = Heating()
                    heating.duration = request.form[i]

                elif i[:15] == 'heating_from_hr':
                    heat_from_hr = request.form[i]

                elif i[:16] == 'heating_from_min':
                    heat_from_min = request.form[i]
                    heating.start = heat_from_hr + ":" + heat_from_min

                elif i[:13] == 'heating_to_hr':
                    heat_to_hr = request.form[i]

                elif i[:14] == 'heating_to_min':
                    heat_to_min = request.form[i]
                    heating.end = heat_to_hr + ":" + heat_to_min

                    heating.datetime = current_time
                    heating.tank_num = int(tid)
                    db.session.add(heating)
                    db.session.commit()

            # 攪拌
            elif i[:4] == 'stir':
                if i[:13] == 'stir_duration':
                    stir = Stir()
                    stir.duration = request.form[i]

                elif i[:12] == 'stir_from_hr':
                    stir_from_hr = request.form[i]

                elif i[:13] == 'stir_from_min':
                    stir_from_min = request.form[i]
                    stir.start = stir_from_hr + ":" + stir_from_min

                elif i[:10] == 'stir_to_hr':
                    stir_to_hr = request.form[i]

                elif i[:11] == 'stir_to_min':
                    stir_to_min = request.form[i]
                    stir.end = stir_to_hr + ":" + stir_to_min

                    stir.datetime = current_time
                    stir.tank_num = int(tid)
                    db.session.add(stir)
                    db.session.commit()

            # 注水
            elif i[:5] == 'water':
                if i[:14] == 'water_duration':
                    water = WaterInjection()
                    water.duration = request.form[i]

                elif i[:13] == 'water_from_hr':
                    water_from_hr = request.form[i]

                elif i[:14] == 'water_from_min':
                    water_from_min = request.form[i]
                    water.start = water_from_hr + ":" + water_from_min

                elif i[:11] == 'water_to_hr':
                    water_to_hr = request.form[i]

                elif i[:12] == 'water_to_min':
                    water_to_min = request.form[i]
                    water.end = water_to_hr + ":" + water_to_min

                    water.datetime = current_time
                    water.tank_num = int(tid)
                    db.session.add(water)
                    db.session.commit()

            # 開上閥
            elif i[:9] == 'highValve':
                if i[:18] == 'highValve_duration':
                    top = TopValve()
                    top.duration = request.form[i]

                elif i[:17] == 'highValve_from_hr':
                    h_valve_from_hr = request.form[i]

                elif i[:18] == 'highValve_from_min':
                    h_valve_from_min = request.form[i]
                    top.start = h_valve_from_hr + ":" + h_valve_from_min

                elif i[:15] == 'highValve_to_hr':
                    h_valve_to_hr = request.form[i]

                elif i[:16] == 'highValve_to_min':
                    h_valve_to_min = request.form[i]
                    top.end = h_valve_to_hr + ":" + h_valve_to_min

                    top.datetime = current_time
                    top.tank_num = int(tid)
                    db.session.add(top)
                    db.session.commit()

            # 開下閥
            elif i[:8] == 'lowValve':
                if i[:17] == 'lowValve_duration':
                    bottom = BottomValve()
                    bottom.duration = request.form[i]

                elif i[:16] == 'lowValve_from_hr':
                    l_valve_from_hr = request.form[i]

                elif i[:17] == 'lowValve_from_min':
                    l_valve_from_min = request.form[i]
                    bottom.start = l_valve_from_hr + ":" + l_valve_from_min

                elif i[:14] == 'lowValve_to_hr':
                    l_valve_to_hr = request.form[i]

                elif i[:15] == 'lowValve_to_min':
                    l_valve_to_min = request.form[i]
                    bottom.end = l_valve_to_hr + ":" + l_valve_to_min

                    bottom.datetime = current_time
                    bottom.tank_num = int(tid)
                    db.session.add(bottom)
                    db.session.commit()

            # 溫度
            elif i[:3] == 'tem':
                if i[:12] == 'tem_duration':
                    tem = Temperature()
                    tem.duration = request.form[i]

                elif i[:11] == 'tem_from_hr':
                    tem_from_hr = request.form[i]

                elif i[:12] == 'tem_from_min':
                    tem_from_min = request.form[i]
                    tem.start = tem_from_hr + ":" + tem_from_min

                elif i[:9] == 'tem_to_hr':
                    tem_to_hr = request.form[i]

                elif i[:10] == 'tem_to_min':
                    tem_to_min = request.form[i]
                    tem.end = tem_to_hr + ":" + tem_to_min

                    tem.datetime = current_time
                    tem.tank_num = int(tid)
                    db.session.add(tem)
                    db.session.commit()

        return render_template('cargo2.html', params=locals())


# 貨櫃2感測器的發酵槽訪問路徑
@main.route('/cargo2_sensor_tanks', methods=['GET', 'POST'])
def cargo2_sensor_tanks_views():
    username = session['uname']
    if request.method == 'GET':
        return render_template('cargo2_sensor_tanks.html', params=locals())
    else:
        pass

# 貨櫃2感測器發酵槽的清單訪問路徑


@main.route('/cargo2_sensor/<tid>', methods=['GET', 'POST'])
def s_tank_views(tid):
    # 判斷用戶是否已關閉瀏覽器或登出後，在訪問這個route，如果沒有session就回登入頁
    try:
        username = session['uname']
    except KeyError:
        return redirect('/')

    if request.method == 'GET':
        # Rita 網頁端 params.tank_tem.tem
        # Coffee/CoffeeProject/app/templates/cargo2_sensor.html
        tank_tem = TankTemSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
        tank_ph = TankPHSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
        tank_ec = TankECSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
        tank_sonic = TankSonicSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
        return render_template('cargo2_sensor.html', params=locals())
    else:
        pass


# 貨櫃2感測器發酵槽歷史數據的訪問路徑
@main.route('/history_data', methods=['GET', 'POST'])
def history_data_views():
    if request.method == 'GET':
        # json
        # tid:tid_D1
        # sensor_name:soil_Temp
        # avg:1
        # max:1
        # min:1
        # time-interval:month
        # date-start:2021-07-01
        # date-end:2021-07-28
        info = request.args.to_dict()
        evt = info['evt']
        avg = int(info['avg'])
        max = int(info['max'])
        min = int(info['min'])
        time_interval = info['time-interval']
        print(info)
        # Rita {'evt': '1-溫濕度', 'avg': '1', 'max': '0', 'min': '0', 'time-interval': 'month',
        # 'date-start': '2021-05-04', 'date-end': '2021-05-18'} {'all': [], 'avg': []}
        # print(info)
        # {'evt': '1-溫濕度', 'avg': '1', 'max': '0', 'min': '0', 'time-interval': 'hour', 'date-start': '2021-01-01', 'date-end': '2021-07-27'}
        # print(D)
        # {'all': [['2021-Feb-19_16:46:10', '24.4'], ['2021-Feb-19_16:46:20', '24.4'], ['2021-Feb-19_16:46:30', '24.4'], ['2021-Feb-19_16:46:41', '24.4'], ['2021-Feb-19_16:46:50', '24.4'], ['2021-Feb-19_16:47:00', '24.4'], ['2021-Feb-19_16:47:10', '24.4'], ['2021-Feb-19_16:47:20', '24.4'], ['2021-Feb-19_16:47:30', '24.4'], ['2021-Feb-19_16:47:40', '24.5'], ['2021-Feb-19_16:47:50', '24.5'], ['2021-Feb-19_16:48:00', '24.5'], ['2021-Feb-19_16:48:10', '24.5'], ['2021-Feb-19_16:48:20', '24.5'], ['2021-Feb-19_16:48:29', '24.5'], ['2021-Feb-19_16:48:39', '24.5'], ['2021-Feb-19_16:48:50', '24.5'], ['2021-Feb-19_16:49:00', '24.5'], ['2021-Feb-19_16:49:10', '24.5'], ['2021-Feb-19_16:49:19', '24.5'], ['2021-Feb-19_16:49:29', '24.5'], ['2021-Feb-19_16:49:39', '24.5'], ['2021-Feb-19_16:49:49', '24.5'], ['2021-Feb-19_16:49:59', '24.5'], ['2021-Feb-19_16:50:10', '24.5'], ['2021-Feb-19_16:50:19', '24.5'], ['2021-Feb-19_16:50:29', '24.5'], ['2021-Feb-19_16:50:39', '24.5'], ['2021-Feb-19_16:50:49', '24.5'], ['2021-Feb-19_16:50:59', '24.5'], ['2021-Feb-19_18:07:10', '25.3'], ['2021-Feb-19_18:07:20', '25.3'], ['2021-Feb-19_18:07:30', '25.3'], ['2021-Feb-19_18:07:40', '25.3'], ['2021-Feb-19_18:07:49', '25.3'], ['2021-Feb-19_18:07:59', '25.3'], ['2021-Feb-19_18:08:10', '25.3'], ['2021-Feb-19_18:08:20', '25.3'], ['2021-Feb-19_18:08:30', '25.2'], ['2021-Feb-19_18:08:39', '25.2'], ['2021-Feb-19_18:08:49', '25.2']], 
        #  'avg': [['2021-02-19 16:00:00', '24.5'], ['2021-02-19 18:00:00', '25.3']]}
        # 192.168.50.65 - - [27/Jul/2021 11:57:23] "GET /history_data?evt=1-溫濕度&avg=1&max=0&min=0&time-interval=hour&date-start=2021-01-01&date-end=2021-07-27 HTTP/1.1" 200 -

        date_start = info['date-start']
        date_end_list = info['date-end'].split('-')         # 先把 'date-end' 的 '2021-05-18' 拆成 ['2021', '05', '18']
        date_end_list[2] = str(int(date_end_list[2]) + 1)   # 18 + 1 = 19 再轉成 str → '19'
        date_end = '-'.join(date_end_list)                  # '2021-05-19'
        tank_num = evt.split('-')[0]                        # 1
        sensor = evt.split('-')[1]                          # 溫濕度

        L = []
        D = {}
        maxData = []
        minData = []
        avgData = []

        def sensorData(data_name):                                              # data_name = "tem"

            def dataResample(time_interval, how, data_name):                    # dataResample('month', how???, "tem")  # 下方 "hour"
                interval = 0
                # 設置resample的第一個參數，要按照逐月、逐日或逐時
                if time_interval == 'month':
                    interval = "M"                                              # interval = "M"
                elif time_interval == 'day':
                    interval = "D"
                elif time_interval == 'hour':
                    interval = "H"

                if how == "max":
                    # data = df.resample(interval, how={data_name:how})
                    # 最新版的pandas
                    data = df.resample(interval).max()                          # 取樣頻率 'H'
                    # 刪除有 NaN 的列, any 任何一欄位為空則刪 (all 全部欄位為空值才刪)
                    data = data.dropna(axis=0, how='any')                       
                    

                    if time_interval == ('hour' or 'day'):
                        data.index = pd.to_datetime(
                            data.index, format='%Y-%b-%d_%H:%M:%S')  # 将数据类型转换为日期类型

                    for a in range(0, len(data.index)):
                        l = []
                        # 如果是逐時，才顯示小時分秒
                        if time_interval == 'hour':
                            l.append(str(data.index[a]))
                        else:
                            l.append(str(data.index[a]).split(' ')[0])

                        l.append(str(data[data_name][a]))
                        maxData.append(l)
                    D['max'] = maxData

                elif how == "mean":
                    # data = df.resample(interval, how={data_name:how})
                    # 最新版的pandas
                    data = df.resample(interval).mean()
                    # 刪除具有NaN的值
                    data = data.dropna(axis=0, how='any')
                    # 將平均數取自小數1位
                    data = data.round({data_name: 1})

                    for a in range(0, len(data.index)):
                        l = []
                        # 如果是逐時，才顯示小時分秒
                        if time_interval == 'hour':
                            l.append(str(data.index[a]))
                        else:
                            l.append(str(data.index[a]).split(' ')[0])
                        l.append(str(data[data_name][a]))
                        avgData.append(l)
                    D['avg'] = avgData

                elif how == "min":
                    # data = df.resample(interval, how={data_name:how})
                    # 最新版的pandas
                    data = df.resample(interval).min()
                    # 刪除具有NaN的值
                    data = data.dropna(axis=0, how='any')

                    for a in range(0, len(data.index)):
                        # print(data.index[a])
                        l = []
                        # 如果是逐時，才顯示小時分秒
                        if time_interval == 'hour':
                            l.append(str(data.index[a]))
                        else:
                            l.append(str(data.index[a]).split(' ')[0])
                        l.append(str(data[data_name][a]))
                        minData.append(l)
                    D['min'] = minData

            df = pd.DataFrame(L, columns=["datetime", data_name])  # 指定欄標籤名稱 為 ["datetime", "tem"]
            df['datetime'] = pd.to_datetime(
                df['datetime'], format='%Y-%b-%d_%H:%M:%S')  # 将数据类型转换为日期类型
            # print(df['datetime'])         # 0    2021-02-19 16:46:10
                                            # 1    2021-02-19 16:46:20
                                            # 2    2021-02-19 16:46:30
                                            # 3    2021-02-19 16:46:41
            df[data_name] = df[data_name].astype(float)
            df = df.set_index('datetime')   # 将datetime设置为index
            # print(df)                     #         datetime             tem
                                            # 2021-02-19 16:46:10  24.4
                                            # 2021-02-19 16:46:20  24.4

            if time_interval == 'month':
                if max:
                    dataResample(time_interval, "max", data_name)
                if avg:
                    dataResample(time_interval, "mean", data_name)
                if min:
                    dataResample(time_interval, "min", data_name)

            elif time_interval == 'day':
                if max:
                    dataResample(time_interval, "max", data_name)
                if avg:
                    dataResample(time_interval, "mean", data_name)
                if min:
                    dataResample(time_interval, "min", data_name)

            elif time_interval == 'hour':
                if max:
                    dataResample(time_interval, "max", data_name)
                if avg:
                    dataResample(time_interval, "mean", data_name)
                if min:
                    dataResample(time_interval, "min", data_name)

        if sensor == '溫濕度':
            # tank_tem = TankTemSensor.query.filter_by(tank_num=int(tank_num)).order_by(text('datetime desc')).all()
            # [7/27 Benson] tank_tem = TankTemSensor.query.filter_by(tank_num=int(tank_num)).filter(TankTemSensor.datetime.between(date_start, date_end)).all()
            tank_tem = dry_tank_SHT11.query.filter(dry_tank_SHT11.datetime.between(date_start, date_end)).all()
            # .filter_by(tank_num="D"+tank_num)

            for tem in tank_tem:
                l = []                                                      # l = []
                time = dt.strftime(tem.datetime, '%Y-%b-%d_%H:%M:%S')       # time = '2021-Feb-19_16:46:10' 轉換時間格式
                # time = dt.strftime(tem.datetime, '%Y-%m-%d')
                l.append(time)                                              # l = ['2021-Feb-19_16:46:10']
                #l.append(tem.tem)                                           # l = ['2021-Feb-19_16:46:10', '24.4']
                l.append(tem.SHT11_Temp)
                L.append(l)                                                 # L = [['2021-Feb-19_16:46:10', '24.4']]

            # print(L)

            D['all'] = L                                                    # D = {'all': [['2021-Feb-19_16:46:10', '24.4']]}  # all 所有符合數據
            sensorData("tem")

        elif sensor == '酸鹼值':
            tank_ph = TankPHSensor.query.filter_by(tank_num=int(tank_num)).filter(
                TankPHSensor.datetime.between(date_start, date_end)).all()
            for ph in tank_ph:
                l = []
                time = dt.strftime(ph.datetime, '%Y-%b-%d_%H:%M:%S')
                # time = dt.strftime(tem.datetime, '%Y-%m-%d')
                l.append(time)
                l.append(ph.ph)
                L.append(l)

            # print(L)

            D['all'] = L
            sensorData("ph")

        elif sensor == 'EC值':
            tank_ec = TankECSensor.query.filter_by(tank_num=int(tank_num)).filter(
                TankECSensor.datetime.between(date_start, date_end)).all()
            for ec in tank_ec:
                l = []
                time = dt.strftime(ec.datetime, '%Y-%b-%d_%H:%M:%S')
                # time = dt.strftime(tem.datetime, '%Y-%m-%d')
                l.append(time)
                l.append(ec.ec)
                L.append(l)

            # print(L)

            D['all'] = L
            sensorData("ec")

        elif sensor == '超音波':
            tank_sonic = TankSonicSensor.query.filter_by(tank_num=int(tank_num)).filter(
                TankSonicSensor.datetime.between(date_start, date_end)).all()
            for sonic in tank_sonic:
                l = []
                time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
                # time = dt.strftime(tem.datetime, '%Y-%m-%d')
                l.append(time)
                l.append(sonic.sonic)
                L.append(l)

            # print(L)

            D['all'] = L
            sensorData("sonic")

        print(D)
        return json.dumps(D)
    else:
        pass


# 貨櫃2制動器的發酵槽訪問路徑
@main.route('/cargo2_actuator_tanks', methods=['GET', 'POST'])
def cargo2_actuator_tanks_views():
    username = session['uname']
    if request.method == 'GET':
        return render_template('cargo2_actuator_tanks.html', params=locals())
    else:
        pass

# 貨櫃2制動器發酵槽的清單訪問路徑


@main.route('/cargo2_actuator/<tid>', methods=['GET', 'POST'])
def cargo2_actuator_views(tid):
    username = session['uname']
    if request.method == 'GET':
        return render_template('cargo2_actuator.html', params=locals())
    else:
        pass


# 貨櫃3的訪問路徑
@main.route('/cargo3', methods=['GET', 'POST'])
def cargo3_views():
    username = session['uname']
    if request.method == 'GET':
        return render_template('cargo3.html', params=locals())
    else:
        pass

# 貨櫃3排程的訪問路徑


@main.route('/cargo3_schedule', methods=['GET', 'POST'])
def cargo3_schedule_views():
    username = session['uname']
    if request.method == 'GET':
        # 將已儲存的排程資料傳給前端
        # 提升機
        try:
            hoist = Hoist.query.order_by(text('datetime desc')).first()
            datetime = hoist.datetime
            hoists = Hoist.query.filter_by(datetime=datetime).all()
        except Exception as e:
            pass

        # 烘乾機
        try:
            dryer = Dryer.query.order_by(text('datetime desc')).first()
            datetime = dryer.datetime
            dryers = Dryer.query.filter_by(datetime=datetime).all()

        except Exception as e:
            pass

        return render_template('cargo3_schedule.html', params=locals())
    else:
        # Rita： "POST /b_cargo3 HTTP/1.1" 404 -
        current_time = dt.now()

        # 循環從前端提交過來的資料
        for i in request.form:
            print('Rita test i :', i)
            # 堤升機
            if i[:5] == 'hoist':
                if i[:14] == 'hoist_duration':
                    hoist = Hoist()
                    hoist.duration = request.form[i]

                elif i[:13] == 'hoist_from_hr':
                    ho_from_hr = request.form[i]

                elif i[:14] == 'hoist_from_min':
                    ho_from_min = request.form[i]
                    hoist.start = ho_from_hr + ":" + ho_from_min

                elif i[:11] == 'hoist_to_hr':
                    ho_to_hr = request.form[i]

                elif i[:12] == 'hoist_to_min':
                    ho_to_min = request.form[i]
                    hoist.end = ho_to_hr + ":" + ho_to_min
                    hoist.datetime = current_time

                    db.session.add(hoist)
                    db.session.commit()

            # 烘乾機
            elif i[:5] == 'dryer':
                if i[:14] == 'dryer_duration':
                    dryer = Dryer()
                    dryer.duration = request.form[i]

                elif i[:13] == 'dryer_from_hr':
                    dry_from_hr = request.form[i]

                elif i[:14] == 'dryer_from_min':
                    dry_from_min = request.form[i]
                    dryer.start = dry_from_hr + ":" + dry_from_min

                elif i[:11] == 'dryer_to_hr':
                    dry_to_hr = request.form[i]

                elif i[:12] == 'dryer_to_min':
                    dry_to_min = request.form[i]
                    dryer.end = dry_to_hr + ":" + dry_to_min

                    dryer.datetime = current_time

                    db.session.add(dryer)
                    db.session.commit()

        return render_template('cargo3.html', params=locals())


# 影像串流的訪問路徑
@main.route('/video', methods=['GET', 'POST'])
def video_views():
    username = session['uname']
    if request.method == 'GET':
        return render_template('video.html', params=locals())
    else:
        pass

# 影像的訪問路徑


@main.route('/learn', methods=['GET', 'POST'])
def learn_views():
    username = session['uname']
    if request.method == 'GET':
        return render_template('learn.html', params=locals())
    else:
        pass

# 獲取relay狀態路徑


@main.route('/relay', methods=['GET', 'POST'])
def relay_views():
    if request.method == 'GET':
        relay = Relay.query.order_by(text('datetime desc')).first()
        relay_status = relay.status
        return jsonify({"relay": relay_status})
    else:
        pass

# 獲取脫皮機狀態路徑


@main.route('/peeling', methods=['GET', 'POST'])
def peeling_views():
    if request.method == 'GET':
        peeling = PeelingMachineRPM.query.order_by(
            text('datetime desc')).first()
        peeling_rpm = peeling.rpm
        return jsonify({"peeling": peeling_rpm})
    else:
        pass


# 退出的訪問路徑
@main.route('/logout')
def logout_views():
    if 'id' in session and 'uname' in session:
        del session['id']
        del session['uname']
    return redirect('/')


@main.route("/udp_client", methods=['POST', 'GET'])
def udp_views():
    # sl(0.5)
    global c_sock
    if request.method == 'GET':
        # def close():
        #     global c_sock
        #     sl(600)
        #     c_sock.close()
        #     c_sock = 0
        #     print("c_sock is closing")

        max_length = 65000
        # max_length = 95000
        # lab1的IP
        host = "192.168.50.65"
        # lab2的IP
        # host = "192.168.51.160"
        port = 8000
        c_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        # t = threading.Thread(target=close)
        # t.daemon = True
        # t.start()

        print("test")
        # dict = request.args.to_dict()
        # nr = int(dict['nr'])
        # if nr == 1:
        #     camara = 0
        # elif nr == 2:
        #     camara = 'rtsp://admin:admin@192.168.50.182/av2_0'
        # elif nr == 3:
        #     camara = 'rtsp://admin:abcd1234@192.168.51.101/av2_0'
        # 地下室小兵
        # cap = cv2.VideoCapture('rtsp://admin:abcd1234@192.168.51.48/av2_0')
        # 主機攝像頭
        # cap = cv2.VideoCapture(0)
        # 外面小兵
        # cap = cv2.VideoCapture('rtsp://admin:admin@192.168.50.182/av2_0')

        cap = cv2.VideoCapture('rtsp://192.168.50.182/av0_0')
        # cap = cv2.VideoCapture(0)
        # cap = cv2.VideoCapture(camara)
        ret, frame = cap.read()

        while ret:
            # compress frame
            frame = cv2.resize(frame, (550, 400), interpolation=cv2.INTER_AREA)
            retval, buffer = cv2.imencode(".jpg", frame)

            if retval:
                # convert to byte array
                buffer = buffer.tobytes()
                # get size of the frame
                buffer_size = len(buffer)

                num_of_packs = 1
                if buffer_size > max_length:
                    num_of_packs = math.ceil(buffer_size / max_length)

                frame_info = {"packs": num_of_packs}

                # send the number of packs to be expected
                # print("Number of packs:", num_of_packs)
                c_sock.sendto(pickle.dumps(frame_info), (host, port))

                left = 0
                right = max_length

                for i in range(num_of_packs):
                    # print("left:", left)
                    # print("right:", right)

                    # truncate data to send
                    data = buffer[left:right]
                    left = right
                    right += max_length

                    # send the frames accordingly
                    c_sock.sendto(data, (host, port))

            ret, frame = cap.read()

        print("done")
        return "done"
    else:
        c_sock.shutdown(2)
        c_sock.close()
        c_sock = 0
        print("c_sock is closing")


# 影像串流的路徑
@main.route("/video_feed", methods=['POST', 'GET'])
def video_feed_views():
    print("test2")
    global s_sock
    if request.method == 'GET':
        # 於10分鐘之後，自動關閉socket server
        # if s_sock == 0:
        #     def socket_server_views():
        #         global s_sock
        #         print("test")
        #         print(s_sock)
        #         sl(600)
        #         if s_sock != 0:
        #             s_sock.close()
        #             s_sock = 0
        #             print('s_sock is closed')
        #
        #     pool.submit(socket_server_views)

        host = "192.168.50.65"
        port = 8000
        max_length = 65540
        # max_length = 95540

        s_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s_sock.bind((host, port))

        frame_info = None
        buffer = None
        frame = None
        encodedImage = None

        print("-> waiting for connection")

        # 影像生成器函數，將影像以jpg格式傳給前端

        def generate():
            while True:
                with lock:
                    global s_sock, frame_info, buffer, frame, encodedImage
                    if s_sock == 0:
                        break
                    data, address = s_sock.recvfrom(max_length)

                    if len(data) < 100:
                        frame_info = pickle.loads(data)

                        if frame_info:
                            nums_of_packs = frame_info["packs"]

                            for i in range(nums_of_packs):
                                if s_sock == 0:
                                    break
                                data, address = s_sock.recvfrom(max_length)

                                if i == 0:
                                    buffer = data
                                else:
                                    buffer += data

                            frame = np.frombuffer(buffer, dtype=np.uint8)
                            frame = frame.reshape(frame.shape[0], 1)

                            frame = cv2.imdecode(frame, cv2.IMREAD_UNCHANGED)

                            # print(frame)

                            # 如果frame為None就跳過
                            if frame is None:
                                continue

                            frame = cv2.resize(
                                frame, (640, 360), interpolation=cv2.INTER_AREA)

                            # encode the frame in JPEG format
                            (flag, encodedImage) = cv2.imencode(".jpg", frame)
                            # ensure the frame was successfully encoded
                            if not flag:
                                continue
                # yield the output frame in the byte format
                yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' +
                       bytearray(encodedImage) + b'\r\n')

        # return the response generated along with the specific media
        # type (mime type)
        return Response(generate(), mimetype="multipart/x-mixed-replace; boundary=frame")
    else:
        if s_sock != 0:
            s_sock.close()
            s_sock = 0
            print('s_sock is closed')
            return "s_sock is closed"
        print("test")
        return "s_sock is closed"


D = {"input_vacuum_status": 0,
     "tank_vacuum_status": 0,
     "tank_threewayvalve_status": 0,
     "tank_diskvalve_status": 0,
     "tank_solenoid_disinfect_status": 0,
     "tank_solenoid_water_status": 0,
     "tank_motor_status": 'none',
     "tank_blower_status": 0,
     "tank_heater1_status": 0,
     "tank_heater2_status": 0,
     "temp1_enable": 0,
     "temp1": 0,
     "output_vacuum_status": 0,

     "tank_threewayvalve_input_status":0, 
     "tank_solenoid_water_total_status": 0,
     "tank_solenoid_disinfect_status": 0,
     "outer_solenoid_water_status": 0,
     "tank_solenoid_water_in_status":0,
     "tank_pump_sensor_status": 0,
     "tank_threewayvalve_bean_status":0,
     "outer_threewayvalve_float_status":0,
     "tank_temp_enable_status":0,
     "tank_temp_status": 'none',

     "tank_pump_waterFloat_status": 0,
     "tank_pump_waterL2_status": 0,
     "tank_pump_waterL4_status": 0,
     "tank_solenoid_waterL3_status": 0,
     "tank_solenoid_waterL5_status": 0,
     "tank_stepping_motor_status": 'none',


}

pub_topic = 'AISKY/Coffee/MK-G/b8:27:eb:b4:59:3e'
# sub_topic = 'AISKY/Coffee/MK-G/b8:27:eb:b4:59:3e/Log'

# mqttObj = MQTT('aisky-client', 'aiskyc', '60.250.156.234', 1883, 60, sub_topic)
mqttObj = MQTT()


# mqtt發布
# @main.route('/mqtt/<tid>', methods=['POST'])
@main.route('/mqtt/<tid>', methods=['POST'])
def mqtt_views(tid):
    import json
    dict = request.form.to_dict()
    json = json.dumps(dict)
    # print('dict:', dict)   # dict: {'tank-number': '1', 'command': 'tank_vacuum_status', 'value': 'on'}
    # print('json:', json)   # json: {"tank-number": "1", tank_vacuum_status", "value": "on"}

    topic = 'AISKY/Coffee/MK-G/b8:27:eb:b4:59:3e'

    # res = mqttObj.mqttPublish(pub_topic, json)
    # print(res)
    # sl(2)
    # print(mqttObj.res)
    #
    # print('test')

    mqtt.publish(topic, json)

    # 入料儲豆槽真空吸料機(ON吸料/OFF排氣)
    if dict['command'] == 'input_vacuum_status':
        time.sleep(1)
        # D[input_vacuum_status]: 0
        print('D[input_vacuum_status]:', D['input_vacuum_status'])
        if D['input_vacuum_status'] == 'on':
            return 'on'
        elif D['input_vacuum_status'] == 'off':
            return 'off'
        else:
            return "input_vacuum_status signal was not received"

    # 真空吸料機
    elif dict['command'] == 'tank_vacuum_status':
        time.sleep(1)
        if D['tank_vacuum_status'] == 'on':
            return 'on'
        elif D['tank_vacuum_status'] == 'off':
            return 'off'
        else:
            return "tank_vacuum_status signal was not received"

    # 三通閥(ON吸料/OFF排氣)
    elif dict['command'] == 'tank_threewayvalve_status':
        time.sleep(1)
        if D['tank_threewayvalve_status'] == 'on':
            return 'on'
        elif D['tank_threewayvalve_status'] == 'off':
            return 'off'
        else:
            return "tank_threewayvalve_status signal was not received"

    # 蝴蝶閥(ON開/OFF關)
    elif dict['command'] == 'tank_diskvalve_status':
        time.sleep(1)
        print("D['tank_diskvalve_status']", D['tank_diskvalve_status'])
        if D['tank_diskvalve_status'] == 'on':
            return 'on'
        elif D['tank_diskvalve_status'] == 'off':
            return 'off'
        else:
            return "tank_diskvalve_status signal was not received"

    # 電磁閥(ON噴灑消毒/OFF關)
    elif dict['command'] == 'tank_solenoid_disinfect_status':
        time.sleep(1)
        if D['tank_solenoid_disinfect_status'] == 'on':
            return 'on'
        elif D['tank_solenoid_disinfect_status'] == 'off':
            return 'off'
        else:
            return "tank_solenoid_disinfect_status signal was not received"

    # 電磁閥(ON排水/OFF關)
    elif dict['command'] == 'tank_solenoid_water_status':
        time.sleep(1)
        if D['tank_solenoid_water_status'] == 'on':
            return 'on'
        elif D['tank_solenoid_water_status'] == 'off':
            return 'off'
        else:
            return "tank_solenoid_water_status signal was not received"

    # 馬達(單位RPM)
    elif dict['command'] == 'tank_motor_status':
        print("D['tank_motor_status']", D['tank_motor_status'])
        time.sleep(1)
        if D['tank_motor_status'] == '0':
            return 'off'
        elif type(D['tank_motor_status']) == int:
            return 'on'
        else:
            return "tank_motor_status signal was not received"

    # 鼓風機(ON開/OFF關)
    elif dict['command'] == 'tank_blower_status':
        time.sleep(1)
        if D['tank_blower_status'] == 'on':
            return 'on'
        elif D['tank_blower_status'] == 'off':
            return 'off'
        else:
            return "tank_blower_status signal was not received"

    # 加熱棒 1(ON開/OFF關)
    elif dict['command'] == 'tank_heater1_status':
        time.sleep(1)
        if D['tank_heater1_status'] == 'on':
            return 'on'
        elif D['tank_heater1_status'] == 'off':
            return 'off'
        else:
            return "tank_heater1_status signal was not received"

    # 加熱棒 2(ON開/OFF關)
    elif dict['command'] == 'tank_heater2_status':
        time.sleep(1)
        if D['tank_heater2_status'] == 'on':
            return 'on'
        elif D['tank_heater2_status'] == 'off':
            return 'off'
        else:
            return "tank_heater2_status signal was not received"

    # 溫度控制(ON開/OFF關)
    elif dict['command'] == 'temp1_enable':
        time.sleep(1)
        if D['temp1_enable'] == 'on':
            return 'on'
        elif D['temp1_enable'] == 'off':
            return 'off'
        else:
            return "temp1_enable_status signal was not received"

    # 設定溫度 (限整數)
    elif dict['command'] == 'temp1':
        time.sleep(1)
        if D['temp1'] == '0':
            return 'off'
        elif type(D['temp1']) == int:
            return 'on'
        else:
            return "temp1 signal was not received"

    # 出料儲豆槽真空吸料機(ON吸料/OFF排氣)
    elif dict['command'] == 'output_vacuum_status':
        time.sleep(1)
        if D['output_vacuum_status'] == 'on':
            return 'on'
        elif D['output_vacuum_status'] == 'off':
            return 'off'
        else:
            return "output_vacuum_status signal was not received"

    # 發酵槽 入料三通閥
    elif dict['command'] == 'tank_threewayvalve_input_status':
        time.sleep(1)
        if D['tank_threewayvalve_input_status'] == 'on':
            return 'on'
        elif D['tank_threewayvalve_input_status'] == 'off':
            return 'off'
        else:
            return "tank_threewayvalve_input_status signal was not received"

    # 發酵槽 總進水
    elif dict['command'] == 'tank_solenoid_water_total_status':
        time.sleep(1)
        if D['tank_solenoid_water_total_status'] == 'on':
            return 'on'
        elif D['tank_solenoid_water_total_status'] == 'off':
            return 'off'
        else:
            return "tank_solenoid_water_total_status signal was not received"

    # 發酵槽 桶內消毒/打菌
    elif dict['command'] == 'tank_solenoid_disinfect_status':
        time.sleep(1)
        if D['tank_solenoid_disinfect_status'] == 'on':
            return 'on'
        elif D['tank_solenoid_disinfect_status'] == 'off':
            return 'off'
        else:
            return "tank_solenoid_disinfect_status signal was not received"

    # 發酵槽 夾層進水
    elif dict['command'] == 'outer_solenoid_water_status':
        time.sleep(1)
        if D['outer_solenoid_water_status'] == 'on':
            return 'on'
        elif D['outer_solenoid_water_status'] == 'off':
            return 'off'
        else:
            return "outer_solenoid_water_status signal was not received"

    # 發酵槽 桶內進水
    elif dict['command'] == 'tank_solenoid_water_in_status':
        time.sleep(1)
        if D['tank_solenoid_water_in_status'] == 'on':
            return 'on'
        elif D['tank_solenoid_water_in_status'] == 'off':
            return 'off'
        else:
            return "tank_solenoid_water_in_status signal was not received"


    # 發酵槽 雙核隔膜泵
    elif dict['command'] == 'tank_pump_sensor_status':
        time.sleep(1)
        if D['tank_pump_sensor_status'] == 'on':
            return 'on'
        elif D['tank_pump_sensor_status'] == 'off':
            return 'off'
        else:
            return "tank_pump_sensor_status signal was not received"


    # 發酵槽 感測器下豆三通閥
    elif dict['command'] == 'tank_threewayvalve_bean_status':
        time.sleep(1)
        if D['tank_threewayvalve_bean_status'] == 'on':
            return 'on'
        elif D['tank_threewayvalve_bean_status'] == 'off':
            return 'off'
        else:
            return "tank_threewayvalve_bean_status signal was not received"


    # 發酵槽 外桶浮選三通閥
    elif dict['command'] == 'outer_threewayvalve_float_status':
        time.sleep(1)
        if D['outer_threewayvalve_float_status'] == 'on':
            return 'on'
        elif D['outer_threewayvalve_float_status'] == 'off':
            return 'off'
        else:
            return "outer_threewayvalve_float_status signal was not received"


    # 發酵槽 溫控開關
    elif dict['command'] == 'tank_temp_enable_status':
        time.sleep(1)
        if D['tank_temp_enable_status'] == 'on':
            return 'on'
        elif D['tank_temp_enable_status'] == 'off':
            return 'off'
        else:
            return "tank_temp_enable_status signal was not received"


    # 發酵槽 設定溫度
    elif dict['command'] == 'tank_temp_status':
        time.sleep(1)
        if D['tank_temp_status'] == '0':
            return 'off'
        elif type(D['tank_temp_status']) == int:
            return 'on'
        else:
            return "tank_temp_status signal was not received"

    # 清洗浮選槽 浮選槽注水
    elif dict['command'] == 'tank_pump_waterFloat_status':
        time.sleep(1)
        if D['tank_pump_waterFloat_status'] == 'on':
            return 'on'
        elif D['tank_pump_waterFloat_status'] == 'off':
            return 'off'
        else:
            return "tank_pump_waterFloat_status signal was not received"
    
    # 清洗浮選槽 清洗第 2 層灑水
    elif dict['command'] == 'tank_pump_waterL2_status':
        time.sleep(1)
        if D['tank_pump_waterL2_status'] == 'on':
            return 'on'
        elif D['tank_pump_waterL2_status'] == 'off':
            return 'off'
        else:
            return "tank_pump_waterL2_status signal was not received"

    # 清洗浮選槽 清洗第 4 層灑水
    elif dict['command'] == 'tank_pump_waterL4_status':
        time.sleep(1)
        if D['tank_pump_waterL4_status'] == 'on':
            return 'on'
        elif D['tank_pump_waterL4_status'] == 'off':
            return 'off'
        else:
            return "tank_pump_waterL4_status signal was not received"

    # 清洗浮選槽 清洗第 3 層電磁閥
    elif dict['command'] == 'tank_solenoid_waterL3_status':
        time.sleep(1)
        if D['tank_solenoid_waterL3_status'] == 'on':
            return 'on'
        elif D['tank_solenoid_waterL3_status'] == 'off':
            return 'off'
        else:
            return "tank_solenoid_waterL3_status signal was not received"

    # 清洗浮選槽 清洗第 5 層電磁閥
    elif dict['command'] == 'tank_solenoid_waterL5_status':
        time.sleep(1)
        if D['tank_solenoid_waterL5_status'] == 'on':
            return 'on'
        elif D['tank_solenoid_waterL5_status'] == 'off':
            return 'off'
        else:
            return "tank_solenoid_waterL5_status signal was not received"

    # 清洗浮選槽 步進馬達
    elif dict['command'] == 'tank_stepping_motor_status':
        time.sleep(1)
        if D['tank_stepping_motor_status'] == '0':
            return 'off'
        elif type(D['tank_stepping_motor_status']) == int:
            return 'on'
        else:
            return "tank_stepping_motor_status signal was not received"

    return "publish done"


# 處理mqtt訂閱的信息
@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
    payload = message.payload.decode()
    payload = json.loads(payload)
    # print("-------msg-------")
    # print('name  :', p['name'])
    # print('email :', p['email'])
    print('payload:', payload)

    # 入料儲豆槽真空吸料機(ON吸料/OFF排氣)
    if payload['command'] == 'input_vacuum_status':
        if payload['response'] == 'on':
            D['input_vacuum_status'] = 'on'
        else:
            D['input_vacuum_status'] = 'off'

    # 真空吸料機
    elif payload['command'] == 'tank_vacuum_status':
        if payload['response'] == 'on':
            # print('test')
            D['tank_vacuum_status'] = 'on'
        else:
            D['tank_vacuum_status'] = 'off'

    # 三通閥(ON吸料/OFF排氣)
    elif payload['command'] == 'tank_threewayvalve_status':
        if payload['response'] == 'on':
            # print('test')
            D['tank_threewayvalve_status'] = 'on'
        else:
            D['tank_threewayvalve_status'] = 'off'

   # 蝴蝶閥(ON開/OFF關)
    elif payload['command'] == 'tank_diskvalve_status':
        if payload['response'] == 'on':
            # print('test')
            D['tank_diskvalve_status'] = 'on'
        else:
            D['tank_diskvalve_status'] = 'off'

    # 電磁閥(ON噴灑消毒/OFF關)
    elif payload['command'] == 'tank_solenoid_disinfect_status':
        if payload['response'] == 'on':
            # print('test')
            D['tank_solenoid_disinfect_status'] = 'on'
        else:
            D['tank_solenoid_disinfect_status'] = 'off'

    # 電磁閥(ON排水/OFF關)
    elif payload['command'] == 'tank_solenoid_water_status':
        if payload['response'] == 'on':
            # print('test')
            D['tank_solenoid_water_status'] = 'on'
        else:
            D['tank_solenoid_water_status'] = 'off'

    # 馬達(單位RPM)
    elif payload['command'] == 'tank_motor_status':
        if payload['response'] == 'off':
            D['tank_motor_status'] = '0'
        else:
            D['tank_motor_status'] = payload['response']

    # 鼓風機(ON開/OFF關)
    elif payload['command'] == 'tank_blower_status':
        if payload['response'] == 'on':
            # print('test')
            D['tank_blower_status'] = 'on'
        else:
            D['tank_blower_status'] = 'off'

    # 加熱棒 1(ON開/OFF關)
    elif payload['command'] == 'tank_heater1_status':
        if payload['response'] == 'on':
            # print('test')
            D['tank_heater1_status'] = 'on'
        else:
            D['tank_heater1_status'] = 'off'

    # 加熱棒 2(ON開/OFF關)
    elif payload['command'] == 'tank_heater2_status':
        if payload['response'] == 'on':
            # print('test')
            D['tank_heater2_status'] = 'on'
        else:
            D['tank_heater2_status'] = 'off'

     # 出料儲豆槽真空吸料機(ON吸料/OFF排氣)
    elif payload['command'] == 'output_vacuum_status':
        if payload['response'] == 'on':
            # print('test')
            D['output_vacuum_status'] = 'on'
        else:
            D['output_vacuum_status'] = 'off'

    # 發酵槽 入料三通閥
    elif payload['command'] == 'tank_threewayvalve_input_status':
        if payload['response'] == 'on':
            # print('test')
            D['tank_threewayvalve_input_status'] = 'on'
        else:
            D['tank_threewayvalve_input_status'] = 'off'

    # 發酵槽 總進水
    elif payload['command'] == 'tank_solenoid_water_total_status':
        if payload['response'] == 'on':
            D['tank_solenoid_water_total_status'] = 'on'
        else:
            D['tank_solenoid_water_total_status'] = 'off'

    # 發酵槽 桶內消毒/打菌
    elif payload['command'] == 'tank_solenoid_disinfect_status':
        if payload['response'] == 'on':
            D['tank_solenoid_disinfect_status'] = 'on'
        else:
            D['tank_solenoid_disinfect_status'] = 'off'

    # 發酵槽 夾層進水
    elif payload['command'] == 'outer_solenoid_water_status':
        if payload['response'] == 'on':
            D['outer_solenoid_water_status'] = 'on'
        else:
            D['outer_solenoid_water_status'] = 'off'

    # 發酵槽 桶內進水
    elif payload['command'] == 'tank_solenoid_water_in_status':
        if payload['response'] == 'on':
            D['tank_solenoid_water_in_status'] = 'on'
        else:
            D['tank_solenoid_water_in_status'] = 'off'

    # 發酵槽 雙核隔膜泵
    elif payload['command'] == 'tank_pump_sensor_status':
        if payload['response'] == 'on':
            D['tank_pump_sensor_status'] = 'on'
        else:
            D['tank_pump_sensor_status'] = 'off'

    # 發酵槽 感測器下豆三通閥
    elif payload['command'] == 'tank_threewayvalve_bean_status':
        if payload['response'] == 'on':
            D['tank_threewayvalve_bean_status'] = 'on'
        else:
            D['tank_threewayvalve_bean_status'] = 'off'

    # 發酵槽 外桶浮選三通閥
    elif payload['command'] == 'outer_threewayvalve_float_status':
        if payload['response'] == 'on':
            D['outer_threewayvalve_float_status'] = 'on'
        else:
            D['outer_threewayvalve_float_status'] = 'off'

    # 發酵槽 溫控開關
    elif payload['command'] == 'tank_temp_enable_status':
        if payload['response'] == 'on':
            D['tank_temp_enable_status'] = 'on'
        else:
            D['tank_temp_enable_status'] = 'off'

    # 發酵槽 設定溫度
    elif payload['command'] == 'tank_temp_status':
        if payload['response'] == 'off':
            D['tank_temp_status'] = '0'
        else:
            D['tank_temp_status'] = payload['response']

    # 清洗浮選槽 浮選槽注水
    elif payload['command'] == 'tank_pump_waterFloat_status':
        if payload['response'] == 'on':
            D['tank_temp_status'] = 'on'
        else:
            D['tank_temp_status'] = 'off'
    
    # 清洗浮選槽 清洗第 2 層灑水
    elif payload['command'] == 'tank_pump_waterL2_status':
        if payload['response'] == 'on':
            D['tank_pump_waterL2_status'] = 'on'
        else:
            D['tank_pump_waterL2_status'] = 'off'

    # 清洗浮選槽 清洗第 4 層灑水
    elif payload['command'] == 'tank_pump_waterL4_status':
        if payload['response'] == 'on':
            D['tank_pump_waterL4_status'] = 'on'
        else:
            D['tank_pump_waterL4_status'] = 'off'

    # 清洗浮選槽 清洗第 3 層電磁閥
    elif payload['command'] == 'tank_solenoid_waterL3_status':
        if payload['response'] == 'on':
            D['tank_solenoid_waterL3_status'] = 'on'
        else:
            D['tank_solenoid_waterL3_status'] = 'off'

    # 清洗浮選槽 清洗第 5 層電磁閥
    elif payload['command'] == 'tank_solenoid_waterL5_status':
        if payload['response'] == 'on':
            D['tank_solenoid_waterL5_status'] = 'on'
        else:
            D['tank_solenoid_waterL5_status'] = 'off'

    # 清洗浮選槽 步進馬達
    elif payload['command'] == 'tank_stepping_motor_status':
        if payload['response'] == 'off':
            D['tank_stepping_motor_status'] = '0'
        else:
            D['tank_stepping_motor_status'] = payload['response']