views_0728??.py 109 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680
  1. # 主業務邏輯中的視圖和路由的定義
  2. import os
  3. import datetime
  4. from flask import Flask, redirect, render_template, request, session, Response, jsonify
  5. from sqlalchemy.sql.expression import desc
  6. # 導入藍圖程序,用於構建路由
  7. from werkzeug.utils import redirect
  8. from . import main
  9. from coffee_manage import mqtt
  10. # 導入db,用於操作數據庫
  11. from coffee_manage import db
  12. # 導入實體類,用於操作數據庫
  13. from ..models import *
  14. import json
  15. from datetime import datetime as dt
  16. from sqlalchemy import text
  17. import pymysql
  18. import pandas as pd
  19. from concurrent.futures import ThreadPoolExecutor
  20. import cv2
  21. import pickle
  22. import socket
  23. import time
  24. import threading
  25. import numpy as np
  26. import math
  27. from .mqtt import MQTT
  28. from matplotlib import pyplot as plt
  29. import random
  30. from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg as FigureCanvas
  31. import io
  32. from flask import make_response
  33. pool = ThreadPoolExecutor(25)
  34. s_sock = 0
  35. lock = threading.Lock()
  36. '''
  37. mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffee',
  38. password='skyeye', database='Coffee', charset='utf8')
  39. mycursor = mydb.cursor()
  40. '''
  41. # 主頁的訪問路徑
  42. @main.route('/')
  43. def main_index():
  44. # 獲取登入信息
  45. if 'id' in session and 'uname' in session:
  46. username = session['uname']
  47. # Rita 參數 params 是用來取得參數的 locals=() 所有參數
  48. return render_template('index.html', params=locals())
  49. else:
  50. # Rita 是否應改為 registration 註冊, 沒有會員資料就導到註冊去
  51. return render_template('sign_in.html')
  52. # Rita 測試
  53. # 使用者名稱測試
  54. # !!! AttributeError: 'NoneType' object has no attribute 'vacuum'
  55. @main.route('/loading/S<stid>', methods=['GET', 'POST'])
  56. def S_loading(stid):
  57. if request.method == 'GET':
  58. # 色選機
  59. return
  60. else:
  61. pass
  62. @main.route('/loading/P<ptid>', methods=['GET', 'POST'])
  63. def P_loading(ptid):
  64. if request.method == 'GET':
  65. # 脫皮機
  66. return
  67. else:
  68. pass
  69. @main.route('/loading/C<ctid>', methods=['GET', 'POST'])
  70. def C_loading(ctid):
  71. if request.method == 'GET':
  72. tank_actuator = clean_tank_actuator.query.filter_by(tank_num='C'+ctid).order_by(text('datetime desc')).first()
  73. tank_vacuum = tank_actuator.vacuum
  74. tank_pump_waterFloat = tank_actuator.pump_waterFloat
  75. tank_pump_waterL2 = tank_actuator.pump_waterL2
  76. tank_pump_waterL4 = tank_actuator.pump_waterL4
  77. tank_solenoid_waterL3 = tank_actuator.solenoid_waterL3
  78. tank_solenoid_waterL5 = tank_actuator.solenoid_waterL5
  79. tank_stepping_motor = tank_actuator.stepping_motor
  80. print('tank_stepping_motor:', tank_stepping_motor)
  81. # 感測器_浮選清洗_超音波感測器
  82. tank_UltraSonic = clean_tank_UltraSonic.query.filter_by(tank_num='C'+ctid).order_by(text('datetime desc')).first()
  83. UltraSonic= tank_UltraSonic.UltraSonic
  84. return jsonify({"UltraSonic":UltraSonic,
  85. "tank_vacuum":tank_vacuum,
  86. "tank_pump_waterFloat":tank_pump_waterFloat,
  87. "tank_pump_waterL2":tank_pump_waterL2,
  88. "tank_pump_waterL4":tank_pump_waterL4,
  89. "tank_solenoid_waterL3":tank_solenoid_waterL3,
  90. "tank_solenoid_waterL5":tank_solenoid_waterL5,
  91. "tank_stepping_motor":tank_stepping_motor
  92. })
  93. else:
  94. pass
  95. @main.route('/loading/F<ftid>', methods=['GET', 'POST'])
  96. def F_loading(ftid):
  97. if request.method == 'GET':
  98. # 制動器_發酵槽_ALL
  99. tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  100. tank_vacuum = tank_actuator.vacuum
  101. tank_threewayvalve_input = tank_actuator.threewayvalve_input
  102. tank_diskvalve = tank_actuator.diskvalve
  103. tank_solenoid_water_total = tank_actuator.solenoid_tank_water_total
  104. tank_solenoid_disinfect = tank_actuator.solenoid_tank_disinfect
  105. outer_solenoid_water = tank_actuator.solenoid_outer_water
  106. tank_solenoid_water_in = tank_actuator.solenoid_tank_water_in
  107. tank_pump_sensor = tank_actuator.pump_sensor
  108. tank_threewayvalve_bean = tank_actuator.threewayvalve_bean
  109. outer_threewayvalve_float = tank_actuator.threewayvalve_outer_float
  110. tank_motor = tank_actuator.motor
  111. tank_heater1 = tank_actuator.heater1
  112. tank_heater2 = tank_actuator.heater2
  113. tank_temp_enable = tank_actuator.temp_enable
  114. tank_temp = tank_actuator.temp
  115. # 感測器_發酵桶_SHT11
  116. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  117. SHT11_Temp = float(tank_SHT11.SHT11_Temp)
  118. SHT11_Humidity = float(tank_SHT11.SHT11_Humidity)
  119. # 感測器_發酵桶_二氧化碳
  120. tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  121. CO2 = float(tank_CO2.CO2)
  122. # 感測器_發酵桶_酸鹼值
  123. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  124. tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  125. tank_DO = ferment_tank_DO.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  126. tank_EC = ferment_tank_EC.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  127. PH = float(tank_PH.PH)
  128. ORP = float(tank_ORP.ORP)
  129. DO = float(tank_DO.DO)
  130. EC = float(tank_EC.EC)
  131. # 感測器_發酵桶_氣壓
  132. tank_PA = ferment_tank_PA.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  133. PA = float(tank_PA.PA)
  134. # 感測器_發酵桶_超音波感測器
  135. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  136. UltraSonic= int(tank_UltraSonic.UltraSonic)
  137. # 感測器_發酵桶_水位計
  138. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  139. WaterLevel = tank_WaterLevel.WaterLevel
  140. return jsonify({"UltraSonic":UltraSonic,
  141. "SHT11_Temp": SHT11_Temp,
  142. "SHT11_Humidity":SHT11_Humidity,
  143. "CO2":CO2,
  144. "PH":PH,
  145. "ORP":ORP,
  146. "DO":DO,
  147. "EC":EC,
  148. "PA":PA,
  149. "WaterLevel":WaterLevel,
  150. "tank_vacuum":tank_vacuum,
  151. "tank_threewayvalve_input":tank_threewayvalve_input,
  152. "tank_diskvalve":tank_diskvalve,
  153. "tank_solenoid_water_total":tank_solenoid_water_total,
  154. "tank_solenoid_disinfect":tank_solenoid_disinfect,
  155. "outer_solenoid_water":outer_solenoid_water,
  156. "tank_solenoid_water_in":tank_solenoid_water_in,
  157. "tank_pump_sensor":tank_pump_sensor,
  158. "tank_threewayvalve_bean":tank_threewayvalve_bean,
  159. "outer_threewayvalve_float":outer_threewayvalve_float,
  160. "tank_motor":tank_motor,
  161. "tank_heater1":tank_heater1,
  162. "tank_heater2":tank_heater2,
  163. "tank_temp_enable":tank_temp_enable,
  164. "tank_temp":tank_temp
  165. })
  166. else:
  167. pass
  168. @main.route('/loading/D<dtid>', methods=['GET', 'POST'])
  169. def D_loading(dtid):
  170. if request.method == 'GET':
  171. # 感測器_乾燥桶_超音波感測器
  172. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  173. UltraSonic = tank_UltraSonic.UltraSonic
  174. # 感測器_乾燥桶_SHT11
  175. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  176. SHT11_Temp = tank_SHT11.SHT11_Temp
  177. SHT11_Humidity = tank_SHT11.SHT11_Humidity
  178. # 感測器_乾燥桶_土壤三合一
  179. tank_Soil = dry_tank_Soil.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  180. soil_Temp = tank_Soil.soil_Temp
  181. soil_Humidity = tank_Soil.soil_Humidity
  182. soil_EC = tank_Soil.soil_EC
  183. # 感測器_乾燥桶_氣壓
  184. tank_PA = dry_tank_PA.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  185. PA = tank_PA.PA
  186. # 制動器_乾燥桶_ALL
  187. tank_brake = dry_tank_brake.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  188. # tank_vacuum = 'ON' if i<100 else 2 if i>100 else 0
  189. tank_vacuum = tank_brake.vacuum
  190. tank_threewayvalve = tank_brake.threewayvalve
  191. tank_diskvalve = tank_brake.diskvalve
  192. tank_solenoid_disinfect = tank_brake.solenoid_disinfect
  193. tank_solenoid_water = tank_brake.solenoid_water
  194. tank_motor = tank_brake.motor
  195. tank_blower = tank_brake.blower
  196. tank_heater1 = tank_brake.heater1
  197. tank_heater2 = tank_brake.heater2
  198. tank_temp1_enable = tank_brake.temp1_enable
  199. tank_temp1 = tank_brake.temp1
  200. #return jsonify({"peeling": peeling_rpm})
  201. return jsonify({"UltraSonic":UltraSonic,
  202. "SHT11_Temp": SHT11_Temp,
  203. "SHT11_Humidity":SHT11_Humidity,
  204. "soil_Temp":soil_Temp,
  205. "soil_Humidity":soil_Humidity,
  206. "soil_EC":soil_EC,
  207. "PA":PA,
  208. "tank_vacuum":tank_vacuum,
  209. "tank_threewayvalve":tank_threewayvalve,
  210. "tank_diskvalve":tank_diskvalve,
  211. "tank_solenoid_disinfect":tank_solenoid_disinfect,
  212. "tank_solenoid_water":tank_solenoid_water,
  213. "tank_motor":tank_motor,
  214. "tank_blower":tank_blower,
  215. "tank_heater1":tank_heater1,
  216. "tank_heater2":tank_heater2,
  217. "tank_temp1_enable":tank_temp1_enable,
  218. "tank_temp1":tank_temp1
  219. })
  220. else:
  221. pass
  222. @main.route('/index_new')
  223. def index_new():
  224. return render_template('index_new.html', params=locals())
  225. @main.route('/user/<name>')
  226. def user(name):
  227. return render_template('hello.html', name=name)
  228. '''
  229. @main.route('/plot.png')
  230. def plot():
  231. # 重新整理會有問題
  232. # 圖的寬和高
  233. fig = plt.figure()
  234. # 在圖中新增子圖, 通常多個圖才會用到?
  235. axis = fig.add_subplot(1, 1, 1)
  236. # x、 軸資料
  237. xs = range(100)
  238. ys = [random.randint(1, 50) for x in xs]
  239. axis.plot(xs, ys)
  240. canvas = FigureCanvas(fig)
  241. output = io.BytesIO()
  242. canvas.print_png(output)
  243. response = make_response(output.getvalue())
  244. response.mimetype = 'image/png'
  245. return response
  246. '''
  247. @main.route('/chart/<sensor_name>/<tid>', methods=['GET', 'POST'])
  248. def chart(sensor_name, tid):
  249. if request.method == 'GET':
  250. return render_template('sensor_chart.html', **locals())
  251. elif request.method == 'POST':
  252. starttime = request.values['sensor_starttime'] # 2021-07-19T09:00
  253. endtime = request.values['sensor_endtime'] # 2021-07-19T12:00
  254. sensor_name = request.values['sensors']
  255. print('sensor_name:', sensor_name)
  256. # 判斷資料索取區間 起<迄
  257. if starttime < endtime :
  258. # print('starttime endtime:', starttime, endtime)
  259. # print('TF:', starttime<endtime ) # 可以比較 起<迄
  260. # [html]2021-07-19T09:00 轉換成 [python]datetime.datetime(2021, 7, 19, 9, 0, 0)
  261. start_YY = starttime[:4] # '2021'
  262. start_MM = starttime[6:7] if starttime[5:7][:1] == '0' else starttime[5:7] # '07'
  263. start_DD = starttime[9:10] if starttime[8:10][:1] == '0' else starttime[8:10] # '19'
  264. start_hh = starttime[12:13] if starttime[11:13][:1] == '0' else starttime[11:13] # '09'
  265. start_mm = starttime[15:] if starttime[14:][:1] == '0' else starttime[14:] # '00'
  266. start_ss = 0
  267. end_YY = endtime[:4] # '2021'
  268. end_MM = endtime[6:7] if endtime[5:7][:1] == '0' else endtime[5:7] # '07'
  269. end_DD = endtime[9:10] if endtime[8:10][:1] == '0' else endtime[8:10] # '19'
  270. end_hh = endtime[12:13] if endtime[11:13][:1] == '0' else endtime[11:13] # '09'
  271. end_mm = endtime[15:] if endtime[14:][:1] == '0' else endtime[14:] # '00'
  272. end_ss = 0
  273. time_range = []
  274. temp_range = []
  275. # 拿掉會 Error, 要使用沒有 GUI 的 matplotlib
  276. plt.switch_backend('agg')
  277. plt.figure()
  278. if sensor_name == 'SHT11_Temp':
  279. for d in db.session.query(dry_tank_SHT11) \
  280. .filter_by(tank_num='D' + tid) \
  281. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_SHT11.datetime) \
  282. .filter(dry_tank_SHT11.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  283. .order_by(dry_tank_SHT11.datetime):
  284. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  285. time_range.append(str(d.datetime))
  286. temp_range.append(float(d.SHT11_Temp))
  287. # 畫出 x 軸基準線
  288. plt.axhline(28.5, color= 'r')
  289. elif sensor_name == 'SHT11_Humidity':
  290. for d in db.session.query(dry_tank_SHT11) \
  291. .filter_by(tank_num='D' + tid) \
  292. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_SHT11.datetime) \
  293. .filter(dry_tank_SHT11.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  294. .order_by(dry_tank_SHT11.datetime):
  295. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  296. time_range.append(str(d.datetime))
  297. temp_range.append(float(d.SHT11_Humidity))
  298. elif sensor_name == 'UltraSonic':
  299. for d in db.session.query(dry_tank_UltraSonic) \
  300. .filter_by(tank_num='D' + tid) \
  301. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_UltraSonic.datetime) \
  302. .filter(dry_tank_UltraSonic.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  303. .order_by(dry_tank_UltraSonic.datetime):
  304. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  305. time_range.append(str(d.datetime))
  306. temp_range.append(float(d.UltraSonic))
  307. elif sensor_name == 'PA':
  308. for d in db.session.query(dry_tank_PA) \
  309. .filter_by(tank_num='D' + tid) \
  310. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_PA.datetime) \
  311. .filter(dry_tank_PA.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  312. .order_by(dry_tank_PA.datetime):
  313. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  314. time_range.append(str(d.datetime))
  315. temp_range.append(float(d.PA))
  316. elif sensor_name == 'soil_Temp':
  317. for d in db.session.query(dry_tank_Soil) \
  318. .filter_by(tank_num='D' + tid) \
  319. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_Soil.datetime) \
  320. .filter(dry_tank_Soil.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  321. .order_by(dry_tank_Soil.datetime):
  322. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  323. time_range.append(str(d.datetime))
  324. temp_range.append(float(d.soil_Temp))
  325. # 畫出 x 軸基準線
  326. plt.axhline(28.5, color= 'r')
  327. elif sensor_name == 'soil_Humidity':
  328. for d in db.session.query(dry_tank_Soil) \
  329. .filter_by(tank_num='D' + tid) \
  330. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_Soil.datetime) \
  331. .filter(dry_tank_Soil.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  332. .order_by(dry_tank_Soil.datetime):
  333. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  334. time_range.append(str(d.datetime))
  335. temp_range.append(float(d.soil_Humidity))
  336. elif sensor_name == 'soil_EC':
  337. for d in db.session.query(dry_tank_Soil) \
  338. .filter_by(tank_num='D' + tid) \
  339. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_Soil.datetime) \
  340. .filter(dry_tank_Soil.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  341. .order_by(dry_tank_Soil.datetime):
  342. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  343. time_range.append(str(d.datetime))
  344. temp_range.append(float(d.soil_EC))
  345. print('time_range:', time_range)
  346. print('temp_range:', temp_range)
  347. # 設定 x 軸資料、y 軸資料、折線顏色
  348. plt.plot(time_range, temp_range, 'bo')
  349. # x 軸標題 (中文無法顯示)
  350. # plt.xlabel('time')
  351. # plt.ylabel(sensor_name)
  352. # x 軸 label 和垂直顯示, rotation='vertical'
  353. plt.xticks(time_range, rotation='vertical' )
  354. # 設定圖表標題
  355. plt.title(sensor_name)
  356. # 調整圖片與周圍的間距
  357. plt.tight_layout()
  358. # plt.show()
  359. # 儲存圖片 應改為相對路徑
  360. plt.savefig('C:/Users/USER/Rita/Coffee/CoffeeProject/app/static/img/new_plot.png')
  361. return render_template('sensor_chart.html', url ="../../static/img/new_plot.png", **locals())
  362. # 判斷資料索取區間 起>迄
  363. else:
  364. return render_template('sensor_chart.html', **locals())
  365. # Rita 測試
  366. # 乾燥桶感測器/制動器測試
  367. # Rita 須加上 <tid> 區分桶號 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  368. @main.route('/dry_tank/1', methods=['GET'])
  369. def dry_tank():
  370. if request.method == 'GET':
  371. return render_template('dry_tank.html')
  372. @main.route('/clean', methods=['GET'])
  373. def clean():
  374. # 制動器_浮選清洗_ALL
  375. tank_actuator = clean_tank_actuator.query.filter_by(tank_num='C1').order_by(text('datetime desc')).first()
  376. tank_vacuum = 'ON' if tank_actuator.vacuum == 1 else 'OFF'
  377. tank_pump_waterFloat = 'ON' if tank_actuator.pump_waterFloat == 1 else 'OFF'
  378. tank_pump_waterL2 = 'ON' if tank_actuator.pump_waterL2 == 1 else 'OFF'
  379. tank_pump_waterL4 = 'ON' if tank_actuator.pump_waterL4 == 1 else 'OFF'
  380. tank_solenoid_waterL3 = 'ON' if tank_actuator.solenoid_waterL3 == 1 else 'OFF'
  381. tank_solenoid_waterL5 = 'ON' if tank_actuator.solenoid_waterL5 == 1 else 'OFF'
  382. tank_stepping_motor = tank_actuator.stepping_motor
  383. print('tank_stepping_motor:', tank_stepping_motor)
  384. # 感測器_浮選清洗_超音波感測器
  385. tank_UltraSonic = clean_tank_UltraSonic.query.filter_by(tank_num='C1').order_by(text('datetime desc')).first()
  386. return render_template('clean.html', **locals())
  387. @main.route('/ferment', methods=['GET'])
  388. def ferment():
  389. '''
  390. # 制動器_入料儲豆槽_真空吸料機
  391. input_vacuum = ferment_input_actuator.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
  392. # print('input_vacuum.vacuum:', input_vacuum.vacuum)
  393. input_vacuum = 'ON' if (input_vacuum.vacuum == 1) else 'OFF'
  394. # print('input_vacuum:', input_vacuum)
  395. # 制動器_發酵槽_ALL
  396. tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
  397. tank_vacuum = 'ON' if tank_actuator.vacuum == 1 else 'OFF'
  398. tank_threewayvalve_input = 'ON' if tank_actuator.threewayvalve_input == 1 else 'OFF'
  399. tank_diskvalve = 'ON' if tank_actuator.diskvalve == 1 else 'OFF'
  400. tank_solenoid_water_total = 'ON' if tank_actuator.solenoid_tank_water_total == 1 else 'OFF'
  401. tank_solenoid_disinfect = 'ON' if tank_actuator.solenoid_tank_disinfect == 1 else 'OFF'
  402. outer_solenoid_water = 'ON' if tank_actuator.solenoid_outer_water == 1 else 'OFF'
  403. tank_solenoid_water_in = 'ON' if tank_actuator.solenoid_tank_water_in == 1 else 'OFF'
  404. tank_pump_sensor = 'ON' if tank_actuator.pump_sensor == 1 else 'OFF'
  405. tank_threewayvalve_bean = 'ON' if tank_actuator.threewayvalve_bean == 1 else 'OFF'
  406. outer_threewayvalve_float = 'ON' if tank_actuator.threewayvalve_outer_float == 1 else 'OFF'
  407. tank_motor = tank_actuator.motor
  408. tank_heater1 = 'ON' if tank_actuator.heater1 == 1 else 'OFF'
  409. tank_heater2 = 'ON' if tank_actuator.heater2 == 1 else 'OFF'
  410. tank_temp_enable = 'ON' if tank_actuator.temp_enable == 1 else 'OFF'
  411. tank_temp = tank_actuator.temp
  412. # 制動器_出料儲豆槽_真空吸引機
  413. output_vacuum = ferment_output_actuator.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
  414. #print('output_vacuum.vacuum: ', output_vacuum.vacuum)
  415. output_vacuum = 'ON' if (output_vacuum.vacuum == 1) else 'OFF'
  416. #print('output_vacuum: ', output_vacuum)
  417. # 感測器_入料儲豆槽_超音波感測器
  418. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
  419. # 感測器_發酵桶_SHT11
  420. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
  421. # 感測器_發酵桶_二氧化碳
  422. tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
  423. # 感測器_發酵桶_酸鹼值
  424. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
  425. tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
  426. tank_DO = ferment_tank_DO.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
  427. tank_EC = ferment_tank_EC.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
  428. # 感測器_發酵桶_氣壓
  429. tank_PA = ferment_tank_PA.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
  430. # 感測器_發酵桶_超音波感測器
  431. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
  432. # 感測器_發酵桶_水位計
  433. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
  434. # 感測器_出料儲豆槽_超音波感測器
  435. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
  436. '''
  437. return render_template('ferment.html', **locals())
  438. @main.route('/dry', methods=['GET'])
  439. def dry():
  440. if request.method == 'GET':
  441. '''
  442. # 感測器_入料儲豆槽_超音波感測器
  443. input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()
  444. # 感測器_乾燥桶_SHT11
  445. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()
  446. # 感測器_乾燥桶_土壤三合一
  447. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()
  448. # 感測器_乾燥桶_氣壓
  449. tank_PA = dry_tank_PA.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()
  450. # 感測器_乾燥桶_超音波感測器
  451. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()
  452. # 感測器_出料儲豆槽_超音波感測器
  453. output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()
  454. tank_brake = dry_tank_brake.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()
  455. tank_vacuum = 'ON' if tank_brake.vacuum == 1 else 'OFF'
  456. tank_threewayvalve = 'ON' if tank_brake.threewayvalve == 1 else 'OFF'
  457. tank_diskvalve = 'ON' if tank_brake.diskvalve == 1 else 'OFF'
  458. tank_solenoid_disinfect = 'ON' if tank_brake.solenoid_disinfect == 1 else 'OFF'
  459. tank_solenoid_water = 'ON' if tank_brake.solenoid_water == 1 else 'OFF'
  460. tank_motor = tank_brake.motor
  461. tank_blower = 'ON' if tank_brake.blower == 1 else 'OFF'
  462. tank_heater1 = 'ON' if tank_brake.heater1 == 1 else 'OFF'
  463. tank_heater2 = 'ON' if tank_brake.heater2 == 1 else 'OFF'
  464. tank_temp1_enable = 'ON' if tank_brake.temp1_enable == 1 else 'OFF'
  465. tank_temp1 = tank_brake.temp1
  466. '''
  467. return render_template('dry.html', **locals())
  468. @main.route('/clean_container/<tid>', methods=['GET', 'POST'])
  469. def clean_container(tid):
  470. if request.method == 'GET':
  471. # 制動器_入料儲豆槽_真空吸料機
  472. input_vacuum = clean_input_actuator.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  473. input_vacuum = 'ON' if (input_vacuum.vacuum == 1) else 'OFF'
  474. # 制動器_浮選清洗_ALL
  475. tank_actuator = clean_tank_actuator.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  476. tank_vacuum = 'ON' if tank_actuator.vacuum == 1 else 'OFF'
  477. tank_pump_waterFloat = 'ON' if tank_actuator.pump_waterFloat == 1 else 'OFF'
  478. tank_pump_waterL2 = 'ON' if tank_actuator.pump_waterL2 == 1 else 'OFF'
  479. tank_pump_waterL4 = 'ON' if tank_actuator.pump_waterL4 == 1 else 'OFF'
  480. tank_solenoid_waterL3 = 'ON' if tank_actuator.solenoid_waterL3 == 1 else 'OFF'
  481. tank_solenoid_waterL5 = 'ON' if tank_actuator.solenoid_waterL5 == 1 else 'OFF'
  482. tank_stepping_motor = tank_actuator.stepping_motor
  483. # 制動器_出料儲豆槽_真空吸料機
  484. output_vacuum = clean_output_actuator.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  485. output_vacuum = 'ON' if (output_vacuum.vacuum == 1) else 'OFF'
  486. # 感測器_浮選清洗_超音波感測器
  487. tank_UltraSonic = clean_tank_UltraSonic.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  488. return render_template('clean_container.html', title='clean_container', **locals())
  489. elif request.method == 'POST':
  490. pass
  491. @main.route('/ferment_container/<tid>', methods=['GET', 'POST'])
  492. def ferment_container(tid):
  493. if request.method == 'GET':
  494. # 制動器_入料儲豆槽_真空吸料機
  495. input_vacuum = ferment_input_actuator.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  496. # print('input_vacuum.vacuum:', input_vacuum.vacuum)
  497. input_vacuum = 'ON' if (input_vacuum.vacuum == 1) else 'OFF'
  498. # print('input_vacuum:', input_vacuum)
  499. # 制動器_發酵槽_ALL
  500. tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  501. tank_vacuum = 'ON' if tank_actuator.vacuum == 1 else 'OFF'
  502. tank_threewayvalve_input = 'ON' if tank_actuator.threewayvalve_input == 1 else 'OFF'
  503. tank_diskvalve = 'ON' if tank_actuator.diskvalve == 1 else 'OFF'
  504. tank_solenoid_water_total = 'ON' if tank_actuator.solenoid_tank_water_total == 1 else 'OFF'
  505. tank_solenoid_disinfect = 'ON' if tank_actuator.solenoid_tank_disinfect == 1 else 'OFF'
  506. outer_solenoid_water = 'ON' if tank_actuator.solenoid_outer_water == 1 else 'OFF'
  507. tank_solenoid_water_in = 'ON' if tank_actuator.solenoid_tank_water_in == 1 else 'OFF'
  508. tank_pump_sensor = 'ON' if tank_actuator.pump_sensor == 1 else 'OFF'
  509. tank_threewayvalve_bean = 'ON' if tank_actuator.threewayvalve_bean == 1 else 'OFF'
  510. outer_threewayvalve_float = 'ON' if tank_actuator.threewayvalve_outer_float == 1 else 'OFF'
  511. tank_motor = tank_actuator.motor
  512. tank_heater1 = 'ON' if tank_actuator.heater1 == 1 else 'OFF'
  513. tank_heater2 = 'ON' if tank_actuator.heater2 == 1 else 'OFF'
  514. tank_temp_enable = 'ON' if tank_actuator.temp_enable == 1 else 'OFF'
  515. tank_temp = tank_actuator.temp
  516. # 制動器_出料儲豆槽_真空吸引機
  517. output_vacuum = ferment_output_actuator.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  518. #print('output_vacuum.vacuum: ', output_vacuum.vacuum)
  519. output_vacuum = 'ON' if (output_vacuum.vacuum == 1) else 'OFF'
  520. #print('output_vacuum: ', output_vacuum)
  521. # 感測器_入料儲豆槽_超音波感測器
  522. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  523. # 感測器_發酵桶_SHT11
  524. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  525. # 感測器_發酵桶_二氧化碳
  526. tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  527. # 感測器_發酵桶_酸鹼值
  528. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  529. tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  530. tank_DO = ferment_tank_DO.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  531. tank_EC = ferment_tank_EC.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  532. # 感測器_發酵桶_氣壓
  533. tank_PA = ferment_tank_PA.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  534. # 感測器_發酵桶_超音波感測器
  535. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  536. # 感測器_發酵桶_水位計
  537. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  538. num_tank_WaterLevel = float(tank_WaterLevel.WaterLevel)
  539. # 感測器_出料儲豆槽_超音波感測器
  540. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  541. return render_template('ferment_container.html', title='ferment_container', **locals())
  542. elif request.method == 'POST':
  543. pass
  544. @main.route('/dry_container_schedule', methods=['GET', 'POST'])
  545. def dry_container_schedule():
  546. if request.method == 'GET':
  547. if 'id' in session and 'uname' in session:
  548. username = session['uname']
  549. # 感測器_入料儲豆槽_超音波感測器
  550. input_UltraSonic = dry_input_sensor.query.order_by(text('datetime desc')).first()
  551. # 感測器_乾燥桶_超音波感測器
  552. tank_UltraSonic = dry_tank_UltraSonic.query.order_by(text('datetime desc')).first()
  553. return render_template('dry_container_schedule.html', title='dry_container_schedule', **locals())
  554. elif request.method == 'POST':
  555. pass
  556. @main.route('/dry_container/<tid>', methods=['GET', 'POST'])
  557. def dry_container(tid):
  558. if request.method == 'GET':
  559. if 'id' in session and 'uname' in session:
  560. username = session['uname']
  561. # Rita 參數 params 是用來取得參數的 locals=() 所有參數
  562. '''
  563. # 開啟本機 coffeetest 資料庫
  564. # mydb = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='g53743001', database='coffeetest', charset='utf8')
  565. mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffee',
  566. password='skyeye', database='Coffee', charset='utf8')
  567. mycursor = mydb.cursor()
  568. '''
  569. # 感測器_入料儲豆槽_超音波感測器
  570. input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  571. # 感測器_乾燥桶_SHT11
  572. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  573. num_SHT11_temp = float(tank_SHT11.SHT11_Temp)
  574. # 感測器_乾燥桶_土壤三合一
  575. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  576. num_Soil_temp = float(tank_Soil.soil_Temp)
  577. # 感測器_乾燥桶_氣壓
  578. tank_PA = dry_tank_PA.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  579. # 感測器_乾燥桶_超音波感測器
  580. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  581. # 感測器_出料儲豆槽_超音波感測器
  582. output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  583. # 制動器_入料儲豆槽_真空吸引機
  584. input_vacuum = dry_input_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  585. # print("input_vacuum:", input_vacuum)
  586. input_vacuum = input_vacuum.vacuum
  587. #print('input_vacuum:', input_vacuum.vacuum)
  588. # 制動器_乾燥桶_ALL
  589. tank_brake = dry_tank_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  590. tank_vacuum = tank_brake.vacuum
  591. tank_threewayvalve = tank_brake.threewayvalve
  592. tank_diskvalve = tank_brake.diskvalve
  593. tank_solenoid_disinfect = tank_brake.solenoid_disinfect
  594. tank_solenoid_water = tank_brake.solenoid_water
  595. tank_motor = tank_brake.motor
  596. tank_blower = tank_brake.blower
  597. tank_heater1 = tank_brake.heater1
  598. tank_heater2 = tank_brake.heater2
  599. tank_temp1_enable = tank_brake.temp1_enable
  600. tank_temp1 = tank_brake.temp1
  601. '''
  602. tank_vacuum = 'ON' if tank_brake.vacuum == 1 else 'OFF'
  603. tank_threewayvalve = 'ON' if tank_brake.threewayvalve == 1 else 'OFF'
  604. tank_diskvalve = 'ON' if tank_brake.diskvalve == 1 else 'OFF'
  605. tank_solenoid_disinfect = 'ON' if tank_brake.solenoid_disinfect == 1 else 'OFF'
  606. tank_solenoid_water = 'ON' if tank_brake.solenoid_water == 1 else 'OFF'
  607. tank_motor = tank_brake.motor
  608. tank_blower = 'ON' if tank_brake.blower == 1 else 'OFF'
  609. tank_heater1 = 'ON' if tank_brake.heater1 == 1 else 'OFF'
  610. tank_heater2 = 'ON' if tank_brake.heater2 == 1 else 'OFF'
  611. tank_temp1_enable = 'ON' if tank_brake.temp1_enable == 1 else 'OFF'
  612. tank_temp1 = tank_brake.temp1
  613. '''
  614. '''
  615. data = mycursor.execute(
  616. 'SELECT * FROM dry_tank_brake ORDER BY datetime DESC;')
  617. data = mycursor.fetchone()
  618. '''
  619. # 制動器_出料儲豆槽_真空吸引機
  620. output_vacuum = dry_output_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  621. #print('output_vacuum.vacuum: ', output_vacuum.vacuum)
  622. output_vacuum = 'ON' if (output_vacuum.vacuum == 1) else 'OFF'
  623. #print('output_vacuum: ', output_vacuum)
  624. # 傳 MQTT 給阿超, 阿超讓硬體動作, 將資料儲存到資料庫
  625. input_data = set_dry_input.query.order_by(text('datetime desc')).first()
  626. schedule_input_height = input_data.input_height
  627. schedule_input_entertime = input_data.input_entertime
  628. schedule_input_exittime = input_data.input_exittime
  629. schedule_tank_height = input_data.tank_height
  630. return render_template('dry_container.html', title='dry_container', **locals())
  631. elif request.method == 'POST':
  632. # 表單輸入處
  633. print('/dry_input_setting POST')
  634. set = set_dry_input()
  635. set.input_height = request.form['schedule_input_height']
  636. set.input_entertime = request.form['schedule_input_entertime']
  637. set.input_exittime = request.form['schedule_input_exittime']
  638. set.tank_height = request.form['schedule_tank_height']
  639. #將數據保存進資料庫 - 註冊
  640. db.session.add(set)
  641. # 手動提交,目的是為了獲取提交後的user的id
  642. db.session.commit()
  643. # 當user成功插入進資料庫之後,程序會自動將所有信息取出來在賦值給user
  644. # 完成登入的操作
  645. # setting = Set_dry_input.query.order_by(text('datetime desc')).first()
  646. #session['id'] = set.userID
  647. #session['uname'] = set.username
  648. return redirect('/dry_container')
  649. # 登入頁面的訪問路徑
  650. @main.route('/login', methods=['GET', 'POST'])
  651. def login_views():
  652. if request.method == 'GET':
  653. if 'id' in session and 'uname' in session:
  654. return redirect('/')
  655. else:
  656. return render_template('sign_in.html')
  657. else:
  658. # 接收前端傳過來的資料
  659. username = request.form['username']
  660. password = request.form['password']
  661. # 使用接收的用戶和密碼到資料庫中查詢
  662. # Rita first() 避免欄位中的 null 值 ???
  663. user = User.query.filter_by(
  664. username=username, password=password).first()
  665. # 如果用戶存在,將信息保存置session並重定向回首頁,否則重定向回登入頁
  666. if user:
  667. resp = redirect('/')
  668. # 判斷是否有記住密碼
  669. if 'rem' in request.form:
  670. userID = str(user.userID)
  671. max_age = 60*60*24*365 # Rita max_age???
  672. resp.set_cookie("username", username, max_age=max_age)
  673. resp.set_cookie("userID", userID, max_age=max_age)
  674. session['uname'] = user.username
  675. session['id'] = user.userID
  676. return resp
  677. else:
  678. errMsg = "Wrong login or password"
  679. return render_template('sign_in.html', errMsg=errMsg)
  680. # 登入重設密碼的頁面
  681. # Rita reset_pwd1 - Email
  682. # Rita reset_pwd2 - New password / Confirm password
  683. @main.route('/reset_password', methods=['POST', 'GET'])
  684. def reset_password_views():
  685. if request.method == 'GET':
  686. if 'mail' in session:
  687. del session['mail']
  688. return render_template('reset_pwd1.html')
  689. else:
  690. # 如果有id在session裡,代表從reset_pwd2過來的 ???????????????
  691. if "mail" in session:
  692. new_pwd = request.form['new_pwd']
  693. confirm_pwd = request.form['confirm_pwd']
  694. # 判斷密碼是否一致
  695. if new_pwd == confirm_pwd:
  696. mail = session['mail']
  697. user = User.query.filter_by(mail=mail).first()
  698. user.password = new_pwd
  699. db.session.add(user)
  700. del session['mail']
  701. # 修改完後回登入頁
  702. return redirect('/login')
  703. else:
  704. errMsg = "Passwords does not match"
  705. # Rita 前面的 errMsg 是指網頁上的 {{errMsg}} 位置
  706. return render_template('reset_pwd2.html', errMsg=errMsg)
  707. email = request.form['email']
  708. user = User.query.filter_by(mail=email).first()
  709. if user: # Rita 有找到對應 email
  710. session['mail'] = user.mail
  711. return render_template('reset_pwd2.html')
  712. else:
  713. errMsg = "Wrong email.Please try again"
  714. return render_template('reset_pwd1.html', errMsg=errMsg)
  715. # 註冊頁面的訪問路徑
  716. @main.route('/register', methods=['POST', "GET"])
  717. def register_views():
  718. if request.method == 'GET':
  719. return render_template('registration.html')
  720. else:
  721. # 獲取文本框的值並賦值給user實體對象
  722. user = User()
  723. user.firstname = request.form['firstname']
  724. user.lastname = request.form['lastname']
  725. user.mail = request.form['email']
  726. user.phone = request.form['phone']
  727. user.username = request.form['username']
  728. user.password = request.form['password']
  729. user.status = 1 # Rita app\models.py 設定 0:admin;1:new;9:disable
  730. #將數據保存進資料庫 - 註冊
  731. db.session.add(user)
  732. # 手動提交,目的是為了獲取提交後的user的id
  733. db.session.commit()
  734. # 當user成功插入進資料庫之後,程序會自動將所有信息取出來在賦值給user
  735. # 完成登入的操作
  736. user = User.query.filter_by(username=user.username).first()
  737. session['id'] = user.userID
  738. session['uname'] = user.username
  739. return redirect('/')
  740. # 驗證email訪問路徑
  741. @main.route('/check_email')
  742. def check_email_views():
  743. email = request.args['email']
  744. user = User.query.filter_by(mail=email).first()
  745. if user:
  746. # Rita email 錯誤時會顯示 Incorrect email address
  747. result = {"errMsg": " "}
  748. else:
  749. result = {"pass": " "}
  750. return json.dumps(result) # ??? 輸出 result 意義???
  751. # 驗證username訪問路徑
  752. @main.route('/check_username')
  753. def check_username_views():
  754. username = request.args['username']
  755. user = User.query.filter_by(username=username).first()
  756. if user:
  757. result = {"errMsg": " "}
  758. else:
  759. result = {"pass": " "}
  760. return json.dumps(result)
  761. # 咖啡貨櫃的訪問路徑
  762. @main.route('/cargo_list', methods=['GET', 'POST'])
  763. def cargo_list_views():
  764. username = session['uname']
  765. if request.method == 'GET':
  766. return render_template('cargo_list.html', params=locals())
  767. else:
  768. pass
  769. # 貨櫃1的訪問路徑
  770. @main.route('/cargo1', methods=['GET', 'POST'])
  771. def cargo1_views():
  772. username = session['uname']
  773. if request.method == 'GET':
  774. return render_template('cargo1.html', params=locals())
  775. else:
  776. pass
  777. # 貨櫃1排程的訪問路徑
  778. @main.route('/cargo1_schedule', methods=['GET', 'POST'])
  779. def cargo1_schedule_views():
  780. username = session['uname']
  781. if request.method == 'GET':
  782. # 將已儲存的排程資料傳給前端
  783. # 進豆閥
  784. try:
  785. bean = BeanValve.query.order_by(text('datetime desc')).first()
  786. datetime = bean.datetime
  787. beans = BeanValve.query.filter_by(
  788. datetime=datetime).all()
  789. except Exception as e:
  790. pass
  791. # 清洗機
  792. try:
  793. wash = WashMachine.query.order_by(text('datetime desc')).first()
  794. datetime = wash.datetime
  795. washes = WashMachine.query.filter_by(datetime=datetime).all()
  796. except Exception as e:
  797. pass
  798. # 輸送帶1
  799. try:
  800. belt1 = ConveyorBelt1.query.order_by(text('datetime desc')).first()
  801. datetime = belt1.datetime
  802. belts1 = ConveyorBelt1.query.filter_by(datetime=datetime).all()
  803. except Exception as e:
  804. pass
  805. # ///////////////////////////////////////////////////////////////////////////////////////////
  806. # 消毒機
  807. try:
  808. disinfect = Cargo1Disinfect.query.order_by(
  809. text('datetime desc')).first()
  810. datetime = disinfect.datetime
  811. disinfects = Cargo1Disinfect.query.filter_by(
  812. datetime=datetime).all()
  813. except Exception as e:
  814. pass
  815. # 色選機
  816. try:
  817. color = ColorMachine.query.order_by(text('datetime desc')).first()
  818. datetime = color.datetime
  819. colors = ColorMachine.query.filter_by(datetime=datetime).all()
  820. except Exception as e:
  821. pass
  822. # 輸送帶2
  823. try:
  824. belt2 = ConveyorBelt2.query.order_by(text('datetime desc')).first()
  825. datetime = belt2.datetime
  826. belts2 = ConveyorBelt2.query.filter_by(datetime=datetime).all()
  827. except Exception as e:
  828. pass
  829. # 去皮機
  830. try:
  831. peeling = PeelingMachine.query.order_by(
  832. text('datetime desc')).first()
  833. datetime = peeling.datetime
  834. peelings = PeelingMachine.query.filter_by(datetime=datetime).all()
  835. except Exception as e:
  836. pass
  837. # 輸送帶3
  838. try:
  839. belt3 = ConveyorBelt3.query.order_by(text('datetime desc')).first()
  840. datetime = belt3.datetime
  841. belts3 = ConveyorBelt3.query.filter_by(datetime=datetime).all()
  842. except Exception as e:
  843. pass
  844. return render_template('cargo1_schedule.html', params=locals())
  845. else:
  846. current_time = dt.now()
  847. # 循環從前端提交過來的資料
  848. for i in request.form:
  849. # 進豆閥
  850. if i[:10] == 'inletValve':
  851. if i[:19] == 'inletValve_duration':
  852. bean = BeanValve()
  853. bean.duration = request.form[i]
  854. elif i[:18] == 'inletValve_from_hr':
  855. iv_from_hr = request.form[i]
  856. elif i[:19] == 'inletValve_from_min':
  857. iv_from_min = request.form[i]
  858. bean.start = iv_from_hr + ":" + iv_from_min
  859. elif i[:16] == 'inletValve_to_hr':
  860. iv_to_hr = request.form[i]
  861. elif i[:17] == 'inletValve_to_min':
  862. iv_to_min = request.form[i]
  863. bean.end = iv_to_hr + ":" + iv_to_min
  864. bean.datetime = current_time
  865. db.session.add(bean)
  866. db.session.commit()
  867. # 清洗機
  868. elif i[:4] == 'wash':
  869. if i[:13] == 'wash_duration':
  870. wash = WashMachine()
  871. wash.duration = request.form[i]
  872. elif i[:12] == 'wash_from_hr':
  873. wash_from_hr = request.form[i]
  874. elif i[:13] == 'wash_from_min':
  875. wash_from_min = request.form[i]
  876. wash.start = wash_from_hr + ":" + wash_from_min
  877. elif i[:10] == 'wash_to_hr':
  878. wash_to_hr = request.form[i]
  879. elif i[:11] == 'wash_to_min':
  880. wash_to_min = request.form[i]
  881. wash.end = wash_to_hr + ":" + wash_to_min
  882. wash.datetime = current_time
  883. db.session.add(wash)
  884. db.session.commit()
  885. # 輸送帶1
  886. elif i[:5] == 'belt1':
  887. if i[:14] == 'belt1_duration':
  888. belt1 = ConveyorBelt1()
  889. belt1.duration = request.form[i]
  890. elif i[:13] == 'belt1_from_hr':
  891. belt1_from_hr = request.form[i]
  892. elif i[:14] == 'belt1_from_min':
  893. belt1_from_min = request.form[i]
  894. belt1.start = belt1_from_hr + ":" + belt1_from_min
  895. elif i[:11] == 'belt1_to_hr':
  896. belt1_to_hr = request.form[i]
  897. elif i[:12] == 'belt1_to_min':
  898. belt1_to_min = request.form[i]
  899. belt1.end = belt1_to_hr + ":" + belt1_to_min
  900. belt1.datetime = current_time
  901. db.session.add(belt1)
  902. db.session.commit()
  903. # 消毒
  904. elif i[:9] == 'disinfect':
  905. if i[:18] == 'disinfect_duration':
  906. disinfect = Cargo1Disinfect()
  907. disinfect.duration = request.form[i]
  908. elif i[:17] == 'disinfect_from_hr':
  909. di_from_hr = request.form[i]
  910. elif i[:18] == 'disinfect_from_min':
  911. di_from_min = request.form[i]
  912. disinfect.start = di_from_hr + ":" + di_from_min
  913. elif i[:15] == 'disinfect_to_hr':
  914. di_to_hr = request.form[i]
  915. elif i[:16] == 'disinfect_to_min':
  916. di_to_min = request.form[i]
  917. disinfect.end = di_to_hr + ":" + di_to_min
  918. disinfect.datetime = current_time
  919. db.session.add(disinfect)
  920. db.session.commit()
  921. # 色選機
  922. elif i[:5] == 'color':
  923. if i[:14] == 'color_duration':
  924. color = ColorMachine()
  925. color.duration = request.form[i]
  926. elif i[:13] == 'color_from_hr':
  927. color_from_hr = request.form[i]
  928. elif i[:14] == 'color_from_min':
  929. color_from_min = request.form[i]
  930. color.start = color_from_hr + ":" + color_from_min
  931. elif i[:11] == 'color_to_hr':
  932. color_to_hr = request.form[i]
  933. elif i[:12] == 'color_to_min':
  934. color_to_min = request.form[i]
  935. color.end = color_to_hr + ":" + color_to_min
  936. color.datetime = current_time
  937. db.session.add(color)
  938. db.session.commit()
  939. # 輸送帶2
  940. elif i[:5] == 'belt2':
  941. if i[:14] == 'belt2_duration':
  942. belt2 = ConveyorBelt2()
  943. belt2.duration = request.form[i]
  944. elif i[:13] == 'belt2_from_hr':
  945. belt2_from_hr = request.form[i]
  946. elif i[:14] == 'belt2_from_min':
  947. belt2_from_min = request.form[i]
  948. belt2.start = belt2_from_hr + ":" + belt2_from_min
  949. elif i[:11] == 'belt2_to_hr':
  950. belt2_to_hr = request.form[i]
  951. elif i[:12] == 'belt2_to_min':
  952. belt2_to_min = request.form[i]
  953. belt2.end = belt2_to_hr + ":" + belt2_to_min
  954. belt2.datetime = current_time
  955. db.session.add(belt2)
  956. db.session.commit()
  957. # 去皮機
  958. elif i[:6] == 'peeled':
  959. if i[:15] == 'peeled_duration':
  960. peeling = PeelingMachine()
  961. peeling.duration = request.form[i]
  962. elif i[:14] == 'peeled_from_hr':
  963. peeled_from_hr = request.form[i]
  964. elif i[:15] == 'peeled_from_min':
  965. peeled_from_min = request.form[i]
  966. peeling.start = peeled_from_hr + ":" + peeled_from_min
  967. elif i[:12] == 'peeled_to_hr':
  968. peeled_to_hr = request.form[i]
  969. elif i[:13] == 'peeled_to_min':
  970. peeled_to_min = request.form[i]
  971. peeling.end = peeled_to_hr + ":" + peeled_to_min
  972. peeling.datetime = current_time
  973. db.session.add(peeling)
  974. db.session.commit()
  975. # 輸送帶3
  976. elif i[:5] == 'belt3':
  977. if i[:14] == 'belt3_duration':
  978. belt3 = ConveyorBelt3()
  979. belt3.duration = request.form[i]
  980. elif i[:13] == 'belt3_from_hr':
  981. belt3_from_hr = request.form[i]
  982. elif i[:14] == 'belt3_from_min':
  983. belt3_from_min = request.form[i]
  984. belt3.start = belt3_from_hr + ":" + belt3_from_min
  985. elif i[:11] == 'belt3_to_hr':
  986. belt3_to_hr = request.form[i]
  987. elif i[:12] == 'belt3_to_min':
  988. belt3_to_min = request.form[i]
  989. belt3.end = belt3_to_hr + ":" + belt3_to_min
  990. belt3.datetime = current_time
  991. db.session.add(belt3)
  992. db.session.commit()
  993. return render_template('cargo1.html', params=locals())
  994. # 貨櫃2的訪問路徑
  995. @main.route('/cargo2', methods=['GET', 'POST'])
  996. def cargo2_views():
  997. username = session['uname']
  998. if request.method == 'GET':
  999. return render_template('cargo2.html', params=locals())
  1000. else:
  1001. pass
  1002. # 貨櫃2排程的發酵槽訪問路徑
  1003. @main.route('/cargo2_schedule_tanks', methods=['GET', 'POST'])
  1004. def cargo2_schedule_tanks_views():
  1005. username = session['uname']
  1006. if request.method == 'GET':
  1007. return render_template('cargo2_schedule_tanks.html', params=locals())
  1008. else:
  1009. pass
  1010. # 貨櫃2排程發酵槽的清單訪問路徑
  1011. @main.route('/cargo2_schedule/<tid>', methods=['GET', 'POST'])
  1012. def cargo2_schedule_views(tid):
  1013. username = session['uname']
  1014. if request.method == 'GET':
  1015. # 將已儲存的排程資料傳給前端
  1016. # 打菌
  1017. try:
  1018. bacteria = Bacteria.query.filter_by(tank_num=int(
  1019. tid)).order_by(text('datetime desc')).first()
  1020. datetime = bacteria.datetime
  1021. bacterias = Bacteria.query.filter_by(datetime=datetime).all()
  1022. except Exception as e:
  1023. pass
  1024. # 消毒
  1025. try:
  1026. disinfect = Cargo2Disinfect.query.filter_by(
  1027. tank_num=int(tid)).order_by(text('datetime desc')).first()
  1028. datetime = disinfect.datetime
  1029. disinfects = Cargo2Disinfect.query.filter_by(
  1030. datetime=datetime).all()
  1031. except Exception as e:
  1032. pass
  1033. # 加熱
  1034. try:
  1035. heating = Heating.query.filter_by(tank_num=int(
  1036. tid)).order_by(text('datetime desc')).first()
  1037. datetime = heating.datetime
  1038. heatings = Heating.query.filter_by(datetime=datetime).all()
  1039. except Exception as e:
  1040. pass
  1041. # 攪拌
  1042. try:
  1043. stir = Stir.query.filter_by(tank_num=int(tid)).order_by(
  1044. text('datetime desc')).first()
  1045. datetime = stir.datetime
  1046. stirs = Stir.query.filter_by(datetime=datetime).all()
  1047. except Exception as e:
  1048. pass
  1049. # 注水
  1050. try:
  1051. water = WaterInjection.query.filter_by(
  1052. tank_num=int(tid)).order_by(text('datetime desc')).first()
  1053. datetime = water.datetime
  1054. waters = WaterInjection.query.filter_by(datetime=datetime).all()
  1055. except Exception as e:
  1056. pass
  1057. # 開上閥
  1058. try:
  1059. top = TopValve.query.filter_by(tank_num=int(
  1060. tid)).order_by(text('datetime desc')).first()
  1061. datetime = top.datetime
  1062. tops = TopValve.query.filter_by(datetime=datetime).all()
  1063. except Exception as e:
  1064. pass
  1065. # 開下閥
  1066. try:
  1067. bottom = BottomValve.query.filter_by(tank_num=int(
  1068. tid)).order_by(text('datetime desc')).first()
  1069. datetime = bottom.datetime
  1070. bottoms = BottomValve.query.filter_by(datetime=datetime).all()
  1071. except Exception as e:
  1072. pass
  1073. # 溫度
  1074. try:
  1075. tem = Temperature.query.filter_by(tank_num=int(
  1076. tid)).order_by(text('datetime desc')).first()
  1077. datetime = tem.datetime
  1078. tems = Temperature.query.filter_by(datetime=datetime).all()
  1079. except Exception as e:
  1080. pass
  1081. return render_template('cargo2_schedule.html', params=locals())
  1082. else:
  1083. current_time = dt.now()
  1084. # 循環從前端提交過來的資料
  1085. for i in request.form:
  1086. # 打菌
  1087. if i[:8] == 'bacteria':
  1088. if i[:17] == 'bacteria_duration':
  1089. bacteria = Bacteria()
  1090. bacteria.duration = request.form[i]
  1091. elif i[:16] == 'bacteria_from_hr':
  1092. bac_from_hr = request.form[i]
  1093. elif i[:17] == 'bacteria_from_min':
  1094. bac_from_min = request.form[i]
  1095. bacteria.start = bac_from_hr + ":" + bac_from_min
  1096. elif i[:14] == 'bacteria_to_hr':
  1097. bac_to_hr = request.form[i]
  1098. elif i[:15] == 'bacteria_to_min':
  1099. bac_to_min = request.form[i]
  1100. bacteria.end = bac_to_hr + ":" + bac_to_min
  1101. bacteria.datetime = current_time
  1102. bacteria.tank_num = int(tid)
  1103. db.session.add(bacteria)
  1104. db.session.commit()
  1105. # 消毒
  1106. elif i[:9] == 'disinfect':
  1107. if i[:18] == 'disinfect_duration':
  1108. disinfect = Cargo2Disinfect()
  1109. disinfect.duration = request.form[i]
  1110. elif i[:17] == 'disinfect_from_hr':
  1111. di_from_hr = request.form[i]
  1112. elif i[:18] == 'disinfect_from_min':
  1113. di_from_min = request.form[i]
  1114. disinfect.start = di_from_hr + ":" + di_from_min
  1115. elif i[:15] == 'disinfect_to_hr':
  1116. di_to_hr = request.form[i]
  1117. elif i[:16] == 'disinfect_to_min':
  1118. di_to_min = request.form[i]
  1119. disinfect.end = di_to_hr + ":" + di_to_min
  1120. disinfect.datetime = current_time
  1121. disinfect.tank_num = int(tid)
  1122. db.session.add(disinfect)
  1123. db.session.commit()
  1124. # 加熱
  1125. elif i[:7] == 'heating':
  1126. if i[:16] == 'heating_duration':
  1127. heating = Heating()
  1128. heating.duration = request.form[i]
  1129. elif i[:15] == 'heating_from_hr':
  1130. heat_from_hr = request.form[i]
  1131. elif i[:16] == 'heating_from_min':
  1132. heat_from_min = request.form[i]
  1133. heating.start = heat_from_hr + ":" + heat_from_min
  1134. elif i[:13] == 'heating_to_hr':
  1135. heat_to_hr = request.form[i]
  1136. elif i[:14] == 'heating_to_min':
  1137. heat_to_min = request.form[i]
  1138. heating.end = heat_to_hr + ":" + heat_to_min
  1139. heating.datetime = current_time
  1140. heating.tank_num = int(tid)
  1141. db.session.add(heating)
  1142. db.session.commit()
  1143. # 攪拌
  1144. elif i[:4] == 'stir':
  1145. if i[:13] == 'stir_duration':
  1146. stir = Stir()
  1147. stir.duration = request.form[i]
  1148. elif i[:12] == 'stir_from_hr':
  1149. stir_from_hr = request.form[i]
  1150. elif i[:13] == 'stir_from_min':
  1151. stir_from_min = request.form[i]
  1152. stir.start = stir_from_hr + ":" + stir_from_min
  1153. elif i[:10] == 'stir_to_hr':
  1154. stir_to_hr = request.form[i]
  1155. elif i[:11] == 'stir_to_min':
  1156. stir_to_min = request.form[i]
  1157. stir.end = stir_to_hr + ":" + stir_to_min
  1158. stir.datetime = current_time
  1159. stir.tank_num = int(tid)
  1160. db.session.add(stir)
  1161. db.session.commit()
  1162. # 注水
  1163. elif i[:5] == 'water':
  1164. if i[:14] == 'water_duration':
  1165. water = WaterInjection()
  1166. water.duration = request.form[i]
  1167. elif i[:13] == 'water_from_hr':
  1168. water_from_hr = request.form[i]
  1169. elif i[:14] == 'water_from_min':
  1170. water_from_min = request.form[i]
  1171. water.start = water_from_hr + ":" + water_from_min
  1172. elif i[:11] == 'water_to_hr':
  1173. water_to_hr = request.form[i]
  1174. elif i[:12] == 'water_to_min':
  1175. water_to_min = request.form[i]
  1176. water.end = water_to_hr + ":" + water_to_min
  1177. water.datetime = current_time
  1178. water.tank_num = int(tid)
  1179. db.session.add(water)
  1180. db.session.commit()
  1181. # 開上閥
  1182. elif i[:9] == 'highValve':
  1183. if i[:18] == 'highValve_duration':
  1184. top = TopValve()
  1185. top.duration = request.form[i]
  1186. elif i[:17] == 'highValve_from_hr':
  1187. h_valve_from_hr = request.form[i]
  1188. elif i[:18] == 'highValve_from_min':
  1189. h_valve_from_min = request.form[i]
  1190. top.start = h_valve_from_hr + ":" + h_valve_from_min
  1191. elif i[:15] == 'highValve_to_hr':
  1192. h_valve_to_hr = request.form[i]
  1193. elif i[:16] == 'highValve_to_min':
  1194. h_valve_to_min = request.form[i]
  1195. top.end = h_valve_to_hr + ":" + h_valve_to_min
  1196. top.datetime = current_time
  1197. top.tank_num = int(tid)
  1198. db.session.add(top)
  1199. db.session.commit()
  1200. # 開下閥
  1201. elif i[:8] == 'lowValve':
  1202. if i[:17] == 'lowValve_duration':
  1203. bottom = BottomValve()
  1204. bottom.duration = request.form[i]
  1205. elif i[:16] == 'lowValve_from_hr':
  1206. l_valve_from_hr = request.form[i]
  1207. elif i[:17] == 'lowValve_from_min':
  1208. l_valve_from_min = request.form[i]
  1209. bottom.start = l_valve_from_hr + ":" + l_valve_from_min
  1210. elif i[:14] == 'lowValve_to_hr':
  1211. l_valve_to_hr = request.form[i]
  1212. elif i[:15] == 'lowValve_to_min':
  1213. l_valve_to_min = request.form[i]
  1214. bottom.end = l_valve_to_hr + ":" + l_valve_to_min
  1215. bottom.datetime = current_time
  1216. bottom.tank_num = int(tid)
  1217. db.session.add(bottom)
  1218. db.session.commit()
  1219. # 溫度
  1220. elif i[:3] == 'tem':
  1221. if i[:12] == 'tem_duration':
  1222. tem = Temperature()
  1223. tem.duration = request.form[i]
  1224. elif i[:11] == 'tem_from_hr':
  1225. tem_from_hr = request.form[i]
  1226. elif i[:12] == 'tem_from_min':
  1227. tem_from_min = request.form[i]
  1228. tem.start = tem_from_hr + ":" + tem_from_min
  1229. elif i[:9] == 'tem_to_hr':
  1230. tem_to_hr = request.form[i]
  1231. elif i[:10] == 'tem_to_min':
  1232. tem_to_min = request.form[i]
  1233. tem.end = tem_to_hr + ":" + tem_to_min
  1234. tem.datetime = current_time
  1235. tem.tank_num = int(tid)
  1236. db.session.add(tem)
  1237. db.session.commit()
  1238. return render_template('cargo2.html', params=locals())
  1239. # 貨櫃2感測器的發酵槽訪問路徑
  1240. @main.route('/cargo2_sensor_tanks', methods=['GET', 'POST'])
  1241. def cargo2_sensor_tanks_views():
  1242. username = session['uname']
  1243. if request.method == 'GET':
  1244. return render_template('cargo2_sensor_tanks.html', params=locals())
  1245. else:
  1246. pass
  1247. # 貨櫃2感測器發酵槽的清單訪問路徑
  1248. @main.route('/cargo2_sensor/<tid>', methods=['GET', 'POST'])
  1249. def s_tank_views(tid):
  1250. # 判斷用戶是否已關閉瀏覽器或登出後,在訪問這個route,如果沒有session就回登入頁
  1251. try:
  1252. username = session['uname']
  1253. except KeyError:
  1254. return redirect('/')
  1255. if request.method == 'GET':
  1256. # Rita 網頁端 params.tank_tem.tem
  1257. # Coffee/CoffeeProject/app/templates/cargo2_sensor.html
  1258. tank_tem = TankTemSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
  1259. tank_ph = TankPHSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
  1260. tank_ec = TankECSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
  1261. tank_sonic = TankSonicSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
  1262. return render_template('cargo2_sensor.html', params=locals())
  1263. else:
  1264. pass
  1265. # 貨櫃2感測器發酵槽歷史數據的訪問路徑
  1266. @main.route('/history_data', methods=['GET', 'POST'])
  1267. def history_data_views():
  1268. if request.method == 'GET':
  1269. # json
  1270. # tid:tid_D1
  1271. # sensor_name:soil_Temp
  1272. # avg:1
  1273. # max:1
  1274. # min:1
  1275. # time-interval:month
  1276. # date-start:2021-07-01
  1277. # date-end:2021-07-28
  1278. info = request.args.to_dict()
  1279. evt = info['evt']
  1280. avg = int(info['avg'])
  1281. max = int(info['max'])
  1282. min = int(info['min'])
  1283. time_interval = info['time-interval']
  1284. print(info)
  1285. # Rita {'evt': '1-溫濕度', 'avg': '1', 'max': '0', 'min': '0', 'time-interval': 'month',
  1286. # 'date-start': '2021-05-04', 'date-end': '2021-05-18'} {'all': [], 'avg': []}
  1287. # print(info)
  1288. # {'evt': '1-溫濕度', 'avg': '1', 'max': '0', 'min': '0', 'time-interval': 'hour', 'date-start': '2021-01-01', 'date-end': '2021-07-27'}
  1289. # print(D)
  1290. # {'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']],
  1291. # 'avg': [['2021-02-19 16:00:00', '24.5'], ['2021-02-19 18:00:00', '25.3']]}
  1292. # 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 -
  1293. date_start = info['date-start']
  1294. date_end_list = info['date-end'].split('-') # 先把 'date-end' 的 '2021-05-18' 拆成 ['2021', '05', '18']
  1295. date_end_list[2] = str(int(date_end_list[2]) + 1) # 18 + 1 = 19 再轉成 str → '19'
  1296. date_end = '-'.join(date_end_list) # '2021-05-19'
  1297. tank_num = evt.split('-')[0] # 1
  1298. sensor = evt.split('-')[1] # 溫濕度
  1299. L = []
  1300. D = {}
  1301. maxData = []
  1302. minData = []
  1303. avgData = []
  1304. def sensorData(data_name): # data_name = "tem"
  1305. def dataResample(time_interval, how, data_name): # dataResample('month', how???, "tem") # 下方 "hour"
  1306. interval = 0
  1307. # 設置resample的第一個參數,要按照逐月、逐日或逐時
  1308. if time_interval == 'month':
  1309. interval = "M" # interval = "M"
  1310. elif time_interval == 'day':
  1311. interval = "D"
  1312. elif time_interval == 'hour':
  1313. interval = "H"
  1314. if how == "max":
  1315. # data = df.resample(interval, how={data_name:how})
  1316. # 最新版的pandas
  1317. data = df.resample(interval).max() # 取樣頻率 'H'
  1318. # 刪除有 NaN 的列, any 任何一欄位為空則刪 (all 全部欄位為空值才刪)
  1319. data = data.dropna(axis=0, how='any')
  1320. if time_interval == ('hour' or 'day'):
  1321. data.index = pd.to_datetime(
  1322. data.index, format='%Y-%b-%d_%H:%M:%S') # 将数据类型转换为日期类型
  1323. for a in range(0, len(data.index)):
  1324. l = []
  1325. # 如果是逐時,才顯示小時分秒
  1326. if time_interval == 'hour':
  1327. l.append(str(data.index[a]))
  1328. else:
  1329. l.append(str(data.index[a]).split(' ')[0])
  1330. l.append(str(data[data_name][a]))
  1331. maxData.append(l)
  1332. D['max'] = maxData
  1333. elif how == "mean":
  1334. # data = df.resample(interval, how={data_name:how})
  1335. # 最新版的pandas
  1336. data = df.resample(interval).mean()
  1337. # 刪除具有NaN的值
  1338. data = data.dropna(axis=0, how='any')
  1339. # 將平均數取自小數1位
  1340. data = data.round({data_name: 1})
  1341. for a in range(0, len(data.index)):
  1342. l = []
  1343. # 如果是逐時,才顯示小時分秒
  1344. if time_interval == 'hour':
  1345. l.append(str(data.index[a]))
  1346. else:
  1347. l.append(str(data.index[a]).split(' ')[0])
  1348. l.append(str(data[data_name][a]))
  1349. avgData.append(l)
  1350. D['avg'] = avgData
  1351. elif how == "min":
  1352. # data = df.resample(interval, how={data_name:how})
  1353. # 最新版的pandas
  1354. data = df.resample(interval).min()
  1355. # 刪除具有NaN的值
  1356. data = data.dropna(axis=0, how='any')
  1357. for a in range(0, len(data.index)):
  1358. # print(data.index[a])
  1359. l = []
  1360. # 如果是逐時,才顯示小時分秒
  1361. if time_interval == 'hour':
  1362. l.append(str(data.index[a]))
  1363. else:
  1364. l.append(str(data.index[a]).split(' ')[0])
  1365. l.append(str(data[data_name][a]))
  1366. minData.append(l)
  1367. D['min'] = minData
  1368. df = pd.DataFrame(L, columns=["datetime", data_name]) # 指定欄標籤名稱 為 ["datetime", "tem"]
  1369. df['datetime'] = pd.to_datetime(
  1370. df['datetime'], format='%Y-%b-%d_%H:%M:%S') # 将数据类型转换为日期类型
  1371. # print(df['datetime']) # 0 2021-02-19 16:46:10
  1372. # 1 2021-02-19 16:46:20
  1373. # 2 2021-02-19 16:46:30
  1374. # 3 2021-02-19 16:46:41
  1375. df[data_name] = df[data_name].astype(float)
  1376. df = df.set_index('datetime') # 将datetime设置为index
  1377. # print(df) # datetime tem
  1378. # 2021-02-19 16:46:10 24.4
  1379. # 2021-02-19 16:46:20 24.4
  1380. if time_interval == 'month':
  1381. if max:
  1382. dataResample(time_interval, "max", data_name)
  1383. if avg:
  1384. dataResample(time_interval, "mean", data_name)
  1385. if min:
  1386. dataResample(time_interval, "min", data_name)
  1387. elif time_interval == 'day':
  1388. if max:
  1389. dataResample(time_interval, "max", data_name)
  1390. if avg:
  1391. dataResample(time_interval, "mean", data_name)
  1392. if min:
  1393. dataResample(time_interval, "min", data_name)
  1394. elif time_interval == 'hour':
  1395. if max:
  1396. dataResample(time_interval, "max", data_name)
  1397. if avg:
  1398. dataResample(time_interval, "mean", data_name)
  1399. if min:
  1400. dataResample(time_interval, "min", data_name)
  1401. if sensor == '溫濕度':
  1402. # tank_tem = TankTemSensor.query.filter_by(tank_num=int(tank_num)).order_by(text('datetime desc')).all()
  1403. # [7/27 Benson] tank_tem = TankTemSensor.query.filter_by(tank_num=int(tank_num)).filter(TankTemSensor.datetime.between(date_start, date_end)).all()
  1404. tank_tem = dry_tank_SHT11.query.filter(dry_tank_SHT11.datetime.between(date_start, date_end)).all()
  1405. # .filter_by(tank_num="D"+tank_num)
  1406. for tem in tank_tem:
  1407. l = [] # l = []
  1408. time = dt.strftime(tem.datetime, '%Y-%b-%d_%H:%M:%S') # time = '2021-Feb-19_16:46:10' 轉換時間格式
  1409. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  1410. l.append(time) # l = ['2021-Feb-19_16:46:10']
  1411. #l.append(tem.tem) # l = ['2021-Feb-19_16:46:10', '24.4']
  1412. l.append(tem.SHT11_Temp)
  1413. L.append(l) # L = [['2021-Feb-19_16:46:10', '24.4']]
  1414. # print(L)
  1415. D['all'] = L # D = {'all': [['2021-Feb-19_16:46:10', '24.4']]} # all 所有符合數據
  1416. sensorData("tem")
  1417. elif sensor == '酸鹼值':
  1418. tank_ph = TankPHSensor.query.filter_by(tank_num=int(tank_num)).filter(
  1419. TankPHSensor.datetime.between(date_start, date_end)).all()
  1420. for ph in tank_ph:
  1421. l = []
  1422. time = dt.strftime(ph.datetime, '%Y-%b-%d_%H:%M:%S')
  1423. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  1424. l.append(time)
  1425. l.append(ph.ph)
  1426. L.append(l)
  1427. # print(L)
  1428. D['all'] = L
  1429. sensorData("ph")
  1430. elif sensor == 'EC值':
  1431. tank_ec = TankECSensor.query.filter_by(tank_num=int(tank_num)).filter(
  1432. TankECSensor.datetime.between(date_start, date_end)).all()
  1433. for ec in tank_ec:
  1434. l = []
  1435. time = dt.strftime(ec.datetime, '%Y-%b-%d_%H:%M:%S')
  1436. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  1437. l.append(time)
  1438. l.append(ec.ec)
  1439. L.append(l)
  1440. # print(L)
  1441. D['all'] = L
  1442. sensorData("ec")
  1443. elif sensor == '超音波':
  1444. tank_sonic = TankSonicSensor.query.filter_by(tank_num=int(tank_num)).filter(
  1445. TankSonicSensor.datetime.between(date_start, date_end)).all()
  1446. for sonic in tank_sonic:
  1447. l = []
  1448. time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
  1449. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  1450. l.append(time)
  1451. l.append(sonic.sonic)
  1452. L.append(l)
  1453. # print(L)
  1454. D['all'] = L
  1455. sensorData("sonic")
  1456. print(D)
  1457. return json.dumps(D)
  1458. else:
  1459. pass
  1460. # 貨櫃2制動器的發酵槽訪問路徑
  1461. @main.route('/cargo2_actuator_tanks', methods=['GET', 'POST'])
  1462. def cargo2_actuator_tanks_views():
  1463. username = session['uname']
  1464. if request.method == 'GET':
  1465. return render_template('cargo2_actuator_tanks.html', params=locals())
  1466. else:
  1467. pass
  1468. # 貨櫃2制動器發酵槽的清單訪問路徑
  1469. @main.route('/cargo2_actuator/<tid>', methods=['GET', 'POST'])
  1470. def cargo2_actuator_views(tid):
  1471. username = session['uname']
  1472. if request.method == 'GET':
  1473. return render_template('cargo2_actuator.html', params=locals())
  1474. else:
  1475. pass
  1476. # 貨櫃3的訪問路徑
  1477. @main.route('/cargo3', methods=['GET', 'POST'])
  1478. def cargo3_views():
  1479. username = session['uname']
  1480. if request.method == 'GET':
  1481. return render_template('cargo3.html', params=locals())
  1482. else:
  1483. pass
  1484. # 貨櫃3排程的訪問路徑
  1485. @main.route('/cargo3_schedule', methods=['GET', 'POST'])
  1486. def cargo3_schedule_views():
  1487. username = session['uname']
  1488. if request.method == 'GET':
  1489. # 將已儲存的排程資料傳給前端
  1490. # 提升機
  1491. try:
  1492. hoist = Hoist.query.order_by(text('datetime desc')).first()
  1493. datetime = hoist.datetime
  1494. hoists = Hoist.query.filter_by(datetime=datetime).all()
  1495. except Exception as e:
  1496. pass
  1497. # 烘乾機
  1498. try:
  1499. dryer = Dryer.query.order_by(text('datetime desc')).first()
  1500. datetime = dryer.datetime
  1501. dryers = Dryer.query.filter_by(datetime=datetime).all()
  1502. except Exception as e:
  1503. pass
  1504. return render_template('cargo3_schedule.html', params=locals())
  1505. else:
  1506. # Rita: "POST /b_cargo3 HTTP/1.1" 404 -
  1507. current_time = dt.now()
  1508. # 循環從前端提交過來的資料
  1509. for i in request.form:
  1510. print('Rita test i :', i)
  1511. # 堤升機
  1512. if i[:5] == 'hoist':
  1513. if i[:14] == 'hoist_duration':
  1514. hoist = Hoist()
  1515. hoist.duration = request.form[i]
  1516. elif i[:13] == 'hoist_from_hr':
  1517. ho_from_hr = request.form[i]
  1518. elif i[:14] == 'hoist_from_min':
  1519. ho_from_min = request.form[i]
  1520. hoist.start = ho_from_hr + ":" + ho_from_min
  1521. elif i[:11] == 'hoist_to_hr':
  1522. ho_to_hr = request.form[i]
  1523. elif i[:12] == 'hoist_to_min':
  1524. ho_to_min = request.form[i]
  1525. hoist.end = ho_to_hr + ":" + ho_to_min
  1526. hoist.datetime = current_time
  1527. db.session.add(hoist)
  1528. db.session.commit()
  1529. # 烘乾機
  1530. elif i[:5] == 'dryer':
  1531. if i[:14] == 'dryer_duration':
  1532. dryer = Dryer()
  1533. dryer.duration = request.form[i]
  1534. elif i[:13] == 'dryer_from_hr':
  1535. dry_from_hr = request.form[i]
  1536. elif i[:14] == 'dryer_from_min':
  1537. dry_from_min = request.form[i]
  1538. dryer.start = dry_from_hr + ":" + dry_from_min
  1539. elif i[:11] == 'dryer_to_hr':
  1540. dry_to_hr = request.form[i]
  1541. elif i[:12] == 'dryer_to_min':
  1542. dry_to_min = request.form[i]
  1543. dryer.end = dry_to_hr + ":" + dry_to_min
  1544. dryer.datetime = current_time
  1545. db.session.add(dryer)
  1546. db.session.commit()
  1547. return render_template('cargo3.html', params=locals())
  1548. # 影像串流的訪問路徑
  1549. @main.route('/video', methods=['GET', 'POST'])
  1550. def video_views():
  1551. username = session['uname']
  1552. if request.method == 'GET':
  1553. return render_template('video.html', params=locals())
  1554. else:
  1555. pass
  1556. # 影像的訪問路徑
  1557. @main.route('/learn', methods=['GET', 'POST'])
  1558. def learn_views():
  1559. username = session['uname']
  1560. if request.method == 'GET':
  1561. return render_template('learn.html', params=locals())
  1562. else:
  1563. pass
  1564. # 獲取relay狀態路徑
  1565. @main.route('/relay', methods=['GET', 'POST'])
  1566. def relay_views():
  1567. if request.method == 'GET':
  1568. relay = Relay.query.order_by(text('datetime desc')).first()
  1569. relay_status = relay.status
  1570. return jsonify({"relay": relay_status})
  1571. else:
  1572. pass
  1573. # 獲取脫皮機狀態路徑
  1574. @main.route('/peeling', methods=['GET', 'POST'])
  1575. def peeling_views():
  1576. if request.method == 'GET':
  1577. peeling = PeelingMachineRPM.query.order_by(
  1578. text('datetime desc')).first()
  1579. peeling_rpm = peeling.rpm
  1580. return jsonify({"peeling": peeling_rpm})
  1581. else:
  1582. pass
  1583. # 退出的訪問路徑
  1584. @main.route('/logout')
  1585. def logout_views():
  1586. if 'id' in session and 'uname' in session:
  1587. del session['id']
  1588. del session['uname']
  1589. return redirect('/')
  1590. @main.route("/udp_client", methods=['POST', 'GET'])
  1591. def udp_views():
  1592. # sl(0.5)
  1593. global c_sock
  1594. if request.method == 'GET':
  1595. # def close():
  1596. # global c_sock
  1597. # sl(600)
  1598. # c_sock.close()
  1599. # c_sock = 0
  1600. # print("c_sock is closing")
  1601. max_length = 65000
  1602. # max_length = 95000
  1603. # lab1的IP
  1604. host = "192.168.50.65"
  1605. # lab2的IP
  1606. # host = "192.168.51.160"
  1607. port = 8000
  1608. c_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  1609. # t = threading.Thread(target=close)
  1610. # t.daemon = True
  1611. # t.start()
  1612. print("test")
  1613. # dict = request.args.to_dict()
  1614. # nr = int(dict['nr'])
  1615. # if nr == 1:
  1616. # camara = 0
  1617. # elif nr == 2:
  1618. # camara = 'rtsp://admin:admin@192.168.50.182/av2_0'
  1619. # elif nr == 3:
  1620. # camara = 'rtsp://admin:abcd1234@192.168.51.101/av2_0'
  1621. # 地下室小兵
  1622. # cap = cv2.VideoCapture('rtsp://admin:abcd1234@192.168.51.48/av2_0')
  1623. # 主機攝像頭
  1624. # cap = cv2.VideoCapture(0)
  1625. # 外面小兵
  1626. # cap = cv2.VideoCapture('rtsp://admin:admin@192.168.50.182/av2_0')
  1627. cap = cv2.VideoCapture('rtsp://192.168.50.182/av0_0')
  1628. # cap = cv2.VideoCapture(0)
  1629. # cap = cv2.VideoCapture(camara)
  1630. ret, frame = cap.read()
  1631. while ret:
  1632. # compress frame
  1633. frame = cv2.resize(frame, (550, 400), interpolation=cv2.INTER_AREA)
  1634. retval, buffer = cv2.imencode(".jpg", frame)
  1635. if retval:
  1636. # convert to byte array
  1637. buffer = buffer.tobytes()
  1638. # get size of the frame
  1639. buffer_size = len(buffer)
  1640. num_of_packs = 1
  1641. if buffer_size > max_length:
  1642. num_of_packs = math.ceil(buffer_size / max_length)
  1643. frame_info = {"packs": num_of_packs}
  1644. # send the number of packs to be expected
  1645. # print("Number of packs:", num_of_packs)
  1646. c_sock.sendto(pickle.dumps(frame_info), (host, port))
  1647. left = 0
  1648. right = max_length
  1649. for i in range(num_of_packs):
  1650. # print("left:", left)
  1651. # print("right:", right)
  1652. # truncate data to send
  1653. data = buffer[left:right]
  1654. left = right
  1655. right += max_length
  1656. # send the frames accordingly
  1657. c_sock.sendto(data, (host, port))
  1658. ret, frame = cap.read()
  1659. print("done")
  1660. return "done"
  1661. else:
  1662. c_sock.shutdown(2)
  1663. c_sock.close()
  1664. c_sock = 0
  1665. print("c_sock is closing")
  1666. # 影像串流的路徑
  1667. @main.route("/video_feed", methods=['POST', 'GET'])
  1668. def video_feed_views():
  1669. print("test2")
  1670. global s_sock
  1671. if request.method == 'GET':
  1672. # 於10分鐘之後,自動關閉socket server
  1673. # if s_sock == 0:
  1674. # def socket_server_views():
  1675. # global s_sock
  1676. # print("test")
  1677. # print(s_sock)
  1678. # sl(600)
  1679. # if s_sock != 0:
  1680. # s_sock.close()
  1681. # s_sock = 0
  1682. # print('s_sock is closed')
  1683. #
  1684. # pool.submit(socket_server_views)
  1685. host = "192.168.50.65"
  1686. port = 8000
  1687. max_length = 65540
  1688. # max_length = 95540
  1689. s_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  1690. s_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1691. s_sock.bind((host, port))
  1692. frame_info = None
  1693. buffer = None
  1694. frame = None
  1695. encodedImage = None
  1696. print("-> waiting for connection")
  1697. # 影像生成器函數,將影像以jpg格式傳給前端
  1698. def generate():
  1699. while True:
  1700. with lock:
  1701. global s_sock, frame_info, buffer, frame, encodedImage
  1702. if s_sock == 0:
  1703. break
  1704. data, address = s_sock.recvfrom(max_length)
  1705. if len(data) < 100:
  1706. frame_info = pickle.loads(data)
  1707. if frame_info:
  1708. nums_of_packs = frame_info["packs"]
  1709. for i in range(nums_of_packs):
  1710. if s_sock == 0:
  1711. break
  1712. data, address = s_sock.recvfrom(max_length)
  1713. if i == 0:
  1714. buffer = data
  1715. else:
  1716. buffer += data
  1717. frame = np.frombuffer(buffer, dtype=np.uint8)
  1718. frame = frame.reshape(frame.shape[0], 1)
  1719. frame = cv2.imdecode(frame, cv2.IMREAD_UNCHANGED)
  1720. # print(frame)
  1721. # 如果frame為None就跳過
  1722. if frame is None:
  1723. continue
  1724. frame = cv2.resize(
  1725. frame, (640, 360), interpolation=cv2.INTER_AREA)
  1726. # encode the frame in JPEG format
  1727. (flag, encodedImage) = cv2.imencode(".jpg", frame)
  1728. # ensure the frame was successfully encoded
  1729. if not flag:
  1730. continue
  1731. # yield the output frame in the byte format
  1732. yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' +
  1733. bytearray(encodedImage) + b'\r\n')
  1734. # return the response generated along with the specific media
  1735. # type (mime type)
  1736. return Response(generate(), mimetype="multipart/x-mixed-replace; boundary=frame")
  1737. else:
  1738. if s_sock != 0:
  1739. s_sock.close()
  1740. s_sock = 0
  1741. print('s_sock is closed')
  1742. return "s_sock is closed"
  1743. print("test")
  1744. return "s_sock is closed"
  1745. D = {"input_vacuum_status": 0,
  1746. "tank_vacuum_status": 0,
  1747. "tank_threewayvalve_status": 0,
  1748. "tank_diskvalve_status": 0,
  1749. "tank_solenoid_disinfect_status": 0,
  1750. "tank_solenoid_water_status": 0,
  1751. "tank_motor_status": 'none',
  1752. "tank_blower_status": 0,
  1753. "tank_heater1_status": 0,
  1754. "tank_heater2_status": 0,
  1755. "temp1_enable": 0,
  1756. "temp1": 0,
  1757. "output_vacuum_status": 0,
  1758. "tank_threewayvalve_input_status":0,
  1759. "tank_solenoid_water_total_status": 0,
  1760. "tank_solenoid_disinfect_status": 0,
  1761. "outer_solenoid_water_status": 0,
  1762. "tank_solenoid_water_in_status":0,
  1763. "tank_pump_sensor_status": 0,
  1764. "tank_threewayvalve_bean_status":0,
  1765. "outer_threewayvalve_float_status":0,
  1766. "tank_temp_enable_status":0,
  1767. "tank_temp_status": 'none',
  1768. "tank_pump_waterFloat_status": 0,
  1769. "tank_pump_waterL2_status": 0,
  1770. "tank_pump_waterL4_status": 0,
  1771. "tank_solenoid_waterL3_status": 0,
  1772. "tank_solenoid_waterL5_status": 0,
  1773. "tank_stepping_motor_status": 'none',
  1774. }
  1775. pub_topic = 'AISKY/Coffee/MK-G/b8:27:eb:b4:59:3e'
  1776. # sub_topic = 'AISKY/Coffee/MK-G/b8:27:eb:b4:59:3e/Log'
  1777. # mqttObj = MQTT('aisky-client', 'aiskyc', '60.250.156.234', 1883, 60, sub_topic)
  1778. mqttObj = MQTT()
  1779. # mqtt發布
  1780. # @main.route('/mqtt/<tid>', methods=['POST'])
  1781. @main.route('/mqtt/<tid>', methods=['POST'])
  1782. def mqtt_views(tid):
  1783. import json
  1784. dict = request.form.to_dict()
  1785. json = json.dumps(dict)
  1786. # print('dict:', dict) # dict: {'tank-number': '1', 'command': 'tank_vacuum_status', 'value': 'on'}
  1787. # print('json:', json) # json: {"tank-number": "1", tank_vacuum_status", "value": "on"}
  1788. topic = 'AISKY/Coffee/MK-G/b8:27:eb:b4:59:3e'
  1789. # res = mqttObj.mqttPublish(pub_topic, json)
  1790. # print(res)
  1791. # sl(2)
  1792. # print(mqttObj.res)
  1793. #
  1794. # print('test')
  1795. mqtt.publish(topic, json)
  1796. # 入料儲豆槽真空吸料機(ON吸料/OFF排氣)
  1797. if dict['command'] == 'input_vacuum_status':
  1798. time.sleep(1)
  1799. # D[input_vacuum_status]: 0
  1800. print('D[input_vacuum_status]:', D['input_vacuum_status'])
  1801. if D['input_vacuum_status'] == 'on':
  1802. return 'on'
  1803. elif D['input_vacuum_status'] == 'off':
  1804. return 'off'
  1805. else:
  1806. return "input_vacuum_status signal was not received"
  1807. # 真空吸料機
  1808. elif dict['command'] == 'tank_vacuum_status':
  1809. time.sleep(1)
  1810. if D['tank_vacuum_status'] == 'on':
  1811. return 'on'
  1812. elif D['tank_vacuum_status'] == 'off':
  1813. return 'off'
  1814. else:
  1815. return "tank_vacuum_status signal was not received"
  1816. # 三通閥(ON吸料/OFF排氣)
  1817. elif dict['command'] == 'tank_threewayvalve_status':
  1818. time.sleep(1)
  1819. if D['tank_threewayvalve_status'] == 'on':
  1820. return 'on'
  1821. elif D['tank_threewayvalve_status'] == 'off':
  1822. return 'off'
  1823. else:
  1824. return "tank_threewayvalve_status signal was not received"
  1825. # 蝴蝶閥(ON開/OFF關)
  1826. elif dict['command'] == 'tank_diskvalve_status':
  1827. time.sleep(1)
  1828. print("D['tank_diskvalve_status']", D['tank_diskvalve_status'])
  1829. if D['tank_diskvalve_status'] == 'on':
  1830. return 'on'
  1831. elif D['tank_diskvalve_status'] == 'off':
  1832. return 'off'
  1833. else:
  1834. return "tank_diskvalve_status signal was not received"
  1835. # 電磁閥(ON噴灑消毒/OFF關)
  1836. elif dict['command'] == 'tank_solenoid_disinfect_status':
  1837. time.sleep(1)
  1838. if D['tank_solenoid_disinfect_status'] == 'on':
  1839. return 'on'
  1840. elif D['tank_solenoid_disinfect_status'] == 'off':
  1841. return 'off'
  1842. else:
  1843. return "tank_solenoid_disinfect_status signal was not received"
  1844. # 電磁閥(ON排水/OFF關)
  1845. elif dict['command'] == 'tank_solenoid_water_status':
  1846. time.sleep(1)
  1847. if D['tank_solenoid_water_status'] == 'on':
  1848. return 'on'
  1849. elif D['tank_solenoid_water_status'] == 'off':
  1850. return 'off'
  1851. else:
  1852. return "tank_solenoid_water_status signal was not received"
  1853. # 馬達(單位RPM)
  1854. elif dict['command'] == 'tank_motor_status':
  1855. print("D['tank_motor_status']", D['tank_motor_status'])
  1856. time.sleep(1)
  1857. if D['tank_motor_status'] == '0':
  1858. return 'off'
  1859. elif type(D['tank_motor_status']) == int:
  1860. return 'on'
  1861. else:
  1862. return "tank_motor_status signal was not received"
  1863. # 鼓風機(ON開/OFF關)
  1864. elif dict['command'] == 'tank_blower_status':
  1865. time.sleep(1)
  1866. if D['tank_blower_status'] == 'on':
  1867. return 'on'
  1868. elif D['tank_blower_status'] == 'off':
  1869. return 'off'
  1870. else:
  1871. return "tank_blower_status signal was not received"
  1872. # 加熱棒 1(ON開/OFF關)
  1873. elif dict['command'] == 'tank_heater1_status':
  1874. time.sleep(1)
  1875. if D['tank_heater1_status'] == 'on':
  1876. return 'on'
  1877. elif D['tank_heater1_status'] == 'off':
  1878. return 'off'
  1879. else:
  1880. return "tank_heater1_status signal was not received"
  1881. # 加熱棒 2(ON開/OFF關)
  1882. elif dict['command'] == 'tank_heater2_status':
  1883. time.sleep(1)
  1884. if D['tank_heater2_status'] == 'on':
  1885. return 'on'
  1886. elif D['tank_heater2_status'] == 'off':
  1887. return 'off'
  1888. else:
  1889. return "tank_heater2_status signal was not received"
  1890. # 溫度控制(ON開/OFF關)
  1891. elif dict['command'] == 'temp1_enable':
  1892. time.sleep(1)
  1893. if D['temp1_enable'] == 'on':
  1894. return 'on'
  1895. elif D['temp1_enable'] == 'off':
  1896. return 'off'
  1897. else:
  1898. return "temp1_enable_status signal was not received"
  1899. # 設定溫度 (限整數)
  1900. elif dict['command'] == 'temp1':
  1901. time.sleep(1)
  1902. if D['temp1'] == '0':
  1903. return 'off'
  1904. elif type(D['temp1']) == int:
  1905. return 'on'
  1906. else:
  1907. return "temp1 signal was not received"
  1908. # 出料儲豆槽真空吸料機(ON吸料/OFF排氣)
  1909. elif dict['command'] == 'output_vacuum_status':
  1910. time.sleep(1)
  1911. if D['output_vacuum_status'] == 'on':
  1912. return 'on'
  1913. elif D['output_vacuum_status'] == 'off':
  1914. return 'off'
  1915. else:
  1916. return "output_vacuum_status signal was not received"
  1917. # 發酵槽 入料三通閥
  1918. elif dict['command'] == 'tank_threewayvalve_input_status':
  1919. time.sleep(1)
  1920. if D['tank_threewayvalve_input_status'] == 'on':
  1921. return 'on'
  1922. elif D['tank_threewayvalve_input_status'] == 'off':
  1923. return 'off'
  1924. else:
  1925. return "tank_threewayvalve_input_status signal was not received"
  1926. # 發酵槽 總進水
  1927. elif dict['command'] == 'tank_solenoid_water_total_status':
  1928. time.sleep(1)
  1929. if D['tank_solenoid_water_total_status'] == 'on':
  1930. return 'on'
  1931. elif D['tank_solenoid_water_total_status'] == 'off':
  1932. return 'off'
  1933. else:
  1934. return "tank_solenoid_water_total_status signal was not received"
  1935. # 發酵槽 桶內消毒/打菌
  1936. elif dict['command'] == 'tank_solenoid_disinfect_status':
  1937. time.sleep(1)
  1938. if D['tank_solenoid_disinfect_status'] == 'on':
  1939. return 'on'
  1940. elif D['tank_solenoid_disinfect_status'] == 'off':
  1941. return 'off'
  1942. else:
  1943. return "tank_solenoid_disinfect_status signal was not received"
  1944. # 發酵槽 夾層進水
  1945. elif dict['command'] == 'outer_solenoid_water_status':
  1946. time.sleep(1)
  1947. if D['outer_solenoid_water_status'] == 'on':
  1948. return 'on'
  1949. elif D['outer_solenoid_water_status'] == 'off':
  1950. return 'off'
  1951. else:
  1952. return "outer_solenoid_water_status signal was not received"
  1953. # 發酵槽 桶內進水
  1954. elif dict['command'] == 'tank_solenoid_water_in_status':
  1955. time.sleep(1)
  1956. if D['tank_solenoid_water_in_status'] == 'on':
  1957. return 'on'
  1958. elif D['tank_solenoid_water_in_status'] == 'off':
  1959. return 'off'
  1960. else:
  1961. return "tank_solenoid_water_in_status signal was not received"
  1962. # 發酵槽 雙核隔膜泵
  1963. elif dict['command'] == 'tank_pump_sensor_status':
  1964. time.sleep(1)
  1965. if D['tank_pump_sensor_status'] == 'on':
  1966. return 'on'
  1967. elif D['tank_pump_sensor_status'] == 'off':
  1968. return 'off'
  1969. else:
  1970. return "tank_pump_sensor_status signal was not received"
  1971. # 發酵槽 感測器下豆三通閥
  1972. elif dict['command'] == 'tank_threewayvalve_bean_status':
  1973. time.sleep(1)
  1974. if D['tank_threewayvalve_bean_status'] == 'on':
  1975. return 'on'
  1976. elif D['tank_threewayvalve_bean_status'] == 'off':
  1977. return 'off'
  1978. else:
  1979. return "tank_threewayvalve_bean_status signal was not received"
  1980. # 發酵槽 外桶浮選三通閥
  1981. elif dict['command'] == 'outer_threewayvalve_float_status':
  1982. time.sleep(1)
  1983. if D['outer_threewayvalve_float_status'] == 'on':
  1984. return 'on'
  1985. elif D['outer_threewayvalve_float_status'] == 'off':
  1986. return 'off'
  1987. else:
  1988. return "outer_threewayvalve_float_status signal was not received"
  1989. # 發酵槽 溫控開關
  1990. elif dict['command'] == 'tank_temp_enable_status':
  1991. time.sleep(1)
  1992. if D['tank_temp_enable_status'] == 'on':
  1993. return 'on'
  1994. elif D['tank_temp_enable_status'] == 'off':
  1995. return 'off'
  1996. else:
  1997. return "tank_temp_enable_status signal was not received"
  1998. # 發酵槽 設定溫度
  1999. elif dict['command'] == 'tank_temp_status':
  2000. time.sleep(1)
  2001. if D['tank_temp_status'] == '0':
  2002. return 'off'
  2003. elif type(D['tank_temp_status']) == int:
  2004. return 'on'
  2005. else:
  2006. return "tank_temp_status signal was not received"
  2007. # 清洗浮選槽 浮選槽注水
  2008. elif dict['command'] == 'tank_pump_waterFloat_status':
  2009. time.sleep(1)
  2010. if D['tank_pump_waterFloat_status'] == 'on':
  2011. return 'on'
  2012. elif D['tank_pump_waterFloat_status'] == 'off':
  2013. return 'off'
  2014. else:
  2015. return "tank_pump_waterFloat_status signal was not received"
  2016. # 清洗浮選槽 清洗第 2 層灑水
  2017. elif dict['command'] == 'tank_pump_waterL2_status':
  2018. time.sleep(1)
  2019. if D['tank_pump_waterL2_status'] == 'on':
  2020. return 'on'
  2021. elif D['tank_pump_waterL2_status'] == 'off':
  2022. return 'off'
  2023. else:
  2024. return "tank_pump_waterL2_status signal was not received"
  2025. # 清洗浮選槽 清洗第 4 層灑水
  2026. elif dict['command'] == 'tank_pump_waterL4_status':
  2027. time.sleep(1)
  2028. if D['tank_pump_waterL4_status'] == 'on':
  2029. return 'on'
  2030. elif D['tank_pump_waterL4_status'] == 'off':
  2031. return 'off'
  2032. else:
  2033. return "tank_pump_waterL4_status signal was not received"
  2034. # 清洗浮選槽 清洗第 3 層電磁閥
  2035. elif dict['command'] == 'tank_solenoid_waterL3_status':
  2036. time.sleep(1)
  2037. if D['tank_solenoid_waterL3_status'] == 'on':
  2038. return 'on'
  2039. elif D['tank_solenoid_waterL3_status'] == 'off':
  2040. return 'off'
  2041. else:
  2042. return "tank_solenoid_waterL3_status signal was not received"
  2043. # 清洗浮選槽 清洗第 5 層電磁閥
  2044. elif dict['command'] == 'tank_solenoid_waterL5_status':
  2045. time.sleep(1)
  2046. if D['tank_solenoid_waterL5_status'] == 'on':
  2047. return 'on'
  2048. elif D['tank_solenoid_waterL5_status'] == 'off':
  2049. return 'off'
  2050. else:
  2051. return "tank_solenoid_waterL5_status signal was not received"
  2052. # 清洗浮選槽 步進馬達
  2053. elif dict['command'] == 'tank_stepping_motor_status':
  2054. time.sleep(1)
  2055. if D['tank_stepping_motor_status'] == '0':
  2056. return 'off'
  2057. elif type(D['tank_stepping_motor_status']) == int:
  2058. return 'on'
  2059. else:
  2060. return "tank_stepping_motor_status signal was not received"
  2061. return "publish done"
  2062. # 處理mqtt訂閱的信息
  2063. @mqtt.on_message()
  2064. def handle_mqtt_message(client, userdata, message):
  2065. payload = message.payload.decode()
  2066. payload = json.loads(payload)
  2067. # print("-------msg-------")
  2068. # print('name :', p['name'])
  2069. # print('email :', p['email'])
  2070. print('payload:', payload)
  2071. # 入料儲豆槽真空吸料機(ON吸料/OFF排氣)
  2072. if payload['command'] == 'input_vacuum_status':
  2073. if payload['response'] == 'on':
  2074. D['input_vacuum_status'] = 'on'
  2075. else:
  2076. D['input_vacuum_status'] = 'off'
  2077. # 真空吸料機
  2078. elif payload['command'] == 'tank_vacuum_status':
  2079. if payload['response'] == 'on':
  2080. # print('test')
  2081. D['tank_vacuum_status'] = 'on'
  2082. else:
  2083. D['tank_vacuum_status'] = 'off'
  2084. # 三通閥(ON吸料/OFF排氣)
  2085. elif payload['command'] == 'tank_threewayvalve_status':
  2086. if payload['response'] == 'on':
  2087. # print('test')
  2088. D['tank_threewayvalve_status'] = 'on'
  2089. else:
  2090. D['tank_threewayvalve_status'] = 'off'
  2091. # 蝴蝶閥(ON開/OFF關)
  2092. elif payload['command'] == 'tank_diskvalve_status':
  2093. if payload['response'] == 'on':
  2094. # print('test')
  2095. D['tank_diskvalve_status'] = 'on'
  2096. else:
  2097. D['tank_diskvalve_status'] = 'off'
  2098. # 電磁閥(ON噴灑消毒/OFF關)
  2099. elif payload['command'] == 'tank_solenoid_disinfect_status':
  2100. if payload['response'] == 'on':
  2101. # print('test')
  2102. D['tank_solenoid_disinfect_status'] = 'on'
  2103. else:
  2104. D['tank_solenoid_disinfect_status'] = 'off'
  2105. # 電磁閥(ON排水/OFF關)
  2106. elif payload['command'] == 'tank_solenoid_water_status':
  2107. if payload['response'] == 'on':
  2108. # print('test')
  2109. D['tank_solenoid_water_status'] = 'on'
  2110. else:
  2111. D['tank_solenoid_water_status'] = 'off'
  2112. # 馬達(單位RPM)
  2113. elif payload['command'] == 'tank_motor_status':
  2114. if payload['response'] == 'off':
  2115. D['tank_motor_status'] = '0'
  2116. else:
  2117. D['tank_motor_status'] = payload['response']
  2118. # 鼓風機(ON開/OFF關)
  2119. elif payload['command'] == 'tank_blower_status':
  2120. if payload['response'] == 'on':
  2121. # print('test')
  2122. D['tank_blower_status'] = 'on'
  2123. else:
  2124. D['tank_blower_status'] = 'off'
  2125. # 加熱棒 1(ON開/OFF關)
  2126. elif payload['command'] == 'tank_heater1_status':
  2127. if payload['response'] == 'on':
  2128. # print('test')
  2129. D['tank_heater1_status'] = 'on'
  2130. else:
  2131. D['tank_heater1_status'] = 'off'
  2132. # 加熱棒 2(ON開/OFF關)
  2133. elif payload['command'] == 'tank_heater2_status':
  2134. if payload['response'] == 'on':
  2135. # print('test')
  2136. D['tank_heater2_status'] = 'on'
  2137. else:
  2138. D['tank_heater2_status'] = 'off'
  2139. # 出料儲豆槽真空吸料機(ON吸料/OFF排氣)
  2140. elif payload['command'] == 'output_vacuum_status':
  2141. if payload['response'] == 'on':
  2142. # print('test')
  2143. D['output_vacuum_status'] = 'on'
  2144. else:
  2145. D['output_vacuum_status'] = 'off'
  2146. # 發酵槽 入料三通閥
  2147. elif payload['command'] == 'tank_threewayvalve_input_status':
  2148. if payload['response'] == 'on':
  2149. # print('test')
  2150. D['tank_threewayvalve_input_status'] = 'on'
  2151. else:
  2152. D['tank_threewayvalve_input_status'] = 'off'
  2153. # 發酵槽 總進水
  2154. elif payload['command'] == 'tank_solenoid_water_total_status':
  2155. if payload['response'] == 'on':
  2156. D['tank_solenoid_water_total_status'] = 'on'
  2157. else:
  2158. D['tank_solenoid_water_total_status'] = 'off'
  2159. # 發酵槽 桶內消毒/打菌
  2160. elif payload['command'] == 'tank_solenoid_disinfect_status':
  2161. if payload['response'] == 'on':
  2162. D['tank_solenoid_disinfect_status'] = 'on'
  2163. else:
  2164. D['tank_solenoid_disinfect_status'] = 'off'
  2165. # 發酵槽 夾層進水
  2166. elif payload['command'] == 'outer_solenoid_water_status':
  2167. if payload['response'] == 'on':
  2168. D['outer_solenoid_water_status'] = 'on'
  2169. else:
  2170. D['outer_solenoid_water_status'] = 'off'
  2171. # 發酵槽 桶內進水
  2172. elif payload['command'] == 'tank_solenoid_water_in_status':
  2173. if payload['response'] == 'on':
  2174. D['tank_solenoid_water_in_status'] = 'on'
  2175. else:
  2176. D['tank_solenoid_water_in_status'] = 'off'
  2177. # 發酵槽 雙核隔膜泵
  2178. elif payload['command'] == 'tank_pump_sensor_status':
  2179. if payload['response'] == 'on':
  2180. D['tank_pump_sensor_status'] = 'on'
  2181. else:
  2182. D['tank_pump_sensor_status'] = 'off'
  2183. # 發酵槽 感測器下豆三通閥
  2184. elif payload['command'] == 'tank_threewayvalve_bean_status':
  2185. if payload['response'] == 'on':
  2186. D['tank_threewayvalve_bean_status'] = 'on'
  2187. else:
  2188. D['tank_threewayvalve_bean_status'] = 'off'
  2189. # 發酵槽 外桶浮選三通閥
  2190. elif payload['command'] == 'outer_threewayvalve_float_status':
  2191. if payload['response'] == 'on':
  2192. D['outer_threewayvalve_float_status'] = 'on'
  2193. else:
  2194. D['outer_threewayvalve_float_status'] = 'off'
  2195. # 發酵槽 溫控開關
  2196. elif payload['command'] == 'tank_temp_enable_status':
  2197. if payload['response'] == 'on':
  2198. D['tank_temp_enable_status'] = 'on'
  2199. else:
  2200. D['tank_temp_enable_status'] = 'off'
  2201. # 發酵槽 設定溫度
  2202. elif payload['command'] == 'tank_temp_status':
  2203. if payload['response'] == 'off':
  2204. D['tank_temp_status'] = '0'
  2205. else:
  2206. D['tank_temp_status'] = payload['response']
  2207. # 清洗浮選槽 浮選槽注水
  2208. elif payload['command'] == 'tank_pump_waterFloat_status':
  2209. if payload['response'] == 'on':
  2210. D['tank_temp_status'] = 'on'
  2211. else:
  2212. D['tank_temp_status'] = 'off'
  2213. # 清洗浮選槽 清洗第 2 層灑水
  2214. elif payload['command'] == 'tank_pump_waterL2_status':
  2215. if payload['response'] == 'on':
  2216. D['tank_pump_waterL2_status'] = 'on'
  2217. else:
  2218. D['tank_pump_waterL2_status'] = 'off'
  2219. # 清洗浮選槽 清洗第 4 層灑水
  2220. elif payload['command'] == 'tank_pump_waterL4_status':
  2221. if payload['response'] == 'on':
  2222. D['tank_pump_waterL4_status'] = 'on'
  2223. else:
  2224. D['tank_pump_waterL4_status'] = 'off'
  2225. # 清洗浮選槽 清洗第 3 層電磁閥
  2226. elif payload['command'] == 'tank_solenoid_waterL3_status':
  2227. if payload['response'] == 'on':
  2228. D['tank_solenoid_waterL3_status'] = 'on'
  2229. else:
  2230. D['tank_solenoid_waterL3_status'] = 'off'
  2231. # 清洗浮選槽 清洗第 5 層電磁閥
  2232. elif payload['command'] == 'tank_solenoid_waterL5_status':
  2233. if payload['response'] == 'on':
  2234. D['tank_solenoid_waterL5_status'] = 'on'
  2235. else:
  2236. D['tank_solenoid_waterL5_status'] = 'off'
  2237. # 清洗浮選槽 步進馬達
  2238. elif payload['command'] == 'tank_stepping_motor_status':
  2239. if payload['response'] == 'off':
  2240. D['tank_stepping_motor_status'] = '0'
  2241. else:
  2242. D['tank_stepping_motor_status'] = payload['response']