views_1007備份.py 237 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306
  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, false, null
  6. # 導入藍圖程序,用於構建路由
  7. from werkzeug.utils import redirect
  8. from werkzeug.wrappers import response
  9. from . import main
  10. from coffee_manage import mqtt
  11. # 導入db,用於操作數據庫
  12. from coffee_manage import db
  13. # 導入實體類,用於操作數據庫
  14. from ..models import *
  15. import json
  16. from datetime import datetime as dt
  17. from sqlalchemy import text
  18. import pymysql
  19. import pandas as pd
  20. from concurrent.futures import ThreadPoolExecutor
  21. import cv2
  22. import pickle
  23. import socket
  24. import time
  25. import threading
  26. import numpy as np
  27. import math
  28. from .mqtt import MQTT
  29. from matplotlib import pyplot as plt
  30. import random
  31. from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg as FigureCanvas
  32. import io
  33. from flask import make_response
  34. import psutil
  35. pool = ThreadPoolExecutor(25)
  36. s_sock = 0
  37. lock = threading.Lock()
  38. '''
  39. mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffee',
  40. password='skyeye', database='Coffee', charset='utf8')
  41. mycursor = mydb.cursor()
  42. '''
  43. # 主頁的訪問路徑
  44. @main.route('/')
  45. def main_index():
  46. # 獲取登入信息
  47. if 'id' in session and 'uname' in session and 'status' in session:
  48. username = session['uname']
  49. status = session['status']
  50. if status == 9:
  51. return render_template('signin_disable.html', params=locals())
  52. if status == 8:
  53. return render_template('signin_new.html', params=locals())
  54. # Rita 參數 params 是用來取得參數的 locals=() 所有參數
  55. return render_template('index.html', params=locals())
  56. else:
  57. return render_template('sign_in.html')
  58. # Rita 測試
  59. # 使用者名稱測試
  60. # !!! AttributeError: 'NoneType' object has no attribute 'vacuum'
  61. # 乾燥槽自動化測試頁
  62. @main.route('/dry_auto')
  63. def dry_auto():
  64. # 獲取登入信息
  65. if 'id' in session and 'uname' in session and 'status' in session:
  66. username = session['uname']
  67. status = session['status']
  68. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  69. DI1 = dry_status.Dry_Input_1
  70. DI2 = dry_status.Dry_Input_2
  71. D1 = dry_status.Dry_Tank_1
  72. D2 = dry_status.Dry_Tank_2
  73. D3 = dry_status.Dry_Tank_3
  74. D4 = dry_status.Dry_Tank_4
  75. D5 = dry_status.Dry_Tank_5
  76. D6 = dry_status.Dry_Tank_6
  77. D7 = dry_status.Dry_Tank_7
  78. D8 = dry_status.Dry_Tank_8
  79. D9 = dry_status.Dry_Tank_9
  80. D10 = dry_status.Dry_Tank_10
  81. D11 = dry_status.Dry_Tank_11
  82. D12 = dry_status.Dry_Tank_12
  83. DO1 = dry_status.Dry_Output_1
  84. DO2 = dry_status.Dry_Output_2
  85. return render_template('dry_auto.html', title="[測試] 乾燥自動化", **locals())
  86. else:
  87. return render_template('sign_in.html')
  88. @main.route('/dry_auto_status')
  89. def dry_auto_test():
  90. # [介面] 讓使用者可以選擇排程內有乾燥/清洗/校正, 此處預設為 True
  91. Dry_btn = True
  92. # 從資料庫資料表中取得最新狀態
  93. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  94. DI1 = dry_status.Dry_Input_1
  95. DI2 = dry_status.Dry_Input_2
  96. D1 = dry_status.Dry_Tank_1
  97. D2 = dry_status.Dry_Tank_2
  98. D3 = dry_status.Dry_Tank_3
  99. D4 = dry_status.Dry_Tank_4
  100. D5 = dry_status.Dry_Tank_5
  101. D6 = dry_status.Dry_Tank_6
  102. D7 = dry_status.Dry_Tank_7
  103. D8 = dry_status.Dry_Tank_8
  104. D9 = dry_status.Dry_Tank_9
  105. D10 = dry_status.Dry_Tank_10
  106. D11 = dry_status.Dry_Tank_11
  107. D12 = dry_status.Dry_Tank_12
  108. DO1 = dry_status.Dry_Output_1
  109. DO2 = dry_status.Dry_Output_2
  110. FO1 = 'FO_Waiting' # 'FO_OutputtingBean'
  111. FO2 = 'FO_Waiting'
  112. D_UP_tanklist = [D1, D2, D3, D4, D5, D6]
  113. D_DOWN_tanklist = [D7, D8, D9, D10, D11, D12]
  114. # ----- 乾燥桶槽 D1~D6 入料暫停→入料判斷 ------------------------------
  115. Dry_InputtingBeanPause_number = int(D_UP_tanklist.count('D_InputtingBean_Pause'))
  116. # 若入料儲豆槽可出豆, 且 D1~D6 其中有桶槽入料暫停 (就是入料時桶槽豆子未滿 or 儲豆槽=='DI_Waiting' 已空) 時, 優先入豆
  117. if DI1 == 'DI_OutputtingBean' and Dry_InputtingBeanPause_number >= 1:
  118. if D1 == 'D_InputtingBean_Pause':
  119. D1 = 'D_InputtingBean'
  120. print('-- D1 狀態更新:入料中 --')
  121. elif D2 == 'D_InputtingBean_Pause':
  122. D2 = 'D_InputtingBean'
  123. print('-- D2 狀態更新:入料中 --')
  124. elif D3 == 'D_InputtingBean_Pause':
  125. D3 = 'D_InputtingBean'
  126. print('-- D3 狀態更新:入料中 --')
  127. elif D4 == 'D_InputtingBean_Pause':
  128. D4 = 'D_InputtingBean'
  129. print('-- D4 狀態更新:入料中 --')
  130. elif D5 == 'D_InputtingBean_Pause':
  131. D5 = 'D_InputtingBean'
  132. print('-- D5 狀態更新:入料中 --')
  133. elif D6 == 'D_InputtingBean_Pause':
  134. D6 = 'D_InputtingBean'
  135. print('-- D6 狀態更新:入料中 --')
  136. # ----- 乾燥桶槽 D1~D6 等待→入料判斷 ------------------------------
  137. # 目前乾燥槽 D1~D6 正在入豆的桶槽數量 (應小於一桶)
  138. Dry_InputtingBean_number = int(D_UP_tanklist.count('D_InputtingBean'))
  139. # [介面] 若未啟用 發酵 狀態
  140. if not Dry_btn:
  141. print('未指定乾燥流程')
  142. # 入料儲豆槽 非可出料狀態
  143. elif Dry_btn and DI1 != 'DI_OutputtingBean':
  144. print('入料儲豆槽空, 無法入料')
  145. # 若 D1~D6 乾燥桶槽為 入豆暫停, 則狀態改為入豆優先入豆
  146. elif Dry_btn and DI1 == 'DI_OutputtingBean' and Dry_InputtingBeanPause_number >= 1:
  147. print('乾燥槽 D', D_UP_tanklist.index('D_InputtingBean_Pause')+1, '優先入料中')
  148. print('-- D', D_UP_tanklist.index('D_InputtingBean_Pause')+1, ' 入料中 --')
  149. # 若 D1~D6 發酵桶槽為 入豆, 則桶槽數字小者 優先入豆
  150. elif Dry_btn and DI1 == 'DI_OutputtingBean' and Dry_InputtingBean_number >= 1:
  151. print('乾燥槽 D', D_UP_tanklist.index('D_InputtingBean')+1, '優先入料中')
  152. print('-- D', D_UP_tanklist.index('D_InputtingBean')+1, ' 入料中 --')
  153. elif Dry_btn and DI1 == 'DI_OutputtingBean' \
  154. and Dry_InputtingBean_number == 0 and Dry_InputtingBeanPause_number == 0:
  155. # 當達標準入料條件
  156. if D1 == 'D_Waiting':
  157. D1 = 'D_InputtingBean'
  158. print('-- D1 狀態更新:入料中 --')
  159. elif D2 == 'D_Waiting':
  160. D2 = 'D_InputtingBean'
  161. print('-- D2 狀態更新:入料中 --')
  162. elif D3 == 'D_Waiting':
  163. D3 = 'D_InputtingBean'
  164. print('-- D3 狀態更新:入料中 --')
  165. elif D4 == 'D_Waiting':
  166. D4 = 'D_InputtingBean'
  167. print('-- D4 狀態更新:入料中 --')
  168. elif D5 == 'D_Waiting':
  169. D5 = 'D_InputtingBean'
  170. print('-- D5 狀態更新:入料中 --')
  171. elif D6 == 'D_Waiting':
  172. D6 = 'D_InputtingBean'
  173. print('-- D6 狀態更新:入料中 --')
  174. # ----- 乾燥桶槽 D1~D6 入料→入料暫停判斷 ------------------------------
  175. Dry_InputtingBean_number = int(D_UP_tanklist.count('D_InputtingBean'))
  176. # -- 取得乾燥桶槽 D1~D6 超音波生豆高度 UltraSonic -------------
  177. D_UP_tank_UltraSonic = []
  178. for i in range(1, 7, 1):
  179. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
  180. UltraSonic = int(tank_UltraSonic.UltraSonic)
  181. D_UP_tank_UltraSonic.append(UltraSonic)
  182. print('D_UP_tank_UltraSonic: ', D_UP_tank_UltraSonic)
  183. # -- 取得乾燥桶槽 D1~D6 超音波生豆高度 UltraSonic -------------
  184. if DI1 != 'DI_OutputtingBean' and Dry_InputtingBean_number >= 1:
  185. if D1 == 'D_InputtingBean' and D_UP_tank_UltraSonic[0] < 110:
  186. D1 = 'D_InputtingBean_Pause'
  187. print('-- D1 狀態更新:入料暫停 --')
  188. else:
  189. D1 = 'D_InputtingBean_Finish'
  190. print('-- D1 狀態更新:入料完成 --')
  191. if D2 == 'D_InputtingBean' and D_UP_tank_UltraSonic[1] < 110:
  192. D2 = 'D_InputtingBean_Pause'
  193. print('-- D2 狀態更新:入料暫停 --')
  194. else:
  195. D2 = 'D_InputtingBean_Finish'
  196. print('-- D2 狀態更新:入料完成 --')
  197. if D3 == 'D_InputtingBean' and D_UP_tank_UltraSonic[2] < 110:
  198. D3 = 'D_InputtingBean_Pause'
  199. print('-- D3 狀態更新:入料暫停 --')
  200. else:
  201. D3 = 'D_InputtingBean_Finish'
  202. print('-- D3 狀態更新:入料完成 --')
  203. if D4 == 'D_InputtingBean' and D_UP_tank_UltraSonic[3] < 110:
  204. D4 = 'D_InputtingBean_Pause'
  205. print('-- D4 狀態更新:入料暫停 --')
  206. else:
  207. D4 = 'D_InputtingBean_Finish'
  208. print('-- D4 狀態更新:入料完成 --')
  209. if D5 == 'D_InputtingBean' and D_UP_tank_UltraSonic[4] < 110:
  210. D5 = 'D_InputtingBean_Pause'
  211. print('-- D5 狀態更新:入料暫停 --')
  212. else:
  213. D5 = 'D_InputtingBean_Finish'
  214. print('-- D5 狀態更新:入料完成 --')
  215. if D6 == 'D_InputtingBean' and D_UP_tank_UltraSonic[5] < 110:
  216. D6 = 'D_InputtingBean_Pause'
  217. print('-- D6 狀態更新:入料暫停 --')
  218. else:
  219. D6 = 'D_InputtingBean_Finish'
  220. print('-- D6 狀態更新:入料完成 --')
  221. # # ----- 乾燥桶槽 D1~D6 入料完成→乾燥判斷 ------------------------------
  222. # Dry_InputtingBeanFinish_number = int(D_UP_tanklist.count('D_InputtingBean_Finish'))
  223. # # 乾燥條件:當前桶槽入豆達指定高度, 則開始乾燥 (可以多桶乾燥)
  224. # # !!! 乾燥槽 D_Drying 狀態應該請硬體判斷
  225. # # !!! 若狀態為 D_InputtingBean 且 超音波值>指定生豆高度, 狀態改為 D_Drying 乾燥
  226. # if D1 == 'D_InputtingBean_Finish' or D1 == 'D_InputtingBean_Pause' and D_UP_tank_UltraSonic[0] >= 110:
  227. # D1 = 'D_Drying'
  228. # print('-- D1 狀態更新:乾燥中 --')
  229. # if D2 == 'D_InputtingBean_Finish' and D_UP_tank_UltraSonic[1] >= 110:
  230. # D2 = 'D_Drying'
  231. # print('-- D2 狀態更新:乾燥中 --')
  232. # if D3 == 'D_InputtingBean_Finish' and D_UP_tank_UltraSonic[2] >= 110:
  233. # D3 = 'D_Drying'
  234. # print('-- D3 狀態更新:乾燥中 --')
  235. # if D4 == 'D_InputtingBean_Finish' and D_UP_tank_UltraSonic[3] >= 110:
  236. # D4 = 'D_Drying'
  237. # print('-- D4 狀態更新:乾燥中 --')
  238. # if D5 == 'D_InputtingBean_Finish' and D_UP_tank_UltraSonic[4] >= 110:
  239. # D5 = 'D_Drying'
  240. # print('-- D5 狀態更新:乾燥中 --')
  241. # if D6 == 'D_InputtingBean_Finish' and D_UP_tank_UltraSonic[5] >= 110:
  242. # D6 = 'D_Drying'
  243. # print('-- D6 狀態更新:乾燥中 --')
  244. # ----- 乾燥桶槽 D1~D6 發酵→可出豆 判斷 ------------------------------
  245. # !!! 發酵槽 D_OutputtingBean 狀態應該請硬體判斷
  246. # !!! 若狀態為 D_Drying 且 達指定乾燥條件, 狀態改為 D_OutputtingBean 可出豆
  247. # 可以多桶各自執行發酵排程
  248. # ----- [測試用] !!!!! D1~D6 入料完成→可出豆 判斷 ------------------------------
  249. if D1 == 'D_InputtingBean_Finish': D1 = 'D_OutputtingBean'
  250. if D2 == 'D_InputtingBean_Finish': D2 = 'D_OutputtingBean'
  251. if D3 == 'D_InputtingBean_Finish': D3 = 'D_OutputtingBean'
  252. if D4 == 'D_InputtingBean_Finish': D4 = 'D_OutputtingBean'
  253. if D5 == 'D_InputtingBean_Finish': D5 = 'D_OutputtingBean'
  254. if D6 == 'D_InputtingBean_Finish': D6 = 'D_OutputtingBean'
  255. # ----- [測試用] !!!!! D1~D6 入料完成→可出豆 判斷 ------------------------------
  256. # # ----- 乾燥桶槽 D1~D6 可出豆→出料儲豆槽 DO1 判斷 ------------------------------
  257. Dry_OutputtingBean_number = int(D_UP_tanklist.count('D_OutputtingBean'))
  258. # # !!! 若出料儲豆槽狀態為 DO_Waiting(空桶等待) 且 桶槽狀態為 D_OutputtingBean 可出豆, 與 DO1 配合開始出豆
  259. # if DO1 == 'DO_Waiting' and Dry_OutputtingBean_number >= 1:
  260. # if D1 == 'D_OutputtingBean':
  261. # DO1 = 'DO_InputtingBean'
  262. # print('-- D1 狀態更新:出豆中 --')
  263. # print('-- DO1 狀態更新:入豆中 --')
  264. # elif D2 == 'D_OutputtingBean':
  265. # DO1 = 'DO_InputtingBean'
  266. # print('-- D2 狀態更新:出豆中 --')
  267. # print('-- DO1 狀態更新:入豆中 --')
  268. # elif D3 == 'D_OutputtingBean':
  269. # DO1 = 'DO_InputtingBean'
  270. # print('-- D3 狀態更新:出豆中 --')
  271. # print('-- DO1 狀態更新:入豆中 --')
  272. # elif D4 == 'D_OutputtingBean':
  273. # DO1 = 'DO_InputtingBean'
  274. # print('-- D4 狀態更新:出豆中 --')
  275. # print('-- DO1 狀態更新:入豆中 --')
  276. # elif D5 == 'D_OutputtingBean':
  277. # DO1 = 'DO_InputtingBean'
  278. # print('-- D5 狀態更新:出豆中 --')
  279. # print('-- DO1 狀態更新:入豆中 --')
  280. # elif D6 == 'D_OutputtingBean':
  281. # DO1 = 'DO_InputtingBean'
  282. # print('-- D6 狀態更新:出豆中 --')
  283. # print('-- DO1 狀態更新:入豆中 --')
  284. # ----- 乾燥入料儲豆槽 DI1~DI2 入豆→可出豆判斷 ------------------------------
  285. # -- 取得乾燥入料儲豆槽 FI1~FI2 桶內高度 UltraSonic -------------
  286. DI_UP_UltraSoniclist = []
  287. for i in range(1, 3, 1):
  288. input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI' + str(i)).order_by(text('datetime desc')).first()
  289. UltraSonic = int(input_UltraSonic.UltraSonic)
  290. DI_UP_UltraSoniclist.append(UltraSonic)
  291. print('DI_UP_UltraSoniclist: ', DI_UP_UltraSoniclist)
  292. # !!! 乾燥入料儲豆槽 D_OutputtingBean 狀態應該請硬體判斷
  293. # 入料儲豆槽等待中、且發酵槽出料儲豆槽可出豆時, 入料儲豆槽入豆
  294. if DI1 == 'DI_Waiting' and FO1 == 'FO_OutputtingBean':
  295. DI1 = 'DI_InputtingBean'
  296. print('-- DI1 狀態更新:入豆中 --')
  297. # 入料儲豆槽入豆時 且 (發酵儲豆槽有入料 或者 前方儲豆槽非可出豆), 則停止入豆
  298. elif DI1 == 'DI_InputtingBean' and (DI_UP_UltraSoniclist[0] > 55) and (FO1 != 'FO_OutputtingBean') :
  299. DI1 = 'DI_OutputtingBean'
  300. print('-- DI1 狀態更新:可出豆 --')
  301. # 若入料儲豆槽可出豆 且 儲豆槽內高度低於 40 且 前方脫皮機儲豆槽可出豆 且 目前無桶槽需入料時
  302. elif DI1 == 'DI_OutputtingBean' and (DI_UP_UltraSoniclist[0] < 40) and FO1 == 'FO_OutputtingBean' and Dry_InputtingBean_number == 0 and Dry_InputtingBeanPause_number == 0:
  303. DI1 = 'DI_InputtingBean'
  304. print('-- DI1 狀態更新:入豆中 --')
  305. # if DI2 == 'DI_Waiting' and FO2 == 'FO_OutputtingBean':
  306. # DI2 = 'DI_InputtingBean'
  307. # print('-- DI2 狀態更新:入豆中 --')
  308. # elif DI2 == 'DI_InputtingBean' and ((DI_DOWN_UltraSoniclist[1] > 55) or (FO2 == 'FO_OutputtingBean')) :
  309. # DI2 = 'DI_OutputtingBean'
  310. # print('-- DI2 狀態更新:可出豆 --')
  311. # elif DI2 == 'DI_OutputtingBean' and (DI_DOWN_UltraSoniclist[1] < 40) and FO2 == 'FO_OutputtingBean' and Dry_InputtingBean_number == 0 and Dry_InputtingBeanPause_number == 0:
  312. # DI2 = 'DI_InputtingBean'
  313. # print('-- DI2 狀態更新:入豆中 --')
  314. # ----- 乾燥出料儲豆槽 DO1~DO2 入豆→可出豆判斷 ------------------------------
  315. # -- 取得乾燥出料儲豆槽 DO1~DO2 桶內高度 UltraSonic -------------
  316. DO_UP_UltraSoniclist = []
  317. for i in range(1, 3, 1):
  318. output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO' + str(i)).order_by(text('datetime desc')).first()
  319. UltraSonic = int(output_UltraSonic.UltraSonic)
  320. DO_UP_UltraSoniclist.append(UltraSonic)
  321. print('DO_UP_UltraSoniclist: ', DO_UP_UltraSoniclist)
  322. # 桶槽可出豆, 且出料儲豆槽等待時, 出料儲豆槽入豆
  323. # 參考 -- 乾燥桶槽 F1~F6 可出豆→出料儲豆槽 FO1 判斷 --
  324. # 出料儲豆槽入料 且滿時, 出料儲豆槽可出豆
  325. if DO1 == ('DO_InputtingBean' and DO_UP_UltraSoniclist[0] > 55):
  326. DO1 = 'DO_OutputtingBean'
  327. # 出料儲豆槽入料 且未滿, 桶槽可出豆已空
  328. # -- 取得乾燥桶槽 D1~D6 桶內高度 UltraSonic -------------
  329. D_UP_UltraSoniclist = []
  330. for i in range(1, 7, 1):
  331. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
  332. UltraSonic = int(tank_UltraSonic.UltraSonic)
  333. D_UP_UltraSoniclist.append(UltraSonic)
  334. print('D_UP_UltraSoniclist: ', D_UP_UltraSoniclist)
  335. # -- 取得乾燥桶槽 D1~D6 桶內高度 UltraSonic -------------
  336. if DO1 == 'DO_InputtingBean' and Dry_OutputtingBean_number >= 1:
  337. if D1 == 'D_OutputtingBean' and D_UP_UltraSoniclist[0] < 5:
  338. D1 = 'D_Waiting'
  339. DO1 = 'DO_OutputtingBean'
  340. print('-- D1 狀態更新:空桶等待 --')
  341. print('-- DO1 狀態更新:可出豆 --')
  342. elif D2 == 'D_OutputtingBean' and D_UP_UltraSoniclist[1] < 5:
  343. D2 = 'D_Waiting'
  344. DO1 = 'DO_OutputtingBean'
  345. print('-- D2 狀態更新:空桶等待 --')
  346. print('-- DO1 狀態更新:可出豆 --')
  347. elif D3 == 'D_OutputtingBean' and D_UP_UltraSoniclist[2] < 5:
  348. D3 = 'D_Waiting'
  349. DO1 = 'DO_OutputtingBean'
  350. print('-- D3 狀態更新:空桶等待 --')
  351. print('-- DO1 狀態更新:可出豆 --')
  352. elif D4 == 'D_OutputtingBean' and D_UP_UltraSoniclist[3] < 5:
  353. D4 = 'D_Waiting'
  354. DO1 = 'DO_OutputtingBean'
  355. print('-- D4 狀態更新:空桶等待 --')
  356. print('-- DO1 狀態更新:可出豆 --')
  357. elif D5 == 'D_OutputtingBean' and D_UP_UltraSoniclist[4] < 5:
  358. D5 = 'D_Waiting'
  359. DO1 = 'DO_OutputtingBean'
  360. print('-- D5 狀態更新:空桶等待 --')
  361. print('-- DO1 狀態更新:可出豆 --')
  362. elif D6 == 'D_OutputtingBean' and D_UP_UltraSoniclist[5] < 5:
  363. D6 = 'D_Waiting'
  364. DO1 = 'DO_OutputtingBean'
  365. print('-- D6 狀態更新:空桶等待 --')
  366. print('-- DO1 狀態更新:可出豆 --')
  367. elif DO1 == 'DO_OutputtingBean' and DO_UP_UltraSoniclist[0] < 5:
  368. DO1 = 'DO_Waiting'
  369. # ----- 將狀態寫入資料庫 ------------------------------
  370. # 獲取文本框的值並賦值給user實體對象
  371. D_status = dry_container_status()
  372. D_status.Dry_Input_1 = DI1
  373. D_status.Dry_Input_2 = DI2
  374. D_status.Dry_Tank_1 = D1
  375. D_status.Dry_Tank_2 = D2
  376. D_status.Dry_Tank_3 = D3
  377. D_status.Dry_Tank_4 = D4
  378. D_status.Dry_Tank_5 = D5
  379. D_status.Dry_Tank_6 = D6
  380. D_status.Dry_Tank_7 = D7
  381. D_status.Dry_Tank_8 = D8
  382. D_status.Dry_Tank_9 = D9
  383. D_status.Dry_Tank_10 = D10
  384. D_status.Dry_Tank_11 = D11
  385. D_status.Dry_Tank_12 = D12
  386. D_status.Dry_Output_1 = DO1
  387. D_status.Dry_Output_2 = DO2
  388. #將數據保存進資料庫
  389. db.session.add(D_status)
  390. # 手動提交
  391. db.session.commit()
  392. # ----- 將狀態寫入資料庫 ------------------------------
  393. return jsonify({"Dry_Input_1":DI1,
  394. "Dry_Tank_1":D1,
  395. "Dry_Tank_2":D2,
  396. "Dry_Tank_3":D3,
  397. "Dry_Tank_4":D4,
  398. "Dry_Tank_5":D5,
  399. "Dry_Tank_6":D6,
  400. "Dry_Output_1":DO1
  401. })
  402. # 發酵槽自動化測試頁
  403. @main.route('/ferment_auto')
  404. def ferment_auto():
  405. # 獲取登入信息
  406. if 'id' in session and 'uname' in session and 'status' in session:
  407. username = session['uname']
  408. status = session['status']
  409. ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  410. FI1 = ferment_status.Ferment_Input_1
  411. FI2 = ferment_status.Ferment_Input_2
  412. F1 = ferment_status.Ferment_Tank_1
  413. F2 = ferment_status.Ferment_Tank_2
  414. F3 = ferment_status.Ferment_Tank_3
  415. F4 = ferment_status.Ferment_Tank_4
  416. F5 = ferment_status.Ferment_Tank_5
  417. F6 = ferment_status.Ferment_Tank_6
  418. F7 = ferment_status.Ferment_Tank_7
  419. F8 = ferment_status.Ferment_Tank_8
  420. F9 = ferment_status.Ferment_Tank_9
  421. F10 = ferment_status.Ferment_Tank_10
  422. F11 = ferment_status.Ferment_Tank_11
  423. F12 = ferment_status.Ferment_Tank_12
  424. FO1 = ferment_status.Ferment_Output_1
  425. FO2 = ferment_status.Ferment_Output_2
  426. return render_template('ferment_auto.html', title="[測試] 發酵自動化", **locals())
  427. else:
  428. return render_template('sign_in.html')
  429. @main.route('/ferment_auto_status')
  430. def ferment_auto_test():
  431. # [介面] 讓使用者可以選擇排程內有發酵/清洗/校正, 此處預設為 True
  432. Ferment_btn = True
  433. # 從資料庫資料表中取得最新狀態
  434. ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  435. FI1 = ferment_status.Ferment_Input_1
  436. FI2 = ferment_status.Ferment_Input_2
  437. F1 = ferment_status.Ferment_Tank_1
  438. F2 = ferment_status.Ferment_Tank_2
  439. F3 = ferment_status.Ferment_Tank_3
  440. F4 = ferment_status.Ferment_Tank_4
  441. F5 = ferment_status.Ferment_Tank_5
  442. F6 = ferment_status.Ferment_Tank_6
  443. F7 = ferment_status.Ferment_Tank_7
  444. F8 = ferment_status.Ferment_Tank_8
  445. F9 = ferment_status.Ferment_Tank_9
  446. F10 = ferment_status.Ferment_Tank_10
  447. F11 = ferment_status.Ferment_Tank_11
  448. F12 = ferment_status.Ferment_Tank_12
  449. FO1 = ferment_status.Ferment_Output_1
  450. FO2 = ferment_status.Ferment_Output_2
  451. PO1 = 'PO_Waiting' # PO_Waiting # PO_OutputtingBean
  452. PO2 = 'PO_Waiting'
  453. F_UP_tanklist = [F1, F2, F3, F4, F5, F6]
  454. F_DOWN_tanklist = [F7, F8, F9, F10, F11, F12]
  455. # ----- 發酵桶槽 F1~F6 入料暫停→入料判斷 ------------------------------
  456. Ferment_InputtingBeanPause_number = int(F_UP_tanklist.count('F_InputtingBean_Pause'))
  457. # 若入料儲豆槽可出豆, 且 F1~F6 其中有桶槽入料暫停 (就是入料時桶槽豆子未滿 or 儲豆槽=='FI_Waiting' 已空) 時, 優先入豆
  458. if FI1 == 'FI_OutputtingBean' and Ferment_InputtingBeanPause_number >= 1:
  459. if F1 == 'F_InputtingBean_Pause':
  460. F1 = 'F_InputtingBean'
  461. print('-- F1 狀態更新:入料中 --')
  462. elif F2 == 'F_InputtingBean_Pause':
  463. F2 = 'F_InputtingBean'
  464. print('-- F2 狀態更新:入料中 --')
  465. elif F3 == 'F_InputtingBean_Pause':
  466. F3 = 'F_InputtingBean'
  467. print('-- F3 狀態更新:入料中 --')
  468. elif F4 == 'F_InputtingBean_Pause':
  469. F4 = 'F_InputtingBean'
  470. print('-- F4 狀態更新:入料中 --')
  471. elif F5 == 'F_InputtingBean_Pause':
  472. F5 = 'F_InputtingBean'
  473. print('-- F5 狀態更新:入料中 --')
  474. elif F6 == 'F_InputtingBean_Pause':
  475. F6 = 'F_InputtingBean'
  476. print('-- F6 狀態更新:入料中 --')
  477. # ----- 發酵桶槽 F1~F6 等待→入料判斷 ------------------------------
  478. # 目前發酵槽 F1~F6 正在入豆的桶槽數量 (應小於一桶)
  479. Ferment_InputtingBean_number = int(F_UP_tanklist.count('F_InputtingBean'))
  480. # -- 取得發酵桶槽 F1~F6 桶內高度 UltraSonic -------------
  481. F_UP_UltraSoniclist = []
  482. for i in range(1, 7, 1):
  483. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  484. UltraSonic = int(tank_UltraSonic.UltraSonic)
  485. F_UP_UltraSoniclist.append(UltraSonic)
  486. print('F_UP_UltraSoniclist: ', F_UP_UltraSoniclist)
  487. # -- 取得發酵桶槽 F1~F6 桶內高度 UltraSonic -------------
  488. # [介面] 若未啟用 發酵 狀態
  489. if not Ferment_btn:
  490. print('未指定發酵流程')
  491. # 入料儲豆槽 非可出料狀態
  492. elif FI1 != 'FI_OutputtingBean':
  493. print('發酵入料儲豆槽空, 桶槽無法入料')
  494. # 若 F1~F6 發酵桶槽為 入豆暫停, 則狀態改為入豆優先入豆
  495. elif Ferment_btn and FI1 == 'FI_OutputtingBean' \
  496. and Ferment_InputtingBeanPause_number >= 1:
  497. print('發酵槽 F'+str(F_UP_tanklist.index('F_InputtingBean_Pause')+1)+' 優先入料中')
  498. print('-- F'+str(F_UP_tanklist.index('F_InputtingBean_Pause')+1)+' 入料中 --')
  499. # 若 F1~F6 發酵桶槽為 入豆, 則桶槽數字小者 優先入豆
  500. elif Ferment_btn and FI1 == 'FI_OutputtingBean' \
  501. and Ferment_InputtingBean_number >= 1:
  502. print('發酵槽 F'+str(F_UP_tanklist.index('F_InputtingBean')+1)+' 優先入料中')
  503. print('-- F'+str(F_UP_tanklist.index('F_InputtingBean')+1)+' 入料中 --')
  504. elif Ferment_btn and FI1 == 'FI_OutputtingBean' \
  505. and Ferment_InputtingBean_number == 0 and Ferment_InputtingBeanPause_number == 0:
  506. # 當達標準入料條件
  507. if F1 == 'F_Waiting':
  508. F1 = 'F_InputtingBean'
  509. print('-- F1 狀態更新:入料中 --')
  510. elif F2 == 'F_Waiting':
  511. F2 = 'F_InputtingBean'
  512. print('-- F2 狀態更新:入料中 --')
  513. elif F3 == 'F_Waiting':
  514. F3 = 'F_InputtingBean'
  515. print('-- F3 狀態更新:入料中 --')
  516. elif F4 == 'F_Waiting':
  517. F4 = 'F_InputtingBean'
  518. print('-- F4 狀態更新:入料中 --')
  519. elif F5 == 'F_Waiting':
  520. F5 = 'F_InputtingBean'
  521. print('-- F5 狀態更新:入料中 --')
  522. elif F6 == 'F_Waiting':
  523. F6 = 'F_InputtingBean'
  524. print('-- F6 狀態更新:入料中 --')
  525. elif FI1 == 'F_InputtingBean' and Ferment_InputtingBean_number >= 1:
  526. if F_UP_UltraSoniclist[0] < 110:
  527. F1 = 'F_InputtingBean_Pause'
  528. print('-- F1 狀態更新:入料暫停 --')
  529. else:
  530. F1 = 'F_InputtingBean_Finish'
  531. print('-- F1 狀態更新:入料完成 --')
  532. if F_UP_UltraSoniclist[1] < 110:
  533. F2 = 'F_InputtingBean_Pause'
  534. print('-- F2 狀態更新:入料暫停 --')
  535. else:
  536. F2 = 'F_InputtingBean_Finish'
  537. print('-- F2 狀態更新:入料完成 --')
  538. if F_UP_UltraSoniclist[2] < 110:
  539. F3 = 'F_InputtingBean_Pause'
  540. print('-- F3 狀態更新:入料暫停 --')
  541. else:
  542. F3 = 'F_InputtingBean_Finish'
  543. print('-- F3 狀態更新:入料完成 --')
  544. if F_UP_UltraSoniclist[3] < 110:
  545. F4 = 'F_InputtingBean_Pause'
  546. print('-- F4 狀態更新:入料暫停 --')
  547. else:
  548. F4 = 'F_InputtingBean_Finish'
  549. print('-- F4 狀態更新:入料完成 --')
  550. if F_UP_UltraSoniclist[4] < 110:
  551. F5 = 'F_InputtingBean_Pause'
  552. print('-- F5 狀態更新:入料暫停 --')
  553. else:
  554. F5 = 'F_InputtingBean_Finish'
  555. print('-- F5 狀態更新:入料完成 --')
  556. if F_UP_UltraSoniclist[5] < 110:
  557. F6 = 'F_InputtingBean_Pause'
  558. print('-- F6 狀態更新:入料暫停 --')
  559. else:
  560. F6 = 'F_InputtingBean_Finish'
  561. print('-- F6 狀態更新:入料完成 --')
  562. # ----- 發酵桶槽 F1~F6 入料→入料暫停判斷 ------------------------------
  563. Ferment_InputtingBean_number = int(F_UP_tanklist.count('F_InputtingBean'))
  564. # if FI1 != 'FI_OutputtingBean' and Ferment_InputtingBean_number >= 1:
  565. ### 移到入料
  566. # # ----- 發酵桶槽 F1~F6 入料→入水判斷 ------------------------------
  567. # Ferment_InputtingBeanFinish_number = int(F_UP_tanklist.count('F_InputtingBean_Finish'))
  568. # Ferment_InputtingWater_number = int(F_UP_tanklist.count('F_InputtingWater'))
  569. # # 入水條件:當前桶槽入豆 + 沒有其他桶槽入水
  570. # if Ferment_InputtingBeanFinish_number >= 1 and Ferment_InputtingWater_number == 0:
  571. # # 當入豆到指定高度時, 狀態轉換為入水 (桶槽編號小者優先)
  572. # # !!! 發酵槽 F_InputtingBean_Finish 狀態應該請硬體判斷
  573. # # !!! 若狀態為 F_InputtingBean 且 超音波值>指定生豆高度, 狀態改為 F_InputtingBean_Finish 並等待入水 F_InputtingWater
  574. # # 這邊是考慮一次僅一個桶槽入水, 多桶入水會不會速度變慢?
  575. # if F1 == 'F_InputtingBean_Finish':
  576. # F1 = 'F_InputtingWater'
  577. # print('-- F1 狀態更新:入水中 --')
  578. # elif F2 == 'F_InputtingBean_Finish':
  579. # F2 = 'F_InputtingWater'
  580. # print('-- F2 狀態更新:入水中 --')
  581. # elif F3 == 'F_InputtingBean_Finish':
  582. # F3 = 'F_InputtingWater'
  583. # print('-- F3 狀態更新:入水中 --')
  584. # elif F4 == 'F_InputtingBean_Finish':
  585. # F4 = 'F_InputtingWater'
  586. # print('-- F4 狀態更新:入水中 --')
  587. # elif F5 == 'F_InputtingBean_Finish':
  588. # F5 = 'F_InputtingWater'
  589. # print('-- F5 狀態更新:入水中 --')
  590. # elif F6 == 'F_InputtingBean_Finish':
  591. # F6 = 'F_InputtingWater'
  592. # print('-- F6 狀態更新:入水中 --')
  593. # # ----- 發酵桶槽 F1~F6 入水→發酵判斷 ------------------------------
  594. # # -- 取得發酵桶槽 F1~F6 夾層水位高度 WaterLevel -------------
  595. # F_UP_tank_WaterLevel = []
  596. # for i in range(1, 7, 1):
  597. # tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  598. # WaterLevel = int(tank_WaterLevel.WaterLevel)
  599. # F_UP_tank_WaterLevel.append(WaterLevel)
  600. # print('F_UP_tank_WaterLevel: ', F_UP_tank_WaterLevel)
  601. # # -- 取得發酵桶槽 F1~F6 夾層水位高度 WaterLevel -------------
  602. # # !!! 發酵槽 F_Fermenting 狀態應該請硬體判斷
  603. # # !!! 若狀態為 F_InputtingWater 且 超音波值>指定水位高度 且 夾層水位計 == 1, 狀態改為 F_Fermenting 發酵
  604. # if F1 == 'F_InputtingWater' and F_UP_tank_WaterLevel[0] == 1:
  605. # F1 = 'F_Fermenting'
  606. # print('-- F1 狀態更新:發酵中 --')
  607. # if F2 == 'F_InputtingWater' and F_UP_tank_WaterLevel[1] == 1:
  608. # F2 = 'F_Fermenting'
  609. # print('-- F2 狀態更新:發酵中 --')
  610. # if F3 == 'F_InputtingWater' and F_UP_tank_WaterLevel[2] == 1:
  611. # F3 = 'F_Fermenting'
  612. # print('-- F3 狀態更新:發酵中 --')
  613. # if F4 == 'F_InputtingWater' and F_UP_tank_WaterLevel[3] == 1:
  614. # F4 = 'F_Fermenting'
  615. # print('-- F4 狀態更新:發酵中 --')
  616. # if F5 == 'F_InputtingWater' and F_UP_tank_WaterLevel[4] == 1:
  617. # F5 = 'F_Fermenting'
  618. # print('-- F5 狀態更新:發酵中 --')
  619. # if F6 == 'F_InputtingWater' and F_UP_tank_WaterLevel[5] == 1:
  620. # F6 = 'F_Fermenting'
  621. # print('-- F6 狀態更新:發酵中 --')
  622. # ----- 發酵桶槽 F1~F6 發酵→可出豆 判斷 ------------------------------
  623. # TODO
  624. # !!! 發酵槽 F_Fermenting 狀態應該請硬體判斷
  625. # !!! 若狀態為 F_InputtingWater 且 超音波值>指定水位高度 且 夾層水位計 == 1, 狀態改為 F_Fermenting 發酵
  626. # 可以多桶各自執行發酵排程
  627. # ----- [測試用] !!!!! F1~F6 入料完成→可出豆 判斷 ------------------------------
  628. if F1 == 'F_InputtingBean_Finish': F1 = 'F_OutputtingBean'
  629. if F2 == 'F_InputtingBean_Finish': F2 = 'F_OutputtingBean'
  630. if F3 == 'F_InputtingBean_Finish': F3 = 'F_OutputtingBean'
  631. if F4 == 'F_InputtingBean_Finish': F4 = 'F_OutputtingBean'
  632. if F5 == 'F_InputtingBean_Finish': F5 = 'F_OutputtingBean'
  633. if F6 == 'F_InputtingBean_Finish': F6 = 'F_OutputtingBean'
  634. # ----- [測試用] !!!!! F1~F6 入料完成→可出豆 判斷 ------------------------------
  635. # ----- 發酵桶槽 F1~F6 可出豆→出料儲豆槽 FO1 判斷 ------------------------------
  636. Ferment_OutputtingBean_number = int(F_UP_tanklist.count('F_OutputtingBean'))
  637. # !!! 若出料儲豆槽狀態為 FO_Waiting(空桶等待) 且 桶槽狀態為 F_OutputtingBean 可出豆, 與 FO1 配合開始出豆
  638. if FO1 == 'FO_Waiting' and Ferment_OutputtingBean_number >= 1:
  639. if F1 == 'F_OutputtingBean':
  640. FO1 = 'FO_InputtingBean'
  641. print('-- F1 狀態更新:出豆中 --')
  642. print('-- FO1 狀態更新:入豆中 --')
  643. elif F2 == 'F_OutputtingBean':
  644. FO1 = 'FO_InputtingBean'
  645. print('-- F2 狀態更新:出豆中 --')
  646. print('-- FO1 狀態更新:入豆中 --')
  647. elif F3 == 'F_OutputtingBean':
  648. FO1 = 'FO_InputtingBean'
  649. print('-- F3 狀態更新:出豆中 --')
  650. print('-- FO1 狀態更新:入豆中 --')
  651. elif F4 == 'F_OutputtingBean':
  652. FO1 = 'FO_InputtingBean'
  653. print('-- F4 狀態更新:出豆中 --')
  654. print('-- FO1 狀態更新:入豆中 --')
  655. elif F5 == 'F_OutputtingBean':
  656. FO1 = 'FO_InputtingBean'
  657. print('-- F5 狀態更新:出豆中 --')
  658. print('-- FO1 狀態更新:入豆中 --')
  659. elif F6 == 'F_OutputtingBean':
  660. FO1 = 'FO_InputtingBean'
  661. print('-- F6 狀態更新:出豆中 --')
  662. print('-- FO1 狀態更新:入豆中 --')
  663. # ----- 發酵入料儲豆槽 FI1~FI2 入豆→可出豆判斷 ------------------------------
  664. # -- 取得發酵入料儲豆槽 FI1~FI2 桶內高度 UltraSonic -------------
  665. FI_UP_UltraSoniclist = []
  666. for i in range(1, 3, 1):
  667. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI' + str(i)).order_by(text('datetime desc')).first()
  668. UltraSonic = int(input_UltraSonic.UltraSonic)
  669. FI_UP_UltraSoniclist.append(UltraSonic)
  670. print('FI_UP_UltraSoniclist: ', FI_UP_UltraSoniclist)
  671. # 入料儲豆槽等待中、且脫皮機儲豆槽可出豆時, 入料儲豆槽入豆
  672. if FI1 == 'FI_Waiting' and PO1 == 'PO_OutputtingBean':
  673. FI1 = 'FI_InputtingBean'
  674. print('-- FI1 狀態更新:入豆中 --')
  675. # 入料儲豆槽入豆時 且 (發酵儲豆槽有入料 或者 前方儲豆槽非可出豆), 則停止入豆
  676. elif FI1 == 'FI_InputtingBean' and ((FI_UP_UltraSoniclist[0] > 55) or (PO1 != 'PO_OutputtingBean')) :
  677. FI1 = 'FI_OutputtingBean'
  678. print('-- FI1 狀態更新:可出豆 --')
  679. # 若入料儲豆槽可出豆 且 儲豆槽內高度低於 40 且 前方脫皮機儲豆槽可出豆 且 目前無桶槽需入料時
  680. elif FI1 == 'FI_OutputtingBean' and (FI_UP_UltraSoniclist[0] < 40) and PO1 == 'PO_OutputtingBean' and Ferment_InputtingBean_number == 0 and Ferment_InputtingBeanPause_number == 0:
  681. FI1 = 'FI_InputtingBean'
  682. print('-- FI1 狀態更新:入豆中 --')
  683. # if FI2 == 'FI_Waiting' and PO2 == 'PO_OutputtingBean':
  684. # FI2 = 'FI_InputtingBean'
  685. # print('-- FI2 狀態更新:入豆中 --')
  686. # elif FI2 == 'FI_InputtingBean' and ((FI_UP_UltraSoniclist[1] > 55) or (PO2 != 'PO_OutputtingBean')) :
  687. # FI2 = 'FI_OutputtingBean'
  688. # print('-- FI2 狀態更新:可出豆 --')
  689. # elif FI2 == 'FI_OutputtingBean' and (FI_UP_UltraSoniclist[1] < 40) and PO2 == 'PO_OutputtingBean' and Ferment_InputtingBean_number == 0 and Ferment_InputtingBeanPause_number == 0:
  690. # FI2 = 'FI_InputtingBean'
  691. # print('-- FI2 狀態更新:入豆中 --')
  692. # ----- 發酵出料儲豆槽 FO1~FO2 入豆→可出豆判斷 ------------------------------
  693. # -- 取得發酵出料儲豆槽 FO1~FO2 桶內高度 UltraSonic -------------
  694. FO_UP_UltraSoniclist = []
  695. for i in range(1, 3, 1):
  696. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO' + str(i)).order_by(text('datetime desc')).first()
  697. UltraSonic = int(output_UltraSonic.UltraSonic)
  698. FO_UP_UltraSoniclist.append(UltraSonic)
  699. print('FO_UP_UltraSoniclist: ', FO_UP_UltraSoniclist)
  700. # 桶槽可出豆, 且出料儲豆槽等待時, 出料儲豆槽入豆
  701. # 參考 -- 發酵桶槽 F1~F6 可出豆→出料儲豆槽 FO1 判斷 --
  702. # 出料儲豆槽入料 且滿時, 出料儲豆槽可出豆
  703. if FO1 == ('FO_InputtingBean' and FO_UP_UltraSoniclist[0] > 55):
  704. FO1 = 'FO_OutputtingBean'
  705. # 出料儲豆槽入料 且未滿, 桶槽可出豆已空
  706. # -- 取得發酵桶槽 F1~F6 桶內高度 UltraSonic -------------
  707. F_UP_UltraSoniclist = []
  708. for i in range(1, 7, 1):
  709. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  710. UltraSonic = int(tank_UltraSonic.UltraSonic)
  711. F_UP_UltraSoniclist.append(UltraSonic)
  712. print('F_UP_UltraSoniclist: ', F_UP_UltraSoniclist)
  713. # -- 取得發酵桶槽 F1~F6 桶內高度 UltraSonic -------------
  714. if FO1 == 'FO_InputtingBean' and Ferment_OutputtingBean_number >= 1:
  715. if F1 == 'F_OutputtingBean' and F_UP_UltraSoniclist[0] < 5:
  716. F1 = 'F_Waiting'
  717. FO1 = 'FO_OutputtingBean'
  718. print('-- F1 狀態更新:空桶等待 --')
  719. print('-- FO1 狀態更新:可出豆 --')
  720. elif F2 == 'F_OutputtingBean' and F_UP_UltraSoniclist[1] < 5:
  721. F2 = 'F_Waiting'
  722. FO1 = 'FO_OutputtingBean'
  723. print('-- F2 狀態更新:空桶等待 --')
  724. print('-- FO1 狀態更新:可出豆 --')
  725. elif F3 == 'F_OutputtingBean' and F_UP_UltraSoniclist[2] < 5:
  726. F3 = 'F_Waiting'
  727. FO1 = 'FO_OutputtingBean'
  728. print('-- F3 狀態更新:空桶等待 --')
  729. print('-- FO1 狀態更新:可出豆 --')
  730. elif F4 == 'F_OutputtingBean' and F_UP_UltraSoniclist[3] < 5:
  731. F4 = 'F_Waiting'
  732. FO1 = 'FO_OutputtingBean'
  733. print('-- F4 狀態更新:空桶等待 --')
  734. print('-- FO1 狀態更新:可出豆 --')
  735. elif F5 == 'F_OutputtingBean' and F_UP_UltraSoniclist[4] < 5:
  736. F5 = 'F_Waiting'
  737. FO1 = 'FO_OutputtingBean'
  738. print('-- F5 狀態更新:空桶等待 --')
  739. print('-- FO1 狀態更新:可出豆 --')
  740. elif F6 == 'F_OutputtingBean' and F_UP_UltraSoniclist[5] < 5:
  741. F6 = 'F_Waiting'
  742. FO1 = 'FO_OutputtingBean'
  743. print('-- F6 狀態更新:空桶等待 --')
  744. print('-- FO1 狀態更新:可出豆 --')
  745. elif FO1 == 'FO_OutputtingBean' and FO_UP_UltraSoniclist[0] < 5:
  746. FO1 = 'FO_Waiting'
  747. # ----- 將狀態寫入資料庫 ------------------------------
  748. # 獲取文本框的值並賦值給user實體對象
  749. F_status = ferment_container_status()
  750. F_status.Ferment_Input_1 = FI1
  751. F_status.Ferment_Input_2 = FI2
  752. F_status.Ferment_Tank_1 = F1
  753. F_status.Ferment_Tank_2 = F2
  754. F_status.Ferment_Tank_3 = F3
  755. F_status.Ferment_Tank_4 = F4
  756. F_status.Ferment_Tank_5 = F5
  757. F_status.Ferment_Tank_6 = F6
  758. F_status.Ferment_Tank_7 = F7
  759. F_status.Ferment_Tank_8 = F8
  760. F_status.Ferment_Tank_9 = F9
  761. F_status.Ferment_Tank_10 = F10
  762. F_status.Ferment_Tank_11 = F11
  763. F_status.Ferment_Tank_12 = F12
  764. F_status.Ferment_Output_1 = FO1
  765. F_status.Ferment_Output_2 = FO2
  766. #將數據保存進資料庫
  767. db.session.add(F_status)
  768. # 手動提交
  769. db.session.commit()
  770. # ----- 將狀態寫入資料庫 ------------------------------
  771. return jsonify({"Ferment_Input_1":FI1,
  772. "Ferment_Tank_1":F1,
  773. "Ferment_Tank_2":F2,
  774. "Ferment_Tank_3":F3,
  775. "Ferment_Tank_4":F4,
  776. "Ferment_Tank_5":F5,
  777. "Ferment_Tank_6":F6,
  778. "Ferment_Output_1":FO1
  779. })
  780. '''
  781. return jsonify({"Ferment_Input_1":FI1,
  782. "Ferment_Input_2":FI2,
  783. "Ferment_Tank_1":F1,
  784. "Ferment_Tank_2":F2,
  785. "Ferment_Tank_3":F3,
  786. "Ferment_Tank_4":F4,
  787. "Ferment_Tank_5":F5,
  788. "Ferment_Tank_6":F6,
  789. "Ferment_Tank_7":F7,
  790. "Ferment_Tank_8":F8,
  791. "Ferment_Tank_9":F9,
  792. "Ferment_Tank_10":F10,
  793. "Ferment_Tank_11":F11,
  794. "Ferment_Tank_12":F12,
  795. "Ferment_Output_1":FO1,
  796. "Ferment_Output_2":FO2
  797. })
  798. '''
  799. # 舊有 video 介面
  800. @main.route('/video')
  801. def main_video():
  802. # 獲取登入信息
  803. if 'id' in session and 'uname' in session and 'status' in session:
  804. username = session['uname']
  805. status = session['status']
  806. if status == 9:
  807. return render_template('signin_disable.html', params=locals())
  808. if status == 8:
  809. return render_template('signin_new.html', params=locals())
  810. return render_template('video.html', params=locals())
  811. else:
  812. return render_template('sign_in.html')
  813. @main.route('/index_navbar', methods=['GET'])
  814. def index_navbar():
  815. return render_template('index_navbar.html')
  816. @main.route('/camera_dry', methods=['GET', 'POST'])
  817. def camera_dry():
  818. if request.method == 'GET':
  819. if 'id' in session and 'uname' in session and 'status' in session:
  820. username = session['uname']
  821. status = session['status']
  822. if status == 9:
  823. return render_template('signin_disable.html', params=locals())
  824. if status == 8:
  825. return render_template('signin_new.html', params=locals())
  826. return render_template('camera_dry.html', title='乾燥貨櫃攝影機', **locals())
  827. else:
  828. return render_template('sign_in.html')
  829. @main.route('/camera_ferment', methods=['GET', 'POST'])
  830. def camera_ferment():
  831. if request.method == 'GET':
  832. if 'id' in session and 'uname' in session and 'status' in session:
  833. username = session['uname']
  834. status = session['status']
  835. if status == 9:
  836. return render_template('signin_disable.html', params=locals())
  837. if status == 8:
  838. return render_template('signin_new.html', params=locals())
  839. return render_template('camera_ferment.html', title='發酵貨櫃攝影機', **locals())
  840. else:
  841. return render_template('sign_in.html')
  842. @main.route('/camera_clean', methods=['GET', 'POST'])
  843. def camera_clean():
  844. if request.method == 'GET':
  845. if 'id' in session and 'uname' in session and 'status' in session:
  846. username = session['uname']
  847. status = session['status']
  848. if status == 9:
  849. return render_template('signin_disable.html', params=locals())
  850. if status == 8:
  851. return render_template('signin_new.html', params=locals())
  852. return render_template('camera_clean.html', title='清洗貨櫃攝影機', **locals())
  853. else:
  854. return render_template('sign_in.html')
  855. @main.route('/camera_dry_1', methods=['GET', 'POST'])
  856. def camera_dry_2():
  857. if request.method == 'GET':
  858. return render_template('camera_dry_1.html', title='乾燥貨櫃攝影機', **locals())
  859. @main.route('/camera_<tid>', methods=['GET', 'POST'])
  860. def camera(tid):
  861. if request.method == 'GET':
  862. if 'id' in session and 'uname' in session and 'status' in session:
  863. username = session['uname']
  864. status = session['status']
  865. if status == 9:
  866. return render_template('signin_disable.html', params=locals())
  867. if status == 8:
  868. return render_template('signin_new.html', params=locals())
  869. if tid == 'CCargo_in':
  870. WS_URL = 'ws:///60.250.156.230:1111'
  871. camera_title = '清洗貨櫃內部'
  872. return render_template('camera.html', title='[畫面]' + camera_title, **locals())
  873. elif tid == 'CCargo_out':
  874. WS_URL = 'ws:///60.250.156.230:1111'
  875. camera_title = '清洗貨櫃外部'
  876. return render_template('camera.html', title='[畫面]' + camera_title, **locals())
  877. elif tid == 'FCargo_in':
  878. WS_URL = 'ws:///60.250.156.230:1111'
  879. camera_title = '發酵貨櫃內部'
  880. return render_template('camera.html', title='[畫面]' + camera_title, **locals())
  881. elif tid == 'FCargo_out':
  882. WS_URL = 'ws:///60.250.156.230:1111'
  883. camera_title = '發酵貨櫃外部'
  884. return render_template('camera.html', title='[畫面]' + camera_title, **locals())
  885. elif tid == 'DCargo_in':
  886. WS_URL = 'ws:///60.250.156.230:1111'
  887. camera_title = '乾燥貨櫃內部'
  888. return render_template('camera.html', title='[畫面]' + camera_title, **locals())
  889. elif tid == 'DCargo_out':
  890. WS_URL = 'ws:///60.250.156.230:1111'
  891. camera_title = '乾燥貨櫃外部'
  892. return render_template('camera.html', title='[畫面]' + camera_title, **locals())
  893. elif tid[:2] == 'DO':
  894. WS_URL_list = ['ws:///60.250.156.230:1111',
  895. 'ws:///60.250.156.230:2222'
  896. ]
  897. WS_URL = WS_URL_list[int(tid[2:])-1]
  898. camera_title = '乾燥出料儲豆槽'
  899. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  900. elif tid[:2] == 'DI':
  901. WS_URL_list = ['ws:///60.250.156.230:1111',
  902. 'ws:///60.250.156.230:2222'
  903. ]
  904. WS_URL = WS_URL_list[int(tid[2:])-1]
  905. camera_title = '乾燥入料儲豆槽'
  906. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  907. elif tid[:1] == 'D':
  908. WS_URL_list = ['ws:///60.250.156.230:8093', # D1 攝影機已安裝
  909. 'ws:///60.250.156.230:2222',
  910. 'ws:///60.250.156.230:3333',
  911. 'ws:///60.250.156.230:4444',
  912. 'ws:///60.250.156.230:5555',
  913. 'ws:///60.250.156.230:6666',
  914. 'ws:///60.250.156.230:7777',
  915. 'ws:///60.250.156.230:8888',
  916. 'ws:///60.250.156.230:9999',
  917. 'ws:///60.250.156.230:1010',
  918. 'ws:///60.250.156.230:1111',
  919. 'ws:///60.250.156.230:1212'
  920. ]
  921. WS_URL = WS_URL_list[int(tid[1:])-1]
  922. camera_title = '乾燥槽'
  923. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  924. elif tid[:2] == 'FO':
  925. WS_URL_list = ['ws:///60.250.156.230:1111',
  926. 'ws:///60.250.156.230:2222'
  927. ]
  928. WS_URL = WS_URL_list[int(tid[2:])-1]
  929. camera_title = '發酵出料儲豆槽'
  930. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  931. elif tid[:2] == 'FI':
  932. WS_URL_list = ['ws:///60.250.156.230:1111',
  933. 'ws:///60.250.156.230:2222'
  934. ]
  935. WS_URL = WS_URL_list[int(tid[2:])-1]
  936. camera_title = '發酵入料儲豆槽'
  937. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  938. elif tid[:1] == 'F':
  939. WS_URL_list = ['ws:///60.250.156.230:8089', # F1 攝影機已安裝
  940. 'ws:///60.250.156.230:2222',
  941. 'ws:///60.250.156.230:3333',
  942. 'ws:///60.250.156.230:4444',
  943. 'ws:///60.250.156.230:5555',
  944. 'ws:///60.250.156.230:6666',
  945. 'ws:///60.250.156.230:7777',
  946. 'ws:///60.250.156.230:8888',
  947. 'ws:///60.250.156.230:9999',
  948. 'ws:///60.250.156.230:1010',
  949. 'ws:///60.250.156.230:1111',
  950. 'ws:///60.250.156.230:1212'
  951. ]
  952. WS_URL = WS_URL_list[int(tid[1:])-1]
  953. camera_title = '發酵槽'
  954. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  955. elif tid[:2] == 'CO':
  956. WS_URL_list = ['ws:///60.250.156.230:1111',
  957. 'ws:///60.250.156.230:2222'
  958. ]
  959. WS_URL = WS_URL_list[int(tid[2:])-1]
  960. camera_title = '清洗浮選出料儲豆槽'
  961. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  962. elif tid[:1] == 'C':
  963. WS_URL_list = ['ws:///60.250.156.230:8088', # C1 攝影機已安裝
  964. 'ws:///60.250.156.230:2222'
  965. ]
  966. WS_URL = WS_URL_list[int(tid[1:])-1]
  967. camera_title = '清洗浮選槽'
  968. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  969. elif tid[:2] == 'SO':
  970. WS_URL_list = ['ws:///60.250.156.230:1111',
  971. 'ws:///60.250.156.230:2222'
  972. ]
  973. WS_URL = WS_URL_list[int(tid[2:])-1]
  974. camera_title = '色選機出料儲豆槽'
  975. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  976. elif tid[:1] == 'S':
  977. WS_URL_list = ['ws:///60.250.156.230:1111',
  978. 'ws:///60.250.156.230:2222'
  979. ]
  980. WS_URL = WS_URL_list[int(tid[1:])-1]
  981. camera_title = '色選機'
  982. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  983. elif tid[:2] == 'PO':
  984. WS_URL_list = ['ws:///60.250.156.230:1111',
  985. 'ws:///60.250.156.230:2222'
  986. ]
  987. WS_URL = WS_URL_list[int(tid[2:])-1]
  988. camera_title = '脫皮機出料儲豆槽'
  989. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  990. elif tid[:1] == 'P':
  991. WS_URL_list = ['ws:///60.250.156.230:1111',
  992. 'ws:///60.250.156.230:2222'
  993. ]
  994. WS_URL = WS_URL_list[int(tid[1:])-1]
  995. camera_title = '脫皮機'
  996. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  997. else:
  998. return render_template('sign_in.html')
  999. else:
  1000. pass
  1001. @main.route('/dry_SHT11_<dtid>', methods=['GET', 'POST'])
  1002. def dry_SHT11(dtid):
  1003. if request.method == 'GET':
  1004. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D' + dtid).order_by(text('datetime desc')).first()
  1005. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D' + dtid).order_by(text('datetime desc')).first()
  1006. SHT11_Temp = tank_SHT11.SHT11_Temp
  1007. SHT11_Humidity = tank_SHT11.SHT11_Humidity
  1008. Soil_Temp = tank_Soil.soil_Temp
  1009. return jsonify({"SHT11_Temp":SHT11_Temp,
  1010. "SHT11_Humidity":SHT11_Humidity,
  1011. "Soil_Temp":Soil_Temp
  1012. })
  1013. else:
  1014. pass
  1015. @main.route('/dry_UltraSonic_<dtid>', methods=['GET', 'POST'])
  1016. def dry_UltraSonic(dtid):
  1017. if request.method == 'GET':
  1018. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D' + dtid).order_by(text('datetime desc')).first()
  1019. UltraSonic = tank_UltraSonic.UltraSonic
  1020. return jsonify({"UltraSonic":UltraSonic
  1021. })
  1022. else:
  1023. pass
  1024. @main.route('/dry_input_UltraSonic_<dtid>', methods=['GET', 'POST'])
  1025. def dry_input_UltraSonic(dtid):
  1026. if request.method == 'GET':
  1027. input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI' + dtid).order_by(text('datetime desc')).first()
  1028. UltraSonic = input_UltraSonic.UltraSonic
  1029. return jsonify({"UltraSonic":UltraSonic
  1030. })
  1031. else:
  1032. pass
  1033. @main.route('/dry_output_UltraSonic_<dtid>', methods=['GET', 'POST'])
  1034. def dry_output_UltraSonic(dtid):
  1035. if request.method == 'GET':
  1036. output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO' + dtid).order_by(text('datetime desc')).first()
  1037. UltraSonic = output_UltraSonic.UltraSonic
  1038. return jsonify({"UltraSonic":UltraSonic
  1039. })
  1040. else:
  1041. pass
  1042. @main.route('/ferment_SHT11_<ftid>', methods=['GET', 'POST'])
  1043. def ferment_SHT11(ftid):
  1044. if request.method == 'GET':
  1045. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  1046. SHT11_Temp = tank_SHT11.SHT11_Temp
  1047. return jsonify({"SHT11_Temp":SHT11_Temp
  1048. })
  1049. else:
  1050. pass
  1051. @main.route('/ferment_WaterLevel_<ftid>', methods=['GET', 'POST'])
  1052. def ferment_WaterLevel(ftid):
  1053. if request.method == 'GET':
  1054. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  1055. WaterLevel = tank_WaterLevel.WaterLevel
  1056. return jsonify({"WaterLevel":WaterLevel
  1057. })
  1058. else:
  1059. pass
  1060. @main.route('/ferment_WaterIn_<ftid>', methods=['GET', 'POST'])
  1061. def ferment_WaterIn(ftid):
  1062. if request.method == 'GET':
  1063. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  1064. UltraSonic = tank_UltraSonic.UltraSonic
  1065. # tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  1066. # PressureWaterLevel = '{:.2f}'.format((float(tank_PressureWaterLevel.PressureWaterLevel) -15 -90.278)/9.4214)
  1067. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  1068. WaterLevel = tank_WaterLevel.WaterLevel
  1069. return jsonify({"UltraSonic":UltraSonic,
  1070. "WaterLevel":WaterLevel
  1071. })
  1072. else:
  1073. pass
  1074. @main.route('/ferment_UltraSonic_<ftid>', methods=['GET', 'POST'])
  1075. def ferment_UltraSonic(ftid):
  1076. if request.method == 'GET':
  1077. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  1078. UltraSonic = tank_UltraSonic.UltraSonic
  1079. return jsonify({"UltraSonic":UltraSonic
  1080. })
  1081. else:
  1082. pass
  1083. '''
  1084. @main.route('/ferment_LiDAR_<ftid>', methods=['GET', 'POST'])
  1085. def ferment_LiDAR(ftid):
  1086. if request.method == 'GET':
  1087. tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  1088. LiDAR = tank_LiDAR.LiDAR
  1089. return jsonify({"LiDAR":LiDAR
  1090. })
  1091. else:
  1092. pass
  1093. '''
  1094. @main.route('/ferment_input_UltraSonic_<ftid>', methods=['GET', 'POST'])
  1095. def ferment_input_UltraSonic_(ftid):
  1096. if request.method == 'GET':
  1097. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI' + ftid).order_by(text('datetime desc')).first()
  1098. UltraSonic = input_UltraSonic.UltraSonic
  1099. return jsonify({"UltraSonic":UltraSonic
  1100. })
  1101. else:
  1102. pass
  1103. @main.route('/ferment_output_UltraSonic_<ftid>', methods=['GET', 'POST'])
  1104. def ferment_output_UltraSonic_(ftid):
  1105. if request.method == 'GET':
  1106. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO' + ftid).order_by(text('datetime desc')).first()
  1107. UltraSonic = output_UltraSonic.UltraSonic
  1108. return jsonify({"UltraSonic":UltraSonic
  1109. })
  1110. else:
  1111. pass
  1112. @main.route('/ferment_watertesting_<tid>', methods=['GET', 'POST'])
  1113. def ferment_watertesting(tid):
  1114. if request.method == 'GET':
  1115. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  1116. tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  1117. tank_DO = ferment_tank_DO.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  1118. tank_EC = ferment_tank_EC.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  1119. PH = tank_PH.PH
  1120. ORP = tank_ORP.ORP
  1121. DO = tank_DO.DO
  1122. EC = tank_EC.EC
  1123. return jsonify({"PH":PH,
  1124. "ORP":ORP,
  1125. "DO":DO,
  1126. "EC":EC,
  1127. })
  1128. '''
  1129. @main.route('/ferment_PressureWaterLevel_<ftid>', methods=['GET', 'POST'])
  1130. def ferment_PressureWaterLevel(ftid):
  1131. if request.method == 'GET':
  1132. tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  1133. PressureWaterLevel = float(tank_PressureWaterLevel.PressureWaterLevel)
  1134. #PressureWaterLevel = '{:.2f}'.format((float(tank_PressureWaterLevel.PressureWaterLevel) -15 -90.278)/9.4214)
  1135. print("PressureWaterLevel_start: ", PressureWaterLevel)
  1136. return jsonify({"PressureWaterLevel":PressureWaterLevel
  1137. })
  1138. # 此段刪除
  1139. while int(PressureWaterLevel) < int(testing_water_height):
  1140. tank_water_status = 'NO'
  1141. time.sleep(3)
  1142. # print(ferment_water_height(testing_water_height))
  1143. # [目前桶內水位高度]發酵槽_感測器_壓力式水位計
  1144. tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
  1145. PressureWaterLevel = tank_PressureWaterLevel.PressureWaterLevel
  1146. print("-- MySQL --")
  1147. print("tank_PressureWaterLevel: ", tank_PressureWaterLevel)
  1148. # tank_water_height()
  1149. # print("PressureWaterLevel_while: ", PressureWaterLevel)
  1150. ferment_water_height(testing_water_height)
  1151. return jsonify({"testing_water_height":testing_water_height,
  1152. "tank_water_status":tank_water_status
  1153. })
  1154. else:
  1155. tank_water_status = 'OK'
  1156. print("PressureWaterLevel_else: ", PressureWaterLevel)
  1157. return jsonify({"testing_water_height":testing_water_height,
  1158. "tank_water_status":tank_water_status
  1159. })
  1160. '''
  1161. '''
  1162. def tank_water_height():
  1163. tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
  1164. PressureWaterLevel = tank_PressureWaterLevel.PressureWaterLevel
  1165. print("tank_water_height", PressureWaterLevel)
  1166. return PressureWaterLevel
  1167. '''
  1168. @main.route('/loading/SO<sotid>', methods=['GET', 'POST'])
  1169. def SO_loading(sotid):
  1170. if request.method == 'GET':
  1171. # 制動器_脫皮機_ALL
  1172. output_actuator = colorselect_output_actuator.query.filter_by(tank_num='SO'+sotid).order_by(text('datetime desc')).first()
  1173. output_vacuum = output_actuator.vacuum
  1174. return jsonify({"output_vacuum":output_vacuum
  1175. })
  1176. else:
  1177. pass
  1178. @main.route('/loading/S<stid>', methods=['GET', 'POST'])
  1179. def S_loading(stid):
  1180. if request.method == 'GET':
  1181. # 色選機
  1182. return
  1183. else:
  1184. pass
  1185. @main.route('/loading/PO<potid>', methods=['GET', 'POST'])
  1186. def PO_loading(potid):
  1187. if request.method == 'GET':
  1188. # 制動器_脫皮機_ALL
  1189. output_actuator = peel_output_actuator.query.filter_by(tank_num='PO'+potid).order_by(text('datetime desc')).first()
  1190. output_vacuum = output_actuator.vacuum
  1191. return jsonify({"output_vacuum":output_vacuum
  1192. })
  1193. else:
  1194. pass
  1195. @main.route('/loading/P<ptid>', methods=['GET', 'POST'])
  1196. def P_loading(ptid):
  1197. if request.method == 'GET':
  1198. # 制動器_脫皮機_ALL
  1199. tank_actuator = peel_tank_actuator.query.filter_by(tank_num='P'+ptid).order_by(text('datetime desc')).first()
  1200. tank_vacuum = tank_actuator.vacuum
  1201. tank_motor = tank_actuator.motor
  1202. return jsonify({"tank_vacuum":tank_vacuum,
  1203. "tank_motor":tank_motor})
  1204. else:
  1205. pass
  1206. @main.route('/loading/CO<cotid>', methods=['GET', 'POST'])
  1207. def CO_loading(cotid):
  1208. if request.method == 'GET':
  1209. output_actuator = clean_output_actuator.query.filter_by(tank_num='CO'+cotid).order_by(text('datetime desc')).first()
  1210. output_vacuum = output_actuator.vacuum
  1211. return jsonify({"output_vacuum":output_vacuum
  1212. })
  1213. else:
  1214. pass
  1215. @main.route('/loading/C<ctid>', methods=['GET', 'POST'])
  1216. def C_loading(ctid):
  1217. if request.method == 'GET':
  1218. # 制動器_浮選清洗_ALL
  1219. tank_actuator = clean_tank_actuator.query.filter_by(tank_num='C'+ctid).order_by(text('datetime desc')).first()
  1220. tank_vacuum = tank_actuator.vacuum
  1221. tank_pump_waterInput = tank_actuator.pump_waterInput
  1222. tank_pump_waterL2L3 = tank_actuator.pump_waterL2L3
  1223. tank_pump_waterL4L5 = tank_actuator.pump_waterL4L5
  1224. tank_solenoid_waterL2L3 = tank_actuator.solenoid_waterL2L3
  1225. tank_solenoid_waterL4L5 = tank_actuator.solenoid_waterL4L5
  1226. tank_stepping_motor = tank_actuator.stepping_motor
  1227. print('tank_stepping_motor:', tank_stepping_motor)
  1228. # 感測器_浮選清洗_超音波感測器
  1229. tank_UltraSonic = clean_tank_UltraSonic.query.filter_by(tank_num='C'+ctid).order_by(text('datetime desc')).first()
  1230. UltraSonic= tank_UltraSonic.UltraSonic
  1231. return jsonify({"UltraSonic":UltraSonic,
  1232. "tank_vacuum":tank_vacuum,
  1233. "tank_pump_waterInput":tank_pump_waterInput,
  1234. "tank_pump_waterL2L3":tank_pump_waterL2L3,
  1235. "tank_pump_waterL4L5":tank_pump_waterL4L5,
  1236. "tank_solenoid_waterL2L3":tank_solenoid_waterL2L3,
  1237. "tank_solenoid_waterL4L5":tank_solenoid_waterL4L5,
  1238. "tank_stepping_motor":tank_stepping_motor
  1239. })
  1240. else:
  1241. pass
  1242. @main.route('/loading/F<ftid>', methods=['GET', 'POST'])
  1243. def F_loading(ftid):
  1244. if request.method == 'GET':
  1245. # 制動器_發酵槽_ALL
  1246. tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  1247. tank_vacuum = tank_actuator.vacuum
  1248. tank_threewayvalve_input = tank_actuator.threewayvalve_input
  1249. tank_diskvalve = tank_actuator.diskvalve
  1250. tank_solenoid_water_total = tank_actuator.solenoid_tank_water_total
  1251. tank_solenoid_disinfect = tank_actuator.solenoid_tank_disinfect
  1252. outer_solenoid_water = tank_actuator.solenoid_outer_water
  1253. tank_solenoid_water_in = tank_actuator.solenoid_tank_water_in
  1254. tank_pump_sensor = tank_actuator.pump_sensor
  1255. tank_threewayvalve_bean = tank_actuator.threewayvalve_bean
  1256. outer_threewayvalve_float = tank_actuator.threewayvalve_outer_float
  1257. tank_motor = tank_actuator.motor
  1258. tank_heater1 = tank_actuator.heater1
  1259. tank_heater2 = tank_actuator.heater2
  1260. tank_temp_enable = tank_actuator.temp_enable
  1261. tank_temp = tank_actuator.temp
  1262. # 感測器_發酵桶_SHT11
  1263. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  1264. SHT11_Temp = float(tank_SHT11.SHT11_Temp)
  1265. SHT11_Humidity = float(tank_SHT11.SHT11_Humidity)
  1266. # 感測器_發酵桶_二氧化碳
  1267. tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  1268. CO2 = float(tank_CO2.CO2)
  1269. # 感測器_發酵桶_酸鹼值
  1270. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  1271. tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  1272. tank_DO = ferment_tank_DO.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  1273. tank_EC = ferment_tank_EC.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  1274. PH = float(tank_PH.PH)
  1275. ORP = float(tank_ORP.ORP)
  1276. DO = float(tank_DO.DO)
  1277. EC = float(tank_EC.EC)
  1278. # 感測器_發酵桶_氣壓
  1279. tank_PA = ferment_tank_PA.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  1280. PA = float(tank_PA.PA)
  1281. # 感測器_發酵桶_超音波感測器
  1282. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  1283. UltraSonic= int(tank_UltraSonic.UltraSonic)
  1284. # 感測器_發酵桶_保溫夾層水位計
  1285. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  1286. WaterLevel = tank_WaterLevel.WaterLevel
  1287. # 感測器_發酵桶_咖啡生豆高度
  1288. # tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  1289. # LiDAR = tank_LiDAR.LiDAR
  1290. # 感測器_發酵桶_水位高度
  1291. # tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  1292. # PressureWaterLevel = '{:.2f}'.format((float(tank_PressureWaterLevel.PressureWaterLevel) -15 -90.278)/9.4214)
  1293. return jsonify({"SHT11_Temp": SHT11_Temp,
  1294. "SHT11_Humidity":SHT11_Humidity,
  1295. "CO2":CO2,
  1296. "PH":PH,
  1297. "ORP":ORP,
  1298. "DO":DO,
  1299. "EC":EC,
  1300. "PA":PA,
  1301. "WaterLevel":WaterLevel,
  1302. "UltraSonic":UltraSonic,
  1303. "tank_vacuum":tank_vacuum,
  1304. "tank_threewayvalve_input":tank_threewayvalve_input,
  1305. "tank_diskvalve":tank_diskvalve,
  1306. "tank_solenoid_water_total":tank_solenoid_water_total,
  1307. "tank_solenoid_disinfect":tank_solenoid_disinfect,
  1308. "outer_solenoid_water":outer_solenoid_water,
  1309. "tank_solenoid_water_in":tank_solenoid_water_in,
  1310. "tank_pump_sensor":tank_pump_sensor,
  1311. "tank_threewayvalve_bean":tank_threewayvalve_bean,
  1312. "outer_threewayvalve_float":outer_threewayvalve_float,
  1313. "tank_motor":tank_motor,
  1314. "tank_heater1":tank_heater1,
  1315. "tank_heater2":tank_heater2,
  1316. "tank_temp_enable":tank_temp_enable,
  1317. "tank_temp":tank_temp
  1318. })
  1319. else:
  1320. pass
  1321. @main.route('/loading/FI<fitid>', methods=['GET', 'POST'])
  1322. def FI_loading(fitid):
  1323. if request.method == 'GET':
  1324. input_actuator = ferment_input_actuator.query.filter_by(tank_num='FI'+fitid).order_by(text('datetime desc')).first()
  1325. input_vacuum = input_actuator.vacuum
  1326. input_sensor = ferment_input_UltraSonic.query.filter_by(tank_num='FI'+fitid).order_by(text('datetime desc')).first()
  1327. input_UltraSonic = input_sensor.UltraSonic
  1328. return jsonify({"input_UltraSonic":input_UltraSonic,
  1329. "input_vacuum":input_vacuum
  1330. })
  1331. else:
  1332. pass
  1333. @main.route('/loading/FO<fotid>', methods=['GET', 'POST'])
  1334. def FO_loading(fotid):
  1335. if request.method == 'GET':
  1336. output_actuator = ferment_output_actuator.query.filter_by(tank_num='FO'+fotid).order_by(text('datetime desc')).first()
  1337. output_vacuum = output_actuator.vacuum
  1338. output_sensor = ferment_output_UltraSonic.query.filter_by(tank_num='FO'+fotid).order_by(text('datetime desc')).first()
  1339. output_UltraSonic = output_sensor.UltraSonic
  1340. tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+fotid).order_by(text('datetime desc')).first()
  1341. LiDAR = tank_LiDAR.LiDAR
  1342. return jsonify({"output_UltraSonic":output_UltraSonic,
  1343. "output_vacuum":output_vacuum,
  1344. "LiDAR":LiDAR
  1345. })
  1346. else:
  1347. pass
  1348. @main.route('/loading/DI<ditid>', methods=['GET', 'POST'])
  1349. def DI_loading(ditid):
  1350. if request.method == 'GET':
  1351. input_actuator = dry_input_brake.query.filter_by(tank_num='DI'+ditid).order_by(text('datetime desc')).first()
  1352. input_vacuum = input_actuator.vacuum
  1353. input_sensor = dry_input_sensor.query.filter_by(tank_num='DI'+ditid).order_by(text('datetime desc')).first()
  1354. input_UltraSonic = input_sensor.UltraSonic
  1355. return jsonify({"input_UltraSonic":input_UltraSonic,
  1356. "input_vacuum":input_vacuum
  1357. })
  1358. else:
  1359. pass
  1360. @main.route('/loading/DO<dotid>', methods=['GET', 'POST'])
  1361. def DO_loading(dotid):
  1362. if request.method == 'GET':
  1363. output_actuator = dry_output_brake.query.filter_by(tank_num='DO'+dotid).order_by(text('datetime desc')).first()
  1364. output_vacuum = output_actuator.vacuum
  1365. output_sensor = dry_output_sensor.query.filter_by(tank_num='DO'+dotid).order_by(text('datetime desc')).first()
  1366. output_UltraSonic = output_sensor.UltraSonic
  1367. return jsonify({"output_vacuum":output_vacuum,
  1368. "output_UltraSonic":output_UltraSonic
  1369. })
  1370. else:
  1371. pass
  1372. @main.route('/loading/D<dtid>', methods=['GET', 'POST'])
  1373. def D_loading(dtid):
  1374. if request.method == 'GET':
  1375. # 感測器_乾燥桶_超音波感測器
  1376. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  1377. UltraSonic = tank_UltraSonic.UltraSonic
  1378. # 感測器_乾燥桶_SHT11
  1379. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  1380. SHT11_Temp = tank_SHT11.SHT11_Temp
  1381. SHT11_Humidity = tank_SHT11.SHT11_Humidity
  1382. # 感測器_乾燥桶_土壤三合一
  1383. tank_Soil = dry_tank_Soil.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  1384. soil_Temp = tank_Soil.soil_Temp
  1385. soil_Humidity = tank_Soil.soil_Humidity
  1386. soil_EC = tank_Soil.soil_EC
  1387. # 感測器_乾燥桶_氣壓
  1388. tank_PA = dry_tank_PA.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  1389. PA = tank_PA.PA
  1390. # 制動器_乾燥桶_ALL
  1391. tank_brake = dry_tank_brake.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  1392. # tank_vacuum = 'ON' if i<100 else 2 if i>100 else 0
  1393. tank_vacuum = tank_brake.vacuum
  1394. tank_threewayvalve = tank_brake.threewayvalve
  1395. tank_diskvalve = tank_brake.diskvalve
  1396. tank_solenoid_disinfect = tank_brake.solenoid_disinfect
  1397. tank_solenoid_water = tank_brake.solenoid_water
  1398. tank_motor = tank_brake.motor
  1399. tank_blower = tank_brake.blower
  1400. tank_heater1 = tank_brake.heater1
  1401. tank_heater2 = tank_brake.heater2
  1402. tank_temp1_enable = tank_brake.temp1_enable
  1403. tank_temp1 = tank_brake.temp1
  1404. #return jsonify({"peeling": peeling_rpm})
  1405. '''
  1406. info = psutil.virtual_memory()
  1407. print('記憶體使用: ', psutil.Process(os.getpid()).memory_info().rss)
  1408. # print('總記憶體: ', info.total)
  1409. print('記憶體占比: ', info.percent)
  1410. print('cpu 個數: ', psutil.cpu_count())
  1411. '''
  1412. return jsonify({"UltraSonic":UltraSonic,
  1413. "SHT11_Temp": SHT11_Temp,
  1414. "SHT11_Humidity":SHT11_Humidity,
  1415. "soil_Temp":soil_Temp,
  1416. "soil_Humidity":soil_Humidity,
  1417. "soil_EC":soil_EC,
  1418. "PA":PA,
  1419. "tank_vacuum":tank_vacuum,
  1420. "tank_threewayvalve":tank_threewayvalve,
  1421. "tank_diskvalve":tank_diskvalve,
  1422. "tank_solenoid_disinfect":tank_solenoid_disinfect,
  1423. "tank_solenoid_water":tank_solenoid_water,
  1424. "tank_motor":tank_motor,
  1425. "tank_blower":tank_blower,
  1426. "tank_heater1":tank_heater1,
  1427. "tank_heater2":tank_heater2,
  1428. "tank_temp1_enable":tank_temp1_enable,
  1429. "tank_temp1":tank_temp1
  1430. })
  1431. else:
  1432. pass
  1433. @main.route('/index_new')
  1434. def index_new():
  1435. if 'id' in session and 'uname' in session and 'status' in session:
  1436. username = session['uname']
  1437. status = session['status']
  1438. if status == 9:
  1439. return render_template('signin_disable.html', **locals())
  1440. elif status == 8:
  1441. return render_template('signin_new.html', **locals())
  1442. else:
  1443. return render_template('oops.html', **locals())
  1444. return render_template('index_new.html', title='Smart Coffee', **locals())
  1445. @main.route('/user/<name>')
  1446. def user(name):
  1447. return render_template('hello.html', name=name)
  1448. '''
  1449. @main.route('/plot.png')
  1450. def plot():
  1451. # 重新整理會有問題
  1452. # 圖的寬和高
  1453. fig = plt.figure()
  1454. # 在圖中新增子圖, 通常多個圖才會用到?
  1455. axis = fig.add_subplot(1, 1, 1)
  1456. # x、 軸資料
  1457. xs = range(100)
  1458. ys = [random.randint(1, 50) for x in xs]
  1459. axis.plot(xs, ys)
  1460. canvas = FigureCanvas(fig)
  1461. output = io.BytesIO()
  1462. canvas.print_png(output)
  1463. response = make_response(output.getvalue())
  1464. response.mimetype = 'image/png'
  1465. return response
  1466. '''
  1467. @main.route('/chart_<tank>/<sensor_name>/<tid>', methods=['GET', 'POST'])
  1468. def chart_D(tank, sensor_name, tid):
  1469. if request.method == 'GET':
  1470. if 'id' in session and 'uname' in session and 'status' in session:
  1471. username = session['uname']
  1472. status = session['status']
  1473. if status == 9:
  1474. return render_template('signin_disable.html', params=locals())
  1475. elif status == 8:
  1476. return render_template('signin_new.html', params=locals())
  1477. else:
  1478. return render_template('oops.html', params=locals())
  1479. if tank == 'DI':
  1480. return render_template('sensor_chart_DI.html', title='[圖表]' + tank + tid + '乾燥入料儲豆槽', **locals())
  1481. elif tank == 'DO':
  1482. return render_template('sensor_chart_DO.html', title='[圖表]' + tank + tid + '乾燥出料儲豆槽', **locals())
  1483. elif tank == 'FI':
  1484. return render_template('sensor_chart_FI.html', title='[圖表]' + tank + tid + '發酵入料儲豆槽', **locals())
  1485. elif tank == 'FO':
  1486. return render_template('sensor_chart_FO.html', title='[圖表]' + tank + tid + '發酵出料儲豆槽', **locals())
  1487. elif tank == 'F':
  1488. return render_template('sensor_chart_F.html', title='[圖表]' + tank + tid + '發酵槽', **locals())
  1489. else:
  1490. return render_template('sensor_chart_D.html', title='[圖表]' + tank + tid + '乾燥槽', **locals())
  1491. elif request.method == 'POST':
  1492. if 'id' in session and 'uname' in session and 'status' in session:
  1493. username = session['uname']
  1494. status = session['status']
  1495. if status == 9:
  1496. return render_template('signin_disable.html', params=locals())
  1497. elif status == 8:
  1498. return render_template('signin_new.html', params=locals())
  1499. else:
  1500. return render_template('oops.html', params=locals())
  1501. starttime = request.values['sensor_starttime'] # 2021-07-19T09:00
  1502. endtime = request.values['sensor_endtime'] # 2021-07-19T12:00
  1503. sensor_name = request.values['sensors']
  1504. print('sensor_name:', sensor_name)
  1505. # 判斷資料索取區間 起<迄
  1506. if starttime < endtime :
  1507. # print('starttime endtime:', starttime, endtime)
  1508. # print('TF:', starttime<endtime ) # 可以比較 起<迄
  1509. # [html]2021-07-19T09:00 轉換成 [python]datetime.datetime(2021, 7, 19, 9, 0, 0)
  1510. start_YY = starttime[:4] # '2021'
  1511. start_MM = starttime[6:7] if starttime[5:7][:1] == '0' else starttime[5:7] # '07'
  1512. start_DD = starttime[9:10] if starttime[8:10][:1] == '0' else starttime[8:10] # '19'
  1513. start_hh = starttime[12:13] if starttime[11:13][:1] == '0' else starttime[11:13] # '09'
  1514. start_mm = starttime[15:] if starttime[14:][:1] == '0' else starttime[14:] # '00'
  1515. start_ss = 0
  1516. end_YY = endtime[:4] # '2021'
  1517. end_MM = endtime[6:7] if endtime[5:7][:1] == '0' else endtime[5:7] # '07'
  1518. end_DD = endtime[9:10] if endtime[8:10][:1] == '0' else endtime[8:10] # '19'
  1519. end_hh = endtime[12:13] if endtime[11:13][:1] == '0' else endtime[11:13] # '09'
  1520. end_mm = endtime[15:] if endtime[14:][:1] == '0' else endtime[14:] # '00'
  1521. end_ss = 0
  1522. time_range = []
  1523. temp_range = []
  1524. # 拿掉會 Error, 要使用沒有 GUI 的 matplotlib
  1525. plt.switch_backend('agg')
  1526. plt.figure()
  1527. if tank == 'DI':
  1528. print('DI')
  1529. if sensor_name == 'UltraSonic':
  1530. for d in db.session.query(dry_input_sensor) \
  1531. .filter_by(tank_num='DI' + tid) \
  1532. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_input_sensor.datetime) \
  1533. .filter(dry_input_sensor.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1534. .order_by(dry_input_sensor.datetime):
  1535. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  1536. time_range.append(str(d.datetime))
  1537. temp_range.append(float(d.UltraSonic))
  1538. print('time_range:', time_range)
  1539. print('temp_range:', temp_range)
  1540. return render_template('sensor_chart_DI.html', **locals())
  1541. elif tank == 'DO':
  1542. print('DO')
  1543. if sensor_name == 'UltraSonic':
  1544. for d in db.session.query(dry_output_sensor) \
  1545. .filter_by(tank_num='DO' + tid) \
  1546. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_output_sensor.datetime) \
  1547. .filter(dry_output_sensor.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1548. .order_by(dry_output_sensor.datetime):
  1549. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  1550. time_range.append(str(d.datetime))
  1551. temp_range.append(float(d.UltraSonic))
  1552. print('time_range:', time_range)
  1553. print('temp_range:', temp_range)
  1554. return render_template('sensor_chart_DO.html', **locals())
  1555. elif tank == 'D':
  1556. print('D')
  1557. if sensor_name == 'SHT11_Temp':
  1558. for d in db.session.query(dry_tank_SHT11) \
  1559. .filter_by(tank_num='D' + tid) \
  1560. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_SHT11.datetime) \
  1561. .filter(dry_tank_SHT11.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1562. .order_by(dry_tank_SHT11.datetime):
  1563. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  1564. time_range.append(str(d.datetime))
  1565. temp_range.append(float(d.SHT11_Temp))
  1566. # 畫出 x 軸基準線
  1567. # plt.axhline(28.5, color= 'r')
  1568. elif sensor_name == 'SHT11_Humidity':
  1569. for d in db.session.query(dry_tank_SHT11) \
  1570. .filter_by(tank_num='D' + tid) \
  1571. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_SHT11.datetime) \
  1572. .filter(dry_tank_SHT11.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1573. .order_by(dry_tank_SHT11.datetime):
  1574. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  1575. time_range.append(str(d.datetime))
  1576. temp_range.append(float(d.SHT11_Humidity))
  1577. elif sensor_name == 'UltraSonic':
  1578. for d in db.session.query(dry_tank_UltraSonic) \
  1579. .filter_by(tank_num='D' + tid) \
  1580. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_UltraSonic.datetime) \
  1581. .filter(dry_tank_UltraSonic.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1582. .order_by(dry_tank_UltraSonic.datetime):
  1583. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  1584. time_range.append(str(d.datetime))
  1585. temp_range.append(float(d.UltraSonic))
  1586. elif sensor_name == 'PA':
  1587. for d in db.session.query(dry_tank_PA) \
  1588. .filter_by(tank_num='D' + tid) \
  1589. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_PA.datetime) \
  1590. .filter(dry_tank_PA.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1591. .order_by(dry_tank_PA.datetime):
  1592. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  1593. time_range.append(str(d.datetime))
  1594. temp_range.append(float(d.PA))
  1595. elif sensor_name == 'soil_Temp':
  1596. for d in db.session.query(dry_tank_Soil) \
  1597. .filter_by(tank_num='D' + tid) \
  1598. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_Soil.datetime) \
  1599. .filter(dry_tank_Soil.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1600. .order_by(dry_tank_Soil.datetime):
  1601. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  1602. time_range.append(str(d.datetime))
  1603. temp_range.append(float(d.soil_Temp))
  1604. # 畫出 x 軸基準線
  1605. plt.axhline(28.5, color= 'r')
  1606. elif sensor_name == 'soil_Humidity':
  1607. for d in db.session.query(dry_tank_Soil) \
  1608. .filter_by(tank_num='D' + tid) \
  1609. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_Soil.datetime) \
  1610. .filter(dry_tank_Soil.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1611. .order_by(dry_tank_Soil.datetime):
  1612. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  1613. time_range.append(str(d.datetime))
  1614. temp_range.append(float(d.soil_Humidity))
  1615. elif sensor_name == 'soil_EC':
  1616. for d in db.session.query(dry_tank_Soil) \
  1617. .filter_by(tank_num='D' + tid) \
  1618. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_Soil.datetime) \
  1619. .filter(dry_tank_Soil.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1620. .order_by(dry_tank_Soil.datetime):
  1621. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  1622. time_range.append(str(d.datetime))
  1623. temp_range.append(float(d.soil_EC))
  1624. print('time_range:', time_range)
  1625. print('temp_range:', temp_range)
  1626. return render_template('sensor_chart_D.html', **locals())
  1627. elif tank == 'FI':
  1628. print('FI')
  1629. if sensor_name == 'UltraSonic':
  1630. for d in db.session.query(ferment_input_UltraSonic) \
  1631. .filter_by(tank_num='FI' + tid) \
  1632. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_input_UltraSonic.datetime) \
  1633. .filter(ferment_input_UltraSonic.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1634. .order_by(ferment_input_UltraSonic.datetime):
  1635. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  1636. time_range.append(str(d.datetime))
  1637. temp_range.append(float(d.UltraSonic))
  1638. print('time_range:', time_range)
  1639. print('temp_range:', temp_range)
  1640. return render_template('sensor_chart_FI.html', **locals())
  1641. elif tank == 'FO':
  1642. print('FO')
  1643. if sensor_name == 'UltraSonic':
  1644. for d in db.session.query(ferment_output_UltraSonic) \
  1645. .filter_by(tank_num='FO' + tid) \
  1646. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_output_UltraSonic.datetime) \
  1647. .filter(ferment_output_UltraSonic.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1648. .order_by(ferment_output_UltraSonic.datetime):
  1649. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  1650. time_range.append(str(d.datetime))
  1651. temp_range.append(float(d.UltraSonic))
  1652. print('time_range:', time_range)
  1653. print('temp_range:', temp_range)
  1654. return render_template('sensor_chart_FO.html', **locals())
  1655. elif tank == 'F':
  1656. print('F')
  1657. if sensor_name == 'LiDAR':
  1658. for d in db.session.query(ferment_tank_LiDAR) \
  1659. .filter_by(tank_num='F' + tid) \
  1660. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_LiDAR.datetime) \
  1661. .filter(ferment_tank_LiDAR.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1662. .order_by(ferment_tank_LiDAR.datetime):
  1663. time_range.append(str(d.datetime))
  1664. temp_range.append(float(d.LiDAR))
  1665. elif sensor_name == 'PressureWaterLevel':
  1666. for d in db.session.query(ferment_tank_PressureWaterLevel) \
  1667. .filter_by(tank_num='F' + tid) \
  1668. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_PressureWaterLevel.datetime) \
  1669. .filter(ferment_tank_PressureWaterLevel.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1670. .order_by(ferment_tank_PressureWaterLevel.datetime):
  1671. time_range.append(str(d.datetime))
  1672. temp_range.append('{:.2f}'.format((float(d.PressureWaterLevel) -10 -90.278)/9.4214))
  1673. elif sensor_name == 'SHT11_Temp':
  1674. for d in db.session.query(ferment_tank_SHT11) \
  1675. .filter_by(tank_num='F' + tid) \
  1676. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_PressureWaterLevel.datetime) \
  1677. .filter(ferment_tank_SHT11.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1678. .order_by(ferment_tank_SHT11.datetime):
  1679. time_range.append(str(d.datetime))
  1680. temp_range.append(float(d.SHT11_Temp))
  1681. elif sensor_name == 'SHT11_Humidity':
  1682. for d in db.session.query(ferment_tank_SHT11) \
  1683. .filter_by(tank_num='F' + tid) \
  1684. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_SHT11.datetime) \
  1685. .filter(ferment_tank_SHT11.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1686. .order_by(ferment_tank_SHT11.datetime):
  1687. time_range.append(str(d.datetime))
  1688. temp_range.append(float(d.SHT11_Humidity))
  1689. elif sensor_name == 'CO2':
  1690. for d in db.session.query(ferment_tank_CO2) \
  1691. .filter_by(tank_num='F' + tid) \
  1692. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_CO2.datetime) \
  1693. .filter(ferment_tank_CO2.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1694. .order_by(ferment_tank_CO2.datetime):
  1695. time_range.append(str(d.datetime))
  1696. temp_range.append(float(d.CO2))
  1697. elif sensor_name == 'PH':
  1698. for d in db.session.query(ferment_tank_PH) \
  1699. .filter_by(tank_num='F' + tid) \
  1700. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_PH.datetime) \
  1701. .filter(ferment_tank_PH.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1702. .order_by(ferment_tank_PH.datetime):
  1703. time_range.append(str(d.datetime))
  1704. temp_range.append(float(d.PH))
  1705. elif sensor_name == 'ORP':
  1706. for d in db.session.query(ferment_tank_ORP) \
  1707. .filter_by(tank_num='F' + tid) \
  1708. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_ORP.datetime) \
  1709. .filter(ferment_tank_ORP.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1710. .order_by(ferment_tank_ORP.datetime):
  1711. time_range.append(str(d.datetime))
  1712. temp_range.append(float(d.ORP))
  1713. elif sensor_name == 'DO':
  1714. for d in db.session.query(ferment_tank_DO) \
  1715. .filter_by(tank_num='F' + tid) \
  1716. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_DO.datetime) \
  1717. .filter(ferment_tank_DO.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1718. .order_by(ferment_tank_DO.datetime):
  1719. time_range.append(str(d.datetime))
  1720. temp_range.append(float(d.DO))
  1721. elif sensor_name == 'EC':
  1722. for d in db.session.query(ferment_tank_EC) \
  1723. .filter_by(tank_num='F' + tid) \
  1724. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_EC.datetime) \
  1725. .filter(ferment_tank_EC.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1726. .order_by(ferment_tank_EC.datetime):
  1727. time_range.append(str(d.datetime))
  1728. temp_range.append(float(d.EC))
  1729. elif sensor_name == 'PA':
  1730. for d in db.session.query(ferment_tank_PA) \
  1731. .filter_by(tank_num='F' + tid) \
  1732. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_PA.datetime) \
  1733. .filter(ferment_tank_PA.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1734. .order_by(ferment_tank_PA.datetime):
  1735. time_range.append(str(d.datetime))
  1736. temp_range.append(float(d.PA))
  1737. print('time_range:', time_range)
  1738. print('temp_range:', temp_range)
  1739. return render_template('sensor_chart_DO.html', **locals())
  1740. '''
  1741. # 設定 x 軸資料、y 軸資料、折線顏色
  1742. plt.plot(time_range, temp_range, 'bo')
  1743. # x 軸標題 (中文無法顯示)
  1744. # plt.xlabel('time')
  1745. # plt.ylabel(sensor_name)
  1746. # x 軸 label 和垂直顯示, rotation='vertical'
  1747. plt.xticks(time_range, rotation='vertical' )
  1748. # 設定圖表標題
  1749. plt.title(sensor_name)
  1750. # 調整圖片與周圍的間距
  1751. plt.tight_layout()
  1752. # plt.show()
  1753. # 儲存圖片 應改為相對路徑
  1754. plt.savefig('C:/Users/USER/Rita/Coffee/CoffeeProject/app/static/img/new_plot.png')
  1755. '''
  1756. # 判斷資料索取區間 起>迄
  1757. else:
  1758. return render_template('sensor_chart_D.html', **locals())
  1759. '''
  1760. @main.route('/chart_DI/<sensor_name>/<tid>', methods=['GET', 'POST'])
  1761. def chart_DI(sensor_name, tid):
  1762. if request.method == 'GET':
  1763. return render_template('sensor_chart_DI.html', **locals())
  1764. elif request.method == 'POST':
  1765. starttime = request.values['sensor_starttime'] # 2021-07-19T09:00
  1766. endtime = request.values['sensor_endtime'] # 2021-07-19T12:00
  1767. sensor_name = request.values['sensors']
  1768. print('sensor_name:', sensor_name)
  1769. # 判斷資料索取區間 起<迄
  1770. if starttime < endtime :
  1771. start_YY = starttime[:4] # '2021'
  1772. start_MM = starttime[6:7] if starttime[5:7][:1] == '0' else starttime[5:7] # '07'
  1773. start_DD = starttime[9:10] if starttime[8:10][:1] == '0' else starttime[8:10] # '19'
  1774. start_hh = starttime[12:13] if starttime[11:13][:1] == '0' else starttime[11:13] # '09'
  1775. start_mm = starttime[15:] if starttime[14:][:1] == '0' else starttime[14:] # '00'
  1776. start_ss = 0
  1777. end_YY = endtime[:4] # '2021'
  1778. end_MM = endtime[6:7] if endtime[5:7][:1] == '0' else endtime[5:7] # '07'
  1779. end_DD = endtime[9:10] if endtime[8:10][:1] == '0' else endtime[8:10] # '19'
  1780. end_hh = endtime[12:13] if endtime[11:13][:1] == '0' else endtime[11:13] # '09'
  1781. end_mm = endtime[15:] if endtime[14:][:1] == '0' else endtime[14:] # '00'
  1782. end_ss = 0
  1783. time_range = []
  1784. temp_range = []
  1785. # 拿掉會 Error, 要使用沒有 GUI 的 matplotlib
  1786. plt.switch_backend('agg')
  1787. plt.figure()
  1788. if sensor_name == 'UltraSonic':
  1789. for d in db.session.query(dry_input_sensor) \
  1790. .filter_by(tank_num='DI' + tid) \
  1791. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_UltraSonic.datetime) \
  1792. .filter(dry_tank_UltraSonic.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1793. .order_by(dry_tank_UltraSonic.datetime):
  1794. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  1795. time_range.append(str(d.datetime))
  1796. temp_range.append(float(d.UltraSonic))
  1797. # 畫出 x 軸基準線
  1798. # plt.axhline(28.5, color= 'r')
  1799. print('time_range:', time_range)
  1800. print('temp_range:', temp_range)
  1801. return render_template('sensor_chart_DI.html', **locals())
  1802. # 判斷資料索取區間 起>迄
  1803. else:
  1804. return render_template('sensor_chart_DI.html', **locals())
  1805. @main.route('/chart_DO/<sensor_name>/<tid>', methods=['GET', 'POST'])
  1806. def chart_DO(sensor_name, tid):
  1807. if request.method == 'GET':
  1808. return render_template('sensor_chart_DO.html', **locals())
  1809. elif request.method == 'POST':
  1810. starttime = request.values['sensor_starttime'] # 2021-07-19T09:00
  1811. endtime = request.values['sensor_endtime'] # 2021-07-19T12:00
  1812. sensor_name = request.values['sensors']
  1813. print('sensor_name:', sensor_name)
  1814. # 判斷資料索取區間 起<迄
  1815. if starttime < endtime :
  1816. start_YY = starttime[:4] # '2021'
  1817. start_MM = starttime[6:7] if starttime[5:7][:1] == '0' else starttime[5:7] # '07'
  1818. start_DD = starttime[9:10] if starttime[8:10][:1] == '0' else starttime[8:10] # '19'
  1819. start_hh = starttime[12:13] if starttime[11:13][:1] == '0' else starttime[11:13] # '09'
  1820. start_mm = starttime[15:] if starttime[14:][:1] == '0' else starttime[14:] # '00'
  1821. start_ss = 0
  1822. end_YY = endtime[:4] # '2021'
  1823. end_MM = endtime[6:7] if endtime[5:7][:1] == '0' else endtime[5:7] # '07'
  1824. end_DD = endtime[9:10] if endtime[8:10][:1] == '0' else endtime[8:10] # '19'
  1825. end_hh = endtime[12:13] if endtime[11:13][:1] == '0' else endtime[11:13] # '09'
  1826. end_mm = endtime[15:] if endtime[14:][:1] == '0' else endtime[14:] # '00'
  1827. end_ss = 0
  1828. time_range = []
  1829. temp_range = []
  1830. # 拿掉會 Error, 要使用沒有 GUI 的 matplotlib
  1831. plt.switch_backend('agg')
  1832. plt.figure()
  1833. if sensor_name == 'UltraSonic':
  1834. for d in db.session.query(dry_input_sensor) \
  1835. .filter_by(tank_num='DO' + tid) \
  1836. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_UltraSonic.datetime) \
  1837. .filter(dry_tank_UltraSonic.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  1838. .order_by(dry_tank_UltraSonic.datetime):
  1839. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  1840. time_range.append(str(d.datetime))
  1841. temp_range.append(float(d.UltraSonic))
  1842. # 畫出 x 軸基準線
  1843. # plt.axhline(28.5, color= 'r')
  1844. print('time_range:', time_range)
  1845. print('temp_range:', temp_range)
  1846. return render_template('sensor_chart_DO.html', **locals())
  1847. # 判斷資料索取區間 起>迄
  1848. else:
  1849. return render_template('sensor_chart_DO.html', **locals())
  1850. '''
  1851. # Rita 測試
  1852. # 乾燥桶感測器/制動器測試
  1853. # Rita 須加上 <tid> 區分桶號 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  1854. @main.route('/dry_tank/1', methods=['GET'])
  1855. def dry_tank():
  1856. if request.method == 'GET':
  1857. return render_template('dry_tank.html')
  1858. @main.route('/clean', methods=['GET'])
  1859. def clean():
  1860. if 'id' in session and 'uname' in session and 'status' in session:
  1861. username = session['uname']
  1862. status = session['status']
  1863. if status == 9:
  1864. return render_template('signin_disable.html', params=locals())
  1865. elif status == 8:
  1866. return render_template('signin_new.html', params=locals())
  1867. else:
  1868. return render_template('oops.html', params=locals())
  1869. return render_template('clean.html', title='清洗貨櫃', **locals())
  1870. @main.route('/ferment', methods=['GET'])
  1871. def ferment():
  1872. if 'id' in session and 'uname' in session and 'status' in session:
  1873. username = session['uname']
  1874. status = session['status']
  1875. if status == 9:
  1876. return render_template('signin_disable.html', params=locals())
  1877. elif status == 8:
  1878. return render_template('signin_new.html', params=locals())
  1879. else:
  1880. return render_template('oops.html', params=locals())
  1881. return render_template('ferment.html', title='發酵貨櫃', **locals())
  1882. @main.route('/dry', methods=['GET'])
  1883. def dry():
  1884. if request.method == 'GET':
  1885. if 'id' in session and 'uname' in session and 'status' in session:
  1886. username = session['uname']
  1887. status = session['status']
  1888. if status == 9:
  1889. return render_template('signin_disable.html', params=locals())
  1890. elif status == 8:
  1891. return render_template('signin_new.html', params=locals())
  1892. else:
  1893. return render_template('oops.html', params=locals())
  1894. return render_template('dry.html', title='乾燥貨櫃', **locals())
  1895. @main.route('/peel_container/<tid>', methods=['GET', 'POST'])
  1896. def peel_container(tid):
  1897. if request.method == 'GET':
  1898. if 'id' in session and 'uname' in session and 'status' in session:
  1899. username = session['uname']
  1900. status = session['status']
  1901. if status == 9:
  1902. return render_template('signin_disable.html', params=locals())
  1903. elif status == 8:
  1904. return render_template('signin_new.html', params=locals())
  1905. else:
  1906. return render_template('oops.html', params=locals())
  1907. # 制動器_入料儲豆槽_真空吸料機
  1908. input_vacuum = peel_input_actuator.query.filter_by(tank_num='P'+str(tid)).order_by(text('datetime desc')).first()
  1909. input_vacuum = input_vacuum.vacuum
  1910. print("input_vacuum:", input_vacuum)
  1911. # 制動器_脫皮機_ALL
  1912. tank_actuator = peel_tank_actuator.query.filter_by(tank_num='P'+str(tid)).order_by(text('datetime desc')).first()
  1913. tank_vacuum = tank_actuator.vacuum
  1914. tank_motor = tank_actuator.motor
  1915. # 制動器_出料儲豆槽_真空吸料機
  1916. output_vacuum = peel_output_actuator.query.filter_by(tank_num='P'+str(tid)).order_by(text('datetime desc')).first()
  1917. output_vacuum = output_vacuum.vacuum
  1918. return render_template('peel_container.html', title='脫皮機P' + tid + '總操作介面', **locals())
  1919. elif request.method == 'POST':
  1920. pass
  1921. @main.route('/clean_container/<tid>', methods=['GET', 'POST'])
  1922. def clean_container(tid):
  1923. if request.method == 'GET':
  1924. if 'id' in session and 'uname' in session and 'status' in session:
  1925. username = session['uname']
  1926. status = session['status']
  1927. if status == 9:
  1928. return render_template('signin_disable.html', params=locals())
  1929. elif status == 8:
  1930. return render_template('signin_new.html', params=locals())
  1931. else:
  1932. return render_template('oops.html', params=locals())
  1933. # 制動器_入料儲豆槽_真空吸料機
  1934. input_vacuum = clean_input_actuator.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  1935. input_vacuum = 'ON' if (input_vacuum.vacuum == 1) else 'OFF'
  1936. # 制動器_浮選清洗_ALL
  1937. tank_actuator = clean_tank_actuator.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  1938. tank_vacuum = 'ON' if tank_actuator.vacuum == 1 else 'OFF'
  1939. tank_pump_waterInput = 'ON' if tank_actuator.pump_waterInput == 1 else 'OFF'
  1940. tank_pump_waterL2L3 = 'ON' if tank_actuator.pump_waterL2L3 == 1 else 'OFF'
  1941. tank_pump_waterL4L5 = 'ON' if tank_actuator.pump_waterL4L5 == 1 else 'OFF'
  1942. tank_solenoid_waterL2L3 = 'ON' if tank_actuator.solenoid_waterL2L3 == 1 else 'OFF'
  1943. tank_solenoid_waterL4L5 = 'ON' if tank_actuator.solenoid_waterL4L5 == 1 else 'OFF'
  1944. tank_stepping_motor = tank_actuator.stepping_motor
  1945. # 制動器_出料儲豆槽_真空吸料機
  1946. output_vacuum = clean_output_actuator.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  1947. output_vacuum = 'ON' if (output_vacuum.vacuum == 1) else 'OFF'
  1948. # 感測器_浮選清洗_超音波感測器
  1949. tank_UltraSonic = clean_tank_UltraSonic.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  1950. return render_template('clean_container.html', title='清洗浮選槽C' + tid + '總操作介面', **locals())
  1951. elif request.method == 'POST':
  1952. pass
  1953. @main.route('/ferment_container/<tid>', methods=['GET', 'POST'])
  1954. def ferment_container(tid):
  1955. if request.method == 'GET':
  1956. if 'id' in session and 'uname' in session and 'status' in session:
  1957. username = session['uname']
  1958. status = session['status']
  1959. if status == 9:
  1960. return render_template('signin_disable.html', params=locals())
  1961. elif status == 8:
  1962. return render_template('signin_new.html', params=locals())
  1963. else:
  1964. return render_template('oops.html', params=locals())
  1965. # 制動器_發酵槽_ALL
  1966. tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  1967. tank_vacuum = 'ON' if tank_actuator.vacuum == 1 else 'OFF'
  1968. tank_threewayvalve_input = 'ON' if tank_actuator.threewayvalve_input == 1 else 'OFF'
  1969. tank_diskvalve = 'ON' if tank_actuator.diskvalve == 1 else 'OFF'
  1970. tank_solenoid_water_total = 'ON' if tank_actuator.solenoid_tank_water_total == 1 else 'OFF'
  1971. tank_solenoid_disinfect = 'ON' if tank_actuator.solenoid_tank_disinfect == 1 else 'OFF'
  1972. outer_solenoid_water = 'ON' if tank_actuator.solenoid_outer_water == 1 else 'OFF'
  1973. tank_solenoid_water_in = 'ON' if tank_actuator.solenoid_tank_water_in == 1 else 'OFF'
  1974. tank_pump_sensor = 'ON' if tank_actuator.pump_sensor == 1 else 'OFF'
  1975. tank_threewayvalve_bean = 'ON' if tank_actuator.threewayvalve_bean == 1 else 'OFF'
  1976. outer_threewayvalve_float = 'ON' if tank_actuator.threewayvalve_outer_float == 1 else 'OFF'
  1977. tank_motor = tank_actuator.motor
  1978. tank_heater1 = 'ON' if tank_actuator.heater1 == 1 else 'OFF'
  1979. tank_heater2 = 'ON' if tank_actuator.heater2 == 1 else 'OFF'
  1980. tank_temp_enable = 'ON' if tank_actuator.temp_enable == 1 else 'OFF'
  1981. tank_temp = tank_actuator.temp
  1982. # 感測器_發酵桶_SHT11
  1983. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  1984. # 感測器_發酵桶_二氧化碳
  1985. tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  1986. # 感測器_發酵桶_酸鹼值
  1987. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  1988. tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  1989. tank_DO = ferment_tank_DO.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  1990. tank_EC = ferment_tank_EC.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  1991. # 感測器_發酵桶_氣壓
  1992. tank_PA = ferment_tank_PA.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  1993. # 感測器_發酵桶_超音波感測器
  1994. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  1995. # 感測器_發酵桶_水位計
  1996. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  1997. num_tank_WaterLevel = float(tank_WaterLevel.WaterLevel)
  1998. print('tank_WaterLevel', tank_WaterLevel.WaterLevel)
  1999. if tank_WaterLevel.WaterLevel == '1':
  2000. WaterLevel = '滿'
  2001. elif tank_WaterLevel.WaterLevel == '0':
  2002. WaterLevel = '未達滿水高度'
  2003. else:
  2004. WaterLevel = 'ERROR'
  2005. # 感測器_發酵桶_咖啡生豆高度
  2006. tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  2007. LiDAR = tank_LiDAR.LiDAR
  2008. # 感測器_發酵桶_水位高度
  2009. tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  2010. PressureWaterLevel = '{:.2f}'.format((float(tank_PressureWaterLevel.PressureWaterLevel) -15 -90.278)/9.4214)
  2011. if tid in ['1', '2', '3', '4', '5', '6']:
  2012. # print("1")
  2013. # 感測器_入料儲豆槽_超音波感測器
  2014. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI1').order_by(text('datetime desc')).first()
  2015. # 制動器_入料儲豆槽_真空吸引機
  2016. input_vacuum = ferment_input_actuator.query.filter_by(tank_num='FI1').order_by(text('datetime desc')).first()
  2017. input_vacuum = input_vacuum.vacuum
  2018. # 感測器_出料儲豆槽_超音波感測器
  2019. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO1').order_by(text('datetime desc')).first()
  2020. # 制動器_出料儲豆槽_真空吸引機
  2021. output_vacuum = ferment_output_actuator.query.filter_by(tank_num='FO1').order_by(text('datetime desc')).first()
  2022. output_vacuum = output_vacuum.vacuum
  2023. elif tid in ['7', '8', '9', '10', '11', '12']:
  2024. # print("2")
  2025. # 感測器_入料儲豆槽_超音波感測器
  2026. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI2').order_by(text('datetime desc')).first()
  2027. # 制動器_入料儲豆槽_真空吸引機
  2028. input_vacuum = ferment_input_actuator.query.filter_by(tank_num='FI2').order_by(text('datetime desc')).first()
  2029. input_vacuum = input_vacuum.vacuum
  2030. print("input_vacuum", input_vacuum)
  2031. # 感測器_出料儲豆槽_超音波感測器
  2032. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO2').order_by(text('datetime desc')).first()
  2033. # 制動器_出料儲豆槽_真空吸引機
  2034. output_vacuum = ferment_output_actuator.query.filter_by(tank_num='FO2').order_by(text('datetime desc')).first()
  2035. output_vacuum = output_vacuum.vacuum
  2036. print("output_vacuum", output_vacuum)
  2037. return render_template('ferment_container.html', title='發酵槽F' + tid + '總操作介面' , **locals())
  2038. elif request.method == 'POST':
  2039. pass
  2040. @main.route('/ferment_container_tank/<tid>', methods=['GET', 'POST'])
  2041. def ferment_container_tank(tid):
  2042. if request.method == 'GET':
  2043. if 'id' in session and 'uname' in session and 'status' in session:
  2044. username = session['uname']
  2045. status = session['status']
  2046. if status == 9:
  2047. return render_template('signin_disable.html', params=locals())
  2048. elif status == 8:
  2049. return render_template('signin_new.html', params=locals())
  2050. else:
  2051. return render_template('oops.html', params=locals())
  2052. # 制動器_發酵槽_ALL
  2053. tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  2054. tank_vacuum = 'ON' if tank_actuator.vacuum == 1 else 'OFF'
  2055. tank_threewayvalve_input = 'ON' if tank_actuator.threewayvalve_input == 1 else 'OFF'
  2056. tank_diskvalve = 'ON' if tank_actuator.diskvalve == 1 else 'OFF'
  2057. tank_solenoid_water_total = 'ON' if tank_actuator.solenoid_tank_water_total == 1 else 'OFF'
  2058. tank_solenoid_disinfect = 'ON' if tank_actuator.solenoid_tank_disinfect == 1 else 'OFF'
  2059. outer_solenoid_water = 'ON' if tank_actuator.solenoid_outer_water == 1 else 'OFF'
  2060. tank_solenoid_water_in = 'ON' if tank_actuator.solenoid_tank_water_in == 1 else 'OFF'
  2061. tank_pump_sensor = 'ON' if tank_actuator.pump_sensor == 1 else 'OFF'
  2062. tank_threewayvalve_bean = 'ON' if tank_actuator.threewayvalve_bean == 1 else 'OFF'
  2063. outer_threewayvalve_float = 'ON' if tank_actuator.threewayvalve_outer_float == 1 else 'OFF'
  2064. tank_motor = tank_actuator.motor
  2065. tank_heater1 = 'ON' if tank_actuator.heater1 == 1 else 'OFF'
  2066. tank_heater2 = 'ON' if tank_actuator.heater2 == 1 else 'OFF'
  2067. tank_temp_enable = 'ON' if tank_actuator.temp_enable == 1 else 'OFF'
  2068. tank_temp = tank_actuator.temp
  2069. # 感測器_發酵桶_SHT11
  2070. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  2071. # 感測器_發酵桶_二氧化碳
  2072. tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  2073. # 感測器_發酵桶_酸鹼值
  2074. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  2075. tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  2076. tank_DO = ferment_tank_DO.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  2077. tank_EC = ferment_tank_EC.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  2078. # 感測器_發酵桶_氣壓
  2079. tank_PA = ferment_tank_PA.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  2080. # 感測器_發酵桶_超音波感測器
  2081. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  2082. # 感測器_發酵桶_水位計
  2083. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  2084. num_tank_WaterLevel = float(tank_WaterLevel.WaterLevel)
  2085. if tank_WaterLevel.WaterLevel == '1':
  2086. WaterLevel = '滿'
  2087. elif tank_WaterLevel.WaterLevel == '0':
  2088. WaterLevel = '未達滿水高度'
  2089. else:
  2090. WaterLevel = 'ERROR'
  2091. # 感測器_發酵桶_咖啡生豆高度
  2092. #tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  2093. #LiDAR = tank_LiDAR.LiDAR
  2094. # 感測器_發酵桶_水位高度
  2095. #tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  2096. #PressureWaterLevel = '{:.2f}'.format((float(tank_PressureWaterLevel.PressureWaterLevel) -15 -90.278)/9.4214)
  2097. return render_template('ferment_container_tank.html', title='[操作] F' + tid + ' 發酵槽操作介面', **locals())
  2098. elif request.method == 'POST':
  2099. pass
  2100. @main.route('/ferment_container_input/<tid>', methods=['GET', 'POST'])
  2101. def ferment_container_input(tid):
  2102. if request.method == 'GET':
  2103. if 'id' in session and 'uname' in session and 'status' in session:
  2104. username = session['uname']
  2105. status = session['status']
  2106. if status == 9:
  2107. return render_template('signin_disable.html', params=locals())
  2108. elif status == 8:
  2109. return render_template('signin_new.html', params=locals())
  2110. else:
  2111. return render_template('oops.html', params=locals())
  2112. # 感測器_入料儲豆槽_超音波感測器
  2113. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI' + tid).order_by(text('datetime desc')).first()
  2114. # 制動器_入料儲豆槽_真空吸引機
  2115. input_vacuum = ferment_input_actuator.query.filter_by(tank_num='FI' + tid).order_by(text('datetime desc')).first()
  2116. input_vacuum = input_vacuum.vacuum
  2117. return render_template('ferment_container_input.html', title='[操作] FI' + tid + ' 發酵入料儲豆槽操作介面', **locals())
  2118. elif request.method == 'POST':
  2119. pass
  2120. @main.route('/ferment_container_output/<tid>', methods=['GET', 'POST'])
  2121. def ferment_container_output(tid):
  2122. if request.method == 'GET':
  2123. if 'id' in session and 'uname' in session and 'status' in session:
  2124. username = session['uname']
  2125. status = session['status']
  2126. if status == 9:
  2127. return render_template('signin_disable.html', params=locals())
  2128. elif status == 8:
  2129. return render_template('signin_new.html', params=locals())
  2130. else:
  2131. return render_template('oops.html', params=locals())
  2132. # 感測器_出料儲豆槽_超音波感測器
  2133. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO' + tid).order_by(text('datetime desc')).first()
  2134. # 制動器_出料儲豆槽_真空吸引機
  2135. output_vacuum = ferment_output_actuator.query.filter_by(tank_num='FO' + tid).order_by(text('datetime desc')).first()
  2136. output_vacuum = output_vacuum.vacuum
  2137. tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  2138. LiDAR = tank_LiDAR.LiDAR
  2139. return render_template('ferment_container_output.html', title='[操作] FO' + tid + ' 發酵出料儲豆槽操作介面', **locals())
  2140. elif request.method == 'POST':
  2141. pass
  2142. @main.route('/dry_container_schedule', methods=['GET', 'POST'])
  2143. def dry_container_schedule():
  2144. if request.method == 'GET':
  2145. if 'id' in session and 'uname' in session:
  2146. username = session['uname']
  2147. # 感測器_入料儲豆槽_超音波感測器
  2148. input_UltraSonic = dry_input_sensor.query.order_by(text('datetime desc')).first()
  2149. # 感測器_乾燥桶_超音波感測器
  2150. tank_UltraSonic = dry_tank_UltraSonic.query.order_by(text('datetime desc')).first()
  2151. return render_template('dry_container_schedule.html', title='dry_container_schedule', **locals())
  2152. elif request.method == 'POST':
  2153. pass
  2154. # 乾燥貨櫃_各制動器控制
  2155. @main.route('/ctrl_DI_<actuator>/<tid>', methods=['GET', 'POST'])
  2156. def ctrl_DI(actuator, tid):
  2157. if request.method == 'GET':
  2158. if actuator == 'Vacuum':
  2159. if 'id' in session and 'uname' in session and 'status' in session:
  2160. username = session['uname']
  2161. status = session['status']
  2162. if status == 9:
  2163. return render_template('signin_disable.html', params=locals())
  2164. elif status == 8:
  2165. return render_template('signin_new.html', params=locals())
  2166. else:
  2167. return render_template('oops.html', params=locals())
  2168. input_brake = dry_input_brake.query.filter_by(tank_num='DI'+str(tid)).order_by(text('datetime desc')).first()
  2169. input_vacuum = input_brake.vacuum
  2170. tank_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI'+str(tid)).order_by(text('datetime desc')).first()
  2171. UltraSonic = tank_UltraSonic.UltraSonic
  2172. return render_template('ctrl_DI_Vacuum.html', title='[操作]DI' + tid + '乾燥槽入料_真空吸料機', **locals())
  2173. elif request.method == 'POST':
  2174. pass
  2175. @main.route('/ctrl_DO_<actuator>/<tid>', methods=['GET', 'POST'])
  2176. def ctrl_DO(actuator, tid):
  2177. if request.method == 'GET':
  2178. if 'id' in session and 'uname' in session and 'status' in session:
  2179. username = session['uname']
  2180. status = session['status']
  2181. if status == 9:
  2182. return render_template('signin_disable.html', params=locals())
  2183. elif status == 8:
  2184. return render_template('signin_new.html', params=locals())
  2185. else:
  2186. return render_template('oops.html', params=locals())
  2187. if actuator == 'Vacuum':
  2188. tank_brake = dry_output_brake.query.filter_by(tank_num='DO'+str(tid)).order_by(text('datetime desc')).first()
  2189. tank_vacuum = tank_brake.vacuum
  2190. tank_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO'+str(tid)).order_by(text('datetime desc')).first()
  2191. UltraSonic = tank_UltraSonic.UltraSonic
  2192. return render_template('ctrl_DO_Vacuum.html', title='[操作]DI' + tid + '乾燥槽出料_真空吸料機', **locals())
  2193. elif request.method == 'POST':
  2194. pass
  2195. @main.route('/ctrl_D_<actuator>/<tid>', methods=['GET', 'POST'])
  2196. def ctrl_D(actuator, tid):
  2197. if request.method == 'GET':
  2198. if 'id' in session and 'uname' in session and 'status' in session:
  2199. username = session['uname']
  2200. status = session['status']
  2201. if status == 9:
  2202. return render_template('signin_disable.html', params=locals())
  2203. elif status == 8:
  2204. return render_template('signin_new.html', params=locals())
  2205. else:
  2206. return render_template('oops.html', params=locals())
  2207. tank_brake = dry_tank_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2208. if actuator == 'Vacuum':
  2209. tank_vacuum = tank_brake.vacuum
  2210. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2211. UltraSonic = tank_UltraSonic.UltraSonic
  2212. return render_template('ctrl_D_Vacuum.html', title='[操作]D' + tid + '乾燥槽_真空吸料機', **locals())
  2213. elif actuator == 'ThreeWayValve':
  2214. tank_threewayvalve = tank_brake.threewayvalve
  2215. return render_template('ctrl_D_ThreeWayValve.html', title='[操作]D' + tid + '乾燥槽_三通閥', **locals())
  2216. elif actuator == 'DiskValve':
  2217. tank_diskvalve = tank_brake.diskvalve
  2218. return render_template('ctrl_D_DiskValve.html', title='[操作]D' + tid + '乾燥槽_蝴蝶閥', **locals())
  2219. elif actuator == 'SolenoidDisinfect':
  2220. tank_solenoid_disinfect = tank_brake.solenoid_disinfect
  2221. return render_template('ctrl_D_SolenoidDisinfect.html', title='[操作]D' + tid + '乾燥槽_消毒電磁閥', **locals())
  2222. elif actuator == 'SolenoidWater':
  2223. tank_solenoid_water = tank_brake.solenoid_water
  2224. return render_template('ctrl_D_SolenoidWater.html', title='[操作]D' + tid + '乾燥槽_排水電磁閥', **locals())
  2225. elif actuator == 'Motor':
  2226. tank_motor = tank_brake.motor
  2227. return render_template('ctrl_D_Motor.html', title='[操作]D' + tid + '乾燥槽_馬達', **locals())
  2228. elif actuator == 'Blower':
  2229. tank_blower = tank_brake.blower
  2230. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2231. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2232. return render_template('ctrl_D_Blower.html', title='[操作]D' + tid + '乾燥槽_鼓風機', **locals())
  2233. elif actuator == 'Heater1':
  2234. tank_heater1 = tank_brake.heater1
  2235. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2236. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2237. return render_template('ctrl_D_Heater1.html', title='[操作]D' + tid + '乾燥槽_加熱器 1', **locals())
  2238. elif actuator == 'Heater2':
  2239. tank_heater2 = tank_brake.heater2
  2240. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2241. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2242. return render_template('ctrl_D_Heater2.html', title='[操作]D' + tid + '乾燥槽_加熱器 2', **locals())
  2243. elif actuator == 'TempEnable':
  2244. tank_temp1_enable = tank_brake.temp1_enable
  2245. return render_template('ctrl_D_TempEnable.html', title='[操作]D' + tid + '乾燥槽_溫控開關', **locals())
  2246. elif actuator == 'Temp':
  2247. tank_temp1_enable = tank_brake.temp1_enable
  2248. tank_temp1 = tank_brake.temp1
  2249. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2250. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2251. return render_template('ctrl_D_Temp.html', title='[操作]D' + tid + '乾燥槽_設定溫度', **locals())
  2252. elif request.method == 'POST':
  2253. pass
  2254. # 發酵貨櫃_各制動器控制
  2255. @main.route('/ctrl_FI_<actuator>/<tid>', methods=['GET', 'POST'])
  2256. def ctrl_FI(actuator, tid):
  2257. if request.method == 'GET':
  2258. if 'id' in session and 'uname' in session and 'status' in session:
  2259. username = session['uname']
  2260. status = session['status']
  2261. if status == 9:
  2262. return render_template('signin_disable.html', params=locals())
  2263. elif status == 8:
  2264. return render_template('signin_new.html', params=locals())
  2265. else:
  2266. return render_template('oops.html', params=locals())
  2267. if actuator == 'Vacuum':
  2268. if 'id' in session and 'uname' in session and 'status' in session:
  2269. username = session['uname']
  2270. status = session['status']
  2271. if status == 9:
  2272. return render_template('signin_disable.html', params=locals())
  2273. elif status == 8:
  2274. return render_template('signin_new.html', params=locals())
  2275. else:
  2276. return render_template('oops.html', params=locals())
  2277. tank_actuator = ferment_input_actuator.query.filter_by(tank_num='FI'+str(tid)).order_by(text('datetime desc')).first()
  2278. tank_vacuum = tank_actuator.vacuum
  2279. tank_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI'+str(tid)).order_by(text('datetime desc')).first()
  2280. UltraSonic = tank_UltraSonic.UltraSonic
  2281. return render_template('ctrl_FI_Vacuum.html', title='[操作]FI' + tid + '發酵入料儲豆槽_真空吸料機', **locals())
  2282. elif request.method == 'POST':
  2283. pass
  2284. @main.route('/ctrl_FO_<actuator>/<tid>', methods=['GET', 'POST'])
  2285. def ctrl_FO(actuator, tid):
  2286. if request.method == 'GET':
  2287. if 'id' in session and 'uname' in session and 'status' in session:
  2288. username = session['uname']
  2289. status = session['status']
  2290. if status == 9:
  2291. return render_template('signin_disable.html', params=locals())
  2292. elif status == 8:
  2293. return render_template('signin_new.html', params=locals())
  2294. else:
  2295. return render_template('oops.html', params=locals())
  2296. if actuator == 'Vacuum':
  2297. tank_actuator = ferment_output_actuator.query.filter_by(tank_num='FO'+str(tid)).order_by(text('datetime desc')).first()
  2298. tank_vacuum = tank_actuator.vacuum
  2299. tank_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO'+str(tid)).order_by(text('datetime desc')).first()
  2300. UltraSonic = tank_UltraSonic.UltraSonic
  2301. return render_template('ctrl_FO_Vacuum.html', title='[操作]FO' + tid + '發酵出料儲豆槽_真空吸料機', **locals())
  2302. elif request.method == 'POST':
  2303. pass
  2304. @main.route('/ctrl_F_<actuator>/<tid>', methods=['GET', 'POST'])
  2305. def ctrl_F(actuator, tid):
  2306. if request.method == 'GET':
  2307. if 'id' in session and 'uname' in session and 'status' in session:
  2308. username = session['uname']
  2309. status = session['status']
  2310. if status == 9:
  2311. return render_template('signin_disable.html', params=locals())
  2312. elif status == 8:
  2313. return render_template('signin_new.html', params=locals())
  2314. else:
  2315. return render_template('oops.html', params=locals())
  2316. tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  2317. if actuator == 'Vacuum':
  2318. tank_vacuum = tank_actuator.vacuum
  2319. tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  2320. LiDAR = tank_LiDAR.LiDAR
  2321. return render_template('ctrl_F_Vacuum.html', title='[操作]F' + tid + '發酵槽_真空吸料機', **locals())
  2322. elif actuator == 'ThreeWayValveInput':
  2323. tank_threewayvalveinput = tank_actuator.threewayvalve_input
  2324. return render_template('ctrl_F_ThreeWayValveInput.html', title='[操作]F' + tid + '發酵槽_入料三通閥', **locals())
  2325. elif actuator == 'SolenoidWaterTotal':
  2326. tank_solenoid_tank_water_total = tank_actuator.solenoid_tank_water_total
  2327. return render_template('ctrl_F_SolenoidWaterTotal.html', title='[操作]F' + tid + '發酵槽_總進水電磁閥', **locals())
  2328. elif actuator == 'SolenoidOuterWater':
  2329. tank_solenoid_outer_water = tank_actuator.solenoid_outer_water
  2330. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  2331. WaterLevel = tank_WaterLevel.WaterLevel
  2332. return render_template('ctrl_F_SolenoidOuterWater.html', title='[操作]F' + tid + '發酵槽_保溫夾層進水電磁閥', **locals())
  2333. elif actuator == 'SolenoidWaterIn':
  2334. tank_solenoid_tank_water_in = tank_actuator.solenoid_tank_water_in
  2335. tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  2336. PressureWaterLevel = tank_PressureWaterLevel.PressureWaterLevel
  2337. return render_template('ctrl_F_SolenoidWaterIn.html', title='[操作]F' + tid + '發酵槽_桶內進水電磁閥', **locals())
  2338. elif actuator == 'PumpSensor':
  2339. tank_pump_sensor = tank_actuator.pump_sensor
  2340. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  2341. tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  2342. tank_DO = ferment_tank_DO.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  2343. tank_EC = ferment_tank_EC.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  2344. PH = tank_PH.PH
  2345. ORP = tank_ORP.ORP
  2346. DO = tank_DO.DO
  2347. EC = tank_EC.EC
  2348. return render_template('ctrl_F_PumpSensor.html', title='[操作]F' + tid + '發酵槽_感測器抽水雙核隔膜泵', **locals())
  2349. elif actuator == 'ThreeWayValveBean':
  2350. tank_threewayvalve_bean = tank_actuator.threewayvalve_bean
  2351. return render_template('ctrl_F_ThreeWayValveBean.html', title='[操作]F' + tid + '發酵槽_感測模組下豆三通閥', **locals())
  2352. elif actuator == 'ThreeWayValveFloat':
  2353. tank_threewayvalve_outer_float = tank_actuator.threewayvalve_outer_float
  2354. return render_template('ctrl_F_ThreeWayValveFloat.html', title='[操作]F' + tid + '發酵槽_外桶浮選三通閥', **locals())
  2355. elif actuator == 'SolenoidDisinfect':
  2356. tank_solenoid_tank_disinfect = tank_actuator.solenoid_tank_disinfect
  2357. return render_template('ctrl_F_SolenoidDisinfect.html', title='[操作]F' + tid + '發酵槽_桶內消毒電磁閥', **locals())
  2358. elif actuator == 'Motor':
  2359. tank_motor = tank_actuator.motor
  2360. return render_template('ctrl_F_Motor.html', title='[操作]F' + tid + '發酵槽_馬達', **locals())
  2361. elif actuator == 'Heater1':
  2362. tank_heater1 = tank_actuator.heater1
  2363. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  2364. return render_template('ctrl_F_Heater1.html', title='[操作]F' + tid + '發酵槽_加熱器 1', **locals())
  2365. elif actuator == 'Heater2':
  2366. tank_heater2 = tank_actuator.heater2
  2367. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  2368. return render_template('ctrl_F_Heater2.html', title='[操作]F' + tid + '發酵槽_加熱器 2', **locals())
  2369. elif actuator == 'TempEnable':
  2370. tank_temp_enable = tank_actuator.temp_enable
  2371. return render_template('ctrl_F_TempEnable.html', title='[操作]F' + tid + '發酵槽_溫控開關', **locals())
  2372. elif actuator == 'Temp':
  2373. tank_temp = tank_actuator.temp
  2374. tank_temp_enable = tank_actuator.temp_enable
  2375. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  2376. return render_template('ctrl_F_Temp.html', title='[操作]F' + tid + '發酵槽_溫度設定', **locals())
  2377. elif actuator == 'DiskValve':
  2378. tank_diskvalve = tank_actuator.diskvalve
  2379. return render_template('ctrl_F_DiskValve.html', title='[操作]F' + tid + '發酵槽_蝴蝶閥', **locals())
  2380. @main.route('/dry_Temp/<tid>/<Temp_Weights_SHT11>/<Temp_Weights_Soil>/<temp_data>', methods=['GET', 'POST'])
  2381. def dry_Temp(tid, Temp_Weights_SHT11, Temp_Weights_Soil, temp_data):
  2382. if request.method == 'GET':
  2383. if 'id' in session and 'uname' in session and 'status' in session:
  2384. username = session['uname']
  2385. status = session['status']
  2386. if status == 9:
  2387. return render_template('signin_disable.html', params=locals())
  2388. elif status == 8:
  2389. return render_template('signin_new.html', params=locals())
  2390. else:
  2391. return render_template('oops.html', params=locals())
  2392. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2393. SHT11_Temp = float(tank_SHT11.SHT11_Temp)
  2394. SHT11_Humidity = tank_SHT11.SHT11_Humidity
  2395. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2396. Soil_Temp = float(tank_Soil.soil_Temp)
  2397. Soil_Humidity = tank_Soil.soil_Humidity
  2398. Temp_Weights_SHT11= float(Temp_Weights_SHT11)
  2399. Temp_Weights_Soil = float(Temp_Weights_Soil)
  2400. temp_data = float(temp_data)
  2401. present_temp = math.ceil( (SHT11_Temp*Temp_Weights_SHT11 + Soil_Temp*Temp_Weights_Soil)/(Temp_Weights_SHT11+Temp_Weights_Soil) )
  2402. # Math.round((present_SHT11_Temp*Temp_Weights_SHT11 + present_SOIL_Temp*Temp_Weights_Soil)/(Temp_Weights_SHT11+Temp_Weights_Soil)*100) / 100
  2403. target_temp = math.ceil(temp_data)
  2404. TempUp = {
  2405. 22:0, 23:6, 24:12, 25:18, 26:24, 27:28, 28:32, 29:36, 30:40, 31:44, 32:48, 33:56, 34:64, 35:72, 36:96, 37:168, 38:288, 39:384, 40:529, 41:697, 42:793, 43:865, 44:1394
  2406. }
  2407. if target_temp in TempUp and present_temp in TempUp:
  2408. TempUpTime = ', 預計 ' + str(TempUp[target_temp] - TempUp[present_temp]) + ' 秒達到指定溫度'
  2409. elif target_temp < 22 or present_temp < 22 :
  2410. TempUpTime = '℃, 指定溫度過低, 持續升溫中'
  2411. elif target_temp > 44 or present_temp > 44 :
  2412. TempUpTime = '℃, 指定溫度過高, 持續升溫中'
  2413. return jsonify({"SHT11_Temp":SHT11_Temp,
  2414. "SHT11_Humidity":SHT11_Humidity,
  2415. "Soil_Temp":Soil_Temp,
  2416. "Soil_Humidity":Soil_Humidity,
  2417. "present_temp":present_temp,
  2418. "TempUpTime":TempUpTime
  2419. })
  2420. else:
  2421. pass
  2422. @main.route('/dry_container_tank/<tid>', methods=['GET', 'POST'])
  2423. def dry_container_tank(tid):
  2424. if request.method == 'GET':
  2425. if 'id' in session and 'uname' in session and 'status' in session:
  2426. username = session['uname']
  2427. status = session['status']
  2428. if status == 9:
  2429. return render_template('signin_disable.html', params=locals())
  2430. elif status == 8:
  2431. return render_template('signin_new.html', params=locals())
  2432. else:
  2433. return render_template('oops.html', params=locals())
  2434. # 感測器_乾燥桶_SHT11
  2435. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2436. num_SHT11_temp = float(tank_SHT11.SHT11_Temp)
  2437. # 感測器_乾燥桶_土壤三合一
  2438. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2439. num_Soil_temp = float(tank_Soil.soil_Temp)
  2440. # 感測器_乾燥桶_氣壓
  2441. tank_PA = dry_tank_PA.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2442. # 感測器_乾燥桶_超音波感測器
  2443. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2444. # 制動器_乾燥桶_ALL
  2445. tank_brake = dry_tank_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2446. tank_vacuum = tank_brake.vacuum
  2447. tank_threewayvalve = tank_brake.threewayvalve
  2448. tank_diskvalve = tank_brake.diskvalve
  2449. tank_solenoid_disinfect = tank_brake.solenoid_disinfect
  2450. tank_solenoid_water = tank_brake.solenoid_water
  2451. tank_motor = tank_brake.motor
  2452. tank_blower = tank_brake.blower
  2453. tank_heater1 = tank_brake.heater1
  2454. tank_heater2 = tank_brake.heater2
  2455. tank_temp1_enable = tank_brake.temp1_enable
  2456. tank_temp1 = tank_brake.temp1
  2457. Temp_weight = num_SHT11_temp * 0.5 + num_Soil_temp * 0.5
  2458. return render_template('dry_container_tank.html', title='[操作] D' + tid + ' 乾燥槽操作介面', **locals())
  2459. elif request.method == 'POST':
  2460. pass
  2461. @main.route('/dry_container_input/<tid>', methods=['GET', 'POST'])
  2462. def dry_container_input(tid):
  2463. if request.method == 'GET':
  2464. if 'id' in session and 'uname' in session and 'status' in session:
  2465. username = session['uname']
  2466. status = session['status']
  2467. if status == 9:
  2468. return render_template('signin_disable.html', params=locals())
  2469. elif status == 8:
  2470. return render_template('signin_new.html', params=locals())
  2471. else:
  2472. return render_template('oops.html', params=locals())
  2473. input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI'+str(tid)).order_by(text('datetime desc')).first()
  2474. input_vacuum = dry_input_brake.query.filter_by(tank_num='DI'+str(tid)).order_by(text('datetime desc')).first()
  2475. input_vacuum = input_vacuum.vacuum
  2476. return render_template('dry_container_input.html', title='[操作] DI' + tid + ' 乾燥入料儲豆槽操作介面', **locals())
  2477. elif request.method == 'POST':
  2478. pass
  2479. @main.route('/dry_container_output/<tid>', methods=['GET', 'POST'])
  2480. def dry_container_output(tid):
  2481. if request.method == 'GET':
  2482. if 'id' in session and 'uname' in session and 'status' in session:
  2483. username = session['uname']
  2484. status = session['status']
  2485. if status == 9:
  2486. return render_template('signin_disable.html', params=locals())
  2487. elif status == 8:
  2488. return render_template('signin_new.html', params=locals())
  2489. else:
  2490. return render_template('oops.html', params=locals())
  2491. output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO'+str(tid)).order_by(text('datetime desc')).first()
  2492. output_vacuum = dry_output_brake.query.filter_by(tank_num='DO'+str(tid)).order_by(text('datetime desc')).first()
  2493. output_vacuum = output_vacuum.vacuum
  2494. return render_template('dry_container_output.html', title='[操作] DO' + tid + ' 乾燥出料儲豆槽操作介面', **locals())
  2495. elif request.method == 'POST':
  2496. pass
  2497. # 原本的乾燥貨櫃控制, 備份用
  2498. @main.route('/dry_container/<tid>', methods=['GET', 'POST'])
  2499. def dry_container(tid):
  2500. if request.method == 'GET':
  2501. if 'id' in session and 'uname' in session and 'status' in session:
  2502. username = session['uname']
  2503. status = session['status']
  2504. if status == 9:
  2505. return render_template('signin_disable.html', params=locals())
  2506. elif status == 8:
  2507. return render_template('signin_new.html', params=locals())
  2508. else:
  2509. return render_template('oops.html', params=locals())
  2510. # Rita 參數 params 是用來取得參數的 locals=() 所有參數
  2511. '''
  2512. # 開啟本機 coffeetest 資料庫
  2513. # mydb = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='g53743001', database='coffeetest', charset='utf8')
  2514. mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffee',
  2515. password='skyeye', database='Coffee', charset='utf8')
  2516. mycursor = mydb.cursor()
  2517. '''
  2518. # 感測器_乾燥桶_SHT11
  2519. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2520. num_SHT11_temp = float(tank_SHT11.SHT11_Temp)
  2521. # 感測器_乾燥桶_土壤三合一
  2522. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2523. num_Soil_temp = float(tank_Soil.soil_Temp)
  2524. # 感測器_乾燥桶_氣壓
  2525. tank_PA = dry_tank_PA.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2526. # 感測器_乾燥桶_超音波感測器
  2527. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2528. # 感測器_出料儲豆槽_超音波感測器
  2529. output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2530. # 制動器_乾燥桶_ALL
  2531. tank_brake = dry_tank_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2532. tank_vacuum = tank_brake.vacuum
  2533. tank_threewayvalve = tank_brake.threewayvalve
  2534. tank_diskvalve = tank_brake.diskvalve
  2535. tank_solenoid_disinfect = tank_brake.solenoid_disinfect
  2536. tank_solenoid_water = tank_brake.solenoid_water
  2537. tank_motor = tank_brake.motor
  2538. tank_blower = tank_brake.blower
  2539. tank_heater1 = tank_brake.heater1
  2540. tank_heater2 = tank_brake.heater2
  2541. tank_temp1_enable = tank_brake.temp1_enable
  2542. tank_temp1 = tank_brake.temp1
  2543. '''
  2544. tank_vacuum = 'ON' if tank_brake.vacuum == 1 else 'OFF'
  2545. tank_threewayvalve = 'ON' if tank_brake.threewayvalve == 1 else 'OFF'
  2546. tank_diskvalve = 'ON' if tank_brake.diskvalve == 1 else 'OFF'
  2547. tank_solenoid_disinfect = 'ON' if tank_brake.solenoid_disinfect == 1 else 'OFF'
  2548. tank_solenoid_water = 'ON' if tank_brake.solenoid_water == 1 else 'OFF'
  2549. tank_motor = tank_brake.motor
  2550. tank_blower = 'ON' if tank_brake.blower == 1 else 'OFF'
  2551. tank_heater1 = 'ON' if tank_brake.heater1 == 1 else 'OFF'
  2552. tank_heater2 = 'ON' if tank_brake.heater2 == 1 else 'OFF'
  2553. tank_temp1_enable = 'ON' if tank_brake.temp1_enable == 1 else 'OFF'
  2554. tank_temp1 = tank_brake.temp1
  2555. '''
  2556. '''
  2557. data = mycursor.execute(
  2558. 'SELECT * FROM dry_tank_brake ORDER BY datetime DESC;')
  2559. data = mycursor.fetchone()
  2560. '''
  2561. if tid in ['1', '2', '3', '4', '5', '6']:
  2562. # print("1")
  2563. # 感測器_入料儲豆槽_超音波感測器
  2564. input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI1').order_by(text('datetime desc')).first()
  2565. # 制動器_入料儲豆槽_真空吸引機
  2566. input_vacuum = dry_input_brake.query.filter_by(tank_num='DI1').order_by(text('datetime desc')).first()
  2567. input_vacuum = input_vacuum.vacuum
  2568. # 感測器_出料儲豆槽_超音波感測器
  2569. output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO1').order_by(text('datetime desc')).first()
  2570. # 制動器_出料儲豆槽_真空吸引機
  2571. output_vacuum = dry_output_brake.query.filter_by(tank_num='DO1').order_by(text('datetime desc')).first()
  2572. output_vacuum = output_vacuum.vacuum
  2573. elif tid in ['7', '8', '9', '10', '11', '12']:
  2574. print("2")
  2575. # 感測器_入料儲豆槽_超音波感測器
  2576. input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI2').order_by(text('datetime desc')).first()
  2577. # 制動器_入料儲豆槽_真空吸引機
  2578. input_vacuum = dry_input_brake.query.filter_by(tank_num='DI2').order_by(text('datetime desc')).first()
  2579. input_vacuum = input_vacuum.vacuum
  2580. # 感測器_出料儲豆槽_超音波感測器
  2581. output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO2').order_by(text('datetime desc')).first()
  2582. # 制動器_出料儲豆槽_真空吸引機
  2583. output_vacuum = dry_output_brake.query.filter_by(tank_num='DO2').order_by(text('datetime desc')).first()
  2584. output_vacuum = output_vacuum.vacuum
  2585. '''
  2586. # 感測器_入料儲豆槽_超音波感測器
  2587. input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2588. # 制動器_入料儲豆槽_真空吸引機
  2589. input_vacuum = dry_input_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2590. # print("input_vacuum:", input_vacuum)
  2591. input_vacuum = input_vacuum.vacuum
  2592. #print('input_vacuum:', input_vacuum.vacuum)
  2593. # 制動器_出料儲豆槽_真空吸引機
  2594. output_vacuum = dry_output_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  2595. #print('output_vacuum.vacuum: ', output_vacuum.vacuum)
  2596. output_vacuum = 'ON' if (output_vacuum.vacuum == 1) else 'OFF'
  2597. #print('output_vacuum: ', output_vacuum)
  2598. '''
  2599. # 傳 MQTT 給阿超, 阿超讓硬體動作, 將資料儲存到資料庫
  2600. input_data = set_dry_input.query.order_by(text('datetime desc')).first()
  2601. schedule_input_height = input_data.input_height
  2602. schedule_input_entertime = input_data.input_entertime
  2603. schedule_input_exittime = input_data.input_exittime
  2604. schedule_tank_height = input_data.tank_height
  2605. return render_template('dry_container.html', title='dry_container', **locals())
  2606. elif request.method == 'POST':
  2607. # 表單輸入處
  2608. print('/dry_input_setting POST')
  2609. set = set_dry_input()
  2610. set.input_height = request.form['schedule_input_height']
  2611. set.input_entertime = request.form['schedule_input_entertime']
  2612. set.input_exittime = request.form['schedule_input_exittime']
  2613. set.tank_height = request.form['schedule_tank_height']
  2614. #將數據保存進資料庫 - 註冊
  2615. db.session.add(set)
  2616. # 手動提交,目的是為了獲取提交後的user的id
  2617. db.session.commit()
  2618. # 當user成功插入進資料庫之後,程序會自動將所有信息取出來在賦值給user
  2619. # 完成登入的操作
  2620. # setting = Set_dry_input.query.order_by(text('datetime desc')).first()
  2621. #session['id'] = set.userID
  2622. #session['uname'] = set.username
  2623. return redirect('/dry_container')
  2624. # 登入頁面的訪問路徑
  2625. @main.route('/login', methods=['GET', 'POST'])
  2626. def login_views():
  2627. if request.method == 'GET':
  2628. if 'id' in session and 'uname' in session and 'status' in session:
  2629. return redirect('/')
  2630. else:
  2631. return render_template('sign_in.html')
  2632. else:
  2633. # 接收前端傳過來的資料
  2634. username = request.form['username']
  2635. password = request.form['password']
  2636. # 使用接收的用戶和密碼到資料庫中查詢
  2637. user = User.query.filter_by(
  2638. username=username, password=password).first()
  2639. # 如果用戶存在,將信息保存置session並重定向回首頁,否則重定向回登入頁
  2640. if user:
  2641. resp = redirect('/')
  2642. # 判斷是否有記住密碼
  2643. if 'rem' in request.form:
  2644. userID = str(user.userID)
  2645. max_age = 60*60*24*365
  2646. status = str(user.status)
  2647. print('status: ', status)
  2648. # Rita 以秒為單位, 一年
  2649. # Rita 功能和 expires 很像,但此參數並非所有瀏覽器均支持,所以建議使用 expires 參數。
  2650. # Rita expires:指定 Cookie 的有效日期, 當過了有效日期後就不會儲存在瀏覽器
  2651. resp.set_cookie("username", username, max_age=max_age)
  2652. resp.set_cookie("userID", userID, max_age=max_age)
  2653. resp.set_cookie("status", status, max_age=max_age)
  2654. session['uname'] = user.username
  2655. session['id'] = user.userID
  2656. session['status'] = user.status
  2657. return resp
  2658. else:
  2659. errMsg = "Wrong login or password"
  2660. return render_template('sign_in.html', errMsg=errMsg)
  2661. # 登入重設密碼的頁面
  2662. # Rita reset_pwd1 - Email
  2663. # Rita reset_pwd2 - New password / Confirm password
  2664. @main.route('/reset_password', methods=['POST', 'GET'])
  2665. def reset_password_views():
  2666. if request.method == 'GET':
  2667. if 'mail' in session:
  2668. del session['mail']
  2669. return render_template('reset_pwd1.html')
  2670. else:
  2671. # POST
  2672. # 如果有id在session裡,代表從reset_pwd2過來的 ? 對, reset_pwd2 POST (但也有其他可能)
  2673. if "mail" in session:
  2674. new_pwd = request.form['new_pwd']
  2675. confirm_pwd = request.form['confirm_pwd']
  2676. # 判斷密碼是否一致
  2677. if new_pwd == confirm_pwd:
  2678. mail = session['mail']
  2679. user = User.query.filter_by(mail=mail).first()
  2680. print("user: ", user)
  2681. print("user.password_before: ", user.password)
  2682. print("new_pwd: ", new_pwd)
  2683. user.password = new_pwd
  2684. print("user.password_after: ", user.password)
  2685. db.session.add(user)
  2686. db.session.commit()
  2687. del session['mail']
  2688. # 修改完後回登入頁
  2689. return redirect('/login')
  2690. else:
  2691. errMsg = "Passwords does not match"
  2692. # Rita 前面的 errMsg 是指網頁上的 {{errMsg}} 位置
  2693. return render_template('reset_pwd2.html', errMsg=errMsg)
  2694. email = request.form['email']
  2695. user = User.query.filter_by(mail=email).first()
  2696. if user: # Rita 有找到對應 email
  2697. session['mail'] = user.mail
  2698. return render_template('reset_pwd2.html')
  2699. else:
  2700. errMsg = "Wrong email.Please try again"
  2701. return render_template('reset_pwd1.html', errMsg=errMsg)
  2702. # 註冊頁面的訪問路徑
  2703. @main.route('/register', methods=['POST', "GET"])
  2704. def register_views():
  2705. if request.method == 'GET':
  2706. return render_template('registration.html')
  2707. else:
  2708. # 獲取文本框的值並賦值給user實體對象
  2709. user = User()
  2710. user.firstname = request.form['firstname']
  2711. user.lastname = request.form['lastname']
  2712. user.mail = request.form['email']
  2713. user.phone = request.form['phone']
  2714. user.username = request.form['username']
  2715. user.password = request.form['password']
  2716. user.status = 8 # Rita app\models.py 設定 0:admin;1:new;9:disable [0906 更新] 0:admin;1:superuser;2:enduser;8:new;9:disable
  2717. #將數據保存進資料庫 - 註冊
  2718. db.session.add(user)
  2719. # 手動提交,目的是為了獲取提交後的user的id
  2720. db.session.commit()
  2721. # 當user成功插入進資料庫之後,程序會自動將所有信息取出來在賦值給user
  2722. # 完成登入的操作
  2723. user = User.query.filter_by(username=user.username).first()
  2724. session['status'] = user.status
  2725. session['id'] = user.userID
  2726. session['uname'] = user.username
  2727. return redirect('/')
  2728. # 驗證email訪問路徑
  2729. @main.route('/check_email')
  2730. def check_email_views():
  2731. email = request.args['email']
  2732. user = User.query.filter_by(mail=email).first()
  2733. if user:
  2734. # Rita email 錯誤時會顯示 Incorrect email address
  2735. result = {"errMsg": " "}
  2736. else:
  2737. result = {"pass": " "}
  2738. return json.dumps(result)
  2739. # 驗證username訪問路徑
  2740. @main.route('/check_username')
  2741. def check_username_views():
  2742. username = request.args['username']
  2743. user = User.query.filter_by(username=username).first()
  2744. if user:
  2745. result = {"errMsg": " "}
  2746. else:
  2747. result = {"pass": " "}
  2748. return json.dumps(result)
  2749. # 咖啡貨櫃的訪問路徑
  2750. @main.route('/cargo_list', methods=['GET', 'POST'])
  2751. def cargo_list_views():
  2752. username = session['uname']
  2753. if request.method == 'GET':
  2754. return render_template('cargo_list.html', params=locals())
  2755. else:
  2756. pass
  2757. # 貨櫃1的訪問路徑
  2758. @main.route('/cargo1', methods=['GET', 'POST'])
  2759. def cargo1_views():
  2760. username = session['uname']
  2761. if request.method == 'GET':
  2762. return render_template('cargo1.html', params=locals())
  2763. else:
  2764. pass
  2765. # 貨櫃1排程的訪問路徑
  2766. @main.route('/cargo1_schedule', methods=['GET', 'POST'])
  2767. def cargo1_schedule_views():
  2768. username = session['uname']
  2769. if request.method == 'GET':
  2770. # 將已儲存的排程資料傳給前端
  2771. # 進豆閥
  2772. try:
  2773. bean = BeanValve.query.order_by(text('datetime desc')).first()
  2774. datetime = bean.datetime
  2775. beans = BeanValve.query.filter_by(
  2776. datetime=datetime).all()
  2777. except Exception as e:
  2778. pass
  2779. # 清洗機
  2780. try:
  2781. wash = WashMachine.query.order_by(text('datetime desc')).first()
  2782. datetime = wash.datetime
  2783. washes = WashMachine.query.filter_by(datetime=datetime).all()
  2784. except Exception as e:
  2785. pass
  2786. # 輸送帶1
  2787. try:
  2788. belt1 = ConveyorBelt1.query.order_by(text('datetime desc')).first()
  2789. datetime = belt1.datetime
  2790. belts1 = ConveyorBelt1.query.filter_by(datetime=datetime).all()
  2791. except Exception as e:
  2792. pass
  2793. # ///////////////////////////////////////////////////////////////////////////////////////////
  2794. # 消毒機
  2795. try:
  2796. disinfect = Cargo1Disinfect.query.order_by(
  2797. text('datetime desc')).first()
  2798. datetime = disinfect.datetime
  2799. disinfects = Cargo1Disinfect.query.filter_by(
  2800. datetime=datetime).all()
  2801. except Exception as e:
  2802. pass
  2803. # 色選機
  2804. try:
  2805. color = ColorMachine.query.order_by(text('datetime desc')).first()
  2806. datetime = color.datetime
  2807. colors = ColorMachine.query.filter_by(datetime=datetime).all()
  2808. except Exception as e:
  2809. pass
  2810. # 輸送帶2
  2811. try:
  2812. belt2 = ConveyorBelt2.query.order_by(text('datetime desc')).first()
  2813. datetime = belt2.datetime
  2814. belts2 = ConveyorBelt2.query.filter_by(datetime=datetime).all()
  2815. except Exception as e:
  2816. pass
  2817. # 去皮機
  2818. try:
  2819. peeling = PeelingMachine.query.order_by(
  2820. text('datetime desc')).first()
  2821. datetime = peeling.datetime
  2822. peelings = PeelingMachine.query.filter_by(datetime=datetime).all()
  2823. except Exception as e:
  2824. pass
  2825. # 輸送帶3
  2826. try:
  2827. belt3 = ConveyorBelt3.query.order_by(text('datetime desc')).first()
  2828. datetime = belt3.datetime
  2829. belts3 = ConveyorBelt3.query.filter_by(datetime=datetime).all()
  2830. except Exception as e:
  2831. pass
  2832. return render_template('cargo1_schedule.html', params=locals())
  2833. else:
  2834. current_time = dt.now()
  2835. # 循環從前端提交過來的資料
  2836. for i in request.form:
  2837. # 進豆閥
  2838. if i[:10] == 'inletValve':
  2839. if i[:19] == 'inletValve_duration':
  2840. bean = BeanValve()
  2841. bean.duration = request.form[i]
  2842. elif i[:18] == 'inletValve_from_hr':
  2843. iv_from_hr = request.form[i]
  2844. elif i[:19] == 'inletValve_from_min':
  2845. iv_from_min = request.form[i]
  2846. bean.start = iv_from_hr + ":" + iv_from_min
  2847. elif i[:16] == 'inletValve_to_hr':
  2848. iv_to_hr = request.form[i]
  2849. elif i[:17] == 'inletValve_to_min':
  2850. iv_to_min = request.form[i]
  2851. bean.end = iv_to_hr + ":" + iv_to_min
  2852. bean.datetime = current_time
  2853. db.session.add(bean)
  2854. db.session.commit()
  2855. # 清洗機
  2856. elif i[:4] == 'wash':
  2857. if i[:13] == 'wash_duration':
  2858. wash = WashMachine()
  2859. wash.duration = request.form[i]
  2860. elif i[:12] == 'wash_from_hr':
  2861. wash_from_hr = request.form[i]
  2862. elif i[:13] == 'wash_from_min':
  2863. wash_from_min = request.form[i]
  2864. wash.start = wash_from_hr + ":" + wash_from_min
  2865. elif i[:10] == 'wash_to_hr':
  2866. wash_to_hr = request.form[i]
  2867. elif i[:11] == 'wash_to_min':
  2868. wash_to_min = request.form[i]
  2869. wash.end = wash_to_hr + ":" + wash_to_min
  2870. wash.datetime = current_time
  2871. db.session.add(wash)
  2872. db.session.commit()
  2873. # 輸送帶1
  2874. elif i[:5] == 'belt1':
  2875. if i[:14] == 'belt1_duration':
  2876. belt1 = ConveyorBelt1()
  2877. belt1.duration = request.form[i]
  2878. elif i[:13] == 'belt1_from_hr':
  2879. belt1_from_hr = request.form[i]
  2880. elif i[:14] == 'belt1_from_min':
  2881. belt1_from_min = request.form[i]
  2882. belt1.start = belt1_from_hr + ":" + belt1_from_min
  2883. elif i[:11] == 'belt1_to_hr':
  2884. belt1_to_hr = request.form[i]
  2885. elif i[:12] == 'belt1_to_min':
  2886. belt1_to_min = request.form[i]
  2887. belt1.end = belt1_to_hr + ":" + belt1_to_min
  2888. belt1.datetime = current_time
  2889. db.session.add(belt1)
  2890. db.session.commit()
  2891. # 消毒
  2892. elif i[:9] == 'disinfect':
  2893. if i[:18] == 'disinfect_duration':
  2894. disinfect = Cargo1Disinfect()
  2895. disinfect.duration = request.form[i]
  2896. elif i[:17] == 'disinfect_from_hr':
  2897. di_from_hr = request.form[i]
  2898. elif i[:18] == 'disinfect_from_min':
  2899. di_from_min = request.form[i]
  2900. disinfect.start = di_from_hr + ":" + di_from_min
  2901. elif i[:15] == 'disinfect_to_hr':
  2902. di_to_hr = request.form[i]
  2903. elif i[:16] == 'disinfect_to_min':
  2904. di_to_min = request.form[i]
  2905. disinfect.end = di_to_hr + ":" + di_to_min
  2906. disinfect.datetime = current_time
  2907. db.session.add(disinfect)
  2908. db.session.commit()
  2909. # 色選機
  2910. elif i[:5] == 'color':
  2911. if i[:14] == 'color_duration':
  2912. color = ColorMachine()
  2913. color.duration = request.form[i]
  2914. elif i[:13] == 'color_from_hr':
  2915. color_from_hr = request.form[i]
  2916. elif i[:14] == 'color_from_min':
  2917. color_from_min = request.form[i]
  2918. color.start = color_from_hr + ":" + color_from_min
  2919. elif i[:11] == 'color_to_hr':
  2920. color_to_hr = request.form[i]
  2921. elif i[:12] == 'color_to_min':
  2922. color_to_min = request.form[i]
  2923. color.end = color_to_hr + ":" + color_to_min
  2924. color.datetime = current_time
  2925. db.session.add(color)
  2926. db.session.commit()
  2927. # 輸送帶2
  2928. elif i[:5] == 'belt2':
  2929. if i[:14] == 'belt2_duration':
  2930. belt2 = ConveyorBelt2()
  2931. belt2.duration = request.form[i]
  2932. elif i[:13] == 'belt2_from_hr':
  2933. belt2_from_hr = request.form[i]
  2934. elif i[:14] == 'belt2_from_min':
  2935. belt2_from_min = request.form[i]
  2936. belt2.start = belt2_from_hr + ":" + belt2_from_min
  2937. elif i[:11] == 'belt2_to_hr':
  2938. belt2_to_hr = request.form[i]
  2939. elif i[:12] == 'belt2_to_min':
  2940. belt2_to_min = request.form[i]
  2941. belt2.end = belt2_to_hr + ":" + belt2_to_min
  2942. belt2.datetime = current_time
  2943. db.session.add(belt2)
  2944. db.session.commit()
  2945. # 去皮機
  2946. elif i[:6] == 'peeled':
  2947. if i[:15] == 'peeled_duration':
  2948. peeling = PeelingMachine()
  2949. peeling.duration = request.form[i]
  2950. elif i[:14] == 'peeled_from_hr':
  2951. peeled_from_hr = request.form[i]
  2952. elif i[:15] == 'peeled_from_min':
  2953. peeled_from_min = request.form[i]
  2954. peeling.start = peeled_from_hr + ":" + peeled_from_min
  2955. elif i[:12] == 'peeled_to_hr':
  2956. peeled_to_hr = request.form[i]
  2957. elif i[:13] == 'peeled_to_min':
  2958. peeled_to_min = request.form[i]
  2959. peeling.end = peeled_to_hr + ":" + peeled_to_min
  2960. peeling.datetime = current_time
  2961. db.session.add(peeling)
  2962. db.session.commit()
  2963. # 輸送帶3
  2964. elif i[:5] == 'belt3':
  2965. if i[:14] == 'belt3_duration':
  2966. belt3 = ConveyorBelt3()
  2967. belt3.duration = request.form[i]
  2968. elif i[:13] == 'belt3_from_hr':
  2969. belt3_from_hr = request.form[i]
  2970. elif i[:14] == 'belt3_from_min':
  2971. belt3_from_min = request.form[i]
  2972. belt3.start = belt3_from_hr + ":" + belt3_from_min
  2973. elif i[:11] == 'belt3_to_hr':
  2974. belt3_to_hr = request.form[i]
  2975. elif i[:12] == 'belt3_to_min':
  2976. belt3_to_min = request.form[i]
  2977. belt3.end = belt3_to_hr + ":" + belt3_to_min
  2978. belt3.datetime = current_time
  2979. db.session.add(belt3)
  2980. db.session.commit()
  2981. return render_template('cargo1.html', params=locals())
  2982. # 貨櫃2的訪問路徑
  2983. @main.route('/cargo2', methods=['GET', 'POST'])
  2984. def cargo2_views():
  2985. username = session['uname']
  2986. if request.method == 'GET':
  2987. return render_template('cargo2.html', params=locals())
  2988. else:
  2989. pass
  2990. # 貨櫃2排程的發酵槽訪問路徑
  2991. @main.route('/cargo2_schedule_tanks', methods=['GET', 'POST'])
  2992. def cargo2_schedule_tanks_views():
  2993. username = session['uname']
  2994. if request.method == 'GET':
  2995. return render_template('cargo2_schedule_tanks.html', params=locals())
  2996. else:
  2997. pass
  2998. # 貨櫃2排程發酵槽的清單訪問路徑
  2999. @main.route('/cargo2_schedule/<tid>', methods=['GET', 'POST'])
  3000. def cargo2_schedule_views(tid):
  3001. username = session['uname']
  3002. if request.method == 'GET':
  3003. # 將已儲存的排程資料傳給前端
  3004. # 打菌
  3005. try:
  3006. bacteria = Bacteria.query.filter_by(tank_num=int(
  3007. tid)).order_by(text('datetime desc')).first()
  3008. datetime = bacteria.datetime
  3009. bacterias = Bacteria.query.filter_by(datetime=datetime).all()
  3010. except Exception as e:
  3011. pass
  3012. # 消毒
  3013. try:
  3014. disinfect = Cargo2Disinfect.query.filter_by(
  3015. tank_num=int(tid)).order_by(text('datetime desc')).first()
  3016. datetime = disinfect.datetime
  3017. disinfects = Cargo2Disinfect.query.filter_by(
  3018. datetime=datetime).all()
  3019. except Exception as e:
  3020. pass
  3021. # 加熱
  3022. try:
  3023. heating = Heating.query.filter_by(tank_num=int(
  3024. tid)).order_by(text('datetime desc')).first()
  3025. datetime = heating.datetime
  3026. heatings = Heating.query.filter_by(datetime=datetime).all()
  3027. except Exception as e:
  3028. pass
  3029. # 攪拌
  3030. try:
  3031. stir = Stir.query.filter_by(tank_num=int(tid)).order_by(
  3032. text('datetime desc')).first()
  3033. datetime = stir.datetime
  3034. stirs = Stir.query.filter_by(datetime=datetime).all()
  3035. except Exception as e:
  3036. pass
  3037. # 注水
  3038. try:
  3039. water = WaterInjection.query.filter_by(
  3040. tank_num=int(tid)).order_by(text('datetime desc')).first()
  3041. datetime = water.datetime
  3042. waters = WaterInjection.query.filter_by(datetime=datetime).all()
  3043. except Exception as e:
  3044. pass
  3045. # 開上閥
  3046. try:
  3047. top = TopValve.query.filter_by(tank_num=int(
  3048. tid)).order_by(text('datetime desc')).first()
  3049. datetime = top.datetime
  3050. tops = TopValve.query.filter_by(datetime=datetime).all()
  3051. except Exception as e:
  3052. pass
  3053. # 開下閥
  3054. try:
  3055. bottom = BottomValve.query.filter_by(tank_num=int(
  3056. tid)).order_by(text('datetime desc')).first()
  3057. datetime = bottom.datetime
  3058. bottoms = BottomValve.query.filter_by(datetime=datetime).all()
  3059. except Exception as e:
  3060. pass
  3061. # 溫度
  3062. try:
  3063. tem = Temperature.query.filter_by(tank_num=int(
  3064. tid)).order_by(text('datetime desc')).first()
  3065. datetime = tem.datetime
  3066. tems = Temperature.query.filter_by(datetime=datetime).all()
  3067. except Exception as e:
  3068. pass
  3069. return render_template('cargo2_schedule.html', params=locals())
  3070. else:
  3071. current_time = dt.now()
  3072. # 循環從前端提交過來的資料
  3073. for i in request.form:
  3074. # 打菌
  3075. if i[:8] == 'bacteria':
  3076. if i[:17] == 'bacteria_duration':
  3077. bacteria = Bacteria()
  3078. bacteria.duration = request.form[i]
  3079. elif i[:16] == 'bacteria_from_hr':
  3080. bac_from_hr = request.form[i]
  3081. elif i[:17] == 'bacteria_from_min':
  3082. bac_from_min = request.form[i]
  3083. bacteria.start = bac_from_hr + ":" + bac_from_min
  3084. elif i[:14] == 'bacteria_to_hr':
  3085. bac_to_hr = request.form[i]
  3086. elif i[:15] == 'bacteria_to_min':
  3087. bac_to_min = request.form[i]
  3088. bacteria.end = bac_to_hr + ":" + bac_to_min
  3089. bacteria.datetime = current_time
  3090. bacteria.tank_num = int(tid)
  3091. db.session.add(bacteria)
  3092. db.session.commit()
  3093. # 消毒
  3094. elif i[:9] == 'disinfect':
  3095. if i[:18] == 'disinfect_duration':
  3096. disinfect = Cargo2Disinfect()
  3097. disinfect.duration = request.form[i]
  3098. elif i[:17] == 'disinfect_from_hr':
  3099. di_from_hr = request.form[i]
  3100. elif i[:18] == 'disinfect_from_min':
  3101. di_from_min = request.form[i]
  3102. disinfect.start = di_from_hr + ":" + di_from_min
  3103. elif i[:15] == 'disinfect_to_hr':
  3104. di_to_hr = request.form[i]
  3105. elif i[:16] == 'disinfect_to_min':
  3106. di_to_min = request.form[i]
  3107. disinfect.end = di_to_hr + ":" + di_to_min
  3108. disinfect.datetime = current_time
  3109. disinfect.tank_num = int(tid)
  3110. db.session.add(disinfect)
  3111. db.session.commit()
  3112. # 加熱
  3113. elif i[:7] == 'heating':
  3114. if i[:16] == 'heating_duration':
  3115. heating = Heating()
  3116. heating.duration = request.form[i]
  3117. elif i[:15] == 'heating_from_hr':
  3118. heat_from_hr = request.form[i]
  3119. elif i[:16] == 'heating_from_min':
  3120. heat_from_min = request.form[i]
  3121. heating.start = heat_from_hr + ":" + heat_from_min
  3122. elif i[:13] == 'heating_to_hr':
  3123. heat_to_hr = request.form[i]
  3124. elif i[:14] == 'heating_to_min':
  3125. heat_to_min = request.form[i]
  3126. heating.end = heat_to_hr + ":" + heat_to_min
  3127. heating.datetime = current_time
  3128. heating.tank_num = int(tid)
  3129. db.session.add(heating)
  3130. db.session.commit()
  3131. # 攪拌
  3132. elif i[:4] == 'stir':
  3133. if i[:13] == 'stir_duration':
  3134. stir = Stir()
  3135. stir.duration = request.form[i]
  3136. elif i[:12] == 'stir_from_hr':
  3137. stir_from_hr = request.form[i]
  3138. elif i[:13] == 'stir_from_min':
  3139. stir_from_min = request.form[i]
  3140. stir.start = stir_from_hr + ":" + stir_from_min
  3141. elif i[:10] == 'stir_to_hr':
  3142. stir_to_hr = request.form[i]
  3143. elif i[:11] == 'stir_to_min':
  3144. stir_to_min = request.form[i]
  3145. stir.end = stir_to_hr + ":" + stir_to_min
  3146. stir.datetime = current_time
  3147. stir.tank_num = int(tid)
  3148. db.session.add(stir)
  3149. db.session.commit()
  3150. # 注水
  3151. elif i[:5] == 'water':
  3152. if i[:14] == 'water_duration':
  3153. water = WaterInjection()
  3154. water.duration = request.form[i]
  3155. elif i[:13] == 'water_from_hr':
  3156. water_from_hr = request.form[i]
  3157. elif i[:14] == 'water_from_min':
  3158. water_from_min = request.form[i]
  3159. water.start = water_from_hr + ":" + water_from_min
  3160. elif i[:11] == 'water_to_hr':
  3161. water_to_hr = request.form[i]
  3162. elif i[:12] == 'water_to_min':
  3163. water_to_min = request.form[i]
  3164. water.end = water_to_hr + ":" + water_to_min
  3165. water.datetime = current_time
  3166. water.tank_num = int(tid)
  3167. db.session.add(water)
  3168. db.session.commit()
  3169. # 開上閥
  3170. elif i[:9] == 'highValve':
  3171. if i[:18] == 'highValve_duration':
  3172. top = TopValve()
  3173. top.duration = request.form[i]
  3174. elif i[:17] == 'highValve_from_hr':
  3175. h_valve_from_hr = request.form[i]
  3176. elif i[:18] == 'highValve_from_min':
  3177. h_valve_from_min = request.form[i]
  3178. top.start = h_valve_from_hr + ":" + h_valve_from_min
  3179. elif i[:15] == 'highValve_to_hr':
  3180. h_valve_to_hr = request.form[i]
  3181. elif i[:16] == 'highValve_to_min':
  3182. h_valve_to_min = request.form[i]
  3183. top.end = h_valve_to_hr + ":" + h_valve_to_min
  3184. top.datetime = current_time
  3185. top.tank_num = int(tid)
  3186. db.session.add(top)
  3187. db.session.commit()
  3188. # 開下閥
  3189. elif i[:8] == 'lowValve':
  3190. if i[:17] == 'lowValve_duration':
  3191. bottom = BottomValve()
  3192. bottom.duration = request.form[i]
  3193. elif i[:16] == 'lowValve_from_hr':
  3194. l_valve_from_hr = request.form[i]
  3195. elif i[:17] == 'lowValve_from_min':
  3196. l_valve_from_min = request.form[i]
  3197. bottom.start = l_valve_from_hr + ":" + l_valve_from_min
  3198. elif i[:14] == 'lowValve_to_hr':
  3199. l_valve_to_hr = request.form[i]
  3200. elif i[:15] == 'lowValve_to_min':
  3201. l_valve_to_min = request.form[i]
  3202. bottom.end = l_valve_to_hr + ":" + l_valve_to_min
  3203. bottom.datetime = current_time
  3204. bottom.tank_num = int(tid)
  3205. db.session.add(bottom)
  3206. db.session.commit()
  3207. # 溫度
  3208. elif i[:3] == 'tem':
  3209. if i[:12] == 'tem_duration':
  3210. tem = Temperature()
  3211. tem.duration = request.form[i]
  3212. elif i[:11] == 'tem_from_hr':
  3213. tem_from_hr = request.form[i]
  3214. elif i[:12] == 'tem_from_min':
  3215. tem_from_min = request.form[i]
  3216. tem.start = tem_from_hr + ":" + tem_from_min
  3217. elif i[:9] == 'tem_to_hr':
  3218. tem_to_hr = request.form[i]
  3219. elif i[:10] == 'tem_to_min':
  3220. tem_to_min = request.form[i]
  3221. tem.end = tem_to_hr + ":" + tem_to_min
  3222. tem.datetime = current_time
  3223. tem.tank_num = int(tid)
  3224. db.session.add(tem)
  3225. db.session.commit()
  3226. return render_template('cargo2.html', params=locals())
  3227. # 貨櫃2感測器的發酵槽訪問路徑
  3228. @main.route('/cargo2_sensor_tanks', methods=['GET', 'POST'])
  3229. def cargo2_sensor_tanks_views():
  3230. username = session['uname']
  3231. if request.method == 'GET':
  3232. return render_template('cargo2_sensor_tanks.html', params=locals())
  3233. else:
  3234. pass
  3235. # 貨櫃2感測器發酵槽的清單訪問路徑
  3236. @main.route('/cargo2_sensor/<tid>', methods=['GET', 'POST'])
  3237. def s_tank_views(tid):
  3238. # 判斷用戶是否已關閉瀏覽器或登出後,在訪問這個route,如果沒有session就回登入頁
  3239. try:
  3240. username = session['uname']
  3241. except KeyError:
  3242. return redirect('/')
  3243. if request.method == 'GET':
  3244. # Rita 網頁端 params.tank_tem.tem
  3245. # Coffee/CoffeeProject/app/templates/cargo2_sensor.html
  3246. tank_tem = TankTemSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
  3247. tank_ph = TankPHSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
  3248. tank_ec = TankECSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
  3249. tank_sonic = TankSonicSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
  3250. return render_template('cargo2_sensor.html', params=locals())
  3251. else:
  3252. pass
  3253. # 貨櫃2感測器發酵槽歷史數據的訪問路徑
  3254. @main.route('/history_data', methods=['GET', 'POST'])
  3255. def history_data_views():
  3256. if request.method == 'GET':
  3257. # json
  3258. # tid:tid_D1
  3259. # sensor_name:soil_Temp
  3260. # avg:1
  3261. # max:1
  3262. # min:1
  3263. # time-interval:month
  3264. # date-start:2021-07-01
  3265. # date-end:2021-07-28
  3266. info = request.args.to_dict()
  3267. evt = info['evt']
  3268. avg = int(info['avg'])
  3269. max = int(info['max'])
  3270. min = int(info['min'])
  3271. time_interval = info['time-interval']
  3272. print(info)
  3273. # Rita {'evt': '1-溫濕度', 'avg': '1', 'max': '0', 'min': '0', 'time-interval': 'month',
  3274. # 'date-start': '2021-05-04', 'date-end': '2021-05-18'} {'all': [], 'avg': []}
  3275. # print(info)
  3276. # {'evt': '1-溫濕度', 'avg': '1', 'max': '0', 'min': '0', 'time-interval': 'hour', 'date-start': '2021-01-01', 'date-end': '2021-07-27'}
  3277. # print(D)
  3278. # {'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']],
  3279. # 'avg': [['2021-02-19 16:00:00', '24.5'], ['2021-02-19 18:00:00', '25.3']]}
  3280. # 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 -
  3281. date_start = info['date-start']
  3282. date_end_list = info['date-end'].split('-') # 先把 'date-end' 的 '2021-05-18' 拆成 ['2021', '05', '18']
  3283. date_end_list[2] = str(int(date_end_list[2]) + 1) # 18 + 1 = 19 再轉成 str → '19'
  3284. date_end = '-'.join(date_end_list) # '2021-05-19'
  3285. tank_num = evt.split('-')[0] # 1
  3286. sensor = evt.split('-')[1] # 溫濕度
  3287. L = []
  3288. D = {}
  3289. maxData = []
  3290. minData = []
  3291. avgData = []
  3292. def sensorData(data_name): # data_name = "tem"
  3293. def dataResample(time_interval, how, data_name): # dataResample('month', how???, "tem") # 下方 "hour"
  3294. interval = 0
  3295. # 設置resample的第一個參數,要按照逐月、逐日或逐時
  3296. if time_interval == 'month':
  3297. interval = "M" # interval = "M"
  3298. elif time_interval == 'day':
  3299. interval = "D"
  3300. elif time_interval == 'hour':
  3301. interval = "H"
  3302. if how == "max":
  3303. # data = df.resample(interval, how={data_name:how})
  3304. # 最新版的pandas
  3305. data = df.resample(interval).max() # 取樣頻率 'H'
  3306. # 刪除有 NaN 的列, any 任何一欄位為空則刪 (all 全部欄位為空值才刪)
  3307. data = data.dropna(axis=0, how='any')
  3308. if time_interval == ('hour' or 'day'):
  3309. data.index = pd.to_datetime(
  3310. data.index, format='%Y-%b-%d_%H:%M:%S') # 将数据类型转换为日期类型
  3311. for a in range(0, len(data.index)):
  3312. l = []
  3313. # 如果是逐時,才顯示小時分秒
  3314. if time_interval == 'hour':
  3315. l.append(str(data.index[a]))
  3316. else:
  3317. l.append(str(data.index[a]).split(' ')[0])
  3318. l.append(str(data[data_name][a]))
  3319. maxData.append(l)
  3320. D['max'] = maxData
  3321. elif how == "mean":
  3322. # data = df.resample(interval, how={data_name:how})
  3323. # 最新版的pandas
  3324. data = df.resample(interval).mean()
  3325. # 刪除具有NaN的值
  3326. data = data.dropna(axis=0, how='any')
  3327. # 將平均數取自小數1位
  3328. data = data.round({data_name: 1})
  3329. for a in range(0, len(data.index)):
  3330. l = []
  3331. # 如果是逐時,才顯示小時分秒
  3332. if time_interval == 'hour':
  3333. l.append(str(data.index[a]))
  3334. else:
  3335. l.append(str(data.index[a]).split(' ')[0])
  3336. l.append(str(data[data_name][a]))
  3337. avgData.append(l)
  3338. D['avg'] = avgData
  3339. elif how == "min":
  3340. # data = df.resample(interval, how={data_name:how})
  3341. # 最新版的pandas
  3342. data = df.resample(interval).min()
  3343. # 刪除具有NaN的值
  3344. data = data.dropna(axis=0, how='any')
  3345. for a in range(0, len(data.index)):
  3346. # print(data.index[a])
  3347. l = []
  3348. # 如果是逐時,才顯示小時分秒
  3349. if time_interval == 'hour':
  3350. l.append(str(data.index[a]))
  3351. else:
  3352. l.append(str(data.index[a]).split(' ')[0])
  3353. l.append(str(data[data_name][a]))
  3354. minData.append(l)
  3355. D['min'] = minData
  3356. df = pd.DataFrame(L, columns=["datetime", data_name]) # 指定欄標籤名稱 為 ["datetime", "tem"]
  3357. df['datetime'] = pd.to_datetime(
  3358. df['datetime'], format='%Y-%b-%d_%H:%M:%S') # 将数据类型转换为日期类型
  3359. # print(df['datetime']) # 0 2021-02-19 16:46:10
  3360. # 1 2021-02-19 16:46:20
  3361. # 2 2021-02-19 16:46:30
  3362. # 3 2021-02-19 16:46:41
  3363. df[data_name] = df[data_name].astype(float)
  3364. df = df.set_index('datetime') # 将datetime设置为index
  3365. # print(df) # datetime tem
  3366. # 2021-02-19 16:46:10 24.4
  3367. # 2021-02-19 16:46:20 24.4
  3368. if time_interval == 'month':
  3369. if max:
  3370. dataResample(time_interval, "max", data_name)
  3371. if avg:
  3372. dataResample(time_interval, "mean", data_name)
  3373. if min:
  3374. dataResample(time_interval, "min", data_name)
  3375. elif time_interval == 'day':
  3376. if max:
  3377. dataResample(time_interval, "max", data_name)
  3378. if avg:
  3379. dataResample(time_interval, "mean", data_name)
  3380. if min:
  3381. dataResample(time_interval, "min", data_name)
  3382. elif time_interval == 'hour':
  3383. if max:
  3384. dataResample(time_interval, "max", data_name)
  3385. if avg:
  3386. dataResample(time_interval, "mean", data_name)
  3387. if min:
  3388. dataResample(time_interval, "min", data_name)
  3389. if sensor == '溫濕度':
  3390. # tank_tem = TankTemSensor.query.filter_by(tank_num=int(tank_num)).order_by(text('datetime desc')).all()
  3391. # [7/27 Benson] tank_tem = TankTemSensor.query.filter_by(tank_num=int(tank_num)).filter(TankTemSensor.datetime.between(date_start, date_end)).all()
  3392. tank_tem = dry_tank_SHT11.query.filter(dry_tank_SHT11.datetime.between(date_start, date_end)).all()
  3393. # .filter_by(tank_num="D"+tank_num)
  3394. for tem in tank_tem:
  3395. l = [] # l = []
  3396. time = dt.strftime(tem.datetime, '%Y-%b-%d_%H:%M:%S') # time = '2021-Feb-19_16:46:10' 轉換時間格式
  3397. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  3398. l.append(time) # l = ['2021-Feb-19_16:46:10']
  3399. #l.append(tem.tem) # l = ['2021-Feb-19_16:46:10', '24.4']
  3400. l.append(tem.SHT11_Temp)
  3401. L.append(l) # L = [['2021-Feb-19_16:46:10', '24.4']]
  3402. # print(L)
  3403. D['all'] = L # D = {'all': [['2021-Feb-19_16:46:10', '24.4']]} # all 所有符合數據
  3404. sensorData("tem")
  3405. elif sensor == '酸鹼值':
  3406. tank_ph = TankPHSensor.query.filter_by(tank_num=int(tank_num)).filter(
  3407. TankPHSensor.datetime.between(date_start, date_end)).all()
  3408. for ph in tank_ph:
  3409. l = []
  3410. time = dt.strftime(ph.datetime, '%Y-%b-%d_%H:%M:%S')
  3411. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  3412. l.append(time)
  3413. l.append(ph.ph)
  3414. L.append(l)
  3415. # print(L)
  3416. D['all'] = L
  3417. sensorData("ph")
  3418. elif sensor == 'EC值':
  3419. tank_ec = TankECSensor.query.filter_by(tank_num=int(tank_num)).filter(
  3420. TankECSensor.datetime.between(date_start, date_end)).all()
  3421. for ec in tank_ec:
  3422. l = []
  3423. time = dt.strftime(ec.datetime, '%Y-%b-%d_%H:%M:%S')
  3424. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  3425. l.append(time)
  3426. l.append(ec.ec)
  3427. L.append(l)
  3428. # print(L)
  3429. D['all'] = L
  3430. sensorData("ec")
  3431. elif sensor == '超音波':
  3432. tank_sonic = TankSonicSensor.query.filter_by(tank_num=int(tank_num)).filter(
  3433. TankSonicSensor.datetime.between(date_start, date_end)).all()
  3434. for sonic in tank_sonic:
  3435. l = []
  3436. time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
  3437. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  3438. l.append(time)
  3439. l.append(sonic.sonic)
  3440. L.append(l)
  3441. # print(L)
  3442. D['all'] = L
  3443. sensorData("sonic")
  3444. print(D)
  3445. return json.dumps(D)
  3446. else:
  3447. pass
  3448. # Rita 改寫
  3449. @main.route('/history_data_new', methods=['GET', 'POST'])
  3450. def history_data_new_views():
  3451. if request.method == 'GET':
  3452. # json
  3453. # tid:tid_D1
  3454. # sensor_name:soil_Temp
  3455. # avg:1
  3456. # max:1
  3457. # min:1
  3458. # time-interval:month
  3459. # date-start:2021-07-01
  3460. # date-end:2021-07-28
  3461. info = request.args.to_dict()
  3462. # evt = info['evt']
  3463. tid = info['tid']
  3464. sensor_name = info['sensor_name']
  3465. avg = int(info['avg'])
  3466. max = int(info['max'])
  3467. min = int(info['min'])
  3468. time_interval = info['time-interval']
  3469. print("info:", info)
  3470. # Rita {'evt': '1-溫濕度', 'avg': '1', 'max': '0', 'min': '0', 'time-interval': 'month',
  3471. # 'date-start': '2021-05-04', 'date-end': '2021-05-18'} {'all': [], 'avg': []}
  3472. # print(info)
  3473. # {'evt': '1-溫濕度', 'avg': '1', 'max': '0', 'min': '0', 'time-interval': 'hour', 'date-start': '2021-01-01', 'date-end': '2021-07-27'}
  3474. # print(D)
  3475. # {'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']],
  3476. # 'avg': [['2021-02-19 16:00:00', '24.5'], ['2021-02-19 18:00:00', '25.3']]}
  3477. # 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 -
  3478. date_start = info['date-start']
  3479. date_end_list = info['date-end'].split('-') # 先把 'date-end' 的 '2021-05-18' 拆成 ['2021', '05', '18']
  3480. date_end_list[2] = str(int(date_end_list[2]) + 1) # 18 + 1 = 19 再轉成 str → '19'
  3481. date_end = '-'.join(date_end_list) # '2021-05-19'
  3482. # tank_num = evt.split('-')[0] # 1
  3483. # sensor = evt.split('-')[1] # 溫濕度
  3484. tank_num = tid # D1
  3485. sensor = sensor_name # soil_Temp
  3486. L = []
  3487. D = {}
  3488. maxData = []
  3489. minData = []
  3490. avgData = []
  3491. def sensorData(data_name): # data_name = "tem"
  3492. def dataResample(time_interval, how, data_name): # dataResample('month', how???, "tem") # 下方 "hour"
  3493. interval = 0
  3494. # 設置resample的第一個參數,要按照逐月、逐日或逐時
  3495. if time_interval == 'month':
  3496. interval = "M" # interval = "M"
  3497. elif time_interval == 'day':
  3498. interval = "D"
  3499. elif time_interval == 'hour':
  3500. interval = "H"
  3501. if how == "max":
  3502. # data = df.resample(interval, how={data_name:how})
  3503. # 最新版的pandas
  3504. data = df.resample(interval).max() # 取樣頻率 'H'
  3505. # 刪除有 NaN 的列, any 任何一欄位為空則刪 (all 全部欄位為空值才刪)
  3506. data = data.dropna(axis=0, how='any')
  3507. if time_interval == ('hour' or 'day'):
  3508. data.index = pd.to_datetime(
  3509. data.index, format='%Y-%b-%d_%H:%M:%S') # 将数据类型转换为日期类型
  3510. for a in range(0, len(data.index)):
  3511. l = []
  3512. # 如果是逐時,才顯示小時分秒
  3513. if time_interval == 'hour':
  3514. l.append(str(data.index[a]))
  3515. else:
  3516. l.append(str(data.index[a]).split(' ')[0])
  3517. l.append(str(data[data_name][a]))
  3518. maxData.append(l)
  3519. D['max'] = maxData
  3520. elif how == "mean":
  3521. # data = df.resample(interval, how={data_name:how})
  3522. # 最新版的pandas
  3523. data = df.resample(interval).mean()
  3524. # 刪除具有NaN的值
  3525. data = data.dropna(axis=0, how='any')
  3526. # 將平均數取自小數1位
  3527. data = data.round({data_name: 1})
  3528. for a in range(0, len(data.index)):
  3529. l = []
  3530. # 如果是逐時,才顯示小時分秒
  3531. if time_interval == 'hour':
  3532. l.append(str(data.index[a]))
  3533. else:
  3534. l.append(str(data.index[a]).split(' ')[0])
  3535. l.append(str(data[data_name][a]))
  3536. avgData.append(l)
  3537. D['avg'] = avgData
  3538. elif how == "min":
  3539. # data = df.resample(interval, how={data_name:how})
  3540. # 最新版的pandas
  3541. data = df.resample(interval).min()
  3542. # 刪除具有NaN的值
  3543. data = data.dropna(axis=0, how='any')
  3544. for a in range(0, len(data.index)):
  3545. # print(data.index[a])
  3546. l = []
  3547. # 如果是逐時,才顯示小時分秒
  3548. if time_interval == 'hour':
  3549. l.append(str(data.index[a]))
  3550. else:
  3551. l.append(str(data.index[a]).split(' ')[0])
  3552. l.append(str(data[data_name][a]))
  3553. minData.append(l)
  3554. D['min'] = minData
  3555. df = pd.DataFrame(L, columns=["datetime", data_name]) # 指定欄標籤名稱 為 ["datetime", "tem"]
  3556. df['datetime'] = pd.to_datetime(
  3557. df['datetime'], format='%Y-%b-%d_%H:%M:%S') # 将数据类型转换为日期类型
  3558. # print(df['datetime']) # 0 2021-02-19 16:46:10
  3559. # 1 2021-02-19 16:46:20
  3560. # 2 2021-02-19 16:46:30
  3561. # 3 2021-02-19 16:46:41
  3562. df[data_name] = df[data_name].astype(float)
  3563. df = df.set_index('datetime') # 将datetime设置为index
  3564. # print(df) # datetime tem
  3565. # 2021-02-19 16:46:10 24.4
  3566. # 2021-02-19 16:46:20 24.4
  3567. if time_interval == 'month':
  3568. if max:
  3569. dataResample(time_interval, "max", data_name)
  3570. if avg:
  3571. dataResample(time_interval, "mean", data_name)
  3572. if min:
  3573. dataResample(time_interval, "min", data_name)
  3574. elif time_interval == 'day':
  3575. if max:
  3576. dataResample(time_interval, "max", data_name)
  3577. if avg:
  3578. dataResample(time_interval, "mean", data_name)
  3579. if min:
  3580. dataResample(time_interval, "min", data_name)
  3581. elif time_interval == 'hour':
  3582. if max:
  3583. dataResample(time_interval, "max", data_name)
  3584. if avg:
  3585. dataResample(time_interval, "mean", data_name)
  3586. if min:
  3587. dataResample(time_interval, "min", data_name)
  3588. if tank_num[:2] == 'DI':
  3589. # 乾燥入料儲豆槽
  3590. if sensor == 'UltraSonic':
  3591. tank_UltraSonic = dry_input_sensor.query.filter_by(tank_num=tank_num).filter(dry_input_sensor.datetime.between(date_start, date_end)).all()
  3592. for sonic in tank_UltraSonic:
  3593. l = []
  3594. time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
  3595. l.append(time)
  3596. l.append(sonic.UltraSonic)
  3597. L.append(l)
  3598. D['all'] = L
  3599. sensorData("UltraSonic")
  3600. elif tank_num[:2] == 'DO':
  3601. # 乾燥出料儲豆槽
  3602. if sensor == 'UltraSonic':
  3603. tank_UltraSonic = dry_output_sensor.query.filter_by(tank_num=tank_num).filter(dry_output_sensor.datetime.between(date_start, date_end)).all()
  3604. for sonic in tank_UltraSonic:
  3605. l = []
  3606. time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
  3607. l.append(time)
  3608. l.append(sonic.UltraSonic)
  3609. L.append(l)
  3610. D['all'] = L
  3611. sensorData("UltraSonic")
  3612. elif tank_num[:1] == 'D':
  3613. # 乾燥槽
  3614. if sensor == 'SHT11_Temp':
  3615. tank_tem = dry_tank_SHT11.query.filter_by(tank_num=tank_num).filter(dry_tank_SHT11.datetime.between(date_start, date_end)).all()
  3616. for tem in tank_tem:
  3617. l = [] # l = []
  3618. time = dt.strftime(tem.datetime, '%Y-%b-%d_%H:%M:%S') # time = '2021-Feb-19_16:46:10' 轉換時間格式
  3619. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  3620. l.append(time) # l = ['2021-Feb-19_16:46:10']
  3621. #l.append(tem.tem) # l = ['2021-Feb-19_16:46:10', '24.4']
  3622. l.append(tem.SHT11_Temp)
  3623. L.append(l) # L = [['2021-Feb-19_16:46:10', '24.4']]
  3624. # print(L)
  3625. D['all'] = L # D = {'all': [['2021-Feb-19_16:46:10', '24.4']]} # all 所有符合數據
  3626. sensorData("SHT11_Temp")
  3627. elif sensor == 'SHT11_Humidity':
  3628. tank_hum = dry_tank_SHT11.query.filter_by(tank_num=tank_num).filter(dry_tank_SHT11.datetime.between(date_start, date_end)).all()
  3629. for hum in tank_hum:
  3630. l = []
  3631. time = dt.strftime(hum.datetime, '%Y-%b-%d_%H:%M:%S')
  3632. l.append(time)
  3633. l.append(hum.SHT11_Humidity)
  3634. L.append(l)
  3635. D['all'] = L
  3636. sensorData("SHT11_Humidity")
  3637. elif sensor == 'UltraSonic':
  3638. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num=tank_num).filter(dry_tank_UltraSonic.datetime.between(date_start, date_end)).all()
  3639. for sonic in tank_UltraSonic:
  3640. l = []
  3641. time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
  3642. l.append(time)
  3643. l.append(sonic.UltraSonic)
  3644. L.append(l)
  3645. D['all'] = L
  3646. sensorData("UltraSonic")
  3647. elif sensor == 'PA':
  3648. tank_PA = dry_tank_PA.query.filter_by(tank_num=tank_num).filter(dry_tank_PA.datetime.between(date_start, date_end)).all()
  3649. for pa in tank_PA:
  3650. l = []
  3651. time = dt.strftime(pa.datetime, '%Y-%b-%d_%H:%M:%S')
  3652. l.append(time)
  3653. l.append(pa.PA)
  3654. L.append(l)
  3655. D['all'] = L
  3656. sensorData("PA")
  3657. elif sensor == 'soil_Temp':
  3658. tank_soiltemp = dry_tank_Soil.query.filter_by(tank_num=tank_num).filter(dry_tank_Soil.datetime.between(date_start, date_end)).all()
  3659. for temp in tank_soiltemp:
  3660. l = []
  3661. time = dt.strftime(temp.datetime, '%Y-%b-%d_%H:%M:%S')
  3662. l.append(time)
  3663. l.append(temp.soil_Temp)
  3664. L.append(l)
  3665. D['all'] = L
  3666. sensorData("soil_Temp")
  3667. elif sensor == 'soil_Humidity':
  3668. tank_soilHum = dry_tank_Soil.query.filter_by(tank_num=tank_num).filter(dry_tank_Soil.datetime.between(date_start, date_end)).all()
  3669. for hum in tank_soilHum:
  3670. l = []
  3671. time = dt.strftime(hum.datetime, '%Y-%b-%d_%H:%M:%S')
  3672. l.append(time)
  3673. l.append(hum.soil_EC)
  3674. L.append(l)
  3675. D['all'] = L
  3676. sensorData("soil_Humidity")
  3677. elif sensor == 'soil_EC':
  3678. tank_soilec = dry_tank_Soil.query.filter_by(tank_num=tank_num).filter(dry_tank_Soil.datetime.between(date_start, date_end)).all()
  3679. for ec in tank_soilec:
  3680. l = []
  3681. time = dt.strftime(ec.datetime, '%Y-%b-%d_%H:%M:%S')
  3682. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  3683. l.append(time)
  3684. l.append(ec.soil_EC)
  3685. L.append(l)
  3686. D['all'] = L
  3687. sensorData("soil_EC")
  3688. elif tank_num[:2] == 'FI':
  3689. if sensor == 'UltraSonic':
  3690. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num=tank_num).filter(ferment_input_UltraSonic.datetime.between(date_start, date_end)).all()
  3691. for UltraSonic in input_UltraSonic:
  3692. l = []
  3693. time = dt.strftime(UltraSonic.datetime, '%Y-%b-%d_%H:%M:%S')
  3694. l.append(time)
  3695. l.append(UltraSonic.UltraSonic)
  3696. L.append(l)
  3697. D['all'] = L
  3698. sensorData("UltraSonic")
  3699. elif tank_num[:2] == 'FO':
  3700. if sensor == 'UltraSonic':
  3701. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num=tank_num).filter(ferment_output_UltraSonic.datetime.between(date_start, date_end)).all()
  3702. for UltraSonic in output_UltraSonic:
  3703. l = []
  3704. time = dt.strftime(UltraSonic.datetime, '%Y-%b-%d_%H:%M:%S')
  3705. l.append(time)
  3706. l.append(UltraSonic.UltraSonic)
  3707. L.append(l)
  3708. D['all'] = L
  3709. sensorData("UltraSonic")
  3710. elif tank_num[:1] == 'F':
  3711. if sensor == 'LiDAR':
  3712. tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num = tank_num)\
  3713. .filter(ferment_tank_LiDAR.datetime.between(date_start, date_end)).all()
  3714. for LiDAR in tank_LiDAR:
  3715. l = []
  3716. time = dt.strftime(LiDAR.datetime, '%Y-%b-%d_%H:%M:%S')
  3717. l.append(time)
  3718. l.append(LiDAR.LiDAR)
  3719. L.append(l)
  3720. D['all'] = L
  3721. sensorData("LiDAR")
  3722. elif sensor == 'PressureWaterLevel':
  3723. tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num = tank_num)\
  3724. .filter(ferment_tank_PressureWaterLevel.datetime.between(date_start, date_end)).all()
  3725. for PressureWaterLevel in tank_PressureWaterLevel:
  3726. l = []
  3727. time = dt.strftime(PressureWaterLevel.datetime, '%Y-%b-%d_%H:%M:%S')
  3728. l.append(time)
  3729. l.append(PressureWaterLevel.PressureWaterLevel)
  3730. l.append('{:.2f}'.format((float(PressureWaterLevel.PressureWaterLevel) -10 -90.278)/9.4214))
  3731. L.append(l)
  3732. D['all'] = L
  3733. sensorData("PressureWaterLevel")
  3734. elif sensor == 'SHT11_Temp':
  3735. tank_Temp = ferment_tank_SHT11.query.filter_by(tank_num = tank_num)\
  3736. .filter(ferment_tank_SHT11.datetime.between(date_start, date_end)).all()
  3737. for Temp in tank_Temp:
  3738. l = []
  3739. time = dt.strftime(Temp.datetime, '%Y-%b-%d_%H:%M:%S')
  3740. l.append(time)
  3741. l.append(Temp.SHT11_Temp)
  3742. L.append(l)
  3743. D['all'] = L
  3744. sensorData("SHT11_Temp")
  3745. elif sensor == 'SHT11_Humidity':
  3746. tank_Humidity = ferment_tank_SHT11.query.filter_by(tank_num = tank_num)\
  3747. .filter(ferment_tank_SHT11.datetime.between(date_start, date_end)).all()
  3748. for Humidity in tank_Humidity:
  3749. l = []
  3750. time = dt.strftime(Humidity.datetime, '%Y-%b-%d_%H:%M:%S')
  3751. l.append(time)
  3752. l.append(Humidity.SHT11_Humidity)
  3753. L.append(l)
  3754. D['all'] = L
  3755. sensorData("SHT11_Humidity")
  3756. elif sensor == 'CO2':
  3757. tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num = tank_num)\
  3758. .filter(ferment_tank_CO2.datetime.between(date_start, date_end)).all()
  3759. for CO2 in tank_CO2:
  3760. l = []
  3761. time = dt.strftime(CO2.datetime, '%Y-%b-%d_%H:%M:%S')
  3762. l.append(time)
  3763. l.append(CO2.CO2)
  3764. L.append(l)
  3765. D['all'] = L
  3766. sensorData("CO2")
  3767. elif sensor == 'PH':
  3768. tank_PH = ferment_tank_PH.query.filter_by(tank_num = tank_num)\
  3769. .filter(ferment_tank_PH.datetime.between(date_start, date_end)).all()
  3770. for PH in tank_PH:
  3771. l = []
  3772. time = dt.strftime(PH.datetime, '%Y-%b-%d_%H:%M:%S')
  3773. l.append(time)
  3774. l.append(PH.PH)
  3775. L.append(l)
  3776. D['all'] = L
  3777. sensorData("PH")
  3778. elif sensor == 'ORP':
  3779. tank_ORP = ferment_tank_ORP.query.filter_by(tank_num = tank_num)\
  3780. .filter(ferment_tank_ORP.datetime.between(date_start, date_end)).all()
  3781. for ORP in tank_ORP:
  3782. l = []
  3783. time = dt.strftime(ORP.datetime, '%Y-%b-%d_%H:%M:%S')
  3784. l.append(time)
  3785. l.append(ORP.ORP)
  3786. L.append(l)
  3787. D['all'] = L
  3788. sensorData("ORP")
  3789. elif sensor == 'DO':
  3790. tank_DO = ferment_tank_DO.query.filter_by(tank_num = tank_num)\
  3791. .filter(ferment_tank_DO.datetime.between(date_start, date_end)).all()
  3792. for DO in tank_DO:
  3793. l = []
  3794. time = dt.strftime(DO.datetime, '%Y-%b-%d_%H:%M:%S')
  3795. l.append(time)
  3796. l.append(DO.DO)
  3797. L.append(l)
  3798. D['all'] = L
  3799. sensorData("DO")
  3800. elif sensor == 'EC':
  3801. tank_EC = ferment_tank_EC.query.filter_by(tank_num = tank_num)\
  3802. .filter(ferment_tank_EC.datetime.between(date_start, date_end)).all()
  3803. for EC in tank_EC:
  3804. l = []
  3805. time = dt.strftime(EC.datetime, '%Y-%b-%d_%H:%M:%S')
  3806. l.append(time)
  3807. l.append(EC.EC)
  3808. L.append(l)
  3809. D['all'] = L
  3810. sensorData("EC")
  3811. elif sensor == 'PA':
  3812. tank_PA = ferment_tank_PA.query.filter_by(tank_num = tank_num)\
  3813. .filter(ferment_tank_PA.datetime.between(date_start, date_end)).all()
  3814. for PA in tank_PA:
  3815. l = []
  3816. time = dt.strftime(PA.datetime, '%Y-%b-%d_%H:%M:%S')
  3817. l.append(time)
  3818. l.append(PA.PA)
  3819. L.append(l)
  3820. D['all'] = L
  3821. sensorData("PA")
  3822. print(D)
  3823. return json.dumps(D)
  3824. else:
  3825. pass
  3826. # 貨櫃2制動器的發酵槽訪問路徑
  3827. @main.route('/cargo2_actuator_tanks', methods=['GET', 'POST'])
  3828. def cargo2_actuator_tanks_views():
  3829. username = session['uname']
  3830. if request.method == 'GET':
  3831. return render_template('cargo2_actuator_tanks.html', params=locals())
  3832. else:
  3833. pass
  3834. # 貨櫃2制動器發酵槽的清單訪問路徑
  3835. @main.route('/cargo2_actuator/<tid>', methods=['GET', 'POST'])
  3836. def cargo2_actuator_views(tid):
  3837. username = session['uname']
  3838. if request.method == 'GET':
  3839. return render_template('cargo2_actuator.html', params=locals())
  3840. else:
  3841. pass
  3842. # 貨櫃3的訪問路徑
  3843. @main.route('/cargo3', methods=['GET', 'POST'])
  3844. def cargo3_views():
  3845. username = session['uname']
  3846. if request.method == 'GET':
  3847. return render_template('cargo3.html', params=locals())
  3848. else:
  3849. pass
  3850. # 貨櫃3排程的訪問路徑
  3851. @main.route('/cargo3_schedule', methods=['GET', 'POST'])
  3852. def cargo3_schedule_views():
  3853. username = session['uname']
  3854. if request.method == 'GET':
  3855. # 將已儲存的排程資料傳給前端
  3856. # 提升機
  3857. try:
  3858. hoist = Hoist.query.order_by(text('datetime desc')).first()
  3859. datetime = hoist.datetime
  3860. hoists = Hoist.query.filter_by(datetime=datetime).all()
  3861. except Exception as e:
  3862. pass
  3863. # 烘乾機
  3864. try:
  3865. dryer = Dryer.query.order_by(text('datetime desc')).first()
  3866. datetime = dryer.datetime
  3867. dryers = Dryer.query.filter_by(datetime=datetime).all()
  3868. except Exception as e:
  3869. pass
  3870. return render_template('cargo3_schedule.html', params=locals())
  3871. else:
  3872. # Rita: "POST /b_cargo3 HTTP/1.1" 404 -
  3873. current_time = dt.now()
  3874. # 循環從前端提交過來的資料
  3875. for i in request.form:
  3876. print('Rita test i :', i)
  3877. # 堤升機
  3878. if i[:5] == 'hoist':
  3879. if i[:14] == 'hoist_duration':
  3880. hoist = Hoist()
  3881. hoist.duration = request.form[i]
  3882. elif i[:13] == 'hoist_from_hr':
  3883. ho_from_hr = request.form[i]
  3884. elif i[:14] == 'hoist_from_min':
  3885. ho_from_min = request.form[i]
  3886. hoist.start = ho_from_hr + ":" + ho_from_min
  3887. elif i[:11] == 'hoist_to_hr':
  3888. ho_to_hr = request.form[i]
  3889. elif i[:12] == 'hoist_to_min':
  3890. ho_to_min = request.form[i]
  3891. hoist.end = ho_to_hr + ":" + ho_to_min
  3892. hoist.datetime = current_time
  3893. db.session.add(hoist)
  3894. db.session.commit()
  3895. # 烘乾機
  3896. elif i[:5] == 'dryer':
  3897. if i[:14] == 'dryer_duration':
  3898. dryer = Dryer()
  3899. dryer.duration = request.form[i]
  3900. elif i[:13] == 'dryer_from_hr':
  3901. dry_from_hr = request.form[i]
  3902. elif i[:14] == 'dryer_from_min':
  3903. dry_from_min = request.form[i]
  3904. dryer.start = dry_from_hr + ":" + dry_from_min
  3905. elif i[:11] == 'dryer_to_hr':
  3906. dry_to_hr = request.form[i]
  3907. elif i[:12] == 'dryer_to_min':
  3908. dry_to_min = request.form[i]
  3909. dryer.end = dry_to_hr + ":" + dry_to_min
  3910. dryer.datetime = current_time
  3911. db.session.add(dryer)
  3912. db.session.commit()
  3913. return render_template('cargo3.html', params=locals())
  3914. # 影像串流的訪問路徑
  3915. @main.route('/video', methods=['GET', 'POST'])
  3916. def video_views():
  3917. username = session['uname']
  3918. if request.method == 'GET':
  3919. return render_template('video.html', params=locals())
  3920. else:
  3921. pass
  3922. # 影像的訪問路徑
  3923. @main.route('/learn', methods=['GET', 'POST'])
  3924. def learn_views():
  3925. username = session['uname']
  3926. if request.method == 'GET':
  3927. return render_template('learn.html', params=locals())
  3928. else:
  3929. pass
  3930. # 獲取relay狀態路徑
  3931. @main.route('/relay', methods=['GET', 'POST'])
  3932. def relay_views():
  3933. if request.method == 'GET':
  3934. relay = Relay.query.order_by(text('datetime desc')).first()
  3935. relay_status = relay.status
  3936. return jsonify({"relay": relay_status})
  3937. else:
  3938. pass
  3939. # 獲取脫皮機狀態路徑
  3940. @main.route('/peel', methods=['GET', 'POST'])
  3941. def peeling_views():
  3942. if request.method == 'GET':
  3943. peeling = PeelingMachineRPM.query.order_by(
  3944. text('datetime desc')).first()
  3945. peeling_rpm = peeling.rpm
  3946. return jsonify({"peeling": peeling_rpm})
  3947. else:
  3948. pass
  3949. # 退出的訪問路徑
  3950. @main.route('/logout')
  3951. def logout_views():
  3952. if 'id' in session and 'uname' in session:
  3953. del session['id']
  3954. del session['uname']
  3955. return redirect('/')
  3956. @main.route("/udp_client", methods=['POST', 'GET'])
  3957. def udp_views():
  3958. # sl(0.5)
  3959. global c_sock
  3960. if request.method == 'GET':
  3961. # def close():
  3962. # global c_sock
  3963. # sl(600)
  3964. # c_sock.close()
  3965. # c_sock = 0
  3966. # print("c_sock is closing")
  3967. max_length = 65000
  3968. # max_length = 95000
  3969. # lab1的IP
  3970. host = "192.168.50.65"
  3971. # lab2的IP
  3972. # host = "192.168.51.160"
  3973. port = 8000
  3974. c_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  3975. # t = threading.Thread(target=close)
  3976. # t.daemon = True
  3977. # t.start()
  3978. print("test")
  3979. # dict = request.args.to_dict()
  3980. # nr = int(dict['nr'])
  3981. # if nr == 1:
  3982. # camara = 0
  3983. # elif nr == 2:
  3984. # camara = 'rtsp://admin:admin@192.168.50.182/av2_0'
  3985. # elif nr == 3:
  3986. # camara = 'rtsp://admin:abcd1234@192.168.51.101/av2_0'
  3987. # 地下室小兵
  3988. # cap = cv2.VideoCapture('rtsp://admin:abcd1234@192.168.51.48/av2_0')
  3989. # 主機攝像頭
  3990. # cap = cv2.VideoCapture(0)
  3991. # 外面小兵
  3992. # cap = cv2.VideoCapture('rtsp://admin:admin@192.168.50.182/av2_0')
  3993. cap = cv2.VideoCapture('rtsp://192.168.50.182/av0_0')
  3994. # cap = cv2.VideoCapture(0)
  3995. # cap = cv2.VideoCapture(camara)
  3996. ret, frame = cap.read()
  3997. while ret:
  3998. # compress frame
  3999. frame = cv2.resize(frame, (550, 400), interpolation=cv2.INTER_AREA)
  4000. retval, buffer = cv2.imencode(".jpg", frame)
  4001. if retval:
  4002. # convert to byte array
  4003. buffer = buffer.tobytes()
  4004. # get size of the frame
  4005. buffer_size = len(buffer)
  4006. num_of_packs = 1
  4007. if buffer_size > max_length:
  4008. num_of_packs = math.ceil(buffer_size / max_length)
  4009. frame_info = {"packs": num_of_packs}
  4010. # send the number of packs to be expected
  4011. # print("Number of packs:", num_of_packs)
  4012. c_sock.sendto(pickle.dumps(frame_info), (host, port))
  4013. left = 0
  4014. right = max_length
  4015. for i in range(num_of_packs):
  4016. # print("left:", left)
  4017. # print("right:", right)
  4018. # truncate data to send
  4019. data = buffer[left:right]
  4020. left = right
  4021. right += max_length
  4022. # send the frames accordingly
  4023. c_sock.sendto(data, (host, port))
  4024. ret, frame = cap.read()
  4025. print("done")
  4026. return "done"
  4027. else:
  4028. c_sock.shutdown(2)
  4029. c_sock.close()
  4030. c_sock = 0
  4031. print("c_sock is closing")
  4032. # 影像串流的路徑
  4033. @main.route("/video_feed", methods=['POST', 'GET'])
  4034. def video_feed_views():
  4035. print("test2")
  4036. global s_sock
  4037. if request.method == 'GET':
  4038. # 於10分鐘之後,自動關閉socket server
  4039. # if s_sock == 0:
  4040. # def socket_server_views():
  4041. # global s_sock
  4042. # print("test")
  4043. # print(s_sock)
  4044. # sl(600)
  4045. # if s_sock != 0:
  4046. # s_sock.close()
  4047. # s_sock = 0
  4048. # print('s_sock is closed')
  4049. #
  4050. # pool.submit(socket_server_views)
  4051. host = "192.168.50.65"
  4052. port = 8000
  4053. max_length = 65540
  4054. # max_length = 95540
  4055. s_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  4056. s_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  4057. s_sock.bind((host, port))
  4058. frame_info = None
  4059. buffer = None
  4060. frame = None
  4061. encodedImage = None
  4062. print("-> waiting for connection")
  4063. # 影像生成器函數,將影像以jpg格式傳給前端
  4064. def generate():
  4065. while True:
  4066. with lock:
  4067. global s_sock, frame_info, buffer, frame, encodedImage
  4068. if s_sock == 0:
  4069. break
  4070. data, address = s_sock.recvfrom(max_length)
  4071. if len(data) < 100:
  4072. frame_info = pickle.loads(data)
  4073. if frame_info:
  4074. nums_of_packs = frame_info["packs"]
  4075. for i in range(nums_of_packs):
  4076. if s_sock == 0:
  4077. break
  4078. data, address = s_sock.recvfrom(max_length)
  4079. if i == 0:
  4080. buffer = data
  4081. else:
  4082. buffer += data
  4083. frame = np.frombuffer(buffer, dtype=np.uint8)
  4084. frame = frame.reshape(frame.shape[0], 1)
  4085. frame = cv2.imdecode(frame, cv2.IMREAD_UNCHANGED)
  4086. # print(frame)
  4087. # 如果frame為None就跳過
  4088. if frame is None:
  4089. continue
  4090. frame = cv2.resize(
  4091. frame, (640, 360), interpolation=cv2.INTER_AREA)
  4092. # encode the frame in JPEG format
  4093. (flag, encodedImage) = cv2.imencode(".jpg", frame)
  4094. # ensure the frame was successfully encoded
  4095. if not flag:
  4096. continue
  4097. # yield the output frame in the byte format
  4098. yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' +
  4099. bytearray(encodedImage) + b'\r\n')
  4100. # return the response generated along with the specific media
  4101. # type (mime type)
  4102. return Response(generate(), mimetype="multipart/x-mixed-replace; boundary=frame")
  4103. else:
  4104. if s_sock != 0:
  4105. s_sock.close()
  4106. s_sock = 0
  4107. print('s_sock is closed')
  4108. return "s_sock is closed"
  4109. print("test")
  4110. return "s_sock is closed"
  4111. D = {"input_vacuum_status": 0,
  4112. "tank_vacuum_status": 0,
  4113. "tank_threewayvalve_status": 0,
  4114. "tank_diskvalve_status": 0,
  4115. "tank_solenoid_disinfect_status": 0,
  4116. "tank_solenoid_water_status": 0,
  4117. "tank_motor_status": 'none',
  4118. "tank_blower_status": 0,
  4119. "tank_heater1_status": 0,
  4120. "tank_heater2_status": 0,
  4121. "temp1_enable": 0,
  4122. "temp1": 0,
  4123. "output_vacuum_status": 0,
  4124. "tank_threewayvalve_input_status":0,
  4125. "tank_solenoid_water_total_status": 0,
  4126. "tank_solenoid_disinfect_status": 0,
  4127. "outer_solenoid_water_status": 0,
  4128. "tank_solenoid_water_in_status":0,
  4129. "tank_pump_sensor_status": 0,
  4130. "tank_threewayvalve_bean_status":0,
  4131. "outer_threewayvalve_float_status":0,
  4132. "tank_temp_enable_status":0,
  4133. "tank_temp_status": 'none',
  4134. "tank_pump_waterFloat_status": 0,
  4135. "tank_pump_waterL2_status": 0,
  4136. "tank_pump_waterL4_status": 0,
  4137. "tank_solenoid_waterL3_status": 0,
  4138. "tank_solenoid_waterL5_status": 0,
  4139. "tank_stepping_motor_status": 'none',
  4140. }
  4141. pub_topic = 'AISKY/Coffee/MK-G/b8:27:eb:b4:59:3e'
  4142. # sub_topic = 'AISKY/Coffee/MK-G/b8:27:eb:b4:59:3e/Log'
  4143. # mqttObj = MQTT('aisky-client', 'aiskyc', '60.250.156.234', 1883, 60, sub_topic)
  4144. mqttObj = MQTT()
  4145. # mqtt發布
  4146. # @main.route('/mqtt/<tid>', methods=['POST'])
  4147. @main.route('/mqtt/<tid>', methods=['POST'])
  4148. def mqtt_views(tid):
  4149. import json
  4150. dict = request.form.to_dict()
  4151. json = json.dumps(dict)
  4152. # print('dict:', dict) # dict: {'tank-number': '1', 'command': 'tank_vacuum_status', 'value': 'on'}
  4153. # print('json:', json) # json: {"tank-number": "1", tank_vacuum_status", "value": "on"}
  4154. topic = 'AISKY/Coffee/MK-G/b8:27:eb:b4:59:3e'
  4155. # res = mqttObj.mqttPublish(pub_topic, json)
  4156. # print(res)
  4157. # sl(2)
  4158. # print(mqttObj.res)
  4159. #
  4160. # print('test')
  4161. mqtt.publish(topic, json)
  4162. # 入料儲豆槽真空吸料機(ON吸料/OFF排氣)
  4163. if dict['command'] == 'input_vacuum_status':
  4164. time.sleep(1)
  4165. # D[input_vacuum_status]: 0
  4166. print('D[input_vacuum_status]:', D['input_vacuum_status'])
  4167. if D['input_vacuum_status'] == 'on':
  4168. return 'on'
  4169. elif D['input_vacuum_status'] == 'off':
  4170. return 'off'
  4171. else:
  4172. return "input_vacuum_status signal was not received"
  4173. # 真空吸料機
  4174. elif dict['command'] == 'tank_vacuum_status':
  4175. time.sleep(1)
  4176. if D['tank_vacuum_status'] == 'on':
  4177. return 'on'
  4178. elif D['tank_vacuum_status'] == 'off':
  4179. return 'off'
  4180. else:
  4181. return "tank_vacuum_status signal was not received"
  4182. # 三通閥(ON吸料/OFF排氣)
  4183. elif dict['command'] == 'tank_threewayvalve_status':
  4184. time.sleep(1)
  4185. if D['tank_threewayvalve_status'] == 'on':
  4186. return 'on'
  4187. elif D['tank_threewayvalve_status'] == 'off':
  4188. return 'off'
  4189. else:
  4190. return "tank_threewayvalve_status signal was not received"
  4191. # 蝴蝶閥(ON開/OFF關)
  4192. elif dict['command'] == 'tank_diskvalve_status':
  4193. time.sleep(1)
  4194. print("D['tank_diskvalve_status']", D['tank_diskvalve_status'])
  4195. if D['tank_diskvalve_status'] == 'on':
  4196. return 'on'
  4197. elif D['tank_diskvalve_status'] == 'off':
  4198. return 'off'
  4199. else:
  4200. return "tank_diskvalve_status signal was not received"
  4201. # 電磁閥(ON噴灑消毒/OFF關)
  4202. elif dict['command'] == 'tank_solenoid_disinfect_status':
  4203. time.sleep(1)
  4204. if D['tank_solenoid_disinfect_status'] == 'on':
  4205. return 'on'
  4206. elif D['tank_solenoid_disinfect_status'] == 'off':
  4207. return 'off'
  4208. else:
  4209. return "tank_solenoid_disinfect_status signal was not received"
  4210. # 電磁閥(ON排水/OFF關)
  4211. elif dict['command'] == 'tank_solenoid_water_status':
  4212. time.sleep(1)
  4213. if D['tank_solenoid_water_status'] == 'on':
  4214. return 'on'
  4215. elif D['tank_solenoid_water_status'] == 'off':
  4216. return 'off'
  4217. else:
  4218. return "tank_solenoid_water_status signal was not received"
  4219. # 馬達(單位RPM)
  4220. elif dict['command'] == 'tank_motor_status':
  4221. print("D['tank_motor_status']", D['tank_motor_status'])
  4222. time.sleep(1)
  4223. if D['tank_motor_status'] == '0':
  4224. return 'off'
  4225. elif type(D['tank_motor_status']) == int:
  4226. return 'on'
  4227. else:
  4228. return "tank_motor_status signal was not received"
  4229. # 鼓風機(ON開/OFF關)
  4230. elif dict['command'] == 'tank_blower_status':
  4231. time.sleep(1)
  4232. if D['tank_blower_status'] == 'on':
  4233. return 'on'
  4234. elif D['tank_blower_status'] == 'off':
  4235. return 'off'
  4236. else:
  4237. return "tank_blower_status signal was not received"
  4238. # 加熱棒 1(ON開/OFF關)
  4239. elif dict['command'] == 'tank_heater1_status':
  4240. time.sleep(1)
  4241. if D['tank_heater1_status'] == 'on':
  4242. return 'on'
  4243. elif D['tank_heater1_status'] == 'off':
  4244. return 'off'
  4245. else:
  4246. return "tank_heater1_status signal was not received"
  4247. # 加熱棒 2(ON開/OFF關)
  4248. elif dict['command'] == 'tank_heater2_status':
  4249. time.sleep(1)
  4250. if D['tank_heater2_status'] == 'on':
  4251. return 'on'
  4252. elif D['tank_heater2_status'] == 'off':
  4253. return 'off'
  4254. else:
  4255. return "tank_heater2_status signal was not received"
  4256. # 溫度控制(ON開/OFF關)
  4257. elif dict['command'] == 'temp1_enable':
  4258. time.sleep(1)
  4259. if D['temp1_enable'] == 'on':
  4260. return 'on'
  4261. elif D['temp1_enable'] == 'off':
  4262. return 'off'
  4263. else:
  4264. return "temp1_enable_status signal was not received"
  4265. # 設定溫度 (限整數)
  4266. elif dict['command'] == 'temp1':
  4267. time.sleep(1)
  4268. if D['temp1'] == '0':
  4269. return 'off'
  4270. elif type(D['temp1']) == int:
  4271. return 'on'
  4272. else:
  4273. return "temp1 signal was not received"
  4274. # 出料儲豆槽真空吸料機(ON吸料/OFF排氣)
  4275. elif dict['command'] == 'output_vacuum_status':
  4276. time.sleep(1)
  4277. if D['output_vacuum_status'] == 'on':
  4278. return 'on'
  4279. elif D['output_vacuum_status'] == 'off':
  4280. return 'off'
  4281. else:
  4282. return "output_vacuum_status signal was not received"
  4283. # 發酵槽 入料三通閥
  4284. elif dict['command'] == 'tank_threewayvalve_input_status':
  4285. time.sleep(1)
  4286. if D['tank_threewayvalve_input_status'] == 'on':
  4287. return 'on'
  4288. elif D['tank_threewayvalve_input_status'] == 'off':
  4289. return 'off'
  4290. else:
  4291. return "tank_threewayvalve_input_status signal was not received"
  4292. # 發酵槽 總進水
  4293. elif dict['command'] == 'tank_solenoid_water_total_status':
  4294. time.sleep(1)
  4295. if D['tank_solenoid_water_total_status'] == 'on':
  4296. return 'on'
  4297. elif D['tank_solenoid_water_total_status'] == 'off':
  4298. return 'off'
  4299. else:
  4300. return "tank_solenoid_water_total_status signal was not received"
  4301. # 發酵槽 桶內消毒/打菌
  4302. elif dict['command'] == 'tank_solenoid_disinfect_status':
  4303. time.sleep(1)
  4304. if D['tank_solenoid_disinfect_status'] == 'on':
  4305. return 'on'
  4306. elif D['tank_solenoid_disinfect_status'] == 'off':
  4307. return 'off'
  4308. else:
  4309. return "tank_solenoid_disinfect_status signal was not received"
  4310. # 發酵槽 夾層進水
  4311. elif dict['command'] == 'outer_solenoid_water_status':
  4312. time.sleep(1)
  4313. if D['outer_solenoid_water_status'] == 'on':
  4314. return 'on'
  4315. elif D['outer_solenoid_water_status'] == 'off':
  4316. return 'off'
  4317. else:
  4318. return "outer_solenoid_water_status signal was not received"
  4319. # 發酵槽 桶內進水
  4320. elif dict['command'] == 'tank_solenoid_water_in_status':
  4321. time.sleep(1)
  4322. if D['tank_solenoid_water_in_status'] == 'on':
  4323. return 'on'
  4324. elif D['tank_solenoid_water_in_status'] == 'off':
  4325. return 'off'
  4326. else:
  4327. return "tank_solenoid_water_in_status signal was not received"
  4328. # 發酵槽 雙核隔膜泵
  4329. elif dict['command'] == 'tank_pump_sensor_status':
  4330. time.sleep(1)
  4331. if D['tank_pump_sensor_status'] == 'on':
  4332. return 'on'
  4333. elif D['tank_pump_sensor_status'] == 'off':
  4334. return 'off'
  4335. else:
  4336. return "tank_pump_sensor_status signal was not received"
  4337. # 發酵槽 感測器下豆三通閥
  4338. elif dict['command'] == 'tank_threewayvalve_bean_status':
  4339. time.sleep(1)
  4340. if D['tank_threewayvalve_bean_status'] == 'on':
  4341. return 'on'
  4342. elif D['tank_threewayvalve_bean_status'] == 'off':
  4343. return 'off'
  4344. else:
  4345. return "tank_threewayvalve_bean_status signal was not received"
  4346. # 發酵槽 外桶浮選三通閥
  4347. elif dict['command'] == 'outer_threewayvalve_float_status':
  4348. time.sleep(1)
  4349. if D['outer_threewayvalve_float_status'] == 'on':
  4350. return 'on'
  4351. elif D['outer_threewayvalve_float_status'] == 'off':
  4352. return 'off'
  4353. else:
  4354. return "outer_threewayvalve_float_status signal was not received"
  4355. # 發酵槽 溫控開關
  4356. elif dict['command'] == 'tank_temp_enable_status':
  4357. time.sleep(1)
  4358. if D['tank_temp_enable_status'] == 'on':
  4359. return 'on'
  4360. elif D['tank_temp_enable_status'] == 'off':
  4361. return 'off'
  4362. else:
  4363. return "tank_temp_enable_status signal was not received"
  4364. # 發酵槽 設定溫度
  4365. elif dict['command'] == 'tank_temp_status':
  4366. time.sleep(1)
  4367. if D['tank_temp_status'] == '0':
  4368. return 'off'
  4369. elif type(D['tank_temp_status']) == int:
  4370. return 'on'
  4371. else:
  4372. return "tank_temp_status signal was not received"
  4373. # 清洗浮選槽 浮選槽注水
  4374. elif dict['command'] == 'tank_pump_waterFloat_status':
  4375. time.sleep(1)
  4376. if D['tank_pump_waterFloat_status'] == 'on':
  4377. return 'on'
  4378. elif D['tank_pump_waterFloat_status'] == 'off':
  4379. return 'off'
  4380. else:
  4381. return "tank_pump_waterFloat_status signal was not received"
  4382. # 清洗浮選槽 清洗第 2 層灑水
  4383. elif dict['command'] == 'tank_pump_waterL2_status':
  4384. time.sleep(1)
  4385. if D['tank_pump_waterL2_status'] == 'on':
  4386. return 'on'
  4387. elif D['tank_pump_waterL2_status'] == 'off':
  4388. return 'off'
  4389. else:
  4390. return "tank_pump_waterL2_status signal was not received"
  4391. # 清洗浮選槽 清洗第 4 層灑水
  4392. elif dict['command'] == 'tank_pump_waterL4_status':
  4393. time.sleep(1)
  4394. if D['tank_pump_waterL4_status'] == 'on':
  4395. return 'on'
  4396. elif D['tank_pump_waterL4_status'] == 'off':
  4397. return 'off'
  4398. else:
  4399. return "tank_pump_waterL4_status signal was not received"
  4400. # 清洗浮選槽 清洗第 3 層電磁閥
  4401. elif dict['command'] == 'tank_solenoid_waterL3_status':
  4402. time.sleep(1)
  4403. if D['tank_solenoid_waterL3_status'] == 'on':
  4404. return 'on'
  4405. elif D['tank_solenoid_waterL3_status'] == 'off':
  4406. return 'off'
  4407. else:
  4408. return "tank_solenoid_waterL3_status signal was not received"
  4409. # 清洗浮選槽 清洗第 5 層電磁閥
  4410. elif dict['command'] == 'tank_solenoid_waterL5_status':
  4411. time.sleep(1)
  4412. if D['tank_solenoid_waterL5_status'] == 'on':
  4413. return 'on'
  4414. elif D['tank_solenoid_waterL5_status'] == 'off':
  4415. return 'off'
  4416. else:
  4417. return "tank_solenoid_waterL5_status signal was not received"
  4418. # 清洗浮選槽 步進馬達
  4419. elif dict['command'] == 'tank_stepping_motor_status':
  4420. time.sleep(1)
  4421. if D['tank_stepping_motor_status'] == '0':
  4422. return 'off'
  4423. elif type(D['tank_stepping_motor_status']) == int:
  4424. return 'on'
  4425. else:
  4426. return "tank_stepping_motor_status signal was not received"
  4427. return "publish done"
  4428. # 處理mqtt訂閱的信息
  4429. @mqtt.on_message()
  4430. def handle_mqtt_message(client, userdata, message):
  4431. payload = message.payload.decode()
  4432. payload = json.loads(payload)
  4433. # print("-------msg-------")
  4434. # print('name :', p['name'])
  4435. # print('email :', p['email'])
  4436. print('payload:', payload)
  4437. # 入料儲豆槽真空吸料機(ON吸料/OFF排氣)
  4438. if payload['command'] == 'input_vacuum_status':
  4439. if payload['response'] == 'on':
  4440. D['input_vacuum_status'] = 'on'
  4441. else:
  4442. D['input_vacuum_status'] = 'off'
  4443. # 真空吸料機
  4444. elif payload['command'] == 'tank_vacuum_status':
  4445. if payload['response'] == 'on':
  4446. # print('test')
  4447. D['tank_vacuum_status'] = 'on'
  4448. else:
  4449. D['tank_vacuum_status'] = 'off'
  4450. # 三通閥(ON吸料/OFF排氣)
  4451. elif payload['command'] == 'tank_threewayvalve_status':
  4452. if payload['response'] == 'on':
  4453. # print('test')
  4454. D['tank_threewayvalve_status'] = 'on'
  4455. else:
  4456. D['tank_threewayvalve_status'] = 'off'
  4457. # 蝴蝶閥(ON開/OFF關)
  4458. elif payload['command'] == 'tank_diskvalve_status':
  4459. if payload['response'] == 'on':
  4460. # print('test')
  4461. D['tank_diskvalve_status'] = 'on'
  4462. else:
  4463. D['tank_diskvalve_status'] = 'off'
  4464. # 電磁閥(ON噴灑消毒/OFF關)
  4465. elif payload['command'] == 'tank_solenoid_disinfect_status':
  4466. if payload['response'] == 'on':
  4467. # print('test')
  4468. D['tank_solenoid_disinfect_status'] = 'on'
  4469. else:
  4470. D['tank_solenoid_disinfect_status'] = 'off'
  4471. # 電磁閥(ON排水/OFF關)
  4472. elif payload['command'] == 'tank_solenoid_water_status':
  4473. if payload['response'] == 'on':
  4474. # print('test')
  4475. D['tank_solenoid_water_status'] = 'on'
  4476. else:
  4477. D['tank_solenoid_water_status'] = 'off'
  4478. # 馬達(單位RPM)
  4479. elif payload['command'] == 'tank_motor_status':
  4480. if payload['response'] == 'off':
  4481. D['tank_motor_status'] = '0'
  4482. else:
  4483. D['tank_motor_status'] = payload['response']
  4484. # 鼓風機(ON開/OFF關)
  4485. elif payload['command'] == 'tank_blower_status':
  4486. if payload['response'] == 'on':
  4487. # print('test')
  4488. D['tank_blower_status'] = 'on'
  4489. else:
  4490. D['tank_blower_status'] = 'off'
  4491. # 加熱棒 1(ON開/OFF關)
  4492. elif payload['command'] == 'tank_heater1_status':
  4493. if payload['response'] == 'on':
  4494. # print('test')
  4495. D['tank_heater1_status'] = 'on'
  4496. else:
  4497. D['tank_heater1_status'] = 'off'
  4498. # 加熱棒 2(ON開/OFF關)
  4499. elif payload['command'] == 'tank_heater2_status':
  4500. if payload['response'] == 'on':
  4501. # print('test')
  4502. D['tank_heater2_status'] = 'on'
  4503. else:
  4504. D['tank_heater2_status'] = 'off'
  4505. # 出料儲豆槽真空吸料機(ON吸料/OFF排氣)
  4506. elif payload['command'] == 'output_vacuum_status':
  4507. if payload['response'] == 'on':
  4508. # print('test')
  4509. D['output_vacuum_status'] = 'on'
  4510. else:
  4511. D['output_vacuum_status'] = 'off'
  4512. # 發酵槽 入料三通閥
  4513. elif payload['command'] == 'tank_threewayvalve_input_status':
  4514. if payload['response'] == 'on':
  4515. # print('test')
  4516. D['tank_threewayvalve_input_status'] = 'on'
  4517. else:
  4518. D['tank_threewayvalve_input_status'] = 'off'
  4519. # 發酵槽 總進水
  4520. elif payload['command'] == 'tank_solenoid_water_total_status':
  4521. if payload['response'] == 'on':
  4522. D['tank_solenoid_water_total_status'] = 'on'
  4523. else:
  4524. D['tank_solenoid_water_total_status'] = 'off'
  4525. # 發酵槽 桶內消毒/打菌
  4526. elif payload['command'] == 'tank_solenoid_disinfect_status':
  4527. if payload['response'] == 'on':
  4528. D['tank_solenoid_disinfect_status'] = 'on'
  4529. else:
  4530. D['tank_solenoid_disinfect_status'] = 'off'
  4531. # 發酵槽 夾層進水
  4532. elif payload['command'] == 'outer_solenoid_water_status':
  4533. if payload['response'] == 'on':
  4534. D['outer_solenoid_water_status'] = 'on'
  4535. else:
  4536. D['outer_solenoid_water_status'] = 'off'
  4537. # 發酵槽 桶內進水
  4538. elif payload['command'] == 'tank_solenoid_water_in_status':
  4539. if payload['response'] == 'on':
  4540. D['tank_solenoid_water_in_status'] = 'on'
  4541. else:
  4542. D['tank_solenoid_water_in_status'] = 'off'
  4543. # 發酵槽 雙核隔膜泵
  4544. elif payload['command'] == 'tank_pump_sensor_status':
  4545. if payload['response'] == 'on':
  4546. D['tank_pump_sensor_status'] = 'on'
  4547. else:
  4548. D['tank_pump_sensor_status'] = 'off'
  4549. # 發酵槽 感測器下豆三通閥
  4550. elif payload['command'] == 'tank_threewayvalve_bean_status':
  4551. if payload['response'] == 'on':
  4552. D['tank_threewayvalve_bean_status'] = 'on'
  4553. else:
  4554. D['tank_threewayvalve_bean_status'] = 'off'
  4555. # 發酵槽 外桶浮選三通閥
  4556. elif payload['command'] == 'outer_threewayvalve_float_status':
  4557. if payload['response'] == 'on':
  4558. D['outer_threewayvalve_float_status'] = 'on'
  4559. else:
  4560. D['outer_threewayvalve_float_status'] = 'off'
  4561. # 發酵槽 溫控開關
  4562. elif payload['command'] == 'tank_temp_enable_status':
  4563. if payload['response'] == 'on':
  4564. D['tank_temp_enable_status'] = 'on'
  4565. else:
  4566. D['tank_temp_enable_status'] = 'off'
  4567. # 發酵槽 設定溫度
  4568. elif payload['command'] == 'tank_temp_status':
  4569. if payload['response'] == 'off':
  4570. D['tank_temp_status'] = '0'
  4571. else:
  4572. D['tank_temp_status'] = payload['response']
  4573. # 清洗浮選槽 浮選槽注水
  4574. elif payload['command'] == 'tank_pump_waterFloat_status':
  4575. if payload['response'] == 'on':
  4576. D['tank_temp_status'] = 'on'
  4577. else:
  4578. D['tank_temp_status'] = 'off'
  4579. # 清洗浮選槽 清洗第 2 層灑水
  4580. elif payload['command'] == 'tank_pump_waterL2_status':
  4581. if payload['response'] == 'on':
  4582. D['tank_pump_waterL2_status'] = 'on'
  4583. else:
  4584. D['tank_pump_waterL2_status'] = 'off'
  4585. # 清洗浮選槽 清洗第 4 層灑水
  4586. elif payload['command'] == 'tank_pump_waterL4_status':
  4587. if payload['response'] == 'on':
  4588. D['tank_pump_waterL4_status'] = 'on'
  4589. else:
  4590. D['tank_pump_waterL4_status'] = 'off'
  4591. # 清洗浮選槽 清洗第 3 層電磁閥
  4592. elif payload['command'] == 'tank_solenoid_waterL3_status':
  4593. if payload['response'] == 'on':
  4594. D['tank_solenoid_waterL3_status'] = 'on'
  4595. else:
  4596. D['tank_solenoid_waterL3_status'] = 'off'
  4597. # 清洗浮選槽 清洗第 5 層電磁閥
  4598. elif payload['command'] == 'tank_solenoid_waterL5_status':
  4599. if payload['response'] == 'on':
  4600. D['tank_solenoid_waterL5_status'] = 'on'
  4601. else:
  4602. D['tank_solenoid_waterL5_status'] = 'off'
  4603. # 清洗浮選槽 步進馬達
  4604. elif payload['command'] == 'tank_stepping_motor_status':
  4605. if payload['response'] == 'off':
  4606. D['tank_stepping_motor_status'] = '0'
  4607. else:
  4608. D['tank_stepping_motor_status'] = payload['response']