1
0

views.py 562 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774
  1. # 主業務邏輯中的視圖和路由的定義
  2. import os
  3. import datetime
  4. from turtle import title
  5. from flask import Flask, redirect, render_template, request, session, Response, jsonify
  6. from sqlalchemy.sql.expression import desc, false, null
  7. # 導入藍圖程序,用於構建路由
  8. from werkzeug.utils import redirect
  9. from werkzeug.wrappers import response
  10. from . import main
  11. from coffee_manage import mqtt
  12. # 導入db,用於操作數據庫
  13. from coffee_manage import db
  14. # 導入實體類,用於操作數據庫
  15. from ..models import *
  16. import json
  17. from datetime import datetime as dt
  18. from datetime import timedelta
  19. from sqlalchemy import text
  20. import pymysql
  21. import pandas as pd
  22. from concurrent.futures import ThreadPoolExecutor
  23. import cv2
  24. import pickle
  25. import socket
  26. import time
  27. import threading
  28. import numpy as np
  29. import math
  30. from .mqtt import MQTT
  31. from matplotlib import pyplot as plt
  32. # import random
  33. from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg as FigureCanvas
  34. # import io
  35. # from flask import make_response
  36. # from distutils.util import strtobool # 將字串 string 轉成布林 boolean
  37. # import psutil
  38. import subprocess
  39. import shutil
  40. import stat
  41. pool = ThreadPoolExecutor(25)
  42. s_sock = 0
  43. lock = threading.Lock()
  44. '''
  45. mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffee',
  46. password='skyeye', database='Coffee', charset='utf8')
  47. mycursor = mydb.cursor()
  48. '''
  49. # 主頁的訪問路徑
  50. @main.route('/')
  51. def main_index():
  52. # 獲取登入信息
  53. if 'id' in session and 'uname' in session and 'status' in session:
  54. username = session['uname']
  55. status = session['status']
  56. if status == 9:
  57. return render_template('signin_disable.html')
  58. elif status == 8:
  59. return render_template('signin_new.html')
  60. # Rita 參數 params 是用來取得參數的 locals=() 所有參數
  61. return render_template('index.html', params=locals())
  62. else:
  63. return render_template('sign_in.html')
  64. # Rita 測試
  65. # sql_get
  66. @main.route('/sql_get', methods=['GET', 'POST'])
  67. def sql_get():
  68. # 取得網頁傳回來的 SQL 指令
  69. # sql = "SELECT * FROM 零件表 WHERE 會計科目 = 04"
  70. info = request.args.to_dict('sql')
  71. datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  72. sql = info['sql'].replace('current_timestamp()', '"' + datetime + '"')
  73. # ip = request.remote_addr
  74. # sql = info['sql'].replace('IPDATA', '"' + ip + '"')
  75. print("[sql_get]sql: ", sql)
  76. # 存入本機
  77. mydb = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='Gold@53743001', database='CoffeeManage', charset='utf8')
  78. mycursor = mydb.cursor()
  79. try:
  80. mycursor.execute(sql)
  81. sql_data = mycursor.fetchall()
  82. except pymysql.err.IntegrityError:
  83. sql_data = "localhost Mysql 存值錯誤"
  84. mydb.commit()
  85. mydb.close()
  86. # 存入 HOME
  87. mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffeemanage', password='skyeye', database='CoffeeManage', charset='utf8')
  88. mycursor = mydb.cursor()
  89. try:
  90. mycursor.execute(sql)
  91. sql_data = mycursor.fetchall()
  92. except pymysql.err.IntegrityError:
  93. sql_data = "Home Mysql 存值錯誤"
  94. mydb.commit()
  95. mydb.close()
  96. return jsonify({"response":sql_data})
  97. # @main.route('/sql_get_HOME', methods=['GET', 'POST'])
  98. # def sql_get_HOME():
  99. # mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffee', password='skyeye', database='Coffee', charset='utf8')
  100. # # mydb = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='Gold@53743001', database='Coffee', charset='utf8')
  101. # mycursor = mydb.cursor()
  102. # # 取得網頁傳回來的 SQL 指令
  103. # # sql = "SELECT * FROM 零件表 WHERE 會計科目 = 04"
  104. # info = request.args.to_dict('sql')
  105. # sql = info['sql']
  106. # print("[sql_get]sql: ", sql)
  107. # try:
  108. # mycursor.execute(sql)
  109. # sql_data = mycursor.fetchall()
  110. # except pymysql.err.IntegrityError:
  111. # sql_data = "請注意 ! 單據不可新增重複的零件"
  112. # mydb.commit()
  113. # mydb.close()
  114. # return jsonify({"response":"OK"})
  115. # Rita 測試
  116. # 使用者名稱測試
  117. @main.route('/test', methods=['GET', 'POST'])
  118. def test():
  119. info = request.args.to_dict()
  120. print(info)
  121. print("info[command]: ", info['command'])
  122. return json.dumps(info)
  123. # Rita 測試
  124. # 板子燒錄請求
  125. @main.route('/board_programmer')
  126. def board_programmer():
  127. prog_data = request.args.to_dict() # {'tank': 'D1'}
  128. CURRENT_PATH = os.path.dirname(__file__) # c:\Users\USER\Rita\Coffee\CoffeeProject\app\main
  129. # # 取得 hex 檔案內容
  130. file = os.path.join(CURRENT_PATH, 'CTO20220622', 'build', 'SDIO.hex') # c:\Users\USER\Rita\Coffee\CoffeeProject\app\main\CTO20220622\SDIO.hex
  131. f = open(file, 'r')
  132. ota_hex = f.read()
  133. # # MQTT 傳送燒錄
  134. MQTT_dict = {
  135. 'command':'Code_upload',
  136. 'tank_num':prog_data['tank'],
  137. 'url':ota_hex
  138. }
  139. import json
  140. json = json.dumps(MQTT_dict)
  141. # print("MQTT_dict: ", MQTT_dict) # MQTT_dict: {'command': 'Code_upload', 'tank_num': 'F1', 'url': ':020000040801F1\n:1000
  142. # print("json: ", json) # json: {"command": "Code_upload", "tank_num": "F1", "url": ":020000040801F1\n:1000
  143. # topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
  144. topic = 'AISKY/Coffee/MK-G/' + str(prog_data['burner_mac'])
  145. mqtt.publish(topic, json)
  146. time.sleep(3)
  147. if board_prog[prog_data['tank']] == 'no reply':
  148. board_prog[prog_data['tank']] = '0'
  149. return 'no reply'
  150. print("===== 下載 Git CoffeeProject_SourceCode ==========================================================")
  151. # # 先下載 Git CoffeeProject_SourceCode
  152. os.system('git clone --single-branch http://60.250.156.230:3000/rita/CoffeeProject_SourceCode.git ' + CURRENT_PATH + '/source_code')
  153. time.sleep(3)
  154. print("===== 將 hex 先複製更名 ==========================================================")
  155. # # 將 hex 先複製更名
  156. copy_old_path = os.path.join(CURRENT_PATH, "CTO20220622", "build", "SDIO.hex")
  157. currentTime = dt.now().strftime("%Y%m%d_%H%M%S")
  158. fileTitle_hex = "[" + currentTime + "_" + prog_data['USERNAME'] + "] " + prog_data['tank'] + "_SDIO.hex"
  159. copy_new_path = os.path.join(CURRENT_PATH, "CTO20220622", "build", fileTitle_hex)
  160. print("copy_new_path: ", copy_new_path)
  161. shutil.copyfile(copy_old_path, copy_new_path)
  162. time.sleep(3)
  163. print("===== 再將 hex 移動到 source_code 資料夾中 ==========================================================")
  164. # # 再將 hex 移動到 source_code 資料夾中
  165. move_new_path = os.path.join(CURRENT_PATH, "source_code", fileTitle_hex)
  166. print("copy_new_path: ", copy_new_path)
  167. print("move_new_path: ", move_new_path)
  168. shutil.move(copy_new_path, move_new_path)
  169. time.sleep(3)
  170. print("===== 將 main.c 先複製更名 ==========================================================")
  171. # # 將 main.c 先複製更名
  172. copy_old_path = os.path.join(CURRENT_PATH, "CTO20220622", "Src", "main.c")
  173. # currentTime = dt.now().strftime("%Y%m%d_%H%M%S") # 同 hex 即可
  174. fileTitle_c = "[" + currentTime + "_" + prog_data['USERNAME'] + "] " + prog_data['tank'] + "_main.c"
  175. copy_new_path = os.path.join(CURRENT_PATH, "CTO20220622", "Src", fileTitle_c)
  176. print("copy_new_path: ", copy_new_path)
  177. shutil.copyfile(copy_old_path, copy_new_path)
  178. time.sleep(3)
  179. print("===== 再將 main.c 移動到 source_code 資料夾中 ==========================================================")
  180. # # 再將 main.c 移動到 source_code 資料夾中
  181. move_new_path = os.path.join(CURRENT_PATH, "source_code", fileTitle_c)
  182. print("copy_new_path: ", copy_new_path)
  183. print("move_new_path: ", move_new_path)
  184. shutil.move(copy_new_path, move_new_path)
  185. time.sleep(3)
  186. print("===== 將 source_code 資料內容 push 到 Git CoffeeProject_SourceCode ==========================================================")
  187. # # 將 source_code 資料內容 push 到 Git CoffeeProject_SourceCode
  188. cwdDATA = os.path.join(CURRENT_PATH, "source_code")
  189. subprocess.call(["git", "add", fileTitle_hex],cwd=cwdDATA)
  190. subprocess.call(["git", "commit","-m", fileTitle_hex],cwd=cwdDATA)
  191. subprocess.call(["git", "add", fileTitle_c],cwd=cwdDATA)
  192. subprocess.call(["git", "commit","-m", fileTitle_c],cwd=cwdDATA)
  193. subprocess.call(["git", "push"],cwd=cwdDATA)
  194. time.sleep(3)
  195. print("===== 刪除 source_code 資料夾 ==========================================================")
  196. # # 刪除 source_code 資料夾
  197. # shutil.rmtree(CURRENT_PATH + "\\source_code", onerror=remove_readonly)
  198. shutil.rmtree(cwdDATA, onerror=remove_readonly)
  199. time.sleep(3)
  200. # # 取得燒錄回傳
  201. print("===== SDIO.hex 燒錄等待中 =====================================================")
  202. res = board_prog[prog_data['tank']]
  203. print("res: ", res)
  204. return "燒錄中..."
  205. # time.sleep(60)
  206. # res = board_prog[prog_data['tank']]
  207. # print("res: ", res)
  208. # if board_prog[prog_data['tank']] == 'no reply':
  209. # board_prog[prog_data['tank']] = '0'
  210. # return 'no reply'
  211. # elif board_prog[prog_data['tank']] == 'success':
  212. # board_prog[prog_data['tank']] = '0'
  213. # return 'success'
  214. # elif board_prog[prog_data['tank']] == 'upload error':
  215. # board_prog[prog_data['tank']] = '0'
  216. # return 'upload error'
  217. # else:
  218. # res = "Code_upload " + prog_data['tank'] + " signal was not received"
  219. # return res
  220. @main.route('/board_programmer_result_<tid>')
  221. def board_programmer_result(tid):
  222. if board_prog[tid] == 'no reply':
  223. board_prog[tid] = '0'
  224. # return board_prog[tid] # 錯誤
  225. return 'no reply'
  226. elif board_prog[tid] == 'success':
  227. board_prog[tid] = '0'
  228. return 'success'
  229. elif board_prog[tid] == 'upload error':
  230. board_prog[tid] = '0'
  231. return 'upload error'
  232. elif board_prog[tid] == '0':
  233. return board_prog[tid]
  234. else:
  235. # res = "Code_upload " + tid + " signal was not received"
  236. return board_prog[tid]
  237. def remove_readonly(func, path, _):
  238. os.chmod(path, stat.S_IWRITE) # 更改權限 stat.S_IWRITE = windows 下取消只读
  239. func(path)
  240. # Rita 測試
  241. # 板子介面測試
  242. @main.route('/board_loadertt')
  243. def board_loadertt():
  244. pin_data = coffee1_0_pin.query.order_by(text('datetime desc')).first()
  245. # DCD1 = block_cond_d1_t.query.order_by(text('datetime desc')).first()
  246. BCD = block_cond_dry_t.query.order_by(text('datetime desc')).first()
  247. return render_template('board_loadertt.html', title="[測試]", **locals())
  248. # 檢視各使用者條件
  249. @main.route('/block_view', methods=['GET', 'POST'])
  250. def block_view():
  251. if request.method == 'GET':
  252. username = session['uname']
  253. status = session['status']
  254. sql = 'SELECT DISTINCT `UserName` FROM `block_cond_dry_t`'
  255. mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffeemanage', password='skyeye', database='CoffeeManage', charset='utf8')
  256. mycursor = mydb.cursor()
  257. try:
  258. mycursor.execute(sql)
  259. username_data = mycursor.fetchall()
  260. except pymysql.err.IntegrityError:
  261. username_data = "UserName is empty"
  262. mydb.commit()
  263. mydb.close()
  264. return render_template('block_view.html', title="檢視積木條件", **locals())
  265. # else:
  266. # prog_username = request.values['prog_username']
  267. # prog_tank = request.values['prog_tank']
  268. # print("prog_username: ", prog_username)
  269. # print("prog_tank: ", prog_tank)
  270. # return redirect('/block_view')
  271. # 桶槽間溝通
  272. @main.route('/tanks_comm')
  273. def tanks_comm():
  274. if 'id' in session and 'uname' in session and 'status' in session:
  275. username = session['uname']
  276. status = session['status']
  277. return render_template('tanks_comm.html', title="設備單元整合運作", **locals())
  278. else:
  279. print("NO session['uname']")
  280. return redirect('/login')
  281. @main.route('/select_cond', methods=['GET', 'POST'])
  282. def select_cond():
  283. info = request.args.to_dict()
  284. username = info['username']
  285. print("username: ", username)
  286. tank = info['tank']
  287. print("tank: ", tank)
  288. cond_data = (block_cond_dry_t.query.filter_by(UserName=str(username),tank_num=str(tank)).order_by(text('datetime desc')).first()).cond
  289. # print("cond_data.cond: ", cond_data.cond, "_type(cond_data.cond): ", type(cond_data.cond))
  290. print("cond_data: ", cond_data, type(cond_data))
  291. return cond_data
  292. @main.route('/board_loader_<tankid>')
  293. def board_loader(tankid):
  294. if 'id' in session and 'uname' in session and 'status' in session:
  295. username = session['uname']
  296. status = session['status']
  297. # 取得桶槽編號
  298. TankID = tankid
  299. # 找到目前桶槽的入料儲豆槽
  300. dry_tank_io = dry_tank_relation.query.filter_by(tank_id=tankid).first()
  301. # 若在 dry_tank_relation 桶槽關聯內無此桶槽, 則回到 /board_loader_D1
  302. if dry_tank_io == None:
  303. return redirect("/tank_relation")
  304. print(dry_tank_io.tank_import) # DI1
  305. tank_import = dry_tank_io.tank_import
  306. # 找到目前桶槽的入料儲豆槽
  307. print(dry_tank_io.tank_export)
  308. tank_export = dry_tank_io.tank_export
  309. # 腳位配置
  310. pin_data = coffee1_0_pin.query.filter_by(tid=tankid).order_by(text('datetime desc')).first()
  311. print("pin_data: ", pin_data)
  312. # 積木條件
  313. BCD = block_cond_dry_t.query.filter_by(tank_num=tankid).order_by(text('datetime desc')).first()
  314. if BCD == None:
  315. # 網頁初始只需要 cond
  316. BCD = {"command":"Dry_OTA",
  317. "cond":[
  318. {"cond_add":[],
  319. "cond_com":[],
  320. "cond_main":""}
  321. ],
  322. "tank_num":tankid}
  323. print("BCD: ", BCD)
  324. return render_template('board_loader-1.html', title="板子燒錄介面", **locals())
  325. else:
  326. print("NO session['uname']")
  327. return redirect('/login')
  328. # if 'id' in session and 'uname' in session:
  329. # print("session['uname']: ", session['uname'])
  330. # username = session['uname']
  331. # print("session['status']: ", session['status'])
  332. # status = session['status']
  333. # pin_data = coffee1_0_pin.query.order_by(text('datetime desc')).first()
  334. # # print("pin_data.R1:", pin_data.R1)
  335. # block_data = dry_block_waiting.query.order_by(text('datetime desc')).first()
  336. # # print("block_data.cond_a1_1:", block_data.cond_a1_1)
  337. # DBW = dry_block_waiting.query.order_by(text('datetime desc')).first()
  338. # return render_template('board_loader-1.html', title="板子燒錄介面", **locals())
  339. # else:
  340. # print("NO session['uname']")
  341. # return redirect('/login')
  342. # 桶槽前後關係設定
  343. @main.route('/tank_relation')
  344. def tank_relation():
  345. dtr = dry_tank_relation.query.all()
  346. # for i in dtr:
  347. # print("dtr", i, ": ", i.tank_id)
  348. return render_template('tank_relation.html', title="桶槽關係建立", **locals())
  349. #致動器功能程式定義
  350. def GPIO(relay,status):
  351. if relay=="R1":
  352. if status=="on":
  353. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_13, GPIO_PIN_RESET);\n"
  354. elif status=="off":
  355. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_13, GPIO_PIN_SET);\n"
  356. else:
  357. act=""
  358. elif relay=="R2":
  359. if status=="on":
  360. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_12, GPIO_PIN_RESET);\n"
  361. elif status=="off":
  362. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_12, GPIO_PIN_SET);\n"
  363. else:
  364. act=""
  365. elif relay=="R3":
  366. if status=="on":
  367. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_11, GPIO_PIN_RESET);\n"
  368. elif status=="off":
  369. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_11, GPIO_PIN_SET);\n"
  370. else:
  371. act=""
  372. elif relay=="R4":
  373. if status=="on":
  374. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_10, GPIO_PIN_RESET);\n"
  375. elif status=="off":
  376. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_10, GPIO_PIN_SET);\n"
  377. else:
  378. act=""
  379. elif relay=="R5":
  380. if status=="on":
  381. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_9, GPIO_PIN_RESET);\n"
  382. elif status=="off":
  383. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_9, GPIO_PIN_SET);\n"
  384. else:
  385. act=""
  386. elif relay=="R6":
  387. if status=="on":
  388. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_8, GPIO_PIN_RESET);\n"
  389. elif status=="off":
  390. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_8, GPIO_PIN_SET);\n"
  391. else:
  392. act=""
  393. elif relay=="R7":
  394. if status=="on":
  395. act=" HAL_GPIO_WritePin(GPIOC,GPIO_PIN_9, GPIO_PIN_RESET);\n"
  396. elif status=="off":
  397. act=" HAL_GPIO_WritePin(GPIOC,GPIO_PIN_9, GPIO_PIN_SET);\n"
  398. else:
  399. act=""
  400. elif relay=="R8":
  401. if status=="on":
  402. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_15, GPIO_PIN_RESET);\n"
  403. elif status=="off":
  404. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_15, GPIO_PIN_SET);\n"
  405. else:
  406. act=""
  407. elif relay=="R9":
  408. if status=="on":
  409. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_14, GPIO_PIN_RESET);\n"
  410. elif status=="off":
  411. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_14, GPIO_PIN_SET);\n"
  412. else:
  413. act=""
  414. elif relay=="R10":
  415. if status=="on":
  416. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_13, GPIO_PIN_RESET);\n"
  417. elif status=="off":
  418. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_13, GPIO_PIN_SET);\n"
  419. else:
  420. act=""
  421. elif relay=="R11":
  422. if status=="on":
  423. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_12, GPIO_PIN_RESET);\n"
  424. elif status=="off":
  425. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_12, GPIO_PIN_SET);\n"
  426. else:
  427. act=""
  428. elif relay=="R12":
  429. if status=="on":
  430. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_11, GPIO_PIN_RESET);\n"
  431. elif status=="off":
  432. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_11, GPIO_PIN_SET);\n"
  433. else:
  434. act=""
  435. elif relay=="R13":
  436. if status=="on":
  437. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_10, GPIO_PIN_RESET);\n"
  438. elif status=="off":
  439. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_10, GPIO_PIN_SET);\n"
  440. else:
  441. act=""
  442. elif relay=="R14":
  443. if status=="on":
  444. act=" HAL_GPIO_WritePin(GPIOB,GPIO_PIN_15, GPIO_PIN_RESET);\n"
  445. elif status=="off":
  446. act=" HAL_GPIO_WritePin(GPIOB,GPIO_PIN_15, GPIO_PIN_SET);\n"
  447. else:
  448. act=""
  449. elif relay=="R15":
  450. if status=="on":
  451. act=" HAL_GPIO_WritePin(GPIOB,GPIO_PIN_14, GPIO_PIN_RESET);\n"
  452. elif status=="off":
  453. act=" HAL_GPIO_WritePin(GPIOB,GPIO_PIN_14, GPIO_PIN_SET);\n"
  454. else:
  455. act=""
  456. elif relay=="R16":
  457. if status=="on":
  458. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_15, GPIO_PIN_RESET);\n"
  459. elif status=="off":
  460. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_15, GPIO_PIN_SET);\n"
  461. else:
  462. act=""
  463. elif relay=="R17":
  464. if status=="on":
  465. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_14, GPIO_PIN_RESET);\n"
  466. elif status=="off":
  467. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_14, GPIO_PIN_SET);\n"
  468. else:
  469. act=""
  470. elif relay=="R18":
  471. if status=="on":
  472. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_13, GPIO_PIN_RESET);\n"
  473. elif status=="off":
  474. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_13, GPIO_PIN_SET);\n"
  475. else:
  476. act=""
  477. elif relay=="R19":
  478. if status=="on":
  479. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_12, GPIO_PIN_RESET);\n"
  480. elif status=="off":
  481. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_12, GPIO_PIN_SET);\n"
  482. else:
  483. act=""
  484. elif relay=="R20":
  485. if status=="on":
  486. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_11, GPIO_PIN_RESET);\n"
  487. elif status=="off":
  488. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_11, GPIO_PIN_SET);\n"
  489. else:
  490. act=""
  491. elif relay=="sleep":
  492. act=" HAL_Delay("+status+"000);\n"
  493. elif relay=="M10":
  494. if int(status)>0:
  495. act=(" user_pwm_setvalue2(0);\n"
  496. +" user_pwm_setvalue("+status+");\n")
  497. elif int(status)<0:
  498. status=-1*int(status)
  499. act=(" user_pwm_setvalue(0);\n"
  500. +" user_pwm_setvalue2("+str(status)+");\n")
  501. else:
  502. act=""
  503. elif relay=="M2":
  504. if status=="on":
  505. act=" user_pwm_setvalue3(50);\n"
  506. elif status=="off":
  507. act=" user_pwm_setvalue3(180);\n"
  508. else:
  509. act=""
  510. elif relay=="M3":
  511. if status=="on":
  512. act=" user_pwm_setvalue4(50);\n"
  513. elif status=="off":
  514. act=" user_pwm_setvalue4(180);\n"
  515. else:
  516. act=""
  517. else:
  518. act=""
  519. return act
  520. #感測器功能程式定義
  521. def PH(pin_position,pin_type):
  522. global pin_variables,pin_code
  523. if pin_position=="M4":
  524. pin="ADC_CHANNEL_0"
  525. elif pin_position=="M5":
  526. pin="ADC_CHANNEL_3"
  527. elif pin_position=="M7":
  528. pin="ADC_CHANNEL_4"
  529. if pin_type =="PH":
  530. print("PH ok")
  531. pin_variables=("uint16_t "+pin_position+"_AD_Value = 0;\n"
  532. +"float "+pin_position+"_voltage_V =0;\n"
  533. +"float "+pin_position+"_pH_mid = 1.500;\n"
  534. +"float "+pin_position+"_pH_low = 2.030;\n"
  535. +"float "+pin_position+"_pH_high =0.975;\n"
  536. +"float "+pin_position+"_"+pin_type+"=0;\n")
  537. pin_code=(" MX_ADC1_Init1("+pin+");\n"
  538. +" HAL_ADC_Start(&hadc1);\n"
  539. +" HAL_ADC_PollForConversion(&hadc1, 50);\n"
  540. +" if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
  541. +" {\n"
  542. +" "+pin_position+"_AD_Value = HAL_ADC_GetValue(&hadc1);\n"
  543. +" "+pin_position+"_voltage_V = "+pin_position+"_AD_Value*3.3f/4096;\n"
  544. +" if ("+pin_position+"_voltage_V > "+pin_position+"_pH_mid)\n"
  545. +" {\n"
  546. +" "+pin_position+"_"+pin_type+" = 7.0 - 3.0 / ("+pin_position+"_pH_low - "+pin_position+"_pH_mid) * ("+pin_position+"_voltage_V - "+pin_position+"_pH_mid);\n"
  547. +" }\n"
  548. +" else\n"
  549. +" {\n"
  550. +" "+pin_position+"_"+pin_type+" = 7.0 - 3.0 / ("+pin_position+"_pH_mid - "+pin_position+"_pH_high) * ("+pin_position+"_voltage_V - "+pin_position+"_pH_mid);\n"
  551. +" }\n"
  552. +" }\n"
  553. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",4,10);\n")
  554. else:
  555. pin_variables=""
  556. pin_code=""
  557. def DO(pin_position,pin_type):
  558. global pin_variables,pin_code
  559. if pin_position=="M4":
  560. pin="ADC_CHANNEL_0"
  561. elif pin_position=="M5":
  562. pin="ADC_CHANNEL_3"
  563. elif pin_position=="M7":
  564. pin="ADC_CHANNEL_4"
  565. if pin_type =="DO":
  566. print("DO ok")
  567. pin_variables=("uint16_t "+pin_position+"_AD_Value = 0;\n"
  568. +"float "+pin_position+"_voltage_V =0;\n"
  569. +"float "+pin_position+"_DO_offset =0.44;\n"
  570. +"float "+pin_position+"_"+pin_type+" =0;\n")
  571. pin_code=(" MX_ADC1_Init1("+pin+");\n"
  572. +" HAL_ADC_Start(&hadc1);\n"
  573. +" HAL_ADC_PollForConversion(&hadc1, 50);\n"
  574. +" if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
  575. +" {\n"
  576. +" "+pin_position+"_AD_Value = HAL_ADC_GetValue(&hadc1);\n"
  577. +" "+pin_position+"_voltage_V = "+pin_position+"_AD_Value*3.3f/4096;\n"
  578. +" "+pin_position+"_"+pin_type+"= ((("+pin_position+"_AD_Value*3.3f/4096)*100)/"+pin_position+"_DO_offset);\n"
  579. +" }\n"
  580. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",4,10);\n")
  581. else:
  582. pin_variables=""
  583. pin_code=""
  584. def WATERLEVEL(pin_position,pin_type):
  585. global pin_variables,pin_code
  586. if pin_position=="M9":
  587. pin="GPIO_PIN_9"
  588. elif pin_position=="M11":
  589. pin="GPIO_PIN_7"
  590. elif pin_position=="M12":
  591. pin="GPIO_PIN_8"
  592. elif pin_position=="M19":
  593. pin="GPIO_PIN_10"
  594. if pin_type =="WATERLEVEL":
  595. print("WATERLEVEL ok")
  596. pin_variables=("int "+pin_position+"_"+pin_type+" =0;\n")
  597. pin_code=(" MX_GPIO_Input1("+pin+");\n"
  598. +" if (HAL_GPIO_ReadPin(GPIOE, "+pin+") == GPIO_PIN_SET)\n"
  599. +" {\n"
  600. +" "+pin_position+"_"+pin_type+" =1;\n"
  601. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
  602. +" }\n"
  603. +" else\n"
  604. +" {\n"
  605. +" "+pin_position+"_"+pin_type+" =0;\n"
  606. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
  607. +" }\n")
  608. else:
  609. pin_variables=""
  610. pin_code=""
  611. def motorfeedback(pin_position,pin_type):
  612. global pin_variables,pin_code
  613. if pin_position=="M9":
  614. pin="GPIO_PIN_9"
  615. elif pin_position=="M11":
  616. pin="GPIO_PIN_7"
  617. elif pin_position=="M12":
  618. pin="GPIO_PIN_8"
  619. elif pin_position=="M19":
  620. pin="GPIO_PIN_10"
  621. if pin_type =="motorfeedback":
  622. print("feedback ok")
  623. pin_variables=("int "+pin_position+"_"+pin_type+" =0;\n")
  624. pin_code=(" MX_GPIO_Input1("+pin+");\n"
  625. +" if (HAL_GPIO_ReadPin(GPIOE, "+pin+") == GPIO_PIN_SET)\n"
  626. +" {\n"
  627. +" "+pin_position+"_"+pin_type+" =1;\n"
  628. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
  629. +" }\n"
  630. +" else\n"
  631. +" {\n"
  632. +" "+pin_position+"_"+pin_type+" =0;\n"
  633. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
  634. +" }\n")
  635. else:
  636. pin_variables=""
  637. pin_code=""
  638. def butterflyvalvefeedback(pin_position,pin_type):
  639. global pin_variables,pin_code
  640. if pin_position=="M9":
  641. pin="GPIO_PIN_9"
  642. elif pin_position=="M11":
  643. pin="GPIO_PIN_7"
  644. elif pin_position=="M12":
  645. pin="GPIO_PIN_8"
  646. elif pin_position=="M19":
  647. pin="GPIO_PIN_10"
  648. if pin_type =="butterflyvalvefeedback":
  649. print("butterflyvalvefeedback ok")
  650. pin_variables=("int "+pin_position+"_"+pin_type+" =0;\n")
  651. pin_code=(" MX_GPIO_Input1("+pin+");\n"
  652. +" if (HAL_GPIO_ReadPin(GPIOE, "+pin+") == GPIO_PIN_SET)\n"
  653. +" {\n"
  654. +" "+pin_position+"_"+pin_type+" =1;\n"
  655. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
  656. +" }\n"
  657. +" else\n"
  658. +" {\n"
  659. +" "+pin_position+"_"+pin_type+" =0;\n"
  660. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
  661. +" }\n")
  662. else:
  663. pin_variables=""
  664. pin_code=""
  665. def ORP(pin_position,pin_type):
  666. global pin_variables,pin_code
  667. if pin_position=="M4":
  668. pin="ADC_CHANNEL_0"
  669. elif pin_position=="M5":
  670. pin="ADC_CHANNEL_3"
  671. elif pin_position=="M7":
  672. pin="ADC_CHANNEL_4"
  673. if pin_type =="ORP":
  674. print("ORP ok")
  675. pin_variables=("uint16_t "+pin_position+"_AD_Value = 0;\n"
  676. +"float "+pin_position+"_voltage_V =0;\n"
  677. +"float "+pin_position+"_ORP_offset =0;\n"
  678. +"float "+pin_position+"_"+pin_type+" =0;\n")
  679. pin_code=(" MX_ADC1_Init1("+pin+");\n"
  680. +" HAL_ADC_Start(&hadc1);\n"
  681. +" HAL_ADC_PollForConversion(&hadc1, 50);\n"
  682. +" if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
  683. +" {\n"
  684. +" "+pin_position+"_AD_Value = HAL_ADC_GetValue(&hadc1);\n"
  685. +" "+pin_position+"_voltage_V = "+pin_position+"_AD_Value*3.3f/4096;\n"
  686. +" "+pin_position+"_"+pin_type+"= ((("+pin_position+"_AD_Value*3.3f/4096)-(1.5+"+pin_position+"_ORP_offset)));\n"
  687. +" }\n"
  688. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",4,10);\n")
  689. else:
  690. pin_variables=""
  691. pin_code=""
  692. def SonicESMUS07(pin_position,pin_type):
  693. global pin_variables,pin_code,pin_add_code
  694. if pin_position=="M1":
  695. pin="ADC_CHANNEL_6"
  696. if pin_type =="SonicESMUS07":
  697. print("ESMUS07 ok")
  698. pin_variables=("uint16_t "+pin_position+"_AD_Value = 0;\n"
  699. +"float "+pin_position+"_voltage_V =0;\n"
  700. +"float "+pin_position+"_"+pin_type+" =0;\n")
  701. pin_code=(" MX_ADC1_Init1("+pin+");\n"
  702. +" HAL_ADC_Start(&hadc1);\n"
  703. +" HAL_ADC_PollForConversion(&hadc1, 50);\n"
  704. +" if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
  705. +" {\n"
  706. +" "+pin_position+"_AD_Value = HAL_ADC_GetValue(&hadc1);\n"
  707. +" "+pin_position+"_voltage_V = "+pin_position+"_AD_Value*5.3f/4096;\n"
  708. +" if ("+pin_position+"_voltage_V==0)\n"
  709. +" {\n"
  710. +" "+pin_position+"_"+pin_type+ " = 100;\n"
  711. +" }\n"
  712. +" else\n"
  713. +" {\n"
  714. +" "+pin_position+"_"+pin_type+ " = ("+pin_position+"_voltage_V*180)+100;\n"
  715. +" }\n"
  716. +" }\n"
  717. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",4,10);\n")
  718. else:
  719. pin_variables=""
  720. pin_code=""
  721. pin_add_code=""
  722. def SEN0189(pin_position,pin_type):
  723. global pin_variables,pin_code,pin_add_code
  724. if pin_position=="M6":
  725. pin="ADC_CHANNEL_13"
  726. elif pin_position=="M13":
  727. pin="ADC_CHANNEL_5"
  728. if pin_type =="SEN0189":
  729. print("SEN0189 ok")
  730. pin_variables=("uint16_t "+pin_position+"_AD_Value = 0;\n"
  731. +"float "+pin_position+"_voltage_V =0;\n"
  732. +"float "+pin_position+"_"+pin_type+" =0;\n")
  733. pin_code=(" MX_ADC1_Init1("+pin+");\n"
  734. +" HAL_ADC_Start(&hadc1);\n"
  735. +" HAL_ADC_PollForConversion(&hadc1, 50);\n"
  736. +" if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
  737. +" {\n"
  738. +" "+pin_position+"_AD_Value = HAL_ADC_GetValue(&hadc1);\n"
  739. +" "+pin_position+"_voltage_V = "+pin_position+"_AD_Value*5.0f/4096;\n"
  740. +" if ("+pin_position+"_voltage_V>4.2)\n"
  741. +" {\n"
  742. +" "+pin_position+"_"+pin_type+ " = 0;\n"
  743. +" }\n"
  744. +" else if ("+pin_position+"_voltage_V<2.5)\n"
  745. +" {\n"
  746. +" "+pin_position+"_"+pin_type+ " = 3000;\n"
  747. +" }\n"
  748. +" else\n"
  749. +" {\n"
  750. +" "+pin_position+"_"+pin_type+"=(-1120.4*"+pin_position+"_voltage_V*"+pin_position+"_voltage_V)+(5742.3*"+pin_position+"_voltage_V)-4352.9;\n"
  751. +" }\n"
  752. +" }\n"
  753. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",4,10);\n")
  754. print(pin_variables)
  755. print(pin_code)
  756. else:
  757. pin_variables=""
  758. pin_code=""
  759. pin_add_code=""
  760. def SERVO(pin_position, pin_type):
  761. global pin_variables, pin_code
  762. if pin_type == "Servo":
  763. print("Servo ok")
  764. pin_code = (
  765. " HAL_UART_Receive_IT(&huart1, (uint8_t *)checkfeedback,sizeof(checkfeedback));\n")
  766. pin_add_code = (" void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)\n"
  767. + "{\n"
  768. + " if(checkfeedback[0]==0xff && checkfeedback[6]==0x0D)\n"
  769. + " {\n"
  770. + " direction=checkfeedback[1];\n"
  771. + " if(direction==0)\n"
  772. + " {\n"
  773. + " HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_RESET);\n"
  774. + " HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, GPIO_PIN_SET);\n"
  775. + " user_pwm_setvalue(50);\n"
  776. + " }\n"
  777. + " else if(direction==1)\n"
  778. + " {\n"
  779. + " HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_RESET);\n"
  780. + " HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, GPIO_PIN_RESET);\n"
  781. + " user_pwm_setvalue(50);\n"
  782. + " }\n"
  783. + " else\n"
  784. + " {\n"
  785. + " HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_SET);\n"
  786. + " HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, GPIO_PIN_RESET);\n"
  787. + " user_pwm_setvalue(0);\n"
  788. + " }\n"
  789. + " }\n"
  790. + "}\n")
  791. print(pin_code)
  792. print(pin_add_code)
  793. else:
  794. pin_variables = ""
  795. pin_code = ""
  796. def MOTOR(pin_position, pin_type):
  797. global pin_variables, pin_code
  798. if pin_type == "Servo":
  799. print("Servo ok")
  800. pin_code = (" HAL_UART_Receive_IT(&huart1, (uint8_t *)checkfeedback,sizeof(checkfeedback));\n"
  801. + " HAL_Delay(100);\n"
  802. + " if(direction==0)\n"
  803. + " {\n"
  804. + " user_pwm_setvalue2(0);\n"
  805. + " user_pwm_setvalue(pwm_value);\n"
  806. + " }\n"
  807. + " else\n"
  808. + " {\n"
  809. + " user_pwm_setvalue2(pwm_value);\n"
  810. + " user_pwm_setvalue(0);\n"
  811. + " }\n")
  812. pin_add_code = (" void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)\n"
  813. + "{\n"
  814. + " if(checkfeedback[0]==0xff && checkfeedback[6]==0x0D)\n"
  815. + " {\n"
  816. + " pwm_value=checkfeedback[1];\n"
  817. + " direction=checkfeedback[2];\n"
  818. + ' printf("%d",pwm_value);\n'
  819. + " }\n"
  820. + "}\n")
  821. print(pin_code)
  822. print(pin_add_code)
  823. else:
  824. pin_variables = ""
  825. pin_code = ""
  826. def SOIL(pin_position,pin_type):
  827. global pin_variables,pin_code,pin_add_code
  828. if pin_type =="Soil":
  829. print("SOIL ok")
  830. pin_variables=("uint8_t soil[8] ={0x01,0x03,0x00,0x00,0x00,0x03,0x05,0xCB};\n"
  831. +"uint8_t data[11] ={0,0,0,0,0,0,0,0,0,0,0};\n"
  832. +"float "+pin_position+"_"+pin_type+" =0;\n"
  833. +"int rh=0;\n"
  834. +"int temp=0;\n"
  835. +"int ec=0;\n")
  836. pin_code=(" HAL_UART_Transmit(&huart2, (uint8_t *)soil,sizeof(soil),50);\n"
  837. +" HAL_UART_Receive_IT(&huart2, (uint8_t *)data,sizeof(data));\n")
  838. pin_add_code=("void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)\n"
  839. +"{\n"
  840. +" if (huart->Instance == USART2)\n"
  841. +" {\n"
  842. +" if (data[0]==0x01 && data[1]==0x03)\n"
  843. +" {\n"
  844. +" rh = (data[3] << 8) + data[4];\n"
  845. +" temp = (data[5] << 8) + data[6];\n"
  846. +" ec = (data[7] << 8) + data[8];\n"
  847. +" }\n"
  848. +" }\n"
  849. +"}\n")
  850. print(pin_code)
  851. print(pin_add_code)
  852. else:
  853. pin_variables=""
  854. pin_code=""
  855. pin_add_code=""
  856. def EC(pin_position,pin_type):
  857. global pin_variables,pin_code,pin_add_code
  858. if pin_type =="EC":
  859. print("EC ok")
  860. pin_variables=("uint8_t data[4] ={0,0,0,0};\n"
  861. +"float "+pin_position+"_"+pin_type+" =0;\n")
  862. pin_code=(" HAL_UART_Receive_IT(&huart2, (uint8_t *)data,sizeof(data));\n")
  863. pin_add_code=("void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)\n"
  864. +"{\n"
  865. +" if (huart->Instance == USART2)\n"
  866. +" {\n"
  867. +" if (data[0]==0x30 && data[1]==0x2E)\n"
  868. +" {\n"
  869. +" HAL_UART_Transmit(&huart4, (uint8_t *)data,sizeof(data),50);\n"
  870. +" }\n"
  871. +" }\n"
  872. +"}\n")
  873. print(pin_variables)
  874. print(pin_code)
  875. print(pin_add_code)
  876. else:
  877. pin_variables=""
  878. pin_code=""
  879. pin_add_code=""
  880. def SHT11(pin_position,pin_type):
  881. global pin_variables,pin_code,pin_add_code
  882. global sensor_code
  883. if pin_position=="M14":
  884. pin_group="GPIOB"
  885. pin1="GPIO_PIN_0"
  886. pin2="GPIO_PIN_1"
  887. if pin_position=="M17":
  888. pin_group="GPIOC"
  889. pin1="GPIO_PIN_6"
  890. pin2="GPIO_PIN_7"
  891. if pin_type =="SHT11":
  892. print("SHT11 ok")
  893. pin_variables=("uint8_t cmd[7]={0xFF,0x00,0x00,0x00,0x00,0x00,0x0D};\n"
  894. +"uint16_t i,val,value_H,value_L,Cvalue,Hvalue;\n"
  895. +"int error;\n"
  896. +"float C1=-2.0468;\n"
  897. +"float C2=0.0367;\n"
  898. +"float C3=-0.0000015955;\n"
  899. +"float RH_Lin;\n"
  900. +"float RH_Ture;\n"
  901. +"float d1=-39.6;\n"
  902. +"float d2=0.01;\n"
  903. +"float T1=0.01;\n"
  904. +"float T2=0.00008;\n"
  905. +"float temp_C=0;\n"
  906. +"int temp;\n"
  907. +"int RH;\n"
  908. +"float "+pin_position+"_"+pin_type+" =0;\n")
  909. sensor_code=("void SHT10_TransStart(void);\n"
  910. +"void SHT10_WriteByte(void);\n"
  911. +"void SHT10_WriteByte2(void);\n"
  912. +"void SHT10_ReadByte(void);\n"
  913. +"void SHT10_Calculate(void);\n"
  914. +"void MX_GPIO_Input1(unsigned long pin);\n")
  915. pin_code=(" Cvalue=0;\n"
  916. +" Hvalue=0;\n"
  917. +" value_H=0;\n"
  918. +" value_L=0;\n"
  919. +" SHT10_TransStart();\n"
  920. +" SHT10_WriteByte();\n"
  921. +" MX_GPIO_Input1("+pin1+");\n"
  922. +" HAL_Delay(250);\n"
  923. +" if (HAL_GPIO_ReadPin("+pin_group+","+pin1+")==0)\n"
  924. +" {\n"
  925. +" SHT10_ReadByte();\n"
  926. +" value_H=val;\n"
  927. +" SHT10_ReadByte();\n"
  928. +" value_L=val;\n"
  929. +" Cvalue = (value_H<< 8 | value_L);\n"
  930. +" }\n"
  931. +" SHT10_TransStart();\n"
  932. +" SHT10_WriteByte2();\n"
  933. +" MX_GPIO_Input1("+pin1+");\n"
  934. +" HAL_Delay(250);\n"
  935. +" if (HAL_GPIO_ReadPin("+pin_group+","+pin1+")==0)\n"
  936. +" {\n"
  937. +" SHT10_ReadByte();\n"
  938. +" value_H=val;\n"
  939. +" SHT10_ReadByte();\n"
  940. +" value_L=val;\n"
  941. +" Hvalue = (value_H<< 8 | value_L);\n"
  942. +" }\n"
  943. +" SHT10_Calculate();\n")
  944. pin_add_code=(" void SHT10_TransStart(void)\n"
  945. +"{\n"
  946. +" MX_GPIO_Init();\n"
  947. +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_SET);\n"
  948. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
  949. +" HAL_Delay(10);\n"
  950. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
  951. +" HAL_Delay(10);\n"
  952. +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_RESET);\n"
  953. +" HAL_Delay(10);\n"
  954. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
  955. +" HAL_Delay(10);\n"
  956. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
  957. +" HAL_Delay(10);\n"
  958. +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_SET);\n"
  959. +" HAL_Delay(10);\n"
  960. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
  961. +" HAL_Delay(10);\n"
  962. +"}\n"
  963. +" void SHT10_WriteByte(void)\n"
  964. +"{\n"
  965. +" MX_GPIO_Init();\n"
  966. +" for (i=0x80;i>0;i/=2)\n"
  967. +" {\n"
  968. +" if (i & 0x03)\n"
  969. +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_SET);\n"
  970. +" else\n"
  971. +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_RESET);\n"
  972. +" HAL_Delay(10);\n"
  973. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
  974. +" HAL_Delay(10);\n"
  975. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
  976. +" HAL_Delay(10);\n"
  977. +" }\n"
  978. +" MX_GPIO_Input1("+pin1+");\n"
  979. +" HAL_Delay(10);\n"
  980. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
  981. +" HAL_Delay(10);\n"
  982. +" error=HAL_GPIO_ReadPin("+pin_group+","+pin1+");\n"
  983. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
  984. +" HAL_Delay(10);\n"
  985. +"}\n"
  986. +" void SHT10_WriteByte2(void)\n"
  987. +"{\n"
  988. +" MX_GPIO_Init();\n"
  989. +" for (i=0x80;i>0;i/=2)\n"
  990. +" {\n"
  991. +" if (i & 0x05)\n"
  992. +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_SET);\n"
  993. +" else\n"
  994. +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_RESET);\n"
  995. +" HAL_Delay(10);\n"
  996. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
  997. +" HAL_Delay(10);\n"
  998. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
  999. +" HAL_Delay(10);\n"
  1000. +" }\n"
  1001. +" MX_GPIO_Input1("+pin1+");\n"
  1002. +" HAL_Delay(10);\n"
  1003. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
  1004. +" HAL_Delay(10);\n"
  1005. +" error=HAL_GPIO_ReadPin("+pin_group+", "+pin1+");\n"
  1006. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
  1007. +" HAL_Delay(10);\n"
  1008. +"}\n"
  1009. +" void SHT10_ReadByte(void)\n"
  1010. +"{\n"
  1011. +" val=0;\n"
  1012. +" MX_GPIO_Input1("+pin1+");\n"
  1013. +" for (i=0x80;i>0;i/=2)\n"
  1014. +" {\n"
  1015. +" HAL_Delay(10);\n"
  1016. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
  1017. +" HAL_Delay(10);\n"
  1018. +" if(HAL_GPIO_ReadPin("+pin_group+","+pin1+"))\n"
  1019. +" val=( val | i );\n"
  1020. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
  1021. +" }\n"
  1022. +" MX_GPIO_Init();\n"
  1023. +" if (1)\n"
  1024. +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_RESET);\n"
  1025. +" else\n"
  1026. +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_SET);\n"
  1027. +" HAL_Delay(10);\n"
  1028. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
  1029. +" HAL_Delay(10);\n"
  1030. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
  1031. +" HAL_Delay(10);\n"
  1032. +"}\n"
  1033. +" void SHT10_Calculate(void)\n"
  1034. +"{\n"
  1035. +" temp_C=d1+d2*Cvalue;\n"
  1036. +" RH_Lin = C1+C2*Hvalue+C3*Hvalue*Hvalue;\n"
  1037. +" RH_Ture= (temp_C-25)*(T1+T2*Hvalue)+RH_Lin;\n"
  1038. +" if (RH_Ture>100)\n"
  1039. +" RH_Ture= 100;\n"
  1040. +" if (RH_Ture<0.1)\n"
  1041. +" RH_Ture=0.1;\n"
  1042. +" if (temp_C<0)\n"
  1043. +" {\n"
  1044. +" cmd[1]=1;\n"
  1045. +" cmd[2]=-1*temp_C;\n"
  1046. +" temp=(-10*temp_C);\n"
  1047. +" cmd[3]=temp%10;\n"
  1048. +" cmd[4]=RH_Ture;\n"
  1049. +" RH=RH_Ture*10;\n"
  1050. +" cmd[5]=RH%10;\n"
  1051. +" }\n"
  1052. +" else\n"
  1053. +" {\n"
  1054. +" cmd[1]=0;\n"
  1055. +" cmd[2]=temp_C;\n"
  1056. +" temp=(10*temp_C);\n"
  1057. +" cmd[3]=temp%10;\n"
  1058. +" cmd[4]=RH_Ture;\n"
  1059. +" RH=RH_Ture*10;\n"
  1060. +" cmd[5]=RH%10;\n"
  1061. +" }\n"
  1062. +"}\n")
  1063. else:
  1064. pin_variables=""
  1065. pin_code=""
  1066. pin_add_code=""
  1067. sensor_code=""
  1068. def DS18B20(pin_position,pin_type):
  1069. global pin_variables,pin_code,pin_add_code
  1070. global sensor_code
  1071. if pin_position=="M14":
  1072. pin1="GPIO_PIN_0"
  1073. if pin_position=="M16":
  1074. pin1="GPIO_PIN_7"
  1075. if pin_type =="DS18B20":
  1076. print("DS18B20 ok")
  1077. pin_variables=("#define CLR_DS18B20() HAL_GPIO_WritePin (GPIOB, "+pin1+",GPIO_PIN_RESET )\n"
  1078. +"#define SET_DS18B20() HAL_GPIO_WritePin (GPIOB, "+pin1+",GPIO_PIN_SET )\n"
  1079. +"#define DS18B20_DQ_IN HAL_GPIO_ReadPin(GPIOB, "+pin1+")\n"
  1080. +"int16_t temp;\n"
  1081. +"int error;\n"
  1082. +"float "+pin_position+"_"+pin_type+" =0;\n")
  1083. sensor_code=("uint8_t DS18B20_Init(void);\n"
  1084. +"short DS18B20_Get_Temp(void);\n"
  1085. +"void DS18B20_Start(void);\n"
  1086. +"void DS18B20_Write_Byte(uint8_t dat);\n"
  1087. +"uint8_t DS18B20_Read_Byte(void);\n"
  1088. +"uint8_t DS18B20_Read_Bit(void);\n"
  1089. +"uint8_t DS18B20_Check(void);\n"
  1090. +"void DS18B20_Rst(void);\n")
  1091. pin_code=(" temp=DS18B20_Get_Temp();\n")
  1092. pin_add_code=(" void delay_us(uint32_t value)\n"
  1093. +"{\n"
  1094. +" uint32_t i;\n"
  1095. +" i = value * 3;\n"
  1096. +" while(i--);\n"
  1097. +"}\n"
  1098. +" void DS18B20_Rst(void)\n"
  1099. +"{\n"
  1100. +" CLR_DS18B20();\n"
  1101. +" delay_us(750);\n"
  1102. +" SET_DS18B20();\n"
  1103. +" delay_us(15);\n"
  1104. +"}\n"
  1105. +" uint8_t DS18B20_Check(void)\n"
  1106. +"{\n"
  1107. +" uint8_t retry=0;\n"
  1108. +" while (DS18B20_DQ_IN&&retry<200)\n"
  1109. +" {\n"
  1110. +" retry++;\n"
  1111. +" delay_us(1);\n"
  1112. +" }\n"
  1113. +" if(retry>=200)return 1;\n"
  1114. +" else retry=0;\n"
  1115. +" while (!DS18B20_DQ_IN&&retry<240)\n"
  1116. +" {\n"
  1117. +" retry++;\n"
  1118. +" delay_us(1);\n"
  1119. +" }\n"
  1120. +" if(retry>=240)return 1;\n"
  1121. +" return 0;\n"
  1122. +"}\n"
  1123. +" uint8_t DS18B20_Read_Bit(void)\n"
  1124. +"{\n"
  1125. +" uint8_t data;\n"
  1126. +" CLR_DS18B20();\n"
  1127. +" delay_us(2);\n"
  1128. +" SET_DS18B20();\n"
  1129. +" delay_us(12);\n"
  1130. +" if(DS18B20_DQ_IN)data=1;\n"
  1131. +" else data=0;\n"
  1132. +" delay_us(50);\n"
  1133. +" return data;\n"
  1134. +"}\n"
  1135. +" uint8_t DS18B20_Read_Byte(void)\n"
  1136. +"{\n"
  1137. +" uint8_t i,j,dat;\n"
  1138. +" dat=0;\n"
  1139. +" for (i=1;i<=8;i++)\n"
  1140. +" {\n"
  1141. +" j=DS18B20_Read_Bit();\n"
  1142. +" dat=(j<<7)|(dat>>1);\n"
  1143. +" }\n"
  1144. +" return dat;\n"
  1145. +"}\n"
  1146. +" void DS18B20_Write_Byte(uint8_t dat)\n"
  1147. +"{\n"
  1148. +" uint8_t j;\n"
  1149. +" uint8_t testb;\n"
  1150. +" for (j=1;j<=8;j++)\n"
  1151. +" {\n"
  1152. +" testb=dat&0x01;\n"
  1153. +" dat=dat>>1;\n"
  1154. +" if (testb)\n"
  1155. +" {\n"
  1156. +" CLR_DS18B20();\n"
  1157. +" delay_us(2);\n"
  1158. +" SET_DS18B20();\n"
  1159. +" delay_us(60);\n"
  1160. +" }\n"
  1161. +" else\n"
  1162. +" {\n"
  1163. +" CLR_DS18B20();\n"
  1164. +" delay_us(60);\n"
  1165. +" SET_DS18B20();\n"
  1166. +" delay_us(2);\n"
  1167. +" }\n"
  1168. +" }\n"
  1169. +"}\n"
  1170. +" uint8_t DS18B20_Init(void)\n"
  1171. +"{\n"
  1172. +" SET_DS18B20();\n"
  1173. +" DS18B20_Rst();\n"
  1174. +" return DS18B20_Check();\n"
  1175. +"}\n"
  1176. +" void DS18B20_Start(void)\n"
  1177. +"{\n"
  1178. +" DS18B20_Rst();\n"
  1179. +" DS18B20_Check();\n"
  1180. +" DS18B20_Write_Byte(0xcc);\n"
  1181. +" DS18B20_Write_Byte(0x44);\n"
  1182. +"}\n"
  1183. +" short DS18B20_Get_Temp(void)\n"
  1184. +"{\n"
  1185. +" uint8_t temp;\n"
  1186. +" uint8_t TL,TH;\n"
  1187. +" short tem;\n"
  1188. +" DS18B20_Start();\n"
  1189. +" DS18B20_Rst();\n"
  1190. +" DS18B20_Check();\n"
  1191. +" DS18B20_Write_Byte(0xcc);\n"
  1192. +" DS18B20_Write_Byte(0xbe);\n"
  1193. +" TL=DS18B20_Read_Byte();\n"
  1194. +" TH=DS18B20_Read_Byte();\n"
  1195. +" if(TH>7)\n"
  1196. +" {\n"
  1197. +" TH=~TH;\n"
  1198. +" TL=~TL;\n"
  1199. +" temp=0;\n"
  1200. +" }\n"
  1201. +" else temp=1;\n"
  1202. +" tem=TH;\n"
  1203. +" tem<<=8;\n"
  1204. +" tem+=TL;\n"
  1205. +" tem=(float)tem*0.625f;\n"
  1206. +" if(temp)return tem;\n"
  1207. +" else return -tem;\n"
  1208. +"}\n")
  1209. else:
  1210. pin_variables=""
  1211. pin_code=""
  1212. pin_add_code=""
  1213. sensor_code=""
  1214. def BMP280(pin_position,pin_type):
  1215. global pin_variables,pin_code,pin_add_code,init_code
  1216. global sensor_code
  1217. if pin_type =="BMP280":
  1218. print("BMP280 ok")
  1219. pin_variables=("uint8_t cmd[7]={0xFF,0x00,0x00,0x00,0x00,0x00,0x0D};\n"
  1220. +"HAL_StatusTypeDef Status;\n"
  1221. +"#define ADDR_AT24C04_WRITE_FIRST_16_PAGES 0xEC\n"
  1222. +"#define ADDR_AT24C04_WRITE_FIRST_16_PAGES 0xEC\n"
  1223. +"#define ADDR_AT24C04_READ 0xED\n"
  1224. +"#define AT24C04_TIMEOUT 0xED\n"
  1225. +"#define AT24C04_PAGE_SIZE 16\n"
  1226. +"#define BUFFER_SIZE 1\n"
  1227. +"uint16_t dig_T1;\n"
  1228. +"uint16_t dig_T2;\n"
  1229. +"uint16_t dig_T3;\n"
  1230. +"uint16_t dig_P1;\n"
  1231. +"uint16_t dig_P2;\n"
  1232. +"uint16_t dig_P3;\n"
  1233. +"uint16_t dig_P4;\n"
  1234. +"uint16_t dig_P5;\n"
  1235. +"uint16_t dig_P6;\n"
  1236. +"uint16_t dig_P7;\n"
  1237. +"uint16_t dig_P8;\n"
  1238. +"uint16_t dig_P9;\n"
  1239. +"uint32_t adc_P=0;\n"
  1240. +"uint32_t adc_T=0;\n"
  1241. +"uint8_t WriteBuffer[BUFFER_SIZE]={0xb6};\n"
  1242. +"uint8_t WriteBuffer1[BUFFER_SIZE]={0xff};\n"
  1243. +"uint8_t WriteBuffer2[BUFFER_SIZE]={0x00};\n"
  1244. +"uint8_t ReadBuffer[BUFFER_SIZE];\n"
  1245. +"int RH;\n"
  1246. +"float "+pin_position+"_"+pin_type+" =0;\n")
  1247. sensor_code=("HAL_StatusTypeDef AT24C04_Write(I2C_HandleTypeDef *hi2c,uint16_t MemAddress,uint8_t *pData);\n"
  1248. +"HAL_StatusTypeDef AT24C04_Read(I2C_HandleTypeDef *hi2c,uint16_t MemAddress,uint8_t *pData);\n"
  1249. +"long bmp280_T_MultipleReadThree(void);\n"
  1250. +"long bmp280_P_MultipleReadThree(void);\n"
  1251. +"short bmp280_MultipleReadTwo(uint16_t addr);\n")
  1252. init_code=(" AT24C04_Write(&hi2c1,0xe0,WriteBuffer);\n"
  1253. +" AT24C04_Write(&hi2c1,0xf4,WriteBuffer1);\n"
  1254. +" AT24C04_Write(&hi2c1,0xf5,WriteBuffer2);\n"
  1255. +" dig_T1 = bmp280_MultipleReadTwo(0x88);\n"
  1256. +" dig_T2 = bmp280_MultipleReadTwo(0x8A);\n"
  1257. +" dig_T3 = bmp280_MultipleReadTwo(0x8C);\n"
  1258. +" dig_P1 = bmp280_MultipleReadTwo(0x8E);\n"
  1259. +" dig_P2 = bmp280_MultipleReadTwo(0x90);\n"
  1260. +" dig_P3 = bmp280_MultipleReadTwo(0x92);\n"
  1261. +" dig_P4 = bmp280_MultipleReadTwo(0x94);\n"
  1262. +" dig_P5 = bmp280_MultipleReadTwo(0x96);\n"
  1263. +" dig_P6 = bmp280_MultipleReadTwo(0x98);\n"
  1264. +" dig_P7 = bmp280_MultipleReadTwo(0x9A);\n"
  1265. +" dig_P8 = bmp280_MultipleReadTwo(0x9C);\n"
  1266. +" dig_P9 = bmp280_MultipleReadTwo(0x9E);\n")
  1267. pin_code=(" adc_T=bmp280_T_MultipleReadThree();\n"
  1268. +" adc_P=bmp280_P_MultipleReadThree();\n"
  1269. +" double var1, var2,t_fine;\n"
  1270. +" var1 = (((double) adc_T) / 16384.0 - ((double) dig_T1) / 1024.0)* ((double) dig_T2);\n"
  1271. +" var2 = ((((double) adc_T) / 131072.0 - ((double) dig_T1) / 8192.0)* (((double) adc_T) / 131072.0 - ((double) dig_T1) / 8192.0))* ((double) dig_T3);\n"
  1272. +" t_fine = (int32_t) (var1 + var2);\n"
  1273. +" double temperature = (var1 + var2) / 5120.0;\n"
  1274. +" double pressure;\n"
  1275. +" var1 = (t_fine / 2.0) - 64000.0;\n"
  1276. +" var2 = var1 * var1 * ((double) dig_P6) / 32768.0;\n"
  1277. +" var2 = var2 + var1 * ((double) dig_P5) * 2.0;\n"
  1278. +" var2 = (var2 / 4.0) + (((double) dig_P4) * 65536.0);\n"
  1279. +" var1 = (((double) dig_P3) * var1 * var1 / 524288.0+ ((double) dig_P2) * var1) / 524288.0;\n"
  1280. +" var1 = (1.0 + var1 / 32768.0) * ((double) dig_P1);\n"
  1281. +" if (var1 == 0.0)\n"
  1282. +" {\n"
  1283. +" var1 = 0;\n"
  1284. +" }\n"
  1285. +" pressure = 1048576.0 - (double) adc_P;\n"
  1286. +" pressure = (pressure - (var2 / 4096.0)) * 6250.0 / var1;\n"
  1287. +" var1 = ((double) dig_P9) * pressure * pressure / 2147483648.0;"
  1288. +" var2 = pressure * ((double) dig_P8) / 32768.0;\n"
  1289. +" pressure = pressure + (var1 + var2 + ((double) dig_P7)) / 16.0;\n"
  1290. +" cmd[1]=pressure/10000; \n"
  1291. +" int pa =pressure;\n"
  1292. +" cmd[2]=(pa%10000)/100;\n"
  1293. +" cmd[3]=(pa%10000)%100;\n"
  1294. +" HAL_UART_Transmit(&huart4, (uint8_t *)cmd, sizeof(cmd),1);\n")
  1295. pin_add_code=("HAL_StatusTypeDef AT24C04_Write(I2C_HandleTypeDef *hi2c,uint16_t MemAddress,uint8_t *pData)\n"
  1296. +"{\n"
  1297. +" Status = HAL_I2C_Mem_Write(&hi2c1, ADDR_AT24C04_WRITE_FIRST_16_PAGES, MemAddress, I2C_MEMADD_SIZE_8BIT, pData, AT24C04_PAGE_SIZE, AT24C04_TIMEOUT);\n"
  1298. +" return Status;\n"
  1299. +"}\n"
  1300. +"HAL_StatusTypeDef AT24C04_Read(I2C_HandleTypeDef *hi2c,uint16_t MemAddress,uint8_t *pData)\n"
  1301. +"{\n"
  1302. +" Status = HAL_I2C_Mem_Read(&hi2c1, ADDR_AT24C04_READ, MemAddress, I2C_MEMADD_SIZE_8BIT, pData, BUFFER_SIZE, AT24C04_TIMEOUT);\n"
  1303. +" return Status;\n"
  1304. +"}\n"
  1305. +" long bmp280_T_MultipleReadThree()\n"
  1306. +"{\n"
  1307. +" uint8_t msb, lsb, xlsb;\n"
  1308. +" int32_t temp = 0;\n"
  1309. +" AT24C04_Read(&hi2c1,0xfa,ReadBuffer);\n"
  1310. +" msb=ReadBuffer[0];\n"
  1311. +" AT24C04_Read(&hi2c1,0xfb,ReadBuffer);\n"
  1312. +" lsb=ReadBuffer[0];\n"
  1313. +" AT24C04_Read(&hi2c1,0xfc,ReadBuffer);\n"
  1314. +" xlsb=ReadBuffer[0];\n"
  1315. +" temp = ((msb << 12)|(lsb << 4)|(xlsb >> 4));\n"
  1316. +" return temp;\n"
  1317. +"}\n"
  1318. +"long bmp280_P_MultipleReadThree()\n"
  1319. +"{\n"
  1320. +" uint8_t msb, lsb, xlsb;\n"
  1321. +" int32_t pressure = 0;\n"
  1322. +" AT24C04_Read(&hi2c1,0xf7,ReadBuffer);\n"
  1323. +" msb=ReadBuffer[0];\n"
  1324. +" AT24C04_Read(&hi2c1,0xf8,ReadBuffer);\n"
  1325. +" lsb=ReadBuffer[0];\n"
  1326. +" AT24C04_Read(&hi2c1,0xf9,ReadBuffer);\n"
  1327. +" xlsb=ReadBuffer[0];\n"
  1328. +" pressure = ((msb << 12)|(lsb << 4)|(xlsb >> 4));\n"
  1329. +" return pressure;\n"
  1330. +"}\n"
  1331. +" short bmp280_MultipleReadTwo(uint16_t addr )\n"
  1332. +"{\n"
  1333. +" uint8_t msb, lsb;\n"
  1334. +" uint16_t temp = 0;\n"
  1335. +" AT24C04_Read(&hi2c1,addr,ReadBuffer);\n"
  1336. +" lsb = ReadBuffer[0];\n"
  1337. +" AT24C04_Read(&hi2c1,addr+1,ReadBuffer);\n"
  1338. +" msb = ReadBuffer[0];\n"
  1339. +" temp = msb << 8|lsb;\n"
  1340. +" return temp;\n"
  1341. +"}\n")
  1342. else:
  1343. pin_variables=""
  1344. pin_code=""
  1345. pin_add_code=""
  1346. init_code=""
  1347. sensor_code=""
  1348. def motor(pin_position,pin_type):
  1349. global act_code,init_code
  1350. global sensor_code
  1351. if pin_type =="Motor":
  1352. print("motor ok")
  1353. sensor_code=("void user_pwm_setvalue(uint16_t value);\n"
  1354. +"void user_pwm_setvalue2(uint16_t value);\n")
  1355. act_code=("void user_pwm_setvalue(uint16_t value)\n"
  1356. +"{\n"
  1357. +" TIM_OC_InitTypeDef sConfigOC;\n"
  1358. +" sConfigOC.OCMode = TIM_OCMODE_PWM1;\n"
  1359. +" sConfigOC.Pulse = value;\n"
  1360. +" sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;\n"
  1361. +" sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;\n"
  1362. +" HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1);\n"
  1363. +" HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);\n"
  1364. +"}\n")
  1365. init_code=(" MX_TIM2_Init();\n")
  1366. else:
  1367. act_code=""
  1368. init_code=""
  1369. sensor_code=""
  1370. def zigbee(pin_type):
  1371. global pin_variables,pin_code,init_code
  1372. if pin_type =="ON":
  1373. print("zigbee ok")
  1374. pin_variables=("uint8_t zigbeecmd1[5]={0xFE,0x00,0x01,0x00,0x01};\n"
  1375. +"uint8_t zigbeecmd2[5]={0xFE,0x00,0x02,0x00,0x02};\n"
  1376. +"uint8_t zigbeestatu[20];\n"
  1377. +"uint8_t zigbeestatu1[5];\n"
  1378. +'uint8_t zigbeecon[7]="connect";\n'
  1379. +'uint8_t zigbeenotcon[11]="not connect";\n'
  1380. +'uint8_t zigbeechang[14]="change is down";\n')
  1381. init_code=(" HAL_UART_Transmit(&huart2, (uint8_t *)zigbeecmd2, sizeof(zigbeecmd2), 10);\n"
  1382. +" HAL_UART_Receive(&huart2, (uint8_t *)zigbeestatu,sizeof(zigbeestatu),2000);\n"
  1383. +" HAL_UART_Transmit(&huart4, (uint8_t *)zigbeestatu, sizeof(zigbeestatu),10);\n"
  1384. +" HAL_UART_Transmit(&huart2, (uint8_t *)zigbeecmd1, sizeof(zigbeecmd1), 10);\n"
  1385. +" HAL_UART_Receive(&huart2, (uint8_t *)zigbeestatu,sizeof(zigbeestatu),2000);\n"
  1386. +" HAL_UART_Transmit(&huart4, (uint8_t *)zigbeestatu, sizeof(zigbeestatu),10);\n"
  1387. +" if (zigbeestatu[18]== 0x01)\n"
  1388. +" {\n"
  1389. +" HAL_UART_Transmit(&huart4, (uint8_t *)zigbeecon, sizeof(zigbeecon),10);\n"
  1390. +" }\n"
  1391. +" else if(zigbeestatu[18]== 0x05 || zigbeestatu[18]== 0x00)\n"
  1392. +" {\n"
  1393. +" HAL_UART_Transmit(&huart4, (uint8_t *)zigbeenotcon, sizeof(zigbeenotcon),10);\n"
  1394. +" }\n")
  1395. else:
  1396. pin_variables=""
  1397. pin_code=""
  1398. init_code=""
  1399. # 控制板燒錄:生成 main.c
  1400. @main.route('/creat_hex')
  1401. def creat_hex():
  1402. info = request.args.to_dict()
  1403. print("info: ", info)
  1404. # info = {'cond_z1_1': 'if', 'cond_tank1_1': 'D1', 'cond_a1_1': 'tank_soil_Temp', 'cond_b1_1': 'Equal', 'cond_c1_1': '11', 'cond_d1_2': 'and', 'cond_a1_2': 'tank_soil_Humidity', 'cond_b1_2': 'Equal', 'cond_c1_2': '12', 'cond_d1_3': 'and', 'cond_a1_3': 'tank_soil_EC', 'cond_b1_3': 'Equal', 'cond_c1_3': '13', 'do_obj1_1': 'tank_heater1_status', 'do_act1_1': 'on', 'do_obj1_2': 'tank_heater2_status', 'do_act1_2': 'on'}
  1405. # 'mainLength': '1', 'addLength': '0', 'comLength': '22', '
  1406. z_range = int(info['mainLength']) + 1
  1407. x_range = int(info['addLength']) + 1
  1408. y_range = int(info['comLength']) + 1
  1409. tank_num_data = info['tank_num']
  1410. # print("tank_num_data: ", tank_num_data)
  1411. cond_main_all_list = []
  1412. for z in range(1, z_range):
  1413. # 初始
  1414. cond_main_all_dict = {}
  1415. cond_add_list = [] # 附加條件 List
  1416. cond_com_list = [] # 物件動作 List
  1417. # cond_main_dict_all = {}
  1418. # cond_add_dict_all = {}
  1419. # cond_com_dict_all = {}
  1420. # print(z)
  1421. # 總條件
  1422. try:
  1423. cond_main_all_dict['cond_main'] = info['cond_main' + str(z)]
  1424. except(KeyError):
  1425. pass
  1426. # print("cond_main_dict: ", cond_main_dict)
  1427. # 附加條件
  1428. for x in range(1, x_range):
  1429. try:
  1430. cond_add_list.append(info['cond_add' + str(z) + '_' + str(x)])
  1431. except(KeyError):
  1432. pass
  1433. # print("cond_add_list: ", cond_add_list)
  1434. cond_main_all_dict['cond_add'] = cond_add_list
  1435. # print("cond_main_dict: ", cond_main_dict)
  1436. # 物件動作
  1437. for y in range(1, y_range):
  1438. try:
  1439. cond_com_list.append(info['cond_com' + str(z) + '_' + str(y)])
  1440. except(KeyError):
  1441. pass
  1442. # print("cond_com_list: ", cond_com_list)
  1443. cond_main_all_dict['cond_com'] = cond_com_list
  1444. # print("cond_main_dict: ", cond_main_dict)
  1445. if cond_com_list != []:
  1446. cond_main_all_list.append(cond_main_all_dict)
  1447. # cond_main_all_list.append(cond_add_dict_all)
  1448. # cond_main_all_list.append(cond_com_dict_all)
  1449. print("cond_main_all_list: ", cond_main_all_list)
  1450. # cond_main_all_list: [{'cond_main': 'if D1 tank_UltraSonic >= 30', 'cond_add': ['and tank_PA <= 1', 'and tank_soil_Temp <= 30'], 'cond_com': ['tank_vacuum_status on', 'tank_motor_status 15']}]
  1451. dry_block_sehedule = {'command':'Dry_OTA', 'tank_num':tank_num_data, 'cond':cond_main_all_list}
  1452. msg = dry_block_sehedule
  1453. # ===== 阿超 CTO.py 程式碼 start ========================================================================================
  1454. # msg = request.args.to_dict()
  1455. print("/creat_hex/<msg> msg: ", msg)
  1456. CURRENT_PATH = os.path.dirname(__file__)
  1457. print("CURRENT_PATH: ", CURRENT_PATH)
  1458. f = open(CURRENT_PATH + "//CTO20220622//Src//main.c", mode='w')
  1459. f.write("/* USER CODE BEGIN Header */\n"
  1460. +"/**\n"
  1461. +" ******************************************************************************\n"
  1462. +" * @file : main.c\n"
  1463. +" * @brief : Main program body\n"
  1464. +" * @attention\n"
  1465. +" *\n"
  1466. +" * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics.\n"
  1467. +" * All rights reserved.</center></h2>\n"
  1468. +" *\n"
  1469. +" * This software component is licensed by ST under BSD 3-Clause license,\n"
  1470. +" * the License; You may not use this file except in compliance with the\n"
  1471. +" * License. You may obtain a copy of the License at:\n"
  1472. +" * www.st.com/SLA0044\n"
  1473. +" *\n"
  1474. +" ******************************************************************************\n"
  1475. +" */\n"
  1476. +"/* USER CODE END Header */\n"
  1477. +"\n"
  1478. +"/* Includes ------------------------------------------------------------------*/\n")
  1479. # 添加標題檔
  1480. header = ('#include"main.h"\n'
  1481. +'#include "adc.h"\n'
  1482. +'#include "usart.h"\n'
  1483. +'#include "i2c.h"\n'
  1484. +'#include "tim.h"\n'
  1485. +'#include "stm32f4xx_hal.h"\n'
  1486. +'#include "gpio.h"\n')
  1487. f.write(header)
  1488. # 變數宣告說明
  1489. f.write("\n"
  1490. + "/* Private variables ---------------------------------------------------------*/\n")
  1491. f.write("\n"
  1492. + "/* Private variables ---------------------------------------------------------*/\n"
  1493. + "#define VECT_TAB_OFFSET 0x10000\n"
  1494. + "int tankstatus = 0;\n")
  1495. # 連接資料庫
  1496. #conn = sqlite3.connect('/home/pi/coffee.db')
  1497. # conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffeemanage', passwd='skyeye', database='CoffeeManage', charset='utf8')
  1498. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='Gold@53743001', database='CoffeeManage', charset='utf8')
  1499. c = conn.cursor()
  1500. print("connect success")
  1501. # 搜尋最新腳位配置時間
  1502. c.execute("SELECT *from coffee1_0_pin ORDER BY datetime ASC")
  1503. results = c.fetchall()
  1504. for row in results:
  1505. time = row[1]
  1506. c.execute("SELECT *from coffee1_0_pin where datetime='%s'"\
  1507. %(time))
  1508. results=c.fetchall()
  1509. for row in results:
  1510. for i in range (19):
  1511. row[i+26]
  1512. if(row[5]=="ON"):
  1513. print("zigbee on")
  1514. zigbee(row[5])
  1515. f.write(pin_variables)
  1516. for i in range (19):
  1517. if(i==3 or i==4 or i==6):
  1518. PH("M"+str(i+1),row[i+26])
  1519. f.write(pin_variables)
  1520. DO("M"+str(i+1),row[i+26])
  1521. f.write(pin_variables)
  1522. ORP("M"+str(i+1),row[i+26])
  1523. f.write(pin_variables)
  1524. if(i==13 or i== 16):
  1525. SHT11("M"+str(i+1),row[i+26])
  1526. f.write(pin_variables)
  1527. if(i==13 or i== 15):
  1528. DS18B20("M"+str(i+1),row[i+26])
  1529. f.write(pin_variables)
  1530. if(i==14):
  1531. BMP280("M"+str(i+1),row[i+26])
  1532. f.write(pin_variables)
  1533. if(i==5 or i==12):
  1534. SEN0189("M"+str(i+1),row[i+26])
  1535. f.write(pin_variables)
  1536. if(i==0):
  1537. SonicESMUS07("M"+str(i+1),row[i+26])
  1538. f.write(pin_variables)
  1539. if(i==7):
  1540. SOIL("M"+str(i+1),row[i+26])
  1541. f.write(pin_variables)
  1542. if(i==8 or i==11 or i==18 or i==10):
  1543. WATERLEVEL("M"+str(i+1),row[i+26])
  1544. f.write(pin_variables)
  1545. motorfeedback("M"+str(i+1),row[i+26])
  1546. f.write(pin_variables)
  1547. butterflyvalvefeedback("M"+str(i+1),row[i+26])
  1548. f.write(pin_variables)
  1549. if(i==15):
  1550. EC("M"+str(i+1),row[i+26])
  1551. f.write(pin_variables)
  1552. #感測器和致動器副函式宣告----------------------------------------------------------------
  1553. f.write("/* USER CODE BEGIN PV */\n"
  1554. +"typedef void (*pFunction)(void);\n"
  1555. +"/* USER CODE END PV */\n"
  1556. +"/* Private function prototypes -----------------------------------------------*/\n"
  1557. +"void SystemClock_Config(void);\n"
  1558. +"void MX_ADC1_Init1(char pin);\n"
  1559. +"void sensor(void);\n")
  1560. #感測器和致動器副函式宣告----------------------------------------------------------------
  1561. #連接資料庫
  1562. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='Gold@53743001', database='CoffeeManage', charset='utf8')
  1563. c = conn.cursor()
  1564. print ("connect success")
  1565. #搜尋最新腳位配置時間
  1566. c.execute("SELECT *from coffee1_0_pin ORDER BY datetime ASC")
  1567. results=c.fetchall()
  1568. for row in results:
  1569. time = row[1]
  1570. #腳位配置加入
  1571. c.execute("SELECT *from coffee1_0_pin where datetime='%s'"\
  1572. %(time))
  1573. results=c.fetchall()
  1574. for row in results:
  1575. for i in range (19):
  1576. row[i+26]
  1577. for i in range (19):
  1578. if(i==13 or i== 16):
  1579. SHT11("M"+str(i+1),row[i+26])
  1580. f.write(sensor_code)
  1581. if(i==13 or i== 15):
  1582. DS18B20("M"+str(i+1),row[i+26])
  1583. f.write(sensor_code)
  1584. if(i==14):
  1585. BMP280("M"+str(i+1),row[i+26])
  1586. f.write(sensor_code)
  1587. if(i==9):
  1588. motor("M"+str(i+1),row[i+26])
  1589. f.write(sensor_code)
  1590. f.write("/* USER CODE BEGIN PFP */\n"
  1591. +"/* USER CODE END PFP */\n"
  1592. +"/* Private user code ---------------------------------------------------------*/\n"
  1593. +"/* USER CODE BEGIN 0 */\n"
  1594. +"/* USER CODE END 0 */\n"
  1595. +"/**\n"
  1596. +"* @brief The application entry point.\n"
  1597. +"* @retval int\n"
  1598. +"*/\n")
  1599. #主程式撰寫--------------------------------------------------------------------------------
  1600. #main宣告
  1601. f.write("int main(void)\n"
  1602. +"{\n"
  1603. +" SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET;\n")
  1604. #致能週邊---------------------------------------------------------------------------------------
  1605. enable=(" HAL_Init();\n"
  1606. +" SystemClock_Config();\n"
  1607. +" MX_GPIO_Init();\n"
  1608. +" MX_USART2_UART_Init();\n"
  1609. +" MX_UART4_Init();\n"
  1610. +" MX_USART1_UART_Init();\n")
  1611. f.write(enable)
  1612. #連接資料庫
  1613. # conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffeemanage', passwd='skyeye', database='CoffeeManage', charset='utf8')
  1614. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='Gold@53743001', database='CoffeeManage', charset='utf8')
  1615. #conn = sqlite3.connect('/home/pi/coffee.db')
  1616. c = conn.cursor()
  1617. print("connect success")
  1618. #搜尋最新腳位配置時間
  1619. c.execute("SELECT *from coffee1_0_pin ORDER BY datetime ASC")
  1620. results = c.fetchall()
  1621. for row in results:
  1622. time = row[1]
  1623. # 腳位配置加入
  1624. c.execute("SELECT *from coffee1_0_pin where datetime='%s'"
  1625. % (time))
  1626. results = c.fetchall()
  1627. for row in results:
  1628. for i in range(19):
  1629. row[i+26]
  1630. if(row[5]=="ON"):
  1631. print("zigbee on")
  1632. zigbee(row[5])
  1633. f.write(init_code)
  1634. for i in range (19):
  1635. if(i==14):
  1636. BMP280("M"+str(i+1),row[i+26])
  1637. f.write(init_code)
  1638. if(i==9):
  1639. motor("M"+str(i+1),row[i+26])
  1640. f.write(init_code)
  1641. #---------------------------------------------------------------------------------------------
  1642. code=(" while (1)\n"
  1643. +" {\n"
  1644. +" sensor();\n")
  1645. f.write(code)
  1646. #MQTT條件分析寫入--------------------------------------------------------------------------------
  1647. for i in range (len(msg['cond'])):
  1648. m=msg['cond'][i]['cond_main'].split(" ")
  1649. if(m[0]=="else" and m[1]=="if"):
  1650. m[0]=m[0]+" "+m[1]
  1651. m[1]=m[1]
  1652. m[2]=m[2]
  1653. m[3]=m[3]
  1654. m[4]=m[4]
  1655. m=""+m[0]+"("+m[1]+m[2]+m[3]
  1656. f.write(" "+m)
  1657. if(m[0] == " "):
  1658. m = ""
  1659. else:
  1660. print(len(msg['cond'][i]['cond_add']))
  1661. if(len(msg['cond'][i]['cond_add'])==0):
  1662. add=")\n"
  1663. f.write(add)
  1664. else:
  1665. for j in range (len(msg['cond'][i]['cond_add'])):
  1666. if(j==len(msg['cond'][i]['cond_add'])-1):
  1667. if(msg['cond'][i]['cond_add'][j]==" "):
  1668. add=")\n"
  1669. else:
  1670. add=" "+str(msg['cond'][i]['cond_add'][j])+")\n"
  1671. f.write(add)
  1672. else:
  1673. if(msg['cond'][i]['cond_add'][j]==" "):
  1674. add=""
  1675. else:
  1676. add=" "+str(msg['cond'][i]['cond_add'][j])
  1677. f.write(add)
  1678. f.write(" {\n")
  1679. for j in range(len(msg['cond'][i]['cond_com'])):
  1680. if(j == len(msg['cond'][i]['cond_com'])-1):
  1681. if(msg['cond'][i]['cond_com'][j] == " "):
  1682. com = "\n}\n"
  1683. else:
  1684. com = msg['cond'][i]['cond_com'][j].split("_")
  1685. comm = msg['cond'][i]['cond_com'][j].split(" ")
  1686. if(comm[0] == "sleep"):
  1687. com[0] = comm[0]
  1688. com = " "+GPIO(com[0], comm[1])+"\n }\n"
  1689. f.write(com)
  1690. else:
  1691. if(msg['cond'][i]['cond_com'][j] == " "):
  1692. com = ""
  1693. else:
  1694. com = msg['cond'][i]['cond_com'][j].split("_")
  1695. comm = msg['cond'][i]['cond_com'][j].split(" ")
  1696. if(comm[0] == "sleep"):
  1697. com[0] = comm[0]
  1698. com = " "+GPIO(com[0], comm[1])+"\n"
  1699. f.write(com)
  1700. f.write(" }\n")
  1701. f.write("}\n")
  1702. # 系統時鐘宣告
  1703. time = ("void SystemClock_Config(void)\n"
  1704. + "{\n"
  1705. + " RCC_OscInitTypeDef RCC_OscInitStruct = {0};\n"
  1706. + " RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};\n"
  1707. + " __HAL_RCC_PWR_CLK_ENABLE();\n"
  1708. + " __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);\n"
  1709. + " RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;\n"
  1710. + " RCC_OscInitStruct.HSIState = RCC_HSI_ON;\n"
  1711. + " RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;\n"
  1712. + " RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;\n"
  1713. + " RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;\n"
  1714. + " RCC_OscInitStruct.PLL.PLLM = 8;\n"
  1715. + " RCC_OscInitStruct.PLL.PLLN = 72;\n"
  1716. + " RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;\n"
  1717. + " RCC_OscInitStruct.PLL.PLLQ = 3;\n"
  1718. + " RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;\n"
  1719. + " if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)\n"
  1720. + " {\n"
  1721. + " Error_Handler();\n"
  1722. + " }\n"
  1723. + " RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK\n"
  1724. + " |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;\n"
  1725. + " RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;\n"
  1726. + " RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;\n"
  1727. + " RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;\n"
  1728. + " RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;\n"
  1729. + " if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)\n"
  1730. + " {\n"
  1731. + " Error_Handler();\n"
  1732. + " }\n"
  1733. + "}\n")
  1734. f.write(time)
  1735. #馬達和伺服馬達副函式------------------------------------------------------------------------------
  1736. add_code2=("void user_pwm_setvalue(uint16_t value)\n"
  1737. +"{\n"
  1738. +" TIM_OC_InitTypeDef sConfigOC;\n"
  1739. +" sConfigOC.OCMode = TIM_OCMODE_PWM1;\n"
  1740. +" sConfigOC.Pulse = value;\n"
  1741. +" sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;\n"
  1742. +" sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;\n"
  1743. +" HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1);\n"
  1744. +" HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);\n"
  1745. +"}\n"
  1746. +"void user_pwm_setvalue2(uint16_t value)\n"
  1747. +"{\n"
  1748. +" TIM_OC_InitTypeDef sConfigOC;\n"
  1749. +" sConfigOC.OCMode = TIM_OCMODE_PWM1;\n"
  1750. +" sConfigOC.Pulse = value;\n"
  1751. +" sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;\n"
  1752. +" sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;\n"
  1753. +" HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_2);\n"
  1754. +" HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_2);\n"
  1755. +"}\n")
  1756. f.write(add_code2)
  1757. #感測器程式-----------------------------------------------------------------------------------------------------
  1758. sensor=("void sensor(void)\n"
  1759. +"{\n")
  1760. f.write(sensor)
  1761. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='Gold@53743001', database='CoffeeManage', charset='utf8')
  1762. #conn = sqlite3.connect('/home/pi/coffee.db')
  1763. c = conn.cursor()
  1764. print ("connect success")
  1765. #搜尋最新腳位配置時間
  1766. c.execute("SELECT *from coffee1_0_pin ORDER BY datetime ASC")
  1767. results = c.fetchall()
  1768. for row in results:
  1769. time = row[1]
  1770. #腳位配置加入
  1771. c.execute("SELECT *from coffee1_0_pin where datetime='%s'"\
  1772. %(time))
  1773. results = c.fetchall()
  1774. for row in results:
  1775. for i in range (19):
  1776. row[i+26]
  1777. if(row[5]=="ON"):
  1778. print("zigbee on")
  1779. zigbee(row[5])
  1780. f.write(pin_code)
  1781. for i in range (19):
  1782. if(i==3 or i==4 or i==6):
  1783. PH("M"+str(i+1),row[i+26])
  1784. f.write(pin_code)
  1785. DO("M"+str(i+1),row[i+26])
  1786. f.write(pin_code)
  1787. ORP("M"+str(i+1),row[i+26])
  1788. f.write(pin_code)
  1789. if(i==13 or i== 16):
  1790. SHT11("M"+str(i+1),row[i+26])
  1791. f.write(pin_code)
  1792. if(i==13 or i== 15):
  1793. DS18B20("M"+str(i+1),row[i+26])
  1794. f.write(pin_code)
  1795. if(i==14):
  1796. BMP280("M"+str(i+1),row[i+26])
  1797. f.write(pin_code)
  1798. if(i==5 or i==12):
  1799. SEN0189("M"+str(i+1),row[i+26])
  1800. f.write(pin_code)
  1801. if(i==0):
  1802. SonicESMUS07("M"+str(i+1),row[i+26])
  1803. f.write(pin_code)
  1804. if(i==7):
  1805. SOIL("M"+str(i+1),row[i+26])
  1806. f.write(pin_code)
  1807. if(i==8 or i==11 or i==18 or i==10):
  1808. WATERLEVEL("M"+str(i+1),row[i+26])
  1809. f.write(pin_code)
  1810. motorfeedback("M"+str(i+1),row[i+26])
  1811. f.write(pin_code)
  1812. butterflyvalvefeedback("M"+str(i+1),row[i+26])
  1813. f.write(pin_code)
  1814. if(i==15):
  1815. EC("M"+str(i+1),row[i+26])
  1816. f.write(pin_code)
  1817. sensor=(" HAL_Delay(10000);\n"
  1818. +"}\n")
  1819. f.write(sensor)
  1820. #加入感測器副函式程式碼-------------------------------------------------------------------------------
  1821. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='Gold@53743001', database='CoffeeManage', charset='utf8')
  1822. c = conn.cursor()
  1823. print ("connect success")
  1824. #搜尋最新腳位配置時間
  1825. c.execute("SELECT *from coffee1_0_pin ORDER BY datetime ASC")
  1826. results = c.fetchall()
  1827. for row in results:
  1828. time = row[1]
  1829. #腳位配置加入
  1830. c.execute("SELECT *from coffee1_0_pin where datetime='%s'"\
  1831. %(time))
  1832. results = c.fetchall()
  1833. for row in results:
  1834. for i in range (19):
  1835. row[i+26]
  1836. for i in range (19):
  1837. if(i==13 or i== 16):
  1838. SHT11("M"+str(i+1),row[i+26])
  1839. f.write(pin_add_code)
  1840. if(i==13 or i== 15):
  1841. DS18B20("M"+str(i+1),row[i+26])
  1842. f.write(pin_add_code)
  1843. if(i==14):
  1844. BMP280("M"+str(i+1),row[i+26])
  1845. f.write(pin_add_code)
  1846. if(i==0):
  1847. SonicESMUS07("M"+str(i+1),row[i+26])
  1848. f.write(pin_add_code)
  1849. if(i==7):
  1850. SOIL("M"+str(i+1),row[i+26])
  1851. f.write(pin_add_code)
  1852. if(i==15):
  1853. EC("M"+str(i+1),row[i+26])
  1854. f.write(pin_add_code)
  1855. #ADC程式宣告----------------------------------------------------------------------------------
  1856. gpio=("void MX_ADC1_Init1(char pin)\n"
  1857. +"{\n"
  1858. +" ADC_ChannelConfTypeDef sConfig = {0};\n"
  1859. +" hadc1.Instance = ADC1;\n"
  1860. +" hadc1.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;\n"
  1861. +" hadc1.Init.Resolution = ADC_RESOLUTION_12B;\n"
  1862. +" hadc1.Init.ScanConvMode = DISABLE;\n"
  1863. +" hadc1.Init.ContinuousConvMode = DISABLE;\n"
  1864. +" hadc1.Init.DiscontinuousConvMode = DISABLE;\n"
  1865. +" hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;\n"
  1866. +" hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;\n"
  1867. +" hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;\n"
  1868. +" hadc1.Init.NbrOfConversion = 1;\n"
  1869. +" hadc1.Init.DMAContinuousRequests = DISABLE;\n"
  1870. +" hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;\n"
  1871. +" if (HAL_ADC_Init(&hadc1) != HAL_OK)\n"
  1872. +" {\n"
  1873. +" Error_Handler();\n"
  1874. +" }\n"
  1875. +" sConfig.Channel = pin;\n"
  1876. +" sConfig.Rank = 1;\n"
  1877. +" sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;\n"
  1878. +" if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)\n"
  1879. +" {\n"
  1880. +" Error_Handler();\n"
  1881. +" }\n"
  1882. +"}\n")
  1883. f.write(gpio)
  1884. #GPIO input程式宣告----------------------------------------------------------------------------------
  1885. gpio2=("void MX_GPIO_Input1(unsigned long pin)\n"
  1886. +"{\n"
  1887. +" GPIO_InitTypeDef GPIO_InitStruct = {0};\n"
  1888. +" __HAL_RCC_GPIOE_CLK_ENABLE();\n"
  1889. +" GPIO_InitStruct.Pin = pin;\n"
  1890. +" GPIO_InitStruct.Mode = GPIO_MODE_INPUT;\n"
  1891. +" GPIO_InitStruct.Pull = GPIO_PULLDOWN;\n"
  1892. +" HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);\n"
  1893. +"}\n")
  1894. f.write(gpio2)
  1895. #錯誤程式-------------------------------------------------------------------------------------
  1896. f.write("void Error_Handler(void)\n{\n}\n")
  1897. f.close()
  1898. f = open(CURRENT_PATH + "//CTO20220622//Src//main.c", mode='r')
  1899. words = f.read()
  1900. # print(words)
  1901. f.close()
  1902. # server_log(msg['command'], "D1", "ok") # 06/15 Rita 原為阿超丟 MQTT 給網頁, 先註解
  1903. # ===== 阿超 CTO.py 程式碼 end ========================================================================================
  1904. # ===== 編譯 CTO20220622整個資料夾並在build資料夾生成所需的hex檔 start ========================
  1905. cwdDATA = os.path.join(CURRENT_PATH, "CTO20220622")
  1906. print("cwdDATA: ", cwdDATA)
  1907. # 以下指令要在 Linux 上測試, Windows 未安裝會報錯
  1908. # make_result = 0
  1909. make_result = subprocess.call(["sudo", "make"],cwd = cwdDATA)
  1910. # ===== 編譯 CTO20220622整個資料夾並在build資料夾生成所需的hex檔 end ========================
  1911. if make_result == 0:
  1912. return "OK"
  1913. else:
  1914. return "NG"
  1915. #
  1916. @main.route('/loader', methods=['GET', 'POST'])
  1917. def loader():
  1918. info = request.args.to_dict()
  1919. # print("info: ", info)
  1920. ethernet_list = info['ethernet_list']
  1921. print("ethernet_list: ", ethernet_list, type(ethernet_list))
  1922. wifi_list = info['wifi_list']
  1923. print("wifi_list: ", wifi_list, type(wifi_list))
  1924. zigbee_list = info['zigbee_list']
  1925. print("zigbee_list: ", zigbee_list, type(zigbee_list))
  1926. # 將 string 以 , 分割成 list
  1927. relay_list = info['relay_list'].split(',')
  1928. print("relay_list: ", relay_list, type(relay_list))
  1929. pwm_list = info['pwm_list'].split(',')
  1930. print("pwm_list: ", pwm_list, type(pwm_list))
  1931. digital_list = info['digital_list'].split(',')
  1932. print("digital_list: ", digital_list, type(digital_list))
  1933. uart_list = info['uart_list'].split(',')
  1934. print("uart_list: ", uart_list, type(uart_list))
  1935. i2c_list = info['i2c_list'].split(',')
  1936. print("i2c_list: ", i2c_list, type(i2c_list))
  1937. s485_list = info['s485_list'].split(',')
  1938. print("s485_list: ", s485_list, type(s485_list))
  1939. ppa_list = info['ppa_list'].split(',')
  1940. print("ppa_list: ", ppa_list, type(ppa_list))
  1941. return jsonify({"response":"OK" })
  1942. # # Rita 測試
  1943. @main.route('/drop_down_list')
  1944. def drop_down_list():
  1945. # 獲取登入信息
  1946. if 'id' in session and 'uname' in session and 'status' in session:
  1947. username = session['uname']
  1948. status = session['status']
  1949. if status == 9:
  1950. return render_template('signin_disable.html')
  1951. elif status == 8:
  1952. return render_template('signin_new.html')
  1953. # TODO
  1954. mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffee',
  1955. password='skyeye', database='Coffee', charset='utf8')
  1956. mycursor = mydb.cursor()
  1957. conn = pymysql.connect(
  1958. host='52.69.200.169',
  1959. port=3306,
  1960. user='coffee',
  1961. password='skyeye',
  1962. database='Coffee',
  1963. charset='utf8'
  1964. )
  1965. cur = conn.cursor()
  1966. #獲取欄位資料
  1967. sql = "select * from product_info"
  1968. cur.execute(sql)
  1969. content = cur.fetchall()
  1970. #獲取欄位名稱
  1971. sql = "SHOW FIELDS FROM product_info"
  1972. cur.execute(sql)
  1973. labels = cur.fetchall()
  1974. # print("labels: ", labels) # labels: (('產品', 'varchar(4)', 'YES', '', None, ''), ('系統', 'varchar(5)', 'YES', '', None, ''),
  1975. labels = [g[0] for g in labels]
  1976. # print("labels: ", labels) # labels: ['產品', '系統', '系統圖號', '狀態', '進貨狀態', '序號', '組序號',
  1977. return render_template('drop_down_list.html', labels=labels, content=content)
  1978. else:
  1979. return render_template('sign_in.html')
  1980. # !!! AttributeError: 'NoneType' object has no attribute 'vacuum'
  1981. @main.route('/loading/container', methods=['GET', 'POST'])
  1982. def container_loading():
  1983. if request.method == 'GET':
  1984. # 清洗浮選狀態
  1985. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  1986. Clean_container_status_list = [clean_status.Clean_Tank_1,
  1987. clean_status.Clean_Tank_2,
  1988. clean_status.Clean_Tank_3,
  1989. clean_status.Clean_Tank_4]
  1990. CLEAN_Waiting_number = int(Clean_container_status_list.count('C_Waiting'))
  1991. CLEAN_Warning_number = int(Clean_container_status_list.count('C_Warning'))
  1992. if CLEAN_Waiting_number == len(Clean_container_status_list): Clean_container = 'Waiting'
  1993. elif CLEAN_Warning_number >= 1: Clean_container = 'Warning'
  1994. else: Clean_container = 'Working'
  1995. # 清洗浮選狀態
  1996. ColorSelect_container_status_list = [clean_status.ColorSelect_Tank_1,
  1997. clean_status.ColorSelect_Tank_2]
  1998. COLORSELECT_Waiting_number = int(ColorSelect_container_status_list.count('S_Waiting'))
  1999. COLORSELECT_Warning_number = int(ColorSelect_container_status_list.count('S_Warning'))
  2000. if COLORSELECT_Waiting_number == len(ColorSelect_container_status_list): ColorSelect_container = 'Waiting'
  2001. elif COLORSELECT_Warning_number >= 1: ColorSelect_container = 'Warning'
  2002. else: ColorSelect_container = 'Working'
  2003. # 脫皮機
  2004. Peel_container_status_list = [clean_status.Peel_Tank_1,
  2005. clean_status.Peel_Tank_2]
  2006. PEEL_Waiting_number = int(Peel_container_status_list.count('P_Waiting'))
  2007. PEEL_Warning_number = int(Peel_container_status_list.count('P_Warning'))
  2008. if PEEL_Waiting_number == len(Peel_container_status_list): Peel_container = 'Waiting'
  2009. elif PEEL_Warning_number >= 1: Peel_container = 'Warning'
  2010. else: Peel_container = 'Working'
  2011. # 發酵槽
  2012. ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  2013. Ferment_container_status_list = [ferment_status.Ferment_Tank_1,
  2014. ferment_status.Ferment_Tank_2,
  2015. ferment_status.Ferment_Tank_3,
  2016. ferment_status.Ferment_Tank_4,
  2017. ferment_status.Ferment_Tank_5,
  2018. ferment_status.Ferment_Tank_6,
  2019. ferment_status.Ferment_Tank_7,
  2020. ferment_status.Ferment_Tank_8,
  2021. ferment_status.Ferment_Tank_9,
  2022. ferment_status.Ferment_Tank_10,
  2023. ferment_status.Ferment_Tank_11,
  2024. ferment_status.Ferment_Tank_12]
  2025. FERMENT_Waiting_number = int(Ferment_container_status_list.count('F_Waiting'))
  2026. FERMENT_Warning_number = int(Ferment_container_status_list.count('F_Warning'))
  2027. if FERMENT_Waiting_number == len(Ferment_container_status_list): Ferment_container = 'Waiting'
  2028. elif FERMENT_Warning_number >= 1: Ferment_container = 'Warning'
  2029. else: Ferment_container = 'Working'
  2030. # 乾燥槽
  2031. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  2032. Dry_container_status_list = [dry_status.Dry_Tank_1,
  2033. dry_status.Dry_Tank_2,
  2034. dry_status.Dry_Tank_3,
  2035. dry_status.Dry_Tank_4,
  2036. dry_status.Dry_Tank_5,
  2037. dry_status.Dry_Tank_6,
  2038. dry_status.Dry_Tank_7,
  2039. dry_status.Dry_Tank_8,
  2040. dry_status.Dry_Tank_9,
  2041. dry_status.Dry_Tank_10,
  2042. dry_status.Dry_Tank_11,
  2043. dry_status.Dry_Tank_12]
  2044. DRY_Waiting_number= int(Dry_container_status_list.count('D_Waiting'))
  2045. DRY_Warning_number= int(Dry_container_status_list.count('D_Warning'))
  2046. if DRY_Waiting_number == len(Dry_container_status_list): Dry_container = 'Waiting'
  2047. elif DRY_Warning_number >= 1: Dry_container = 'Warning'
  2048. else: Dry_container = 'Working'
  2049. return jsonify({"Clean_container":Clean_container,
  2050. "ColorSelect_container":ColorSelect_container,
  2051. "Peel_container":Peel_container,
  2052. "Ferment_container":Ferment_container,
  2053. "Dry_container":Dry_container
  2054. })
  2055. @main.route('/loading_sensors', methods=['GET', 'POST'])
  2056. def loading_sensors():
  2057. C1_UltraSonic = (clean_tank_UltraSonic.query.filter_by(tank_num='C1').order_by(text('datetime desc')).first()).UltraSonic
  2058. C2_UltraSonic = (clean_tank_UltraSonic.query.filter_by(tank_num='C2').order_by(text('datetime desc')).first()).UltraSonic
  2059. PO1_UltraSonic = (peel_output_UltraSonic.query.filter_by(tank_num='PO1').order_by(text('datetime desc')).first()).UltraSonic
  2060. PO2_UltraSonic = (peel_output_UltraSonic.query.filter_by(tank_num='PO2').order_by(text('datetime desc')).first()).UltraSonic
  2061. F1_UltraSonic = (ferment_tank_UltraSonic.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()).UltraSonic
  2062. F1_SHT11Temp = (ferment_tank_SHT11.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()).SHT11_Temp
  2063. F1_SHT11Humidity = (ferment_tank_SHT11.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()).SHT11_Humidity
  2064. F2_UltraSonic = (ferment_tank_UltraSonic.query.filter_by(tank_num='F2').order_by(text('datetime desc')).first()).UltraSonic
  2065. D1_UltraSonic = (dry_tank_UltraSonic.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()).UltraSonic
  2066. D1_SHT11Temp = (dry_tank_SHT11.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()).SHT11_Temp
  2067. D1_SHT11Humidity = (dry_tank_SHT11.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()).SHT11_Humidity
  2068. D2_UltraSonic = (dry_tank_UltraSonic.query.filter_by(tank_num='D2').order_by(text('datetime desc')).first()).UltraSonic
  2069. DO1_UltraSonic = (dry_output_sensor.query.filter_by(tank_num='DO1').order_by(text('datetime desc')).first()).UltraSonic
  2070. DO2_UltraSonic = (dry_output_sensor.query.filter_by(tank_num='DO2').order_by(text('datetime desc')).first()).UltraSonic
  2071. return jsonify({"C1_UltraSonic":C1_UltraSonic,
  2072. "C2_UltraSonic":C2_UltraSonic,
  2073. "PO1_UltraSonic":PO1_UltraSonic,
  2074. "PO2_UltraSonic":PO2_UltraSonic,
  2075. "F1_UltraSonic":F1_UltraSonic,
  2076. "F1_SHT11Temp":F1_SHT11Temp,
  2077. "F1_SHT11Humidity":F1_SHT11Humidity,
  2078. "F2_UltraSonic":F2_UltraSonic,
  2079. "D1_UltraSonic":D1_UltraSonic,
  2080. "D1_SHT11Temp":D1_SHT11Temp,
  2081. "D1_SHT11Humidity":D1_SHT11Humidity,
  2082. "D2_UltraSonic":D2_UltraSonic,
  2083. "DO1_UltraSonic":DO1_UltraSonic,
  2084. "DO2_UltraSonic":DO2_UltraSonic
  2085. })
  2086. @main.route('/demo', methods=['GET', 'POST'])
  2087. def demo():
  2088. if 'id' in session and 'uname' in session and 'status' in session:
  2089. username = session['uname']
  2090. status = session['status']
  2091. if status == 9:
  2092. return render_template('signin_disable.html')
  2093. elif status == 8:
  2094. return render_template('signin_new.html')
  2095. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  2096. CI1 = clean_status.Clean_Input_1
  2097. CI2 = clean_status.Clean_Input_2
  2098. C1 = clean_status.Clean_Tank_1
  2099. C2 = clean_status.Clean_Tank_2
  2100. R1 = clean_status.Reclaimed_Tank_1
  2101. S1 = clean_status.ColorSelect_Tank_1
  2102. S2 = clean_status.ColorSelect_Tank_2
  2103. SOg1 = clean_status.ColorSelect_Output_g1
  2104. SOb1 = clean_status.ColorSelect_Output_b1
  2105. SOg2 = clean_status.ColorSelect_Output_g2
  2106. SOb2 = clean_status.ColorSelect_Output_b2
  2107. P1 = clean_status.Peel_Tank_1
  2108. P2 = clean_status.Peel_Tank_2
  2109. PO1 = clean_status.Peel_Output_1
  2110. PO2 = clean_status.Peel_Output_2
  2111. ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  2112. F1 = ferment_status.Ferment_Tank_1
  2113. F2 = ferment_status.Ferment_Tank_2
  2114. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  2115. D1 = dry_status.Dry_Tank_1
  2116. D2 = dry_status.Dry_Tank_2
  2117. DO1 = dry_status.Dry_Output_1
  2118. DO2 = dry_status.Dry_Output_2
  2119. POb1 = clean_status.Peel_Output_b1
  2120. return render_template('demo.html', title="[測試] DEMO 貨櫃自動化", **locals())
  2121. else:
  2122. return render_template('sign_in.html')
  2123. @main.route('/demo_auto', methods=['GET', 'POST'])
  2124. def demo_auto():
  2125. if 'id' in session and 'uname' in session and 'status' in session:
  2126. username = session['uname']
  2127. status = session['status']
  2128. if status == 9:
  2129. return render_template('signin_disable.html')
  2130. elif status == 8:
  2131. return render_template('signin_new.html')
  2132. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  2133. CI1 = clean_status.Clean_Input_1
  2134. CI2 = clean_status.Clean_Input_2
  2135. C1 = clean_status.Clean_Tank_1
  2136. C2 = clean_status.Clean_Tank_2
  2137. # 中水桶
  2138. S1 = clean_status.ColorSelect_Tank_1
  2139. S2 = clean_status.ColorSelect_Tank_2
  2140. SOg1 = clean_status.ColorSelect_Output_g1
  2141. SOb1 = clean_status.ColorSelect_Output_b1
  2142. SOg2 = clean_status.ColorSelect_Output_g2
  2143. SOb2 = clean_status.ColorSelect_Output_b2
  2144. P1 = clean_status.Peel_Tank_1
  2145. P2 = clean_status.Peel_Tank_2
  2146. PO1 = clean_status.Peel_Output_1
  2147. PO2 = clean_status.Peel_Output_2
  2148. ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  2149. F1 = ferment_status.Ferment_Tank_1
  2150. F2 = ferment_status.Ferment_Tank_2
  2151. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  2152. D1 = dry_status.Dry_Tank_1
  2153. D2 = dry_status.Dry_Tank_2
  2154. DO1 = dry_status.Dry_Output_1
  2155. DO2 = dry_status.Dry_Output_2
  2156. POb1 = clean_status.Peel_Output_b1
  2157. return render_template('demo_auto.html', title="[測試] DEMO 貨櫃自動化", **locals())
  2158. else:
  2159. return render_template('sign_in.html')
  2160. # 脫皮機自動化測試頁
  2161. @main.route('/peel_auto_status', methods=['GET', 'POST'])
  2162. def peel_auto_test():
  2163. info = request.args.to_dict()
  2164. # 寫定出料的空桶標準, 若 <= 2 則為空桶
  2165. Peel_Output_bean_empty = 2
  2166. # 從介面取得 指定生豆高度
  2167. Peel_Tank_bean_height = float(info['Peel_Tank_bean_height'])
  2168. Peel_Tank_motor_rpm = float(info['Peel_Tank_motor_rpm'])
  2169. Peel_Tank_vacuumON_time = float(info['Peel_Tank_vacuumON_time'])
  2170. Peel_Tank_vacuumOFF_time = float(info['Peel_Tank_vacuumOFF_time'])
  2171. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  2172. P1 = clean_status.Peel_Tank_1
  2173. P2 = clean_status.Peel_Tank_2
  2174. PO1 = clean_status.Peel_Output_1
  2175. PO2 = clean_status.Peel_Output_2
  2176. SO1 = 'SO_OutputtingBean' # SO_OutputtingBean SO_Waiting
  2177. SO2 = 'SO_Waiting'
  2178. # -- 取得脫皮機 P1~P2 桶內高度 UltraSonic -------------
  2179. PO_UP_tank_UltraSonic = []
  2180. for i in range(1, 3, 1):
  2181. output_UltraSonic = peel_output_UltraSonic.query.filter_by(tank_num='PO' + str(i)).order_by(text('datetime desc')).first()
  2182. UltraSonic = float(output_UltraSonic.UltraSonic)
  2183. PO_UP_tank_UltraSonic.append(UltraSonic)
  2184. print('PO_UP_tank_UltraSonic: ', PO_UP_tank_UltraSonic)
  2185. # -- 取得脫皮機 P1~P2 桶內高度 UltraSonic -------------
  2186. if P1 == 'P_Waiting' and PO1 != 'PO_OutputtingBean' and SO1 == 'SO_OutputtingBean':
  2187. P1 = 'P_Peeling'
  2188. PO1 = 'PO_InputtingBean'
  2189. print('------- P1 狀態更新:脫皮中 -------')
  2190. print('------- PO1 狀態更新:入豆中 -------')
  2191. # [致動器] 馬達 指定轉速
  2192. data = { "tank_num": "P1", "command": "tank_motor_status", "value": Peel_Tank_motor_rpm}
  2193. print('data: ', data)
  2194. # mqtt_f(data)
  2195. if P1 == 'P_Peeling':
  2196. if PO_UP_tank_UltraSonic[0] >= Peel_Tank_bean_height:
  2197. # [致動器] 真空吸料機 OFF
  2198. data = { "tank_num": "P1", "command": "tank_vacuum_status", "value": "off" }
  2199. print('data: ', data)
  2200. # mqtt_f(data)
  2201. # [致動器] 馬達 0
  2202. data = { "tank_num": "P1", "command": "tank_motor_status", "value": "0" }
  2203. print('data: ', data)
  2204. # mqtt_f(data)
  2205. P1 = 'P_Waiting'
  2206. PO1 = 'PO_OutputtingBean'
  2207. print('------- P1 狀態更新:等待中 -------')
  2208. print('------- PO1 狀態更新:可出豆 -------')
  2209. elif PO_UP_tank_UltraSonic[0] < Peel_Tank_bean_height:
  2210. # [致動器] 真空吸料機 ON
  2211. data = { "tank_num": "P1", "command": "tank_vacuum_status", "value": "on" }
  2212. print('data: ', data)
  2213. # mqtt_f(data)
  2214. timer = time.time()
  2215. while True:
  2216. if (time.time() - timer) > Peel_Tank_vacuumON_time:
  2217. # [致動器] 真空吸料機 OFF
  2218. data = { "tank_num": "P1", "command": "tank_vacuum_status", "value": "off" }
  2219. print('data: ', data)
  2220. # mqtt_f(data)
  2221. timer = time.time()
  2222. break
  2223. while True:
  2224. if (time.time() - timer) > Peel_Tank_vacuumOFF_time:
  2225. break
  2226. if PO1 == 'PO_OutputtingBean' and PO_UP_tank_UltraSonic[0] <= Peel_Output_bean_empty:
  2227. PO1 = 'PO_Waiting'
  2228. print('------- PO1 狀態更新:空桶等待 -------')
  2229. CI1 = 'CI_Warning'
  2230. CI2 = 'CI_Waiting'
  2231. C1 = 'C_Warning'
  2232. C2 = 'C_Waiting'
  2233. C3 = 'C_Waiting'
  2234. C4 = 'C_Waiting'
  2235. SI1 = 'SI_Warning'
  2236. SI2 = 'SI_Waiting'
  2237. S1 = 'S_Warning'
  2238. S2 = 'S_Waiting'
  2239. SOg1 = 'SO_Warning'
  2240. SOb1 = 'SO_Warning'
  2241. SOg2 = 'SO_Waiting'
  2242. SOb2 = 'SO_Waiting'
  2243. POb1 = 'PO_Waiting'
  2244. # ----- 將狀態寫入資料庫 ------------------------------
  2245. # 獲取文本框的值並賦值給user實體對象
  2246. C_status = clean_container_status()
  2247. C_status.Clean_Input_1 = CI1
  2248. C_status.Clean_Input_2 = CI2
  2249. C_status.Clean_Tank_1 = C1
  2250. C_status.Clean_Tank_2 = C2
  2251. C_status.Clean_Tank_3 = C3
  2252. C_status.Clean_Tank_4 = C4
  2253. C_status.ColorSelect_Input_1 = SI1
  2254. C_status.ColorSelect_Input_2 = SI2
  2255. C_status.ColorSelect_Tank_1 = S1
  2256. C_status.ColorSelect_Tank_2 = S2
  2257. C_status.ColorSelect_Output_g1 = SOg1
  2258. C_status.ColorSelect_Output_b1 = SOb1
  2259. C_status.ColorSelect_Output_g2 = SOg2
  2260. C_status.ColorSelect_Output_b2 = SOb2
  2261. C_status.Peel_Tank_1 = P1
  2262. C_status.Peel_Tank_2 = P2
  2263. C_status.Peel_Output_1 = PO1
  2264. C_status.Peel_Output_2 = PO2
  2265. C_status.Peel_Output_b1 = POb1
  2266. #將數據保存進資料庫
  2267. db.session.add(C_status)
  2268. # 手動提交
  2269. db.session.commit()
  2270. # ----- 將狀態寫入資料庫 ------------------------------
  2271. return jsonify({"Peel_Tank_1":P1,
  2272. "Peel_Tank_2":P2,
  2273. "Peel_Output_1":PO1,
  2274. "Peel_Output_2":PO2
  2275. })
  2276. # 乾燥槽狀態更新
  2277. @main.route('/dry_status_update', methods=['GET', 'POST'])
  2278. def dry_status_update():
  2279. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  2280. DI1 = dry_status.Dry_Input_1
  2281. DI2 = dry_status.Dry_Input_2
  2282. D1 = dry_status.Dry_Tank_1
  2283. D2 = dry_status.Dry_Tank_2
  2284. D3 = dry_status.Dry_Tank_3
  2285. D4 = dry_status.Dry_Tank_4
  2286. D5 = dry_status.Dry_Tank_5
  2287. D6 = dry_status.Dry_Tank_6
  2288. D7 = dry_status.Dry_Tank_7
  2289. D8 = dry_status.Dry_Tank_8
  2290. D9 = dry_status.Dry_Tank_9
  2291. D10 = dry_status.Dry_Tank_10
  2292. D11 = dry_status.Dry_Tank_11
  2293. D12 = dry_status.Dry_Tank_12
  2294. DO1 = dry_status.Dry_Output_1
  2295. DO2 = dry_status.Dry_Output_2
  2296. return jsonify({"DI1":DI1,
  2297. "DI2":DI2,
  2298. "D1":D1,
  2299. "D2":D2,
  2300. "D3":D3,
  2301. "D4":D4,
  2302. "D5":D5,
  2303. "D6":D6,
  2304. "D7":D7,
  2305. "D8":D8,
  2306. "D9":D9,
  2307. "D10":D10,
  2308. "D11":D11,
  2309. "D12":D12,
  2310. "DO1":DO1,
  2311. "DO2":DO2
  2312. })
  2313. # 乾燥槽自動化測試頁
  2314. @main.route('/dry_auto', methods=['GET', 'POST'])
  2315. def dry_auto():
  2316. # 獲取登入信息
  2317. if 'id' in session and 'uname' in session and 'status' in session:
  2318. username = session['uname']
  2319. status = session['status']
  2320. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  2321. DI1 = dry_status.Dry_Input_1
  2322. DI2 = dry_status.Dry_Input_2
  2323. D1 = dry_status.Dry_Tank_1
  2324. D2 = dry_status.Dry_Tank_2
  2325. D3 = dry_status.Dry_Tank_3
  2326. D4 = dry_status.Dry_Tank_4
  2327. D5 = dry_status.Dry_Tank_5
  2328. D6 = dry_status.Dry_Tank_6
  2329. D7 = dry_status.Dry_Tank_7
  2330. D8 = dry_status.Dry_Tank_8
  2331. D9 = dry_status.Dry_Tank_9
  2332. D10 = dry_status.Dry_Tank_10
  2333. D11 = dry_status.Dry_Tank_11
  2334. D12 = dry_status.Dry_Tank_12
  2335. DO1 = dry_status.Dry_Output_1
  2336. DO2 = dry_status.Dry_Output_2
  2337. return render_template('dry_auto.html', title="[測試] 乾燥自動化", **locals())
  2338. else:
  2339. return render_template('sign_in.html')
  2340. # 乾燥槽 乾燥暫停 出料
  2341. @main.route('/dryDEMO_outputtingBean', methods=['GET', 'POST'])
  2342. def dryDEMO_outputtingBean():
  2343. info = request.args.to_dict()
  2344. Dry_Output_bean_height = float(info['Dry_Output_bean_height'])
  2345. Dry_Output_vacuumON_time = float(info['Dry_Output_vacuumON_time'])
  2346. Dry_Output_vacuumOFF_time = float(info['Dry_Output_vacuumOFF_time'])
  2347. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  2348. DI1 = dry_status.Dry_Input_1 # DI1 == 'DI_OutputtingBean'
  2349. DI2 = dry_status.Dry_Input_2
  2350. D1 = dry_status.Dry_Tank_1
  2351. D2 = dry_status.Dry_Tank_2
  2352. D3 = dry_status.Dry_Tank_3
  2353. D4 = dry_status.Dry_Tank_4
  2354. D5 = dry_status.Dry_Tank_5
  2355. D6 = dry_status.Dry_Tank_6
  2356. D7 = dry_status.Dry_Tank_7
  2357. D8 = dry_status.Dry_Tank_8
  2358. D9 = dry_status.Dry_Tank_9
  2359. D10 = dry_status.Dry_Tank_10
  2360. D11 = dry_status.Dry_Tank_11
  2361. D12 = dry_status.Dry_Tank_12
  2362. DO1 = dry_status.Dry_Output_1
  2363. DO2 = dry_status.Dry_Output_2
  2364. # # -- 取得乾燥出料儲豆槽 DO1~DO2 桶內高度 UltraSonic -------------
  2365. # DO_UP_UltraSoniclist = []
  2366. # for i in range(1, 3, 1):
  2367. # output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO' + str(i)).order_by(text('datetime desc')).first()
  2368. # UltraSonic = float(output_UltraSonic.UltraSonic)
  2369. # DO_UP_UltraSoniclist.append(UltraSonic)
  2370. # print('DO_UP_UltraSoniclist: ', DO_UP_UltraSoniclist)
  2371. # # -- 取得乾燥出料儲豆槽 DO1~DO2 桶內高度 UltraSonic -------------
  2372. # 將桶槽 D1 狀態轉換成可出豆, DO1 狀態轉換成可入豆
  2373. D1 = 'D_OutputtingBean'
  2374. # [致動器] 設定溫度 0.0
  2375. data = { "tank_num": "D1", "command": "tank_temp", "value": "0.0" }
  2376. print('data: ', data)
  2377. # mqtt_f(data)
  2378. # [致動器] 溫控開關 OFF
  2379. data = { "tank_num": "D1", "command": "tank_temp_enable", "value": "off" }
  2380. print('data: ', data)
  2381. # mqtt_f(data)
  2382. # [致動器] 馬達 0
  2383. data = { "tank_num": "D1", "command": "tank_motor_status", "value": "0" }
  2384. print('data: ', data)
  2385. # mqtt_f(data)
  2386. # [致動器] 排水電磁閥 OFF
  2387. data = { "tank_num": "D1", "command": "tank_solenoid_water_out_status", "value": "off" }
  2388. print('data: ', data)
  2389. # mqtt_f(data)
  2390. # [致動器] D1 蝴蝶閥 ON
  2391. data = { "tank_num": "D1", "command": "tank_diskvalve_status", "value": "on" }
  2392. print('data: ', data)
  2393. # mqtt_f(data)
  2394. # ----- 將狀態寫入資料庫 ------------------------------
  2395. # 獲取文本框的值並賦值給user實體對象
  2396. D_status = dry_container_status()
  2397. D_status.Dry_Input_1 = DI1
  2398. D_status.Dry_Input_2 = DI2
  2399. D_status.Dry_Tank_1 = D1
  2400. D_status.Dry_Tank_2 = D2
  2401. D_status.Dry_Tank_3 = D3
  2402. D_status.Dry_Tank_4 = D4
  2403. D_status.Dry_Tank_5 = D5
  2404. D_status.Dry_Tank_6 = D6
  2405. D_status.Dry_Tank_7 = D7
  2406. D_status.Dry_Tank_8 = D8
  2407. D_status.Dry_Tank_9 = D9
  2408. D_status.Dry_Tank_10 = D10
  2409. D_status.Dry_Tank_11 = D11
  2410. D_status.Dry_Tank_12 = D12
  2411. D_status.Dry_Output_1 = DO1
  2412. D_status.Dry_Output_2 = DO2
  2413. #將數據保存進資料庫
  2414. db.session.add(D_status)
  2415. # 手動提交
  2416. db.session.commit()
  2417. # ----- 將狀態寫入資料庫 ------------------------------
  2418. return jsonify({"Dry_Tank_1":D1,
  2419. "Dry_Tank_2":D2,
  2420. "Dry_Output_1":DO1,
  2421. "Dry_Output_2":DO2
  2422. })
  2423. @main.route('/dryDEMO_auto_status', methods=['GET', 'POST'])
  2424. def dryDEMO_auto_status():
  2425. info = request.args.to_dict()
  2426. # 寫定入料、桶槽、出料的空桶標準, 若 <= 2 則為空桶
  2427. Dry_Tank_bean_empty = 2
  2428. Dry_Output_bean_empty = 2
  2429. # 從介面取得 指定生豆高度/發酵桶槽排程:發酵、清洗、校正 EC、校正攪拌棒
  2430. Dry_Tank_bean_height = float(info['Dry_Tank_bean_height'])
  2431. Dry_Tank_vacuumON_time = float(info['Dry_Tank_vacuumON_time'])
  2432. Dry_Tank_vacuumOFF_time = float(info['Dry_Tank_vacuumOFF_time'])
  2433. Dry_Tank_drying_temp = float(info['Dry_Tank_drying_temp'])
  2434. Dry_Tank_drying_time = float(info['Dry_Tank_drying_time'])
  2435. Dry_Tank_motor_rpm = float(info['Dry_Tank_motor_rpm'])
  2436. Dry_Tank_drying_Humidity = float(info['Dry_Tank_drying_Humidity'])
  2437. Dry_Output_bean_height = float(info['Dry_Output_bean_height'])
  2438. Dry_Output_vacuumON_time = float(info['Dry_Output_vacuumON_time'])
  2439. Dry_Output_vacuumOFF_time = float(info['Dry_Output_vacuumOFF_time'])
  2440. Dry_Tank_Disinfect_time = float(info['Dry_Tank_Disinfect_timef'])
  2441. # [介面] 讓使用者可以選擇排程內有乾燥/清洗/校正, 此處預設為 True
  2442. Dry_btn = True
  2443. # 從資料庫資料表中取得最新狀態
  2444. # ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  2445. # FO1 = 'FO_OutputtingBean'
  2446. # FO2 = 'FO_Waiting'
  2447. # FO1 = 'FO_OutputtingBean' # 'FO_OutputtingBean' FO_Waiting
  2448. # FO2 = 'FO_Waiting'
  2449. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  2450. DI1 = dry_status.Dry_Input_1 # DI1 == 'DI_OutputtingBean'
  2451. DI2 = dry_status.Dry_Input_2
  2452. D1 = dry_status.Dry_Tank_1
  2453. D2 = dry_status.Dry_Tank_2
  2454. D3 = dry_status.Dry_Tank_3
  2455. D4 = dry_status.Dry_Tank_4
  2456. D5 = dry_status.Dry_Tank_5
  2457. D6 = dry_status.Dry_Tank_6
  2458. D7 = dry_status.Dry_Tank_7
  2459. D8 = dry_status.Dry_Tank_8
  2460. D9 = dry_status.Dry_Tank_9
  2461. D10 = dry_status.Dry_Tank_10
  2462. D11 = dry_status.Dry_Tank_11
  2463. D12 = dry_status.Dry_Tank_12
  2464. DO1 = dry_status.Dry_Output_1
  2465. DO2 = dry_status.Dry_Output_2
  2466. D_UP_tanklist = [D1, D2, D3, D4, D5, D6]
  2467. D_DOWN_tanklist = [D7, D8, D9, D10, D11, D12]
  2468. DOutputtingBean_Tank = '' # 出料桶槽號
  2469. DryAuto_cleaning = 0 # 清洗次數
  2470. # 目前乾燥槽 D1~D6 正在入豆的桶槽數量 (應小於一桶)
  2471. DryUp_Waiting_number = int(D_UP_tanklist.count('D_Waiting'))
  2472. DryUp_InputtingBean_number = int(D_UP_tanklist.count('D_InputtingBean'))
  2473. DryUp_InputtingBeanPause_number = int(D_UP_tanklist.count('D_InputtingBean_Pause'))
  2474. # -- 取得乾燥入料儲豆槽 FI1~FI2 桶內高度 UltraSonic -------------
  2475. DI_UP_UltraSoniclist = []
  2476. for i in range(1, 3, 1):
  2477. input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI' + str(i)).order_by(text('datetime desc')).first()
  2478. UltraSonic = float(input_UltraSonic.UltraSonic)
  2479. DI_UP_UltraSoniclist.append(UltraSonic)
  2480. print('DI_UP_UltraSoniclist: ', DI_UP_UltraSoniclist)
  2481. # -- 取得乾燥入料儲豆槽 FI1~FI2 桶內高度 UltraSonic -------------
  2482. # -- 取得乾燥桶槽 D1~D6 超音波生豆高度 UltraSonic -------------
  2483. D_UP_tank_UltraSonic = []
  2484. for i in range(1, 7, 1):
  2485. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
  2486. UltraSonic = float(tank_UltraSonic.UltraSonic)
  2487. D_UP_tank_UltraSonic.append(UltraSonic)
  2488. print('D_UP_tank_UltraSonic: ', D_UP_tank_UltraSonic)
  2489. # -- 取得乾燥桶槽 D1~D6 超音波生豆高度 UltraSonic -------------
  2490. # -- 取得乾燥出料儲豆槽 DO1~DO2 桶內高度 UltraSonic -------------
  2491. DO_UP_UltraSoniclist = []
  2492. for i in range(1, 3, 1):
  2493. output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO' + str(i)).order_by(text('datetime desc')).first()
  2494. UltraSonic = float(output_UltraSonic.UltraSonic)
  2495. DO_UP_UltraSoniclist.append(UltraSonic)
  2496. print('DO_UP_UltraSoniclist: ', DO_UP_UltraSoniclist)
  2497. # -- 取得乾燥出料儲豆槽 DO1~DO2 桶內高度 UltraSonic -------------
  2498. # -- 取得乾燥桶槽 D1~D6 桶內溫濕度計 SHT11 -------------
  2499. D_UP_tank_SHT11Temp = []
  2500. D_UP_tank_SHT11Humidity = []
  2501. for i in range(1, 7, 1):
  2502. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
  2503. SHT11_Temp = float(tank_SHT11.SHT11_Temp)
  2504. D_UP_tank_SHT11Temp.append(SHT11_Temp)
  2505. SHT11_Humidity = float(tank_SHT11.SHT11_Humidity)
  2506. D_UP_tank_SHT11Humidity.append(SHT11_Humidity)
  2507. print('D_UP_tank_SHT11Temp: ', D_UP_tank_SHT11Temp)
  2508. print('D_UP_tank_SHT11Humidity: ', D_UP_tank_SHT11Humidity)
  2509. # -- 取得乾燥桶槽 D1~D6 桶內溫濕度計 SHT11 -------------
  2510. # -- 取得乾燥桶槽 D1~D6 三合一土壤感測器 Soil -------------
  2511. D_UP_tank_SoilTemp = []
  2512. D_UP_tank_SoilHumidity = []
  2513. D_UP_tank_SoilEC = []
  2514. for i in range(1, 7, 1):
  2515. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
  2516. soil_Temp = float(tank_Soil.soil_Temp)
  2517. D_UP_tank_SoilTemp.append(soil_Temp)
  2518. soil_Humidity = float(tank_Soil.soil_Humidity)
  2519. D_UP_tank_SoilHumidity.append(soil_Humidity)
  2520. soil_EC = float(tank_Soil.soil_EC)
  2521. D_UP_tank_SoilEC.append(soil_EC)
  2522. # print('D_UP_tank_SoilTemp: ', D_UP_tank_SoilTemp)
  2523. # print('D_UP_tank_SoilHumidity: ', D_UP_tank_SoilHumidity)
  2524. # print('D_UP_tank_SoilEC: ', D_UP_tank_SoilEC)
  2525. # -- 取得乾燥桶槽 D1~D6 三合一土壤感測器 SHT11 -------------
  2526. # ----- 發酵排程動作 start ------------------------------------------------------------------
  2527. # if D1 == 'D_InputtingBean': D_UP_tank_UltraSonic[0] >= Dry_Tank_bean_height:
  2528. def DInputtingBean_TO_DInputtingBeanFinish(tid):
  2529. # [致動器] 真空吸料機 OFF
  2530. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  2531. print('data: ', data)
  2532. # mqtt_f(data)
  2533. # [致動器] 蝴蝶閥 OFF
  2534. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
  2535. print('data: ', data)
  2536. # mqtt_f(data)
  2537. # # [致動器] F1 蝴蝶閥 OFF [ 1109 測試用 ]
  2538. # data = { "tank_num": "F1", "command": "tank_diskvalve_status", "value": "off" }
  2539. # print('data: ', data)
  2540. # # mqtt_f(data)
  2541. # [致動器] 馬達 0
  2542. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  2543. print('data: ', data)
  2544. # mqtt_f(data)
  2545. # [致動器] 入料三通閥 ON排氣
  2546. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "on" }
  2547. print('data: ', data)
  2548. # mqtt_f(data)
  2549. print('------- ', tid,' 狀態更新:入豆完成 -------')
  2550. # if D1 == 'D_InputtingBean': elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
  2551. def DInputtingBean_AND_notfilled(tid):
  2552. # [致動器] 蝴蝶閥 OFF
  2553. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
  2554. print('data: ', data)
  2555. # mqtt_f(data)
  2556. # [致動器] 入料三通閥 OFF入豆
  2557. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  2558. print('data: ', data)
  2559. # mqtt_f(data)
  2560. # [致動器] 真空吸料機 ON
  2561. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "on" }
  2562. print('data: ', data)
  2563. # mqtt_f(data)
  2564. timer = time.time()
  2565. while True:
  2566. if (time.time() - timer) > Dry_Tank_vacuumON_time:
  2567. # [致動器] 真空吸料機 OFF
  2568. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  2569. print('data: ', data)
  2570. # mqtt_f(data)
  2571. timer = time.time()
  2572. break
  2573. while True:
  2574. if (time.time() - timer) > Dry_Tank_vacuumOFF_time:
  2575. break
  2576. # if D1 == 'D_InputtingBean': elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
  2577. def DInputtingBean_TO_DInputtingBeanPause(tid):
  2578. # [致動器] 蝴蝶閥 OFF
  2579. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
  2580. print('data: ', data)
  2581. # mqtt_f(data)
  2582. # [致動器] 真空吸料機 OFF
  2583. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  2584. print('data: ', data)
  2585. # mqtt_f(data)
  2586. # [致動器] 馬達 0
  2587. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  2588. print('data: ', data)
  2589. # mqtt_f(data)
  2590. print('------- ', tid,' 狀態更新:入豆暫停 -------')
  2591. # elif DryUp_InputtingBeanPause_number == 1 and DI1 == 'DI_OutputtingBean': if D1 == 'D_InputtingBean_Pause':
  2592. def DInputtingBeanPause_TO_DInputtingBean(tid):
  2593. # [致動器] 入料三通閥 OFF入豆
  2594. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  2595. print('data: ', data)
  2596. # mqtt_f(data)
  2597. # [致動器] 馬達 5
  2598. data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
  2599. print('data: ', data)
  2600. # mqtt_f(data)
  2601. print('------- ', tid, ' 狀態更新:入豆中 -------')
  2602. # elif DryUp_InputtingBean_number == 0 and DryUp_InputtingBeanPause_number == 0 and DI1 == 'DI_OutputtingBean' and DryUp_Waiting_number >= 1:
  2603. def DWaiting_TO_DInputtingBean(tid):
  2604. # [致動器] F1 蝴蝶閥 ON
  2605. data = { "tank_num": "F1", "command": "tank_diskvalve_status", "value": "on" }
  2606. print('data: ', data)
  2607. # mqtt_f(data)
  2608. # [致動器] 蝴蝶閥 OFF
  2609. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
  2610. print('data: ', data)
  2611. # mqtt_f(data)
  2612. # [致動器] 入料三通閥 OFF入豆
  2613. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  2614. print('data: ', data)
  2615. # mqtt_f(data)
  2616. # [致動器] 馬達 5
  2617. data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
  2618. print('data: ', data)
  2619. # mqtt_f(data)
  2620. print('------- ', tid, ' 狀態更新:入豆中 -------')
  2621. # else: if D1 == 'D_InputtingBean_Finish':
  2622. def DInputtingBeanFinish_TO_DDrying(tid):
  2623. # [致動器] 馬達 指定轉速
  2624. data = { "tank_num": tid, "command": "tank_motor_status", "value": Dry_Tank_motor_rpm }
  2625. print('data: ', data)
  2626. # mqtt_f(data)
  2627. # [致動器] 排水電磁閥 ON
  2628. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "on" }
  2629. print('data: ', data)
  2630. # mqtt_f(data)
  2631. # # [致動器] 鼓風機 ON
  2632. # data = { "tank_num": tid, "command": "tank_blower_status", "value": "on" }
  2633. # print('data: ', data)
  2634. # # mqtt_f(data)
  2635. # # [致動器] 加熱器 1 ON
  2636. # data = { "tank_num": tid, "command": "tank_heater1_status", "value": "on" }
  2637. # print('data: ', data)
  2638. # # mqtt_f(data)
  2639. # # [致動器] 加熱器 2 ON
  2640. # data = { "tank_num": tid, "command": "tank_heater2_status", "value": "on" }
  2641. # print('data: ', data)
  2642. # # mqtt_f(data)
  2643. # [致動器] 溫控開關 ON
  2644. data = { "tank_num": tid, "command": "tank_temp_enable", "value": "on" }
  2645. print('data: ', data)
  2646. # mqtt_f(data)
  2647. # [致動器] 設定溫度 (指定溫度)
  2648. data = { "tank_num": tid, "command": "tank_temp", "value": Dry_Tank_drying_temp }
  2649. print('data: ', data)
  2650. # mqtt_f(data)
  2651. print('------- ', tid, ' 狀態更新:乾燥中 -------')
  2652. # else: if D1 == 'D_Drying' and D_UP_tank_weightTemp[0] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[0] <= Dry_Tank_drying_Humidity:
  2653. def DDrying_TO_DOutputtingBean(tid):
  2654. # # [致動器] 鼓風機 OFF
  2655. # data = { "tank_num": tid, "command": "tank_blower_status", "value": "off" }
  2656. # print('data: ', data)
  2657. # # mqtt_f(data)
  2658. # # [致動器] 加熱器 1 OFF
  2659. # data = { "tank_num": tid, "command": "tank_heater1_status", "value": "off" }
  2660. # print('data: ', data)
  2661. # # mqtt_f(data)
  2662. # # [致動器] 加熱器 2 OFF
  2663. # data = { "tank_num": tid, "command": "tank_heater2_status", "value": "off" }
  2664. # print('data: ', data)
  2665. # # mqtt_f(data)
  2666. # [致動器] 設定溫度 0
  2667. data = { "tank_num": tid, "command": "tank_temp", "value": "0" }
  2668. print('data: ', data)
  2669. # mqtt_f(data)
  2670. # [致動器] 溫控開關 OFF
  2671. data = { "tank_num": tid, "command": "tank_temp_enable", "value": "off" }
  2672. print('data: ', data)
  2673. # mqtt_f(data)
  2674. # [致動器] 馬達 0
  2675. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  2676. print('data: ', data)
  2677. # mqtt_f(data)
  2678. print("乾燥結束, 返潮暫停 ", Dry_Tank_drying_time, " 秒")
  2679. timer = time.time()
  2680. while True:
  2681. if (time.time() - timer) > Dry_Tank_drying_time:
  2682. # [致動器] 排水電磁閥 OFF
  2683. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  2684. print('data: ', data)
  2685. # mqtt_f(data)
  2686. break
  2687. print('------- ', tid, ' 狀態更新:可出豆 -------')
  2688. # else: if D1 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[0] <= Dry_Tank_bean_empty):
  2689. def DOutputtingBean_TO_DWaiting(tid):
  2690. # [致動器] D1 蝴蝶閥 OFF
  2691. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
  2692. print('data: ', data)
  2693. # mqtt_f(data)
  2694. # D_Cleaning
  2695. def DCleaning(tid):
  2696. # [致動器] 馬達 10
  2697. data = { "tank_num": tid, "command": "tank_motor_status", "value": "10" }
  2698. print('data: ', data)
  2699. # mqtt_f(data)
  2700. # [致動器] 消毒電磁閥 ON
  2701. data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "on" }
  2702. print('data: ', data)
  2703. # mqtt_f(data)
  2704. # [致動器] 排水電磁閥 OFF
  2705. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  2706. print('data: ', data)
  2707. # mqtt_f(data)
  2708. # [致動器] TODO 消毒抽水 pump ON
  2709. print("消毒 ", Dry_Tank_Disinfect_time, " 秒")
  2710. timer = time.time()
  2711. while True:
  2712. if (time.time() - timer) > Dry_Tank_Disinfect_time:
  2713. # [致動器] TODO 消毒抽水 pump OFF
  2714. break
  2715. # [致動器] 消毒電磁閥 OFF
  2716. data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "off" }
  2717. print('data: ', data)
  2718. # mqtt_f(data)
  2719. # [致動器] 馬達 0
  2720. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  2721. print('data: ', data)
  2722. # mqtt_f(data)
  2723. # [致動器] 排水電磁閥 ON
  2724. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "on" }
  2725. print('data: ', data)
  2726. # mqtt_f(data)
  2727. print("桶內排水 ", Dry_Tank_Disinfect_time, " 秒")
  2728. timer = time.time()
  2729. while True:
  2730. if (time.time() - timer) > Dry_Tank_Disinfect_time:
  2731. break
  2732. # [致動器] 排水電磁閥 OFF
  2733. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  2734. print('data: ', data)
  2735. # mqtt_f(data)
  2736. print('------- ', tid, ' 狀態更新:空桶等待 -------')
  2737. # ----- 發酵排程動作 end ------------------------------------------------------------------
  2738. # [介面] 若啟用 乾燥 狀態
  2739. if Dry_btn:
  2740. # ----- 乾燥桶槽 D1~D6 入料桶槽優先入料判斷 ------------------------------
  2741. # 若 D1~D6 桶槽中有一個桶槽入豆中
  2742. if DryUp_InputtingBean_number == 1:
  2743. # 若 D1 桶槽為入豆中
  2744. if D1 == 'D_InputtingBean':
  2745. # 若桶槽生豆高度大於指定生豆高度, 則狀態轉換成 入料完成
  2746. if D_UP_tank_UltraSonic[0] >= Dry_Tank_bean_height:
  2747. DInputtingBean_TO_DInputtingBeanFinish("D1")
  2748. D1 = 'D_InputtingBean_Finish'
  2749. # 若桶槽生豆高度未達指定生豆高度, 且 入料儲豆槽可出豆
  2750. elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
  2751. DInputtingBean_AND_notfilled("D1")
  2752. # 若桶槽生豆高度未達指定生豆高度, 且 入料儲豆槽 非可出豆
  2753. elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
  2754. DInputtingBean_TO_DInputtingBeanPause("D1")
  2755. D1 = 'D_InputtingBean_Pause'
  2756. # 若 D1~D6 桶槽中有一個桶槽入豆暫停
  2757. elif DryUp_InputtingBeanPause_number == 1 and DI1 == 'DI_OutputtingBean':
  2758. if D1 == 'D_InputtingBean_Pause':
  2759. DInputtingBeanPause_TO_DInputtingBean("D1")
  2760. D1 = 'D_InputtingBean'
  2761. # 若 D1~D6 桶槽中皆無 入豆中 和 入豆暫停, 且入料儲豆槽可出豆
  2762. elif DryUp_InputtingBean_number == 0 and DryUp_InputtingBeanPause_number == 0 and DI1 == 'DI_OutputtingBean' and DryUp_Waiting_number >= 1:
  2763. if D1 == 'D_Waiting':
  2764. DWaiting_TO_DInputtingBean("D1")
  2765. D1 = 'D_InputtingBean'
  2766. # 其他
  2767. # else:
  2768. # 以下內容原在此 else 內, 測試無誤後維持
  2769. # 如果桶槽為 入豆完成, 將狀態轉換成 乾燥中
  2770. if D1 == 'D_InputtingBean_Finish':
  2771. DInputtingBeanFinish_TO_DDrying("D1")
  2772. D1 = 'D_Drying'
  2773. # 如果桶槽為 乾燥中, 達乾燥條件後, 將狀態轉換成 可出豆
  2774. if D1 == 'D_Drying' and D_UP_tank_SHT11Temp[0] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[0] <= Dry_Tank_drying_Humidity:
  2775. DDrying_TO_DOutputtingBean("D1")
  2776. D1 = 'D_OutputtingBean'
  2777. if DOutputtingBean_Tank == '': DOutputtingBean_Tank = 'D1'
  2778. # 如果桶槽 D1~D6 可出豆 且 桶槽內為空桶 且 有指定清洗排程, 進行清洗桶槽
  2779. # TODO 發酵次數計算、消毒次數、校正
  2780. if D1 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[0] <= Dry_Tank_bean_empty):
  2781. if DOutputtingBean_Tank == 'D1':
  2782. DOutputtingBean_TO_DWaiting('D1')
  2783. DOutputtingBean_Tank = ''
  2784. if (DryAuto_cleaning == 0): D1 = 'D_Waiting'
  2785. elif (DryAuto_cleaning != 0): D1 = 'D_Cleaning'
  2786. # 避免桶槽可出豆時未賦值
  2787. if DOutputtingBean_Tank == '':
  2788. if D1 == 'D_OutputtingBean': DOutputtingBean_Tank = 'D1'
  2789. # 乾燥槽消毒
  2790. if D1 == 'D_Cleaning':
  2791. DCleaning("D1")
  2792. D1 = 'D_Waiting'
  2793. else:
  2794. print('未啟用乾燥流程')
  2795. # ----- 乾燥出料儲豆槽 DO1~DO2 入豆→可出豆判斷 ------------------------------
  2796. # 若出料儲豆槽狀態為 空桶等待 且 桶槽狀態為 D_OutputtingBean 可出豆, 與 FO1 配合開始出豆
  2797. # # 1109 註解實驗用
  2798. # if DO1 == 'DO_Waiting' and DOutputtingBean_Tank != '':
  2799. # # 判斷要對應出料的桶槽為何, 設定成 DOutputtingBean_Tank = 'D1', 待出完料再把 DOutputtingBean_Tank = ''
  2800. # DO1 = 'DO_InputtingBean'
  2801. # print('------- ' + DOutputtingBean_Tank + ' 狀態更新:出豆中 -------')
  2802. # print('------- DO1 狀態更新:入豆中 -------')
  2803. # # [致動器] D1 蝴蝶閥 ON
  2804. # data = { "tank_num": DOutputtingBean_Tank, "command": "tank_diskvalve_status", "value": "on" }
  2805. # print('data: ', data)
  2806. # # mqtt_f(data)
  2807. # elif DO1 == 'DO_InputtingBean' and DOutputtingBean_Tank != '':
  2808. # if DO_UP_UltraSoniclist[0] >= Dry_Output_bean_height:
  2809. # # [致動器] 出料真空吸料機 OFF
  2810. # data = { "tank_num": DOutputtingBean_Tank, "command": "output_vacuum_status", "value": "off" }
  2811. # print('data: ', data)
  2812. # # mqtt_f(data)
  2813. # # [致動器] D1 蝴蝶閥 OFF
  2814. # data = { "tank_num": DOutputtingBean_Tank, "command": "tank_diskvalve_status", "value": "off" }
  2815. # print('data: ', data)
  2816. # # mqtt_f(data)
  2817. # DO1 = 'DO_OutputtingBean'
  2818. # print('------- DO1 狀態更新:可出豆 -------')
  2819. # elif DO_UP_UltraSoniclist[0] < Dry_Output_bean_height:
  2820. # # [致動器] 出料真空吸料機 ON
  2821. # data = { "tank_num": DOutputtingBean_Tank, "command": "output_vacuum_status", "value": "on" }
  2822. # print('data: ', data)
  2823. # # mqtt_f(data)
  2824. # timer = time.time()
  2825. # while True:
  2826. # if (time.time() - timer) > Dry_Output_vacuumON_time:
  2827. # # [致動器] 出料真空吸料機 OFF
  2828. # data = { "tank_num": DOutputtingBean_Tank, "command": "output_vacuum_status", "value": "off" }
  2829. # print('data: ', data)
  2830. # # mqtt_f(data)
  2831. # timer = time.time()
  2832. # break
  2833. # while True:
  2834. # if (time.time() - timer) > Dry_Output_vacuumOFF_time:
  2835. # break
  2836. # # 若是無桶槽可入豆, 出料儲豆槽判斷是否可出豆或空桶等待入豆
  2837. # elif DO1 == 'DO_InputtingBean' and DOutputtingBean_Tank == '':
  2838. # if DO_UP_UltraSoniclist[0] > Dry_Output_bean_empty:
  2839. # DO1 = 'DO_OutputtingBean'
  2840. # print('------- DO1 狀態更新:可出豆 -------')
  2841. # elif DO_UP_UltraSoniclist[0] <= Dry_Output_bean_empty:
  2842. # DO1 = 'DO_Waiting'
  2843. # print('------- DO1 狀態更新:空桶等待 -------')
  2844. # elif DO1 == 'DO_OutputtingBean' and DO_UP_UltraSoniclist[0] <= Dry_Output_bean_empty:
  2845. # DO1 = 'DO_Waiting'
  2846. # # [致動器] D1 蝴蝶閥 OFF
  2847. # data = { "tank_num": "D1", "command": "tank_diskvalve_status", "value": "off" }
  2848. # print('data: ', data)
  2849. # # mqtt_f(data)
  2850. # print('------- DO1 狀態更新:空桶等待 -------')
  2851. # # 1109 註解實驗用
  2852. # # ----- [測試用] !!!!! D1~D6 入料完成→可出豆 判斷 ------------------------------
  2853. # if D1 == 'D_InputtingBean_Finish': D1 = 'D_OutputtingBean'
  2854. # if D2 == 'D_InputtingBean_Finish': D2 = 'D_OutputtingBean'
  2855. # if D3 == 'D_InputtingBean_Finish': D3 = 'D_OutputtingBean'
  2856. # if D4 == 'D_InputtingBean_Finish': D4 = 'D_OutputtingBean'
  2857. # if D5 == 'D_InputtingBean_Finish': D5 = 'D_OutputtingBean'
  2858. # if D6 == 'D_InputtingBean_Finish': D6 = 'D_OutputtingBean'
  2859. # # ----- [測試用] !!!!! D1~D6 入料完成→可出豆 判斷 ------------------------------
  2860. # ----- 將狀態寫入資料庫 ------------------------------
  2861. # 獲取文本框的值並賦值給user實體對象
  2862. D_status = dry_container_status()
  2863. D_status.Dry_Input_1 = DI1
  2864. D_status.Dry_Input_2 = DI2
  2865. D_status.Dry_Tank_1 = D1
  2866. D_status.Dry_Tank_2 = D2
  2867. D_status.Dry_Tank_3 = D3
  2868. D_status.Dry_Tank_4 = D4
  2869. D_status.Dry_Tank_5 = D5
  2870. D_status.Dry_Tank_6 = D6
  2871. D_status.Dry_Tank_7 = D7
  2872. D_status.Dry_Tank_8 = D8
  2873. D_status.Dry_Tank_9 = D9
  2874. D_status.Dry_Tank_10 = D10
  2875. D_status.Dry_Tank_11 = D11
  2876. D_status.Dry_Tank_12 = D12
  2877. D_status.Dry_Output_1 = DO1
  2878. D_status.Dry_Output_2 = DO2
  2879. #將數據保存進資料庫
  2880. db.session.add(D_status)
  2881. # 手動提交
  2882. db.session.commit()
  2883. # ----- 將狀態寫入資料庫 ------------------------------
  2884. return jsonify({"Dry_Tank_1":D1,
  2885. "Dry_Tank_2":D2,
  2886. "Dry_Output_1":DO1,
  2887. "Dry_Output_2":DO2
  2888. })
  2889. @main.route('/dry_auto_status', methods=['GET', 'POST'])
  2890. def dry_auto_status():
  2891. info = request.args.to_dict()
  2892. # 寫定入料、桶槽、出料的空桶標準, 若 <= 2 則為空桶
  2893. Dry_Input_bean_empty = 2
  2894. Dry_Tank_bean_empty = 2
  2895. Dry_Output_bean_empty = 2
  2896. # 從介面取得 指定生豆高度/發酵桶槽排程:發酵、清洗、校正 EC、校正攪拌棒
  2897. Dry_Input_bean_height = float(info['Dry_Input_bean_height'])
  2898. Dry_Input_vacuumON_time = float(info['Dry_Input_vacuumON_time'])
  2899. Dry_Input_vacuumOFF_time = float(info['Dry_Input_vacuumOFF_time'])
  2900. Dry_Tank_bean_height = float(info['Dry_Tank_bean_height'])
  2901. Dry_Tank_vacuumON_time = float(info['Dry_Tank_vacuumON_time'])
  2902. Dry_Tank_vacuumOFF_time = float(info['Dry_Tank_vacuumOFF_time'])
  2903. Dry_Tank_drying_temp = float(info['Dry_Tank_drying_temp'])
  2904. Dry_Tank_drying_time = float(info['Dry_Tank_drying_time'])
  2905. Dry_Tank_drying_EC = float(info['Dry_Tank_drying_EC'])
  2906. Dry_Tank_motor_rpm = float(info['Dry_Tank_motor_rpm'])
  2907. Dry_Tank_TempWeight_SHT11 = float(info['Dry_Tank_TempWeight_SHT11'])
  2908. Dry_Tank_TempWeight_soil = float(info['Dry_Tank_TempWeight_soil'])
  2909. Dry_Tank_drying_Humidity = float(info['Dry_Tank_drying_Humidity'])
  2910. Dry_Output_bean_height = float(info['Dry_Output_bean_height'])
  2911. Dry_Output_vacuumON_time = float(info['Dry_Output_vacuumON_time'])
  2912. Dry_Output_vacuumOFF_time = float(info['Dry_Output_vacuumOFF_time'])
  2913. Dry_Tank_Disinfect_time = float(info['Dry_Tank_Disinfect_time'])
  2914. # [介面] 讓使用者可以選擇排程內有乾燥/清洗/校正, 此處預設為 True
  2915. Dry_btn = True
  2916. # 從資料庫資料表中取得最新狀態
  2917. ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  2918. FO1 = ferment_status.Ferment_Output_1
  2919. FO2 = ferment_status.Ferment_Output_2
  2920. # FO1 = 'FO_OutputtingBean' # 'FO_OutputtingBean' FO_Waiting
  2921. # FO2 = 'FO_Waiting'
  2922. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  2923. DI1 = dry_status.Dry_Input_1
  2924. DI2 = dry_status.Dry_Input_2
  2925. D1 = dry_status.Dry_Tank_1
  2926. D2 = dry_status.Dry_Tank_2
  2927. D3 = dry_status.Dry_Tank_3
  2928. D4 = dry_status.Dry_Tank_4
  2929. D5 = dry_status.Dry_Tank_5
  2930. D6 = dry_status.Dry_Tank_6
  2931. D7 = dry_status.Dry_Tank_7
  2932. D8 = dry_status.Dry_Tank_8
  2933. D9 = dry_status.Dry_Tank_9
  2934. D10 = dry_status.Dry_Tank_10
  2935. D11 = dry_status.Dry_Tank_11
  2936. D12 = dry_status.Dry_Tank_12
  2937. DO1 = dry_status.Dry_Output_1
  2938. DO2 = dry_status.Dry_Output_2
  2939. D_UP_tanklist = [D1, D2, D3, D4, D5, D6]
  2940. D_DOWN_tanklist = [D7, D8, D9, D10, D11, D12]
  2941. DOutputtingBean_Tank = '' # 出料桶槽號
  2942. DryAuto_cleaning = 0 # 清洗次數
  2943. # 目前乾燥槽 D1~D6 正在入豆的桶槽數量 (應小於一桶)
  2944. DryUp_Waiting_number = int(D_UP_tanklist.count('D_Waiting'))
  2945. DryUp_InputtingBean_number = int(D_UP_tanklist.count('D_InputtingBean'))
  2946. DryUp_InputtingBeanPause_number = int(D_UP_tanklist.count('D_InputtingBean_Pause'))
  2947. # -- 取得乾燥入料儲豆槽 FI1~FI2 桶內高度 UltraSonic -------------
  2948. DI_UP_UltraSoniclist = []
  2949. for i in range(1, 3, 1):
  2950. input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI' + str(i)).order_by(text('datetime desc')).first()
  2951. UltraSonic = float(input_UltraSonic.UltraSonic)
  2952. DI_UP_UltraSoniclist.append(UltraSonic)
  2953. print('DI_UP_UltraSoniclist: ', DI_UP_UltraSoniclist)
  2954. # -- 取得乾燥入料儲豆槽 FI1~FI2 桶內高度 UltraSonic -------------
  2955. # -- 取得乾燥桶槽 D1~D6 超音波生豆高度 UltraSonic -------------
  2956. D_UP_tank_UltraSonic = []
  2957. for i in range(1, 7, 1):
  2958. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
  2959. UltraSonic = float(tank_UltraSonic.UltraSonic)
  2960. D_UP_tank_UltraSonic.append(UltraSonic)
  2961. print('D_UP_tank_UltraSonic: ', D_UP_tank_UltraSonic)
  2962. # -- 取得乾燥桶槽 D1~D6 超音波生豆高度 UltraSonic -------------
  2963. # -- 取得乾燥出料儲豆槽 DO1~DO2 桶內高度 UltraSonic -------------
  2964. DO_UP_UltraSoniclist = []
  2965. for i in range(1, 3, 1):
  2966. output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO' + str(i)).order_by(text('datetime desc')).first()
  2967. UltraSonic = float(output_UltraSonic.UltraSonic)
  2968. DO_UP_UltraSoniclist.append(UltraSonic)
  2969. print('DO_UP_UltraSoniclist: ', DO_UP_UltraSoniclist)
  2970. # -- 取得乾燥出料儲豆槽 DO1~DO2 桶內高度 UltraSonic -------------
  2971. # -- 取得乾燥桶槽 D1~D6 桶內溫濕度計 SHT11 -------------
  2972. D_UP_tank_SHT11Temp = []
  2973. D_UP_tank_SHT11Humidity = []
  2974. for i in range(1, 7, 1):
  2975. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
  2976. SHT11_Temp = float(tank_SHT11.SHT11_Temp)
  2977. D_UP_tank_SHT11Temp.append(SHT11_Temp)
  2978. SHT11_Humidity = float(tank_SHT11.SHT11_Humidity)
  2979. D_UP_tank_SHT11Humidity.append(SHT11_Humidity)
  2980. # print('D_UP_tank_SHT11Temp: ', D_UP_tank_SHT11Temp)
  2981. # print('D_UP_tank_SHT11Humidity: ', D_UP_tank_SHT11Humidity)
  2982. # -- 取得乾燥桶槽 D1~D6 桶內溫濕度計 SHT11 -------------
  2983. # -- 取得乾燥桶槽 D1~D6 三合一土壤感測器 Soil -------------
  2984. D_UP_tank_SoilTemp = []
  2985. D_UP_tank_SoilHumidity = []
  2986. D_UP_tank_SoilEC = []
  2987. for i in range(1, 7, 1):
  2988. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
  2989. soil_Temp = float(tank_Soil.soil_Temp)
  2990. D_UP_tank_SoilTemp.append(soil_Temp)
  2991. soil_Humidity = float(tank_Soil.soil_Humidity)
  2992. D_UP_tank_SoilHumidity.append(soil_Humidity)
  2993. soil_EC = float(tank_Soil.soil_EC)
  2994. D_UP_tank_SoilEC.append(soil_EC)
  2995. # print('D_UP_tank_SoilTemp: ', D_UP_tank_SoilTemp)
  2996. # print('D_UP_tank_SoilHumidity: ', D_UP_tank_SoilHumidity)
  2997. # print('D_UP_tank_SoilEC: ', D_UP_tank_SoilEC)
  2998. # -- 取得乾燥桶槽 D1~D6 三合一土壤感測器 SHT11 -------------
  2999. # -- 取得乾燥桶槽 D1~D6 權重後溫度值 -------------
  3000. D_UP_tank_weightTemp = []
  3001. for i in range(1, 7, 1):
  3002. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
  3003. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
  3004. Temp = (Dry_Tank_TempWeight_SHT11*float(tank_SHT11.SHT11_Temp) + Dry_Tank_TempWeight_soil*float(tank_Soil.soil_Temp))/(Dry_Tank_TempWeight_SHT11+Dry_Tank_TempWeight_soil)
  3005. D_UP_tank_weightTemp.append(Temp)
  3006. print('D_UP_tank_weightTemp: ', D_UP_tank_weightTemp)
  3007. # -- 取得乾燥桶槽 D1~D6 權重後溫度值 -------------
  3008. # ----- 發酵排程動作 start ------------------------------------------------------------------
  3009. # if D1 == 'D_InputtingBean': D_UP_tank_UltraSonic[0] >= Dry_Tank_bean_height:
  3010. def DInputtingBean_TO_DInputtingBeanFinish(tid):
  3011. # [致動器] 真空吸料機 OFF
  3012. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  3013. print('data: ', data)
  3014. # mqtt_f(data)
  3015. # [致動器] 馬達 0
  3016. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  3017. print('data: ', data)
  3018. # mqtt_f(data)
  3019. # [致動器] 入料三通閥 ON排氣
  3020. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "on" }
  3021. print('data: ', data)
  3022. # mqtt_f(data)
  3023. print('------- ', tid,' 狀態更新:入豆完成 -------')
  3024. # if D1 == 'D_InputtingBean': elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
  3025. def DInputtingBean_AND_notfilled(tid):
  3026. # [致動器] 入料三通閥 OFF入豆
  3027. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  3028. print('data: ', data)
  3029. # mqtt_f(data)
  3030. # [致動器] 真空吸料機 ON
  3031. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "on" }
  3032. print('data: ', data)
  3033. # mqtt_f(data)
  3034. timer = time.time()
  3035. while True:
  3036. if (time.time() - timer) > Dry_Tank_vacuumON_time:
  3037. # [致動器] 真空吸料機 OFF
  3038. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  3039. print('data: ', data)
  3040. # mqtt_f(data)
  3041. timer = time.time()
  3042. break
  3043. while True:
  3044. if (time.time() - timer) > Dry_Tank_vacuumOFF_time:
  3045. break
  3046. # if D1 == 'D_InputtingBean': elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
  3047. def DInputtingBean_TO_DInputtingBeanPause(tid):
  3048. # [致動器] 真空吸料機 OFF
  3049. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  3050. print('data: ', data)
  3051. # mqtt_f(data)
  3052. # [致動器] 馬達 0
  3053. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  3054. print('data: ', data)
  3055. # mqtt_f(data)
  3056. print('------- ', tid,' 狀態更新:入豆暫停 -------')
  3057. # elif DryUp_InputtingBeanPause_number == 1 and DI1 == 'DI_OutputtingBean': if D1 == 'D_InputtingBean_Pause':
  3058. def DInputtingBeanPause_TO_DInputtingBean(tid):
  3059. # [致動器] 入料三通閥 OFF入豆
  3060. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  3061. print('data: ', data)
  3062. # mqtt_f(data)
  3063. # [致動器] 馬達 5
  3064. data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
  3065. print('data: ', data)
  3066. # mqtt_f(data)
  3067. print('------- ', tid, ' 狀態更新:入豆中 -------')
  3068. # elif DryUp_InputtingBean_number == 0 and DryUp_InputtingBeanPause_number == 0 and DI1 == 'DI_OutputtingBean' and DryUp_Waiting_number >= 1:
  3069. def DWaiting_TO_DInputtingBean(tid):
  3070. # [致動器] 入料三通閥 OFF入豆
  3071. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  3072. print('data: ', data)
  3073. # mqtt_f(data)
  3074. # [致動器] 馬達 5
  3075. data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
  3076. print('data: ', data)
  3077. # mqtt_f(data)
  3078. print('------- ', tid, ' 狀態更新:入豆中 -------')
  3079. # else: if D1 == 'D_InputtingBean_Finish':
  3080. def DInputtingBeanFinish_TO_DDrying(tid):
  3081. # [致動器] 馬達 指定轉速
  3082. data = { "tank_num": tid, "command": "tank_motor_status", "value": Dry_Tank_motor_rpm }
  3083. print('data: ', data)
  3084. # mqtt_f(data)
  3085. # [致動器] 排水電磁閥 ON
  3086. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "on" }
  3087. print('data: ', data)
  3088. # mqtt_f(data)
  3089. # [致動器] 鼓風機 ON
  3090. data = { "tank_num": tid, "command": "tank_blower_status", "value": "on" }
  3091. print('data: ', data)
  3092. # mqtt_f(data)
  3093. # [致動器] 加熱器 1 ON
  3094. data = { "tank_num": tid, "command": "tank_heater1_status", "value": "on" }
  3095. print('data: ', data)
  3096. # mqtt_f(data)
  3097. # [致動器] 加熱器 2 ON
  3098. data = { "tank_num": tid, "command": "tank_heater2_status", "value": "on" }
  3099. print('data: ', data)
  3100. # mqtt_f(data)
  3101. print('------- ', tid, ' 狀態更新:乾燥中 -------')
  3102. # else: if D1 == 'D_Drying' and D_UP_tank_weightTemp[0] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[0] <= Dry_Tank_drying_Humidity:
  3103. def DDrying_TO_DOutputtingBean(tid):
  3104. # [致動器] 鼓風機 OFF
  3105. data = { "tank_num": tid, "command": "tank_blower_status", "value": "off" }
  3106. print('data: ', data)
  3107. # mqtt_f(data)
  3108. # [致動器] 加熱器 1 OFF
  3109. data = { "tank_num": tid, "command": "tank_heater1_status", "value": "off" }
  3110. print('data: ', data)
  3111. # mqtt_f(data)
  3112. # [致動器] 加熱器 2 OFF
  3113. data = { "tank_num": tid, "command": "tank_heater2_status", "value": "off" }
  3114. print('data: ', data)
  3115. # mqtt_f(data)
  3116. # [致動器] 馬達 0
  3117. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  3118. print('data: ', data)
  3119. # mqtt_f(data)
  3120. print("乾燥結束, 返潮暫停 ", Dry_Tank_drying_time, " 秒")
  3121. timer = time.time()
  3122. while True:
  3123. if (time.time() - timer) > Dry_Tank_drying_time:
  3124. # [致動器] 排水電磁閥 OFF
  3125. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  3126. print('data: ', data)
  3127. # mqtt_f(data)
  3128. break
  3129. print('------- ', tid, ' 狀態更新:可出豆 -------')
  3130. # else: if D1 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[0] <= Dry_Tank_bean_empty):
  3131. def DOutputtingBean_TO_DWaiting(tid):
  3132. # [致動器] D1 蝴蝶閥 OFF
  3133. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
  3134. print('data: ', data)
  3135. # mqtt_f(data)
  3136. # D_Cleaning
  3137. def DCleaning(tid):
  3138. # [致動器] 馬達 10
  3139. data = { "tank_num": tid, "command": "tank_motor_status", "value": "10" }
  3140. print('data: ', data)
  3141. # mqtt_f(data)
  3142. # [致動器] 消毒電磁閥 ON
  3143. data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "on" }
  3144. print('data: ', data)
  3145. # mqtt_f(data)
  3146. # [致動器] 排水電磁閥 OFF
  3147. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  3148. print('data: ', data)
  3149. # mqtt_f(data)
  3150. # [致動器] TODO 消毒抽水 pump ON
  3151. print("消毒 ", Dry_Tank_Disinfect_time, " 秒")
  3152. timer = time.time()
  3153. while True:
  3154. if (time.time() - timer) > Dry_Tank_Disinfect_time:
  3155. # [致動器] TODO 消毒抽水 pump OFF
  3156. break
  3157. # [致動器] 消毒電磁閥 OFF
  3158. data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "off" }
  3159. print('data: ', data)
  3160. # mqtt_f(data)
  3161. # [致動器] 馬達 0
  3162. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  3163. print('data: ', data)
  3164. # mqtt_f(data)
  3165. # [致動器] 排水電磁閥 ON
  3166. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "on" }
  3167. print('data: ', data)
  3168. # mqtt_f(data)
  3169. print("桶內排水 ", Dry_Tank_Disinfect_time, " 秒")
  3170. timer = time.time()
  3171. while True:
  3172. if (time.time() - timer) > Dry_Tank_Disinfect_time:
  3173. break
  3174. # [致動器] 排水電磁閥 OFF
  3175. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  3176. print('data: ', data)
  3177. # mqtt_f(data)
  3178. print('------- ', tid, ' 狀態更新:空桶等待 -------')
  3179. # ----- 發酵排程動作 end ------------------------------------------------------------------
  3180. # ----- 乾燥入料儲豆槽 DI1~DI2 入豆→可出豆判斷 ------------------------------
  3181. # 如果入料儲豆槽 空桶等待, 且發酵出料儲豆槽 FO1 為可出豆, 則開始入豆
  3182. if DI1 == 'DI_Waiting' and FO1 == 'FO_OutputtingBean':
  3183. DI1 = 'DI_InputtingBean'
  3184. print('------- DI1 狀態更新:入料中 -------')
  3185. # 如果入料儲豆槽 入豆中
  3186. elif DI1 == 'DI_InputtingBean':
  3187. # 如果入豆儲豆槽達指定高度時
  3188. if DI_UP_UltraSoniclist[0] >= Dry_Input_bean_height:
  3189. # [致動器] 入料真空吸料機 OFF
  3190. data = { "tank_num": "D1", "command": "input_vacuum_status", "value": "off" }
  3191. print('data: ', data)
  3192. # mqtt_f(data)
  3193. DI1 = 'DI_OutputtingBean'
  3194. print('------- DI1 狀態更新:可出豆 -------')
  3195. # 如果入豆儲豆槽未達指定高度, 且 發酵出料儲豆槽 可出豆
  3196. elif DI_UP_UltraSoniclist[0] < Dry_Input_bean_height and FO1 == 'FO_OutputtingBean':
  3197. # [致動器] 入料真空吸料機 ON
  3198. data = { "tank_num": "D1", "command": "input_vacuum_status", "value": "on" }
  3199. print('data: ', data)
  3200. # mqtt_f(data)
  3201. timer = time.time()
  3202. while True:
  3203. if (time.time() - timer) > Dry_Input_vacuumON_time:
  3204. # [致動器] 入料真空吸料機 OFF
  3205. data = { "tank_num": "D1", "command": "input_vacuum_status", "value": "off" }
  3206. print('data: ', data)
  3207. # mqtt_f(data)
  3208. timer = time.time()
  3209. break
  3210. while True:
  3211. if (time.time() - timer) > Dry_Input_vacuumOFF_time:
  3212. break
  3213. # 如果入料儲豆槽生豆大於空桶高度, 且 前方 FO1 非可出豆, 將狀態轉為可出豆
  3214. elif (DI_UP_UltraSoniclist[0] > Dry_Input_bean_empty) and FO1 != 'FO_OutputtingBean':
  3215. DI1 = 'DI_OutputtingBean'
  3216. print('------- DI1 狀態更新:可出豆 -------')
  3217. # 桶槽內小於空桶高度, 且 前方 FO1 非可出豆, 將狀態轉為空桶等待
  3218. elif (DI_UP_UltraSoniclist[0] <= Dry_Input_bean_empty) and FO1 != 'PO_OutputtingBean':
  3219. DI1 = 'DI_Waiting'
  3220. print('------- FI1 狀態更新:空桶等待 -------')
  3221. # 入料儲豆槽出豆時, 桶槽高度為 空桶高度時, 狀態轉為 空桶等待
  3222. elif DI1 == 'DI_OutputtingBean' and (DI_UP_UltraSoniclist[0] <= Dry_Input_bean_empty):
  3223. DI1 = 'DI_Waiting'
  3224. print('------- DI1 狀態更新:空桶等待 -------')
  3225. # [介面] 若啟用 乾燥 狀態
  3226. if Dry_btn:
  3227. # ----- 乾燥桶槽 D1~D6 入料桶槽優先入料判斷 ------------------------------
  3228. # 若 D1~D6 桶槽中有一個桶槽入豆中
  3229. if DryUp_InputtingBean_number == 1:
  3230. # 若 D1 桶槽為入豆中
  3231. if D1 == 'D_InputtingBean':
  3232. # 若桶槽生豆高度大於指定生豆高度, 則狀態轉換成 入料完成
  3233. if D_UP_tank_UltraSonic[0] >= Dry_Tank_bean_height:
  3234. DInputtingBean_TO_DInputtingBeanFinish("D1")
  3235. D1 = 'D_InputtingBean_Finish'
  3236. # 若桶槽生豆高度未達指定生豆高度, 且 入料儲豆槽可出豆
  3237. elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
  3238. DInputtingBean_AND_notfilled("D1")
  3239. # 若桶槽生豆高度未達指定生豆高度, 且 入料儲豆槽 非可出豆
  3240. elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
  3241. DInputtingBean_TO_DInputtingBeanPause("D1")
  3242. D1 = 'D_InputtingBean_Pause'
  3243. elif D2 == 'D_InputtingBean':
  3244. if D_UP_tank_UltraSonic[1] >= Dry_Tank_bean_height:
  3245. DInputtingBean_TO_DInputtingBeanFinish("D2")
  3246. D2 = 'D_InputtingBean_Finish'
  3247. elif D_UP_tank_UltraSonic[1] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
  3248. DInputtingBean_AND_notfilled("D2")
  3249. elif D_UP_tank_UltraSonic[1] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
  3250. DInputtingBean_TO_DInputtingBeanPause("D2")
  3251. D2 = 'D_InputtingBean_Pause'
  3252. elif D3 == 'D_InputtingBean':
  3253. if D_UP_tank_UltraSonic[2] >= Dry_Tank_bean_height:
  3254. DInputtingBean_TO_DInputtingBeanFinish("D3")
  3255. D3 = 'D_InputtingBean_Finish'
  3256. elif D_UP_tank_UltraSonic[2] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
  3257. DInputtingBean_AND_notfilled("D2")
  3258. elif D_UP_tank_UltraSonic[2] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
  3259. DInputtingBean_TO_DInputtingBeanPause("D2")
  3260. D3 = 'D_InputtingBean_Pause'
  3261. elif D4 == 'D_InputtingBean':
  3262. if D_UP_tank_UltraSonic[3] >= Dry_Tank_bean_height:
  3263. DInputtingBean_TO_DInputtingBeanFinish("D4")
  3264. D4 = 'D_InputtingBean_Finish'
  3265. elif D_UP_tank_UltraSonic[3] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
  3266. DInputtingBean_AND_notfilled("D4")
  3267. elif D_UP_tank_UltraSonic[3] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
  3268. DInputtingBean_TO_DInputtingBeanPause("D4")
  3269. D4 = 'D_InputtingBean_Pause'
  3270. elif D5 == 'D_InputtingBean':
  3271. if D_UP_tank_UltraSonic[4] >= Dry_Tank_bean_height:
  3272. DInputtingBean_TO_DInputtingBeanFinish("D5")
  3273. D5 = 'D_InputtingBean_Finish'
  3274. elif D_UP_tank_UltraSonic[4] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
  3275. DInputtingBean_AND_notfilled("D5")
  3276. elif D_UP_tank_UltraSonic[4] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
  3277. DInputtingBean_TO_DInputtingBeanPause("D5")
  3278. D5 = 'D_InputtingBean_Pause'
  3279. elif D6 == 'D_InputtingBean':
  3280. if D_UP_tank_UltraSonic[5] >= Dry_Tank_bean_height:
  3281. DInputtingBean_TO_DInputtingBeanFinish("D6")
  3282. D6 = 'D_InputtingBean_Finish'
  3283. elif D_UP_tank_UltraSonic[5] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
  3284. DInputtingBean_AND_notfilled("D6")
  3285. elif D_UP_tank_UltraSonic[5] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
  3286. DInputtingBean_TO_DInputtingBeanPause("D6")
  3287. D6 = 'D_InputtingBean_Pause'
  3288. # 若 D1~D6 桶槽中有一個桶槽入豆暫停
  3289. elif DryUp_InputtingBeanPause_number == 1 and DI1 == 'DI_OutputtingBean':
  3290. if D1 == 'D_InputtingBean_Pause':
  3291. DInputtingBeanPause_TO_DInputtingBean("D1")
  3292. D1 = 'D_InputtingBean'
  3293. elif D2 == 'D_InputtingBean_Pause':
  3294. DInputtingBeanPause_TO_DInputtingBean("D2")
  3295. D2 = 'D_InputtingBean'
  3296. elif D3 == 'D_InputtingBean_Pause':
  3297. DInputtingBeanPause_TO_DInputtingBean("D3")
  3298. D3 = 'D_InputtingBean'
  3299. elif D4 == 'D_InputtingBean_Pause':
  3300. DInputtingBeanPause_TO_DInputtingBean("D4")
  3301. D4 = 'D_InputtingBean'
  3302. elif D5 == 'D_InputtingBean_Pause':
  3303. DInputtingBeanPause_TO_DInputtingBean("D5")
  3304. D5 = 'D_InputtingBean'
  3305. elif D6 == 'D_InputtingBean_Pause':
  3306. DInputtingBeanPause_TO_DInputtingBean("D6")
  3307. D6 = 'D_InputtingBean'
  3308. # 若 D1~D6 桶槽中皆無 入豆中 和 入豆暫停, 且入料儲豆槽可出豆
  3309. elif DryUp_InputtingBean_number == 0 and DryUp_InputtingBeanPause_number == 0 and DI1 == 'DI_OutputtingBean' and DryUp_Waiting_number >= 1:
  3310. if D1 == 'D_Waiting':
  3311. DWaiting_TO_DInputtingBean("D1")
  3312. D1 = 'D_InputtingBean'
  3313. elif D2 == 'D_Waiting':
  3314. DWaiting_TO_DInputtingBean("D2")
  3315. D2 = 'D_InputtingBean'
  3316. elif D3 == 'D_Waiting':
  3317. DWaiting_TO_DInputtingBean("D3")
  3318. D3 = 'D_InputtingBean'
  3319. elif D4 == 'D_Waiting':
  3320. DWaiting_TO_DInputtingBean("D4")
  3321. D4 = 'D_InputtingBean'
  3322. elif D5 == 'D_Waiting':
  3323. DWaiting_TO_DInputtingBean("D5")
  3324. D5 = 'D_InputtingBean'
  3325. elif D6 == 'D_Waiting':
  3326. DWaiting_TO_DInputtingBean("D6")
  3327. D6 = 'D_InputtingBean'
  3328. # 其他
  3329. else:
  3330. # 如果桶槽為 入豆完成, 將狀態轉換成 乾燥中
  3331. if D1 == 'D_InputtingBean_Finish':
  3332. DInputtingBeanFinish_TO_DDrying("D1")
  3333. D1 = 'D_Drying'
  3334. if D2 == 'D_InputtingBean_Finish':
  3335. DInputtingBeanFinish_TO_DDrying("D2")
  3336. D2 = 'D_Drying'
  3337. if D3 == 'D_InputtingBean_Finish':
  3338. DInputtingBeanFinish_TO_DDrying("D3")
  3339. D3 = 'D_Drying'
  3340. if D4 == 'D_InputtingBean_Finish':
  3341. DInputtingBeanFinish_TO_DDrying("D4")
  3342. D4 = 'D_Drying'
  3343. if D5 == 'D_InputtingBean_Finish':
  3344. DInputtingBeanFinish_TO_DDrying("D5")
  3345. D5 = 'D_Drying'
  3346. if D6 == 'D_InputtingBean_Finish':
  3347. DInputtingBeanFinish_TO_DDrying("D6")
  3348. D6 = 'D_Drying'
  3349. # 如果桶槽為 乾燥中, 達乾燥條件後, 將狀態轉換成 可出豆
  3350. if D1 == 'D_Drying' and D_UP_tank_weightTemp[0] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[0] <= Dry_Tank_drying_Humidity:
  3351. DDrying_TO_DOutputtingBean("D1")
  3352. D1 = 'D_OutputtingBean'
  3353. if DOutputtingBean_Tank == '': DOutputtingBean_Tank = 'D1'
  3354. if D2 == 'D_Drying' and D_UP_tank_weightTemp[1] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[1] <= Dry_Tank_drying_Humidity:
  3355. DDrying_TO_DOutputtingBean("D2")
  3356. D2 = 'D_OutputtingBean'
  3357. if DOutputtingBean_Tank == '': DOutputtingBean_Tank = 'D2'
  3358. if D3 == 'D_Drying' and D_UP_tank_weightTemp[2] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[2] <= Dry_Tank_drying_Humidity:
  3359. DDrying_TO_DOutputtingBean("D3")
  3360. D3 = 'D_OutputtingBean'
  3361. if DOutputtingBean_Tank == '': DOutputtingBean_Tank = 'D3'
  3362. if D4 == 'D_Drying' and D_UP_tank_weightTemp[3] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[3] <= Dry_Tank_drying_Humidity:
  3363. DDrying_TO_DOutputtingBean("D4")
  3364. D4 = 'D_OutputtingBean'
  3365. if DOutputtingBean_Tank == '': DOutputtingBean_Tank = 'D4'
  3366. if D5 == 'D_Drying' and D_UP_tank_weightTemp[4] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[4] <= Dry_Tank_drying_Humidity:
  3367. DDrying_TO_DOutputtingBean("D5")
  3368. D5 = 'D_OutputtingBean'
  3369. if DOutputtingBean_Tank == '': DOutputtingBean_Tank = 'D5'
  3370. if D6 == 'D_Drying' and D_UP_tank_weightTemp[5] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[5] <= Dry_Tank_drying_Humidity:
  3371. DDrying_TO_DOutputtingBean("D6")
  3372. D6 = 'D_OutputtingBean'
  3373. if DOutputtingBean_Tank == '': DOutputtingBean_Tank = 'D6'
  3374. # 如果桶槽 D1~D6 可出豆 且 桶槽內為空桶 且 有指定清洗排程, 進行清洗桶槽
  3375. # TODO 發酵次數計算、消毒次數、校正
  3376. if D1 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[0] <= Dry_Tank_bean_empty):
  3377. if DOutputtingBean_Tank == 'D1':
  3378. DOutputtingBean_TO_DWaiting('D1')
  3379. DOutputtingBean_Tank = ''
  3380. if (DryAuto_cleaning == 0): D1 = 'D_Waiting'
  3381. elif (DryAuto_cleaning != 0): D1 = 'D_Cleaning'
  3382. if D2 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[1] <= Dry_Tank_bean_empty):
  3383. if DOutputtingBean_Tank == 'D2':
  3384. DOutputtingBean_TO_DWaiting('D2')
  3385. DOutputtingBean_Tank = ''
  3386. if (DryAuto_cleaning == 0): D2 = 'D_Waiting'
  3387. elif (DryAuto_cleaning != 0): D2 = 'D_Cleaning'
  3388. if D3 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[2] <= Dry_Tank_bean_empty):
  3389. if DOutputtingBean_Tank == 'D2':
  3390. DOutputtingBean_TO_DWaiting('D2')
  3391. DOutputtingBean_Tank = ''
  3392. if (DryAuto_cleaning == 0): D3 = 'D_Waiting'
  3393. elif (DryAuto_cleaning != 0): D3 = 'D_Cleaning'
  3394. if D4 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[3] <= Dry_Tank_bean_empty):
  3395. if DOutputtingBean_Tank == 'D4':
  3396. DOutputtingBean_TO_DWaiting('D4')
  3397. DOutputtingBean_Tank = ''
  3398. if (DryAuto_cleaning == 0): D4 = 'D_Waiting'
  3399. elif (DryAuto_cleaning != 0): D4 = 'D_Cleaning'
  3400. if D5 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[4] <= Dry_Tank_bean_empty):
  3401. if DOutputtingBean_Tank == 'D5':
  3402. DOutputtingBean_TO_DWaiting('D5')
  3403. DOutputtingBean_Tank = ''
  3404. if (DryAuto_cleaning == 0): D5 = 'D_Waiting'
  3405. elif (DryAuto_cleaning != 0): D5 = 'D_Cleaning'
  3406. if D6 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[5] <= Dry_Tank_bean_empty):
  3407. if DOutputtingBean_Tank == 'D6':
  3408. DOutputtingBean_TO_DWaiting('D6')
  3409. DOutputtingBean_Tank = ''
  3410. if (DryAuto_cleaning == 0): D6 = 'D_Waiting'
  3411. elif (DryAuto_cleaning != 0): D6 = 'D_Cleaning'
  3412. # 避免桶槽可出豆時未賦值
  3413. if DOutputtingBean_Tank == '':
  3414. if D1 == 'D_OutputtingBean': DOutputtingBean_Tank = 'D1'
  3415. elif D2 == 'D_OutputtingBean': DOutputtingBean_Tank = 'D2'
  3416. elif D3 == 'D_OutputtingBean': DOutputtingBean_Tank = 'D3'
  3417. elif D4 == 'D_OutputtingBean': DOutputtingBean_Tank = 'D4'
  3418. elif D5 == 'D_OutputtingBean': DOutputtingBean_Tank = 'D5'
  3419. elif D6 == 'D_OutputtingBean': DOutputtingBean_Tank = 'D6'
  3420. # 乾燥槽消毒
  3421. if D1 == 'D_Cleaning':
  3422. DCleaning("D1")
  3423. D1 = 'D_Waiting'
  3424. if D2 == 'D_Cleaning':
  3425. DCleaning("D2")
  3426. D2 = 'D_Waiting'
  3427. if D3 == 'D_Cleaning':
  3428. DCleaning("D3")
  3429. D3 = 'D_Waiting'
  3430. if D4 == 'D_Cleaning':
  3431. DCleaning("D4")
  3432. D4 = 'D_Waiting'
  3433. if D5 == 'D_Cleaning':
  3434. DCleaning("D5")
  3435. D5 = 'D_Waiting'
  3436. if D6 == 'D_Cleaning':
  3437. DCleaning("D6")
  3438. D6 = 'D_Waiting'
  3439. else:
  3440. print('未啟用乾燥流程')
  3441. # ----- 乾燥出料儲豆槽 DO1~DO2 入豆→可出豆判斷 ------------------------------
  3442. # 若出料儲豆槽狀態為 空桶等待 且 桶槽狀態為 D_OutputtingBean 可出豆, 與 FO1 配合開始出豆
  3443. if DO1 == 'DO_Waiting' and DOutputtingBean_Tank != '':
  3444. # 判斷要對應出料的桶槽為何, 設定成 DOutputtingBean_Tank = 'D1', 待出完料再把 DOutputtingBean_Tank = ''
  3445. DO1 = 'DO_InputtingBean'
  3446. print('------- ' + DOutputtingBean_Tank + ' 狀態更新:出豆中 -------')
  3447. print('------- DO1 狀態更新:入豆中 -------')
  3448. # [致動器] D1 蝴蝶閥 ON
  3449. data = { "tank_num": DOutputtingBean_Tank, "command": "tank_diskvalve_status", "value": "on" }
  3450. print('data: ', data)
  3451. # mqtt_f(data)
  3452. elif DO1 == 'DO_InputtingBean' and DOutputtingBean_Tank != '':
  3453. if DO_UP_UltraSoniclist[0] >= Dry_Output_bean_height:
  3454. # [致動器] 出料真空吸料機 OFF
  3455. data = { "tank_num": DOutputtingBean_Tank, "command": "output_vacuum_status", "value": "off" }
  3456. print('data: ', data)
  3457. # mqtt_f(data)
  3458. # [致動器] D1 蝴蝶閥 OFF
  3459. data = { "tank_num": DOutputtingBean_Tank, "command": "tank_diskvalve_status", "value": "off" }
  3460. print('data: ', data)
  3461. # mqtt_f(data)
  3462. DO1 = 'DO_OutputtingBean'
  3463. print('------- DO1 狀態更新:可出豆 -------')
  3464. elif DO_UP_UltraSoniclist[0] < Dry_Output_bean_height:
  3465. # [致動器] 出料真空吸料機 ON
  3466. data = { "tank_num": DOutputtingBean_Tank, "command": "output_vacuum_status", "value": "on" }
  3467. print('data: ', data)
  3468. # mqtt_f(data)
  3469. timer = time.time()
  3470. while True:
  3471. if (time.time() - timer) > Dry_Output_vacuumON_time:
  3472. # [致動器] 出料真空吸料機 OFF
  3473. data = { "tank_num": DOutputtingBean_Tank, "command": "output_vacuum_status", "value": "off" }
  3474. print('data: ', data)
  3475. # mqtt_f(data)
  3476. timer = time.time()
  3477. break
  3478. while True:
  3479. if (time.time() - timer) > Dry_Output_vacuumOFF_time:
  3480. break
  3481. # 若是無桶槽可入豆, 出料儲豆槽判斷是否可出豆或空桶等待入豆
  3482. elif DOutputtingBean_Tank == '':
  3483. if DO_UP_UltraSoniclist[0] > Dry_Output_bean_empty:
  3484. DO1 = 'DO_OutputtingBean'
  3485. print('------- DO1 狀態更新:可出豆 -------')
  3486. elif DO_UP_UltraSoniclist[0] <= Dry_Output_bean_empty:
  3487. DO1 = 'DO_Waiting'
  3488. print('------- DO1 狀態更新:空桶等待 -------')
  3489. elif DO1 == 'DO_OutputtingBean' and DO_UP_UltraSoniclist[0] <= Dry_Output_bean_empty:
  3490. DO1 = 'DO_Waiting'
  3491. print('------- DO1 狀態更新:空桶等待 -------')
  3492. # # ----- [測試用] !!!!! D1~D6 入料完成→可出豆 判斷 ------------------------------
  3493. # if D1 == 'D_InputtingBean_Finish': D1 = 'D_OutputtingBean'
  3494. # if D2 == 'D_InputtingBean_Finish': D2 = 'D_OutputtingBean'
  3495. # if D3 == 'D_InputtingBean_Finish': D3 = 'D_OutputtingBean'
  3496. # if D4 == 'D_InputtingBean_Finish': D4 = 'D_OutputtingBean'
  3497. # if D5 == 'D_InputtingBean_Finish': D5 = 'D_OutputtingBean'
  3498. # if D6 == 'D_InputtingBean_Finish': D6 = 'D_OutputtingBean'
  3499. # # ----- [測試用] !!!!! D1~D6 入料完成→可出豆 判斷 ------------------------------
  3500. # ----- 將狀態寫入資料庫 ------------------------------
  3501. # 獲取文本框的值並賦值給user實體對象
  3502. D_status = dry_container_status()
  3503. D_status.Dry_Input_1 = DI1
  3504. D_status.Dry_Input_2 = DI2
  3505. D_status.Dry_Tank_1 = D1
  3506. D_status.Dry_Tank_2 = D2
  3507. D_status.Dry_Tank_3 = D3
  3508. D_status.Dry_Tank_4 = D4
  3509. D_status.Dry_Tank_5 = D5
  3510. D_status.Dry_Tank_6 = D6
  3511. D_status.Dry_Tank_7 = D7
  3512. D_status.Dry_Tank_8 = D8
  3513. D_status.Dry_Tank_9 = D9
  3514. D_status.Dry_Tank_10 = D10
  3515. D_status.Dry_Tank_11 = D11
  3516. D_status.Dry_Tank_12 = D12
  3517. D_status.Dry_Output_1 = DO1
  3518. D_status.Dry_Output_2 = DO2
  3519. #將數據保存進資料庫
  3520. db.session.add(D_status)
  3521. # 手動提交
  3522. db.session.commit()
  3523. # ----- 將狀態寫入資料庫 ------------------------------
  3524. return jsonify({"Dry_Input_1":DI1,
  3525. "Dry_Tank_1":D1,
  3526. "Dry_Tank_2":D2,
  3527. "Dry_Tank_3":D3,
  3528. "Dry_Tank_4":D4,
  3529. "Dry_Tank_5":D5,
  3530. "Dry_Tank_6":D6,
  3531. "Dry_Output_1":DO1
  3532. })
  3533. # 1101 以流程圖判斷, 改寫 def dry_auto_status, 以下為原備份
  3534. @main.route('/dry_auto_status_1101backup', methods=['GET', 'POST'])
  3535. def dry_auto_test_1101backup():
  3536. # [介面] 讓使用者可以選擇排程內有乾燥/清洗/校正, 此處預設為 True
  3537. Dry_btn = True
  3538. # 從資料庫資料表中取得最新狀態
  3539. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  3540. DI1 = dry_status.Dry_Input_1
  3541. DI2 = dry_status.Dry_Input_2
  3542. D1 = dry_status.Dry_Tank_1
  3543. D2 = dry_status.Dry_Tank_2
  3544. D3 = dry_status.Dry_Tank_3
  3545. D4 = dry_status.Dry_Tank_4
  3546. D5 = dry_status.Dry_Tank_5
  3547. D6 = dry_status.Dry_Tank_6
  3548. D7 = dry_status.Dry_Tank_7
  3549. D8 = dry_status.Dry_Tank_8
  3550. D9 = dry_status.Dry_Tank_9
  3551. D10 = dry_status.Dry_Tank_10
  3552. D11 = dry_status.Dry_Tank_11
  3553. D12 = dry_status.Dry_Tank_12
  3554. DO1 = dry_status.Dry_Output_1
  3555. DO2 = dry_status.Dry_Output_2
  3556. FO1 = 'FO_Waiting' # 'FO_OutputtingBean'
  3557. FO2 = 'FO_Waiting'
  3558. D_UP_tanklist = [D1, D2, D3, D4, D5, D6]
  3559. D_DOWN_tanklist = [D7, D8, D9, D10, D11, D12]
  3560. # ----- 乾燥桶槽 D1~D6 入料暫停→入料判斷 ------------------------------
  3561. Dry_InputtingBeanPause_number = int(D_UP_tanklist.count('D_InputtingBean_Pause'))
  3562. # 若入料儲豆槽可出豆, 且 D1~D6 其中有桶槽入料暫停 (就是入料時桶槽豆子未滿 or 儲豆槽=='DI_Waiting' 已空) 時, 優先入豆
  3563. if DI1 == 'DI_OutputtingBean' and Dry_InputtingBeanPause_number >= 1:
  3564. if D1 == 'D_InputtingBean_Pause':
  3565. D1 = 'D_InputtingBean'
  3566. print('------- D1 狀態更新:入料中 -------')
  3567. elif D2 == 'D_InputtingBean_Pause':
  3568. D2 = 'D_InputtingBean'
  3569. print('------- D2 狀態更新:入料中 -------')
  3570. elif D3 == 'D_InputtingBean_Pause':
  3571. D3 = 'D_InputtingBean'
  3572. print('------- D3 狀態更新:入料中 -------')
  3573. elif D4 == 'D_InputtingBean_Pause':
  3574. D4 = 'D_InputtingBean'
  3575. print('------- D4 狀態更新:入料中 -------')
  3576. elif D5 == 'D_InputtingBean_Pause':
  3577. D5 = 'D_InputtingBean'
  3578. print('------- D5 狀態更新:入料中 -------')
  3579. elif D6 == 'D_InputtingBean_Pause':
  3580. D6 = 'D_InputtingBean'
  3581. print('------- D6 狀態更新:入料中 -------')
  3582. # ----- 乾燥桶槽 D1~D6 等待→入料判斷 ------------------------------
  3583. # 目前乾燥槽 D1~D6 正在入豆的桶槽數量 (應小於一桶)
  3584. Dry_InputtingBean_number = int(D_UP_tanklist.count('D_InputtingBean'))
  3585. # [介面] 若未啟用 發酵 狀態
  3586. if not Dry_btn:
  3587. print('未指定乾燥流程')
  3588. # 入料儲豆槽 非可出料狀態
  3589. elif Dry_btn and DI1 != 'DI_OutputtingBean':
  3590. print('入料儲豆槽非可出豆, 無法入料')
  3591. # 若 D1~D6 乾燥桶槽為 入豆暫停, 則狀態改為入豆優先入豆
  3592. elif Dry_btn and DI1 == 'DI_OutputtingBean' and Dry_InputtingBeanPause_number >= 1:
  3593. print('乾燥槽 D', D_UP_tanklist.index('D_InputtingBean_Pause')+1, '優先入料中')
  3594. print('------- D', D_UP_tanklist.index('D_InputtingBean_Pause')+1, ' 入料中 -------')
  3595. # 若 D1~D6 發酵桶槽為 入豆, 則桶槽數字小者 優先入豆
  3596. elif Dry_btn and DI1 == 'DI_OutputtingBean' and Dry_InputtingBean_number >= 1:
  3597. print('乾燥槽 D', D_UP_tanklist.index('D_InputtingBean')+1, '優先入料中')
  3598. print('------- D', D_UP_tanklist.index('D_InputtingBean')+1, ' 入料中 -------')
  3599. elif Dry_btn and DI1 == 'DI_OutputtingBean' \
  3600. and Dry_InputtingBean_number == 0 and Dry_InputtingBeanPause_number == 0:
  3601. # 當達標準入料條件
  3602. if D1 == 'D_Waiting':
  3603. D1 = 'D_InputtingBean'
  3604. print('------- D1 狀態更新:入料中 -------')
  3605. elif D2 == 'D_Waiting':
  3606. D2 = 'D_InputtingBean'
  3607. print('------- D2 狀態更新:入料中 -------')
  3608. elif D3 == 'D_Waiting':
  3609. D3 = 'D_InputtingBean'
  3610. print('------- D3 狀態更新:入料中 -------')
  3611. elif D4 == 'D_Waiting':
  3612. D4 = 'D_InputtingBean'
  3613. print('------- D4 狀態更新:入料中 -------')
  3614. elif D5 == 'D_Waiting':
  3615. D5 = 'D_InputtingBean'
  3616. print('------- D5 狀態更新:入料中 -------')
  3617. elif D6 == 'D_Waiting':
  3618. D6 = 'D_InputtingBean'
  3619. print('------- D6 狀態更新:入料中 -------')
  3620. # ----- 乾燥桶槽 D1~D6 入料→入料暫停判斷 ------------------------------
  3621. Dry_InputtingBean_number = int(D_UP_tanklist.count('D_InputtingBean'))
  3622. # -- 取得乾燥桶槽 D1~D6 超音波生豆高度 UltraSonic -------------
  3623. D_UP_tank_UltraSonic = []
  3624. for i in range(1, 7, 1):
  3625. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
  3626. UltraSonic = int(tank_UltraSonic.UltraSonic)
  3627. D_UP_tank_UltraSonic.append(UltraSonic)
  3628. print('D_UP_tank_UltraSonic: ', D_UP_tank_UltraSonic)
  3629. # -- 取得乾燥桶槽 D1~D6 超音波生豆高度 UltraSonic -------------
  3630. if DI1 != 'DI_OutputtingBean' and Dry_InputtingBean_number >= 1:
  3631. if D1 == 'D_InputtingBean' and D_UP_tank_UltraSonic[0] < 110:
  3632. D1 = 'D_InputtingBean_Pause'
  3633. print('------- D1 狀態更新:入料暫停 -------')
  3634. else:
  3635. D1 = 'D_InputtingBean_Finish'
  3636. print('------- D1 狀態更新:入料完成 -------')
  3637. if D2 == 'D_InputtingBean' and D_UP_tank_UltraSonic[1] < 110:
  3638. D2 = 'D_InputtingBean_Pause'
  3639. print('------- D2 狀態更新:入料暫停 -------')
  3640. else:
  3641. D2 = 'D_InputtingBean_Finish'
  3642. print('------- D2 狀態更新:入料完成 -------')
  3643. if D3 == 'D_InputtingBean' and D_UP_tank_UltraSonic[2] < 110:
  3644. D3 = 'D_InputtingBean_Pause'
  3645. print('------- D3 狀態更新:入料暫停 -------')
  3646. else:
  3647. D3 = 'D_InputtingBean_Finish'
  3648. print('------- D3 狀態更新:入料完成 -------')
  3649. if D4 == 'D_InputtingBean' and D_UP_tank_UltraSonic[3] < 110:
  3650. D4 = 'D_InputtingBean_Pause'
  3651. print('------- D4 狀態更新:入料暫停 -------')
  3652. else:
  3653. D4 = 'D_InputtingBean_Finish'
  3654. print('------- D4 狀態更新:入料完成 -------')
  3655. if D5 == 'D_InputtingBean' and D_UP_tank_UltraSonic[4] < 110:
  3656. D5 = 'D_InputtingBean_Pause'
  3657. print('------- D5 狀態更新:入料暫停 -------')
  3658. else:
  3659. D5 = 'D_InputtingBean_Finish'
  3660. print('------- D5 狀態更新:入料完成 -------')
  3661. if D6 == 'D_InputtingBean' and D_UP_tank_UltraSonic[5] < 110:
  3662. D6 = 'D_InputtingBean_Pause'
  3663. print('------- D6 狀態更新:入料暫停 -------')
  3664. else:
  3665. D6 = 'D_InputtingBean_Finish'
  3666. print('------- D6 狀態更新:入料完成 -------')
  3667. # # ----- 乾燥桶槽 D1~D6 入料完成→乾燥判斷 ------------------------------
  3668. # Dry_InputtingBeanFinish_number = int(D_UP_tanklist.count('D_InputtingBean_Finish'))
  3669. # # 乾燥條件:當前桶槽入豆達指定高度, 則開始乾燥 (可以多桶乾燥)
  3670. # # !!! 乾燥槽 D_Drying 狀態應該請硬體判斷
  3671. # # !!! 若狀態為 D_InputtingBean 且 超音波值>指定生豆高度, 狀態改為 D_Drying 乾燥
  3672. # if D1 == 'D_InputtingBean_Finish' or D1 == 'D_InputtingBean_Pause' and D_UP_tank_UltraSonic[0] >= 110:
  3673. # D1 = 'D_Drying'
  3674. # print('------- D1 狀態更新:乾燥中 -------')
  3675. # if D2 == 'D_InputtingBean_Finish' and D_UP_tank_UltraSonic[1] >= 110:
  3676. # D2 = 'D_Drying'
  3677. # print('------- D2 狀態更新:乾燥中 -------')
  3678. # if D3 == 'D_InputtingBean_Finish' and D_UP_tank_UltraSonic[2] >= 110:
  3679. # D3 = 'D_Drying'
  3680. # print('------- D3 狀態更新:乾燥中 -------')
  3681. # if D4 == 'D_InputtingBean_Finish' and D_UP_tank_UltraSonic[3] >= 110:
  3682. # D4 = 'D_Drying'
  3683. # print('------- D4 狀態更新:乾燥中 -------')
  3684. # if D5 == 'D_InputtingBean_Finish' and D_UP_tank_UltraSonic[4] >= 110:
  3685. # D5 = 'D_Drying'
  3686. # print('------- D5 狀態更新:乾燥中 -------')
  3687. # if D6 == 'D_InputtingBean_Finish' and D_UP_tank_UltraSonic[5] >= 110:
  3688. # D6 = 'D_Drying'
  3689. # print('------- D6 狀態更新:乾燥中 -------')
  3690. # ----- 乾燥桶槽 D1~D6 發酵→可出豆 判斷 ------------------------------
  3691. # !!! 發酵槽 D_OutputtingBean 狀態應該請硬體判斷
  3692. # !!! 若狀態為 D_Drying 且 達指定乾燥條件, 狀態改為 D_OutputtingBean 可出豆
  3693. # 可以多桶各自執行發酵排程
  3694. # ----- [測試用] !!!!! D1~D6 入料完成→可出豆 判斷 ------------------------------
  3695. if D1 == 'D_InputtingBean_Finish': D1 = 'D_OutputtingBean'
  3696. if D2 == 'D_InputtingBean_Finish': D2 = 'D_OutputtingBean'
  3697. if D3 == 'D_InputtingBean_Finish': D3 = 'D_OutputtingBean'
  3698. if D4 == 'D_InputtingBean_Finish': D4 = 'D_OutputtingBean'
  3699. if D5 == 'D_InputtingBean_Finish': D5 = 'D_OutputtingBean'
  3700. if D6 == 'D_InputtingBean_Finish': D6 = 'D_OutputtingBean'
  3701. # ----- [測試用] !!!!! D1~D6 入料完成→可出豆 判斷 ------------------------------
  3702. # # ----- 乾燥桶槽 D1~D6 可出豆→出料儲豆槽 DO1 判斷 ------------------------------
  3703. Dry_OutputtingBean_number = int(D_UP_tanklist.count('D_OutputtingBean'))
  3704. # # !!! 若出料儲豆槽狀態為 DO_Waiting(空桶等待) 且 桶槽狀態為 D_OutputtingBean 可出豆, 與 DO1 配合開始出豆
  3705. # if DO1 == 'DO_Waiting' and Dry_OutputtingBean_number >= 1:
  3706. # if D1 == 'D_OutputtingBean':
  3707. # DO1 = 'DO_InputtingBean'
  3708. # print('------- D1 狀態更新:出豆中 -------')
  3709. # print('------- DO1 狀態更新:入豆中 -------')
  3710. # elif D2 == 'D_OutputtingBean':
  3711. # DO1 = 'DO_InputtingBean'
  3712. # print('------- D2 狀態更新:出豆中 -------')
  3713. # print('------- DO1 狀態更新:入豆中 -------')
  3714. # elif D3 == 'D_OutputtingBean':
  3715. # DO1 = 'DO_InputtingBean'
  3716. # print('------- D3 狀態更新:出豆中 -------')
  3717. # print('------- DO1 狀態更新:入豆中 -------')
  3718. # elif D4 == 'D_OutputtingBean':
  3719. # DO1 = 'DO_InputtingBean'
  3720. # print('------- D4 狀態更新:出豆中 -------')
  3721. # print('------- DO1 狀態更新:入豆中 -------')
  3722. # elif D5 == 'D_OutputtingBean':
  3723. # DO1 = 'DO_InputtingBean'
  3724. # print('------- D5 狀態更新:出豆中 -------')
  3725. # print('------- DO1 狀態更新:入豆中 -------')
  3726. # elif D6 == 'D_OutputtingBean':
  3727. # DO1 = 'DO_InputtingBean'
  3728. # print('------- D6 狀態更新:出豆中 -------')
  3729. # print('------- DO1 狀態更新:入豆中 -------')
  3730. # ----- 乾燥入料儲豆槽 DI1~DI2 入豆→可出豆判斷 ------------------------------
  3731. # -- 取得乾燥入料儲豆槽 FI1~FI2 桶內高度 UltraSonic -------------
  3732. DI_UP_UltraSoniclist = []
  3733. for i in range(1, 3, 1):
  3734. input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI' + str(i)).order_by(text('datetime desc')).first()
  3735. UltraSonic = int(input_UltraSonic.UltraSonic)
  3736. DI_UP_UltraSoniclist.append(UltraSonic)
  3737. print('DI_UP_UltraSoniclist: ', DI_UP_UltraSoniclist)
  3738. # !!! 乾燥入料儲豆槽 D_OutputtingBean 狀態應該請硬體判斷
  3739. # 入料儲豆槽等待中、且發酵槽出料儲豆槽可出豆時, 入料儲豆槽入豆
  3740. if DI1 == 'DI_Waiting' and FO1 == 'FO_OutputtingBean':
  3741. DI1 = 'DI_InputtingBean'
  3742. print('------- DI1 狀態更新:入豆中 -------')
  3743. # 入料儲豆槽入豆時 且 (發酵儲豆槽有入料 或者 前方儲豆槽非可出豆), 則停止入豆
  3744. elif DI1 == 'DI_InputtingBean' and (DI_UP_UltraSoniclist[0] > 35) and (FO1 != 'FO_OutputtingBean') :
  3745. DI1 = 'DI_OutputtingBean'
  3746. print('------- DI1 狀態更新:可出豆 -------')
  3747. # 若入料儲豆槽可出豆 且 儲豆槽內高度低於 40 且 前方脫皮機儲豆槽可出豆 且 目前無桶槽需入料時
  3748. elif DI1 == 'DI_OutputtingBean' and (DI_UP_UltraSoniclist[0] < 40) and FO1 == 'FO_OutputtingBean' and Dry_InputtingBean_number == 0 and Dry_InputtingBeanPause_number == 0:
  3749. DI1 = 'DI_InputtingBean'
  3750. print('------- DI1 狀態更新:入豆中 -------')
  3751. # if DI2 == 'DI_Waiting' and FO2 == 'FO_OutputtingBean':
  3752. # DI2 = 'DI_InputtingBean'
  3753. # print('------- DI2 狀態更新:入豆中 -------')
  3754. # elif DI2 == 'DI_InputtingBean' and ((DI_DOWN_UltraSoniclist[1] > 35) or (FO2 == 'FO_OutputtingBean')) :
  3755. # DI2 = 'DI_OutputtingBean'
  3756. # print('------- DI2 狀態更新:可出豆 -------')
  3757. # elif DI2 == 'DI_OutputtingBean' and (DI_DOWN_UltraSoniclist[1] < 40) and FO2 == 'FO_OutputtingBean' and Dry_InputtingBean_number == 0 and Dry_InputtingBeanPause_number == 0:
  3758. # DI2 = 'DI_InputtingBean'
  3759. # print('------- DI2 狀態更新:入豆中 -------')
  3760. # ----- 乾燥出料儲豆槽 DO1~DO2 入豆→可出豆判斷 ------------------------------
  3761. # -- 取得乾燥出料儲豆槽 DO1~DO2 桶內高度 UltraSonic -------------
  3762. DO_UP_UltraSoniclist = []
  3763. for i in range(1, 3, 1):
  3764. output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO' + str(i)).order_by(text('datetime desc')).first()
  3765. UltraSonic = int(output_UltraSonic.UltraSonic)
  3766. DO_UP_UltraSoniclist.append(UltraSonic)
  3767. print('DO_UP_UltraSoniclist: ', DO_UP_UltraSoniclist)
  3768. # 桶槽可出豆, 且出料儲豆槽等待時, 出料儲豆槽入豆
  3769. # 參考 -- 乾燥桶槽 F1~F6 可出豆→出料儲豆槽 FO1 判斷 --
  3770. # 出料儲豆槽入料 且滿時, 出料儲豆槽可出豆
  3771. if DO1 == ('DO_InputtingBean' and DO_UP_UltraSoniclist[0] > 35):
  3772. DO1 = 'DO_OutputtingBean'
  3773. # 出料儲豆槽入料 且未滿, 桶槽可出豆已空
  3774. # -- 取得乾燥桶槽 D1~D6 桶內高度 UltraSonic -------------
  3775. D_UP_UltraSoniclist = []
  3776. for i in range(1, 7, 1):
  3777. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
  3778. UltraSonic = int(tank_UltraSonic.UltraSonic)
  3779. D_UP_UltraSoniclist.append(UltraSonic)
  3780. print('D_UP_UltraSoniclist: ', D_UP_UltraSoniclist)
  3781. # -- 取得乾燥桶槽 D1~D6 桶內高度 UltraSonic -------------
  3782. if DO1 == 'DO_InputtingBean' and Dry_OutputtingBean_number >= 1:
  3783. if D1 == 'D_OutputtingBean' and D_UP_UltraSoniclist[0] < 5:
  3784. D1 = 'D_Waiting'
  3785. DO1 = 'DO_OutputtingBean'
  3786. print('------- D1 狀態更新:空桶等待 -------')
  3787. print('------- DO1 狀態更新:可出豆 -------')
  3788. elif D2 == 'D_OutputtingBean' and D_UP_UltraSoniclist[1] < 5:
  3789. D2 = 'D_Waiting'
  3790. DO1 = 'DO_OutputtingBean'
  3791. print('------- D2 狀態更新:空桶等待 -------')
  3792. print('------- DO1 狀態更新:可出豆 -------')
  3793. elif D3 == 'D_OutputtingBean' and D_UP_UltraSoniclist[2] < 5:
  3794. D3 = 'D_Waiting'
  3795. DO1 = 'DO_OutputtingBean'
  3796. print('------- D3 狀態更新:空桶等待 -------')
  3797. print('------- DO1 狀態更新:可出豆 -------')
  3798. elif D4 == 'D_OutputtingBean' and D_UP_UltraSoniclist[3] < 5:
  3799. D4 = 'D_Waiting'
  3800. DO1 = 'DO_OutputtingBean'
  3801. print('------- D4 狀態更新:空桶等待 -------')
  3802. print('------- DO1 狀態更新:可出豆 -------')
  3803. elif D5 == 'D_OutputtingBean' and D_UP_UltraSoniclist[4] < 5:
  3804. D5 = 'D_Waiting'
  3805. DO1 = 'DO_OutputtingBean'
  3806. print('------- D5 狀態更新:空桶等待 -------')
  3807. print('------- DO1 狀態更新:可出豆 -------')
  3808. elif D6 == 'D_OutputtingBean' and D_UP_UltraSoniclist[5] < 5:
  3809. D6 = 'D_Waiting'
  3810. DO1 = 'DO_OutputtingBean'
  3811. print('------- D6 狀態更新:空桶等待 -------')
  3812. print('------- DO1 狀態更新:可出豆 -------')
  3813. elif DO1 == 'DO_OutputtingBean' and DO_UP_UltraSoniclist[0] < 5:
  3814. DO1 = 'DO_Waiting'
  3815. # # ----- 將狀態寫入資料庫 ------------------------------
  3816. # # 獲取文本框的值並賦值給user實體對象
  3817. # D_status = dry_container_status()
  3818. # D_status.Dry_Input_1 = DI1
  3819. # D_status.Dry_Input_2 = DI2
  3820. # D_status.Dry_Tank_1 = D1
  3821. # D_status.Dry_Tank_2 = D2
  3822. # D_status.Dry_Tank_3 = D3
  3823. # D_status.Dry_Tank_4 = D4
  3824. # D_status.Dry_Tank_5 = D5
  3825. # D_status.Dry_Tank_6 = D6
  3826. # D_status.Dry_Tank_7 = D7
  3827. # D_status.Dry_Tank_8 = D8
  3828. # D_status.Dry_Tank_9 = D9
  3829. # D_status.Dry_Tank_10 = D10
  3830. # D_status.Dry_Tank_11 = D11
  3831. # D_status.Dry_Tank_12 = D12
  3832. # D_status.Dry_Output_1 = DO1
  3833. # D_status.Dry_Output_2 = DO2
  3834. # #將數據保存進資料庫
  3835. # db.session.add(D_status)
  3836. # # 手動提交
  3837. # db.session.commit()
  3838. # # ----- 將狀態寫入資料庫 ------------------------------
  3839. return jsonify({"Dry_Input_1":DI1,
  3840. "Dry_Tank_1":D1,
  3841. "Dry_Tank_2":D2,
  3842. "Dry_Tank_3":D3,
  3843. "Dry_Tank_4":D4,
  3844. "Dry_Tank_5":D5,
  3845. "Dry_Tank_6":D6,
  3846. "Dry_Output_1":DO1
  3847. })
  3848. # 1101 以流程圖判斷, 改寫 def dry_auto_status, 以上為原備份
  3849. # 發酵槽自動化測試頁
  3850. @main.route('/ferment_auto', methods=['GET', 'POST'])
  3851. def ferment_auto():
  3852. # 獲取登入信息
  3853. if 'id' in session and 'uname' in session and 'status' in session:
  3854. username = session['uname']
  3855. status = session['status']
  3856. ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  3857. FI1 = ferment_status.Ferment_Input_1
  3858. FI2 = ferment_status.Ferment_Input_2
  3859. F1 = ferment_status.Ferment_Tank_1
  3860. F2 = ferment_status.Ferment_Tank_2
  3861. F3 = ferment_status.Ferment_Tank_3
  3862. F4 = ferment_status.Ferment_Tank_4
  3863. F5 = ferment_status.Ferment_Tank_5
  3864. F6 = ferment_status.Ferment_Tank_6
  3865. F7 = ferment_status.Ferment_Tank_7
  3866. F8 = ferment_status.Ferment_Tank_8
  3867. F9 = ferment_status.Ferment_Tank_9
  3868. F10 = ferment_status.Ferment_Tank_10
  3869. F11 = ferment_status.Ferment_Tank_11
  3870. F12 = ferment_status.Ferment_Tank_12
  3871. FO1 = ferment_status.Ferment_Output_1
  3872. FO2 = ferment_status.Ferment_Output_2
  3873. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  3874. PO1 = clean_status.Peel_Output_1 # PO_Waiting # PO_OutputtingBean
  3875. return render_template('ferment_auto.html', title="[測試] 發酵自動化", **locals())
  3876. else:
  3877. return render_template('sign_in.html')
  3878. @main.route('/fermentDEMO_auto_status', methods=['GET', 'POST'])
  3879. def fermentDEMO_auto_status():
  3880. info = request.args.to_dict()
  3881. Ferment_Tank_bean_height = float(info['Ferment_Tank_bean_height'])
  3882. Ferment_Tank_vacuumON_time = float(info['Ferment_Tank_vacuumON_time'])
  3883. Ferment_Tank_vacuumOFF_time = float(info['Ferment_Tank_vacuumOFF_time'])
  3884. Ferment_Tank_water_height = float(info['Ferment_Tank_water_height'])
  3885. Ferment_Tank_fermenting_temp = float(info['Ferment_Tank_fermenting_temp'])
  3886. Ferment_Tank_fermenting_time = float(info['Ferment_Tank_fermenting_time'])
  3887. Ferment_Tank_motor_rpm = float(info['Ferment_Tank_motor_rpm'])
  3888. Ferment_Tank_WaterOut_time = float(info['Ferment_Tank_WaterOut_time'])
  3889. Ferment_btn = True
  3890. # 從資料庫資料表中取得最新狀態
  3891. ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  3892. FI1 = ferment_status.Ferment_Input_1 # FI1 = 'FI_OutputtingBean'
  3893. FI2 = ferment_status.Ferment_Input_2
  3894. F1 = ferment_status.Ferment_Tank_1
  3895. F2 = ferment_status.Ferment_Tank_2
  3896. F3 = ferment_status.Ferment_Tank_3
  3897. F4 = ferment_status.Ferment_Tank_4
  3898. F5 = ferment_status.Ferment_Tank_5
  3899. F6 = ferment_status.Ferment_Tank_6
  3900. F7 = ferment_status.Ferment_Tank_7
  3901. F8 = ferment_status.Ferment_Tank_8
  3902. F9 = ferment_status.Ferment_Tank_9
  3903. F10 = ferment_status.Ferment_Tank_10
  3904. F11 = ferment_status.Ferment_Tank_11
  3905. F12 = ferment_status.Ferment_Tank_12
  3906. FO1 = ferment_status.Ferment_Output_1
  3907. FO2 = ferment_status.Ferment_Output_2
  3908. F_UP_tanklist = [F1, F2, F3, F4, F5, F6]
  3909. FOutputtingBean_Tank = '' # 這是給出料儲豆槽判斷目前出豆的桶槽
  3910. # 寫定入料、桶槽、出料的空桶標準, 若 <= 2 則為空桶
  3911. Ferment_Input_bean_empty = 2
  3912. Ferment_Tank_bean_empty = 2
  3913. Ferment_Output_bean_empty = 2
  3914. # 目前發酵槽 F1~F6 正在入豆、入水的桶槽數量 (應小於一桶)
  3915. FermentUp_Waiting_number = int(F_UP_tanklist.count('F_Waiting'))
  3916. FermentUp_InputtingBean_number = int(F_UP_tanklist.count('F_InputtingBean'))
  3917. FermentUp_InputtingBeanPause_number = int(F_UP_tanklist.count('F_InputtingBean_Pause'))
  3918. FermentUp_InputtingBeanFinish_number = int(F_UP_tanklist.count('F_InputtingBean_Finish'))
  3919. FermentUp_InputtingWater_number = int(F_UP_tanklist.count('F_InputtingWater'))
  3920. # -- 取得發酵 入料儲豆槽 FI1~FI2 / 桶槽 F1~F6 / 出料 FO1~FO2 桶內高度 UltraSonic start -------------
  3921. FI_UP_UltraSoniclist = []
  3922. for i in range(1, 3, 1):
  3923. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  3924. # UltraSonic = float("{:.2f}".format(34.6 - float(input_UltraSonic.UltraSonic)))
  3925. UltraSonic = float(input_UltraSonic.UltraSonic)
  3926. FI_UP_UltraSoniclist.append(UltraSonic)
  3927. print('FI_UP_UltraSoniclist: ', FI_UP_UltraSoniclist)
  3928. F_UP_UltraSoniclist = []
  3929. for i in range(1, 7, 1):
  3930. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  3931. UltraSonic = (float(tank_UltraSonic.UltraSonic))
  3932. F_UP_UltraSoniclist.append(UltraSonic)
  3933. print('F_UP_UltraSoniclist: ', F_UP_UltraSoniclist)
  3934. FO_UP_UltraSoniclist = []
  3935. for i in range(1, 3, 1):
  3936. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO' + str(i)).order_by(text('datetime desc')).first()
  3937. UltraSonic = float(output_UltraSonic.UltraSonic)
  3938. FO_UP_UltraSoniclist.append(UltraSonic)
  3939. print('FO_UP_UltraSoniclist: ', FO_UP_UltraSoniclist)
  3940. # -- 取得發酵 入料儲豆槽 FI1~FI2 / 桶槽 F1~F6 / 出料 FO1~FO2 桶內高度 UltraSonic end -------------
  3941. # -- 取得發酵桶槽 F1~F6 夾層水位高度 WaterLevel start -------------
  3942. F_UP_tank_WaterLevel = []
  3943. for i in range(1, 7, 1):
  3944. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  3945. WaterLevel = float(tank_WaterLevel.WaterLevel)
  3946. F_UP_tank_WaterLevel.append(WaterLevel)
  3947. print('F_UP_tank_WaterLevel: ', F_UP_tank_WaterLevel)
  3948. # -- 取得發酵桶槽 F1~F6 夾層水位高度 WaterLevel end -------------
  3949. # -- 取得發酵桶槽 F1~F6 pH -------------
  3950. F_UP_tank_PH = []
  3951. for i in range(1, 7, 1):
  3952. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  3953. PH = float(tank_PH.PH)
  3954. F_UP_tank_PH.append(PH)
  3955. print('F_UP_tank_PH: ', F_UP_tank_PH)
  3956. # -- 取得發酵桶槽 F1~F6 pH -------------
  3957. # -- 取得發酵桶槽 F1~F6 SHT11_TEMP -------------
  3958. F_UP_tank_SHT11_Temp = []
  3959. for i in range(1, 7, 1):
  3960. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  3961. SHT11_Temp = float(tank_SHT11.SHT11_Temp)
  3962. F_UP_tank_SHT11_Temp.append(SHT11_Temp)
  3963. print('F_UP_tank_SHT11_Temp: ', F_UP_tank_SHT11_Temp)
  3964. # -- 取得發酵桶槽 F1~F6 SHT11_TEMP -------------
  3965. # ----- 發酵排程動作 start ------------------------------------------------------------------
  3966. # F1 == 'F_InputtingBean' AND (F_UP_UltraSoniclist[0] >= Ferment_Tank_bean_height):
  3967. def FInputtingBean_TO_FInputtingBeanFinish(tid): # 1108 [測試] 入豆後直接出豆
  3968. # [致動器] 蝴蝶閥 OFF
  3969. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
  3970. print('data: ', data)
  3971. # mqtt_f(data)
  3972. # [致動器] 真空吸料機 OFF
  3973. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  3974. print('data: ', data)
  3975. # mqtt_f(data)
  3976. # [致動器] 馬達 0
  3977. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  3978. print('data: ', data)
  3979. # mqtt_f(data)
  3980. # [致動器] 入料三通閥 ON排氣
  3981. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "on" }
  3982. print('data: ', data)
  3983. # mqtt_f(data)
  3984. # print('------- ', tid,' 狀態更新:入料完成 -------')
  3985. print('------- ', tid,' 狀態更新:可出豆 -------')
  3986. # (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height) AND FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height):
  3987. def FInputtingBean_AND_notfilled(tid):
  3988. # [致動器] 蝴蝶閥 OFF
  3989. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
  3990. print('data: ', data)
  3991. # mqtt_f(data)
  3992. # [致動器] 入料三通閥 OFF入豆
  3993. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  3994. print('data: ', data)
  3995. # mqtt_f(data)
  3996. # [致動器] 真空吸料機 ON
  3997. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "on" }
  3998. print('data: ', data)
  3999. # mqtt_f(data)
  4000. timer = time.time()
  4001. while True:
  4002. if (time.time() - timer) > Ferment_Tank_vacuumON_time:
  4003. # [致動器] 入料真空吸料機 OFF
  4004. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  4005. print('data: ', data)
  4006. # mqtt_f(data)
  4007. timer = time.time()
  4008. break
  4009. while True:
  4010. if (time.time() - timer) > Ferment_Tank_vacuumOFF_time:
  4011. break
  4012. # (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height) AND FI1 != 'FI_OutputtingBean'
  4013. def FInputtingBean_TO_FInputtingBeanPause(tid):
  4014. # [致動器] 蝴蝶閥 OFF
  4015. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
  4016. print('data: ', data)
  4017. # mqtt_f(data)
  4018. # [致動器] 真空吸料機 OFF
  4019. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  4020. print('data: ', data)
  4021. # mqtt_f(data)
  4022. # [致動器] 入料三通閥 OFF入豆
  4023. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  4024. print('data: ', data)
  4025. # mqtt_f(data)
  4026. # [致動器] 馬達 0
  4027. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  4028. print('data: ', data)
  4029. # mqtt_f(data)
  4030. print('------- ', tid,' 狀態更新:入豆暫停 -------')
  4031. # FermentUp_InputtingBeanPause_number == 1 and FI1 == 'FI_OutputtingBean'
  4032. # if F1 == 'F_InputtingBean_Pause' AND FI1 == 'FI_OutputtingBean'
  4033. def FInputtingBeanPause_AND_FIOutputtingBean(tid):
  4034. # [致動器] 入料三通閥 OFF入豆
  4035. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  4036. print('data: ', data)
  4037. # mqtt_f(data)
  4038. # [致動器] 馬達 5
  4039. data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
  4040. print('data: ', data)
  4041. # mqtt_f(data)
  4042. print('------- ', tid, ' 狀態更新:入料中 -------')
  4043. # elif FermentUp_InputtingBean_number == 0 and FermentUp_InputtingBeanPause_number == 0 and FI1 == 'FI_OutputtingBean' and FermentUp_Waiting_number >= 1
  4044. def FWaiting_TO_FInputtingBean(tid):
  4045. # [致動器] 蝴蝶閥 OFF
  4046. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
  4047. print('data: ', data)
  4048. # mqtt_f(data)
  4049. # [致動器] 入料三通閥 OFF入豆
  4050. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  4051. print('data: ', data)
  4052. # mqtt_f(data)
  4053. # [致動器] 馬達 5
  4054. data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
  4055. print('data: ', data)
  4056. # mqtt_f(data)
  4057. print('------- ', tid, ' 狀態更新:入料中 -------')
  4058. # elif FermentUp_InputtingWater_number == 0 and FermentUp_InputtingBeanFinish_number >= 1:
  4059. def FInputtingBeanFinish_TO_FInputtingWater_UP(tid, sn):
  4060. print('------- ', tid,' 狀態更新:入水中 -------')
  4061. # # [致動器] 浮選三通閥 ON
  4062. # data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "on" }
  4063. # print('data: ', data)
  4064. # # # mqtt_f(data)
  4065. # if (F_UP_tank_WaterLevel[sn] == 0):
  4066. # # [致動器] 桶外進水電磁閥 ON
  4067. # data = { "tank_num": tid, "command": "outer_solenoid_water_status", "value": "on" }
  4068. # print('data: ', data)
  4069. # # mqtt_f(data)
  4070. if (F_UP_UltraSoniclist[sn] < Ferment_Tank_water_height):
  4071. # 桶內高度若低於水位指定高度, [致動器] 桶內進水電磁閥 ON
  4072. data = { "tank_num": tid, "command": "tank_solenoid_water_in_status", "value": "on" }
  4073. print('data: ', data)
  4074. # mqtt_f(data)
  4075. # elif FermentUp_InputtingWater_number == 1:
  4076. # 'F_InputtingWater' if (F_UP_tank_WaterLevel[0] == 1) and (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height):
  4077. def FInputtingWater_TO_FFermenting(tid):
  4078. # 若夾層入水達水位計高度 且 桶內入水達指定水位高度, 狀態轉換為發酵中
  4079. # 桶外水位高度高於水位計高度, [致動器] 桶外進水電磁閥 OFF
  4080. # data = { "tank_num": tid, "command": "outer_solenoid_water_status", "value": "off" }
  4081. # print('data: ', data)
  4082. # # mqtt_f(data)
  4083. # 桶內高度若高於水位指定高度, [致動器] 桶內進水電磁閥 OFF
  4084. data = { "tank_num": tid, "command": "tank_solenoid_water_in_status", "value": "off" }
  4085. print('data: ', data)
  4086. # mqtt_f(data)
  4087. print('------- ', tid, ' 狀態更新:發酵中 -------')
  4088. # [致動器] 馬達 (指定轉速)
  4089. data = { "tank_num": tid, "command": "tank_motor_status", "value": Ferment_Tank_motor_rpm }
  4090. print('data: ', data)
  4091. # mqtt_f(data)
  4092. # [致動器] 溫控開關 ON
  4093. # data = { "tank_num": tid, "command": "tank_temp_enable", "value": "on", "duration": Ferment_Tank_fermenting_time}
  4094. # print('data: ', data)
  4095. # # mqtt_f(data)
  4096. # [致動器] 設定溫度、持溫時間
  4097. # [致動器] 加熱器 1 ON
  4098. # data = { "tank_num": tid, "command": "tank_heater1_status", "value": "on" }
  4099. # print('data: ', data)
  4100. # mqtt_f(data)
  4101. # [致動器] 加熱器 2 ON
  4102. # data = { "tank_num": tid, "command": "tank_heater2_status", "value": "on" }
  4103. # print('data: ', data)
  4104. # mqtt_f(data)
  4105. # # [致動器] 雙核薄膜泵 水質檢測 ON
  4106. # data = { "tank_num": tid, "command": "tank_pump_sensor_status", "value": "on"}
  4107. # print('data: ', data)
  4108. # # mqtt_f(data)
  4109. # TODO 增加發酵條件等
  4110. # 'F_InputtingWater' AND (F_UP_tank_WaterLevel[0] == 1)
  4111. def FInputtingWater_AND_WaterLevel1(tid):
  4112. # # [致動器] 桶外進水電磁閥 OFF
  4113. # data = { "tank_num": tid, "command": "outer_solenoid_water_status", "value": "off" }
  4114. # print('data: ', data)
  4115. # # mqtt_f(data)
  4116. pass
  4117. # 'F_InputtingWater' AND (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height)
  4118. def FInputtingWater_AND_tankwaterfilled(tid):
  4119. # 桶內高度若高於水位指定高度, [致動器] 桶內進水電磁閥 OFF
  4120. data = { "tank_num": tid, "command": "tank_solenoid_water_in_status", "value": "off" }
  4121. print('data: ', data)
  4122. # mqtt_f(data)
  4123. # else
  4124. # F1 == 'F_Fermenting' and F_UP_tank_SHT11_Temp[0] >= Ferment_Tank_fermenting_temp and F_UP_tank_PH[0] <= Ferment_Tank_fermenting_pH:
  4125. def FFermenting_TO_FOutputtingBean(tid):
  4126. print(tid, ' 發酵等待 ', Ferment_Tank_fermenting_time, ' 秒')
  4127. timer = time.time()
  4128. while True:
  4129. if (time.time() - timer) > Ferment_Tank_fermenting_time :
  4130. # [致動器] 外桶浮選三通閥 OFF
  4131. data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "off" }
  4132. print('data: ', data)
  4133. # mqtt_f(data)
  4134. # [致動器] 馬達 0
  4135. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  4136. print('data: ', data)
  4137. # mqtt_f(data)
  4138. # [致動器] 設定溫度 0
  4139. # data = { "tank_num": tid, "command": "tank_temp", "value": "0" }
  4140. # print('data: ', data)
  4141. # # mqtt_f(data)
  4142. # [致動器] 溫控開關 OFF
  4143. # data = { "tank_num": tid, "command": "tank_temp_enable", "value": "off" }
  4144. # print('data: ', data)
  4145. # # mqtt_f(data)
  4146. # [致動器] 加熱器 1 OFF
  4147. data = { "tank_num": tid, "command": "tank_heater1_status", "value": "off" }
  4148. print('data: ', data)
  4149. # mqtt_f(data)
  4150. # [致動器] 加熱器 2 OFF
  4151. data = { "tank_num": tid, "command": "tank_heater2_status", "value": "off" }
  4152. print('data: ', data)
  4153. # mqtt_f(data)
  4154. # # [致動器] 雙核薄膜泵 水質檢測 OFF
  4155. # data = { "tank_num": tid, "command": "tank_pump_sensor_status", "value": "off"}
  4156. # print('data: ', data)
  4157. # # mqtt_f(data)
  4158. # TODO 增加發酵條件等
  4159. break
  4160. # [致動器] 廢水排水閥 (桶內) ON
  4161. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "on" }
  4162. print('data: ', data)
  4163. # mqtt_f(data)
  4164. print(tid, '桶內廢水排水 ', Ferment_Tank_WaterOut_time, ' 秒')
  4165. timer = time.time()
  4166. while True:
  4167. if (time.time() - timer) > Ferment_Tank_WaterOut_time:
  4168. # [致動器] 廢水排水閥 (桶內) OFF
  4169. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  4170. print('data: ', data)
  4171. # mqtt_f(data)
  4172. break
  4173. print('------- ', tid, ' 狀態更新:可出豆 -------')
  4174. # else: if F1 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[0] <= Ferment_Tank_bean_empty):
  4175. def FOutputtingBean_TO_FWaiting(tid):
  4176. # [致動器] F1 蝴蝶閥 ON
  4177. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "on" }
  4178. print('data: ', data)
  4179. # mqtt_f(data)
  4180. # ----- 發酵排程動作 end ------------------------------------------------------------------
  4181. # [介面] 若啟用 發酵 狀態
  4182. if Ferment_btn:
  4183. # ----- 發酵桶槽 F1~F6 入料桶槽優先入料判斷 ------------------------------
  4184. # 若 F1~F6 桶槽中有一個桶槽入豆中
  4185. if FermentUp_InputtingBean_number == 1:
  4186. # 若 F1 桶槽為入豆中
  4187. if F1 == 'F_InputtingBean':
  4188. if (F_UP_UltraSoniclist[0] >= Ferment_Tank_bean_height):
  4189. FInputtingBean_TO_FInputtingBeanFinish("F1")
  4190. # F1 = 'F_InputtingBean_Finish'
  4191. F1 = 'F_OutputtingBean'
  4192. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height):
  4193. FInputtingBean_AND_notfilled("F1")
  4194. elif FI1 != 'FI_OutputtingBean':
  4195. FInputtingBean_TO_FInputtingBeanPause("F1")
  4196. F1 = 'F_InputtingBean_Pause'
  4197. # 若 F1~F6 桶槽中有一個桶槽入豆暫停中, 且 FI1 可出豆
  4198. elif FermentUp_InputtingBeanPause_number == 1 and FI1 == 'FI_OutputtingBean':
  4199. # 若 F1 桶槽為入豆暫停 且 FI1 可出料
  4200. if F1 == 'F_InputtingBean_Pause':
  4201. FInputtingBeanPause_AND_FIOutputtingBean("F1")
  4202. F1 = 'F_InputtingBean'
  4203. # 若 F1~F6 桶槽中 無桶槽正在入料或入料等待, 且 FI1 可出豆時
  4204. elif FermentUp_InputtingBean_number == 0 and FermentUp_InputtingBeanPause_number == 0 and FI1 == 'FI_OutputtingBean' and FermentUp_Waiting_number >= 1:
  4205. if F1 == 'F_Waiting':
  4206. FWaiting_TO_FInputtingBean("F1")
  4207. F1 = 'F_InputtingBean'
  4208. # 若 F1~F6 桶槽中 無桶槽正在入水, 則入豆完成者轉換狀態 開始入水
  4209. elif FermentUp_InputtingWater_number == 0 and FermentUp_InputtingBeanFinish_number >= 1:
  4210. if F1 == 'F_InputtingBean_Finish':
  4211. F1 = 'F_InputtingWater'
  4212. FInputtingBeanFinish_TO_FInputtingWater_UP("F1", 0)
  4213. elif FermentUp_InputtingWater_number == 1:
  4214. if F1 == 'F_InputtingWater':
  4215. if (F_UP_tank_WaterLevel[0] == 1) and (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height):
  4216. F1 = 'F_Fermenting'
  4217. FInputtingWater_TO_FFermenting("F1")
  4218. elif (F_UP_tank_WaterLevel[0] == 1):
  4219. FInputtingWater_AND_WaterLevel1("F1")
  4220. elif (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height):
  4221. FInputtingWater_AND_tankwaterfilled("F1")
  4222. else:
  4223. if F1 == 'F_Fermenting' and F_UP_tank_SHT11_Temp[0] >= Ferment_Tank_fermenting_temp:
  4224. FFermenting_TO_FOutputtingBean("F1")
  4225. F1 = 'F_OutputtingBean'
  4226. # 將可出豆桶槽賦值
  4227. if FOutputtingBean_Tank == '': FOutputtingBean_Tank = 'F1'
  4228. # 若桶槽 F1~F6 可出豆 且 桶槽內為空桶 且 有指定清洗排程, 進行清洗桶槽
  4229. # TODO 發酵次數計算、消毒次數、校正
  4230. if F1 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[0] <= Ferment_Tank_bean_empty):
  4231. if FOutputtingBean_Tank == 'F1':
  4232. FOutputtingBean_TO_FWaiting('F1')
  4233. FOutputtingBean_Tank = ''
  4234. F1 = 'F_Waiting'
  4235. print('------- F1 狀態更新:空桶等待 -------')
  4236. # 避免桶槽可出豆時未賦值
  4237. if FOutputtingBean_Tank == '':
  4238. if F1 == 'F_OutputtingBean': FOutputtingBean_Tank = 'F1'
  4239. # 若桶槽 F1~F6 為清洗中
  4240. if F1 == 'F_Cleaning':
  4241. # FCleaning("F1")
  4242. F1 = 'F_Waiting'
  4243. print('------- F1 狀態更新:空桶等待 -------')
  4244. # # ----- [測試用] !!!!! F1~F6 入料完成→可出豆 判斷 ------------------------------
  4245. # if F1 == 'F_InputtingBean_Finish': F1 = 'F_OutputtingBean'
  4246. # if F2 == 'F_InputtingBean_Finish': F2 = 'F_OutputtingBean'
  4247. # if F3 == 'F_InputtingBean_Finish': F3 = 'F_OutputtingBean'
  4248. # if F4 == 'F_InputtingBean_Finish': F4 = 'F_OutputtingBean'
  4249. # if F5 == 'F_InputtingBean_Finish': F5 = 'F_OutputtingBean'
  4250. # if F6 == 'F_InputtingBean_Finish': F6 = 'F_OutputtingBean'
  4251. # # ----- [測試用] !!!!! F1~F6 入料完成→可出豆 判斷 ------------------------------
  4252. else:
  4253. # [介面] 若未啟用 發酵 狀態
  4254. print('未啟用發酵流程')
  4255. # ----- 將狀態寫入資料庫 ------------------------------
  4256. # 獲取文本框的值並賦值給user實體對象
  4257. F_status = ferment_container_status()
  4258. F_status.Ferment_Input_1 = FI1
  4259. F_status.Ferment_Input_2 = FI2
  4260. F_status.Ferment_Tank_1 = F1
  4261. F_status.Ferment_Tank_2 = F2
  4262. F_status.Ferment_Tank_3 = F3
  4263. F_status.Ferment_Tank_4 = F4
  4264. F_status.Ferment_Tank_5 = F5
  4265. F_status.Ferment_Tank_6 = F6
  4266. F_status.Ferment_Tank_7 = F7
  4267. F_status.Ferment_Tank_8 = F8
  4268. F_status.Ferment_Tank_9 = F9
  4269. F_status.Ferment_Tank_10 = F10
  4270. F_status.Ferment_Tank_11 = F11
  4271. F_status.Ferment_Tank_12 = F12
  4272. F_status.Ferment_Output_1 = FO1
  4273. F_status.Ferment_Output_2 = FO2
  4274. #將數據保存進資料庫
  4275. db.session.add(F_status)
  4276. # 手動提交
  4277. db.session.commit()
  4278. # ----- 將狀態寫入資料庫 ------------------------------
  4279. return jsonify({"Ferment_Tank_1":F1,
  4280. "Ferment_Tank_2":F2
  4281. })
  4282. @main.route('/ferment_auto_status', methods=['GET', 'POST'])
  4283. def ferment_auto_test():
  4284. info = request.args.to_dict()
  4285. # 寫定入料、桶槽、出料的空桶標準, 若 <= 2 則為空桶
  4286. Ferment_Input_bean_empty = 2
  4287. Ferment_Tank_bean_empty = 2
  4288. Ferment_Output_bean_empty = 2
  4289. # 從介面取得 指定生豆高度/發酵桶槽排程:發酵、清洗、校正 EC、校正攪拌棒
  4290. FermentAuto_fermenting = int(info['FermentAuto_fermenting'])
  4291. FermentAuto_cleaning = int(info['FermentAuto_cleaning'])
  4292. FermentAuto_calibratingEC = int(info['FermentAuto_calibratingEC'])
  4293. FermentAuto_calibratingSTIR = int(info['FermentAuto_calibratingSTIR'])
  4294. Ferment_Input_bean_height = float(info['Ferment_Input_bean_height'])
  4295. Ferment_Input_vacuumON_time = float(info['Ferment_Input_vacuumON_time'])
  4296. Ferment_Input_vacuumOFF_time = float(info['Ferment_Input_vacuumOFF_time'])
  4297. Ferment_Tank_bean_height = float(info['Ferment_Tank_bean_height'])
  4298. Ferment_Tank_vacuumON_time = float(info['Ferment_Tank_vacuumON_time'])
  4299. Ferment_Tank_vacuumOFF_time = float(info['Ferment_Tank_vacuumOFF_time'])
  4300. Ferment_Tank_water_height = float(info['Ferment_Tank_water_height'])
  4301. Ferment_Tank_fermenting_temp = float(info['Ferment_Tank_fermenting_temp'])
  4302. Ferment_Tank_fermenting_time = float(info['Ferment_Tank_fermenting_time'])
  4303. Ferment_Tank_motor_rpm = float(info['Ferment_Tank_motor_rpm'])
  4304. Ferment_Tank_motor_time = float(info['Ferment_Tank_motor_time'])
  4305. Ferment_Tank_fermenting_pH = float(info['Ferment_Tank_fermenting_pH'])
  4306. Ferment_Output_bean_height = float(info['Ferment_Output_bean_height'])
  4307. Ferment_Output_vacuumON_time = float(info['Ferment_Output_vacuumON_time'])
  4308. Ferment_Output_vacuumOFF_time = float(info['Ferment_Output_vacuumOFF_time'])
  4309. Ferment_Tank_WaterOut_time = float(info['Ferment_Tank_WaterOut_time'])
  4310. Ferment_Tank_Disinfect_time = float(info['Ferment_Tank_Disinfect_time'])
  4311. Ferment_cb_vacuum = info['Ferment_cb_vacuum'] # 'true' 'false'
  4312. Ferment_cb_vacuum_time = float(info['Ferment_cb_vacuum_time'])
  4313. # [介面] 讓使用者可以選擇排程內有發酵/清洗/校正, 此處預設為 True
  4314. Ferment_btn = FermentAuto_fermenting # Ferment_btn = True
  4315. # 從資料庫資料表中取得最新狀態
  4316. ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  4317. FI1 = ferment_status.Ferment_Input_1
  4318. FI2 = ferment_status.Ferment_Input_2
  4319. F1 = ferment_status.Ferment_Tank_1
  4320. F2 = ferment_status.Ferment_Tank_2
  4321. F3 = ferment_status.Ferment_Tank_3
  4322. F4 = ferment_status.Ferment_Tank_4
  4323. F5 = ferment_status.Ferment_Tank_5
  4324. F6 = ferment_status.Ferment_Tank_6
  4325. F7 = ferment_status.Ferment_Tank_7
  4326. F8 = ferment_status.Ferment_Tank_8
  4327. F9 = ferment_status.Ferment_Tank_9
  4328. F10 = ferment_status.Ferment_Tank_10
  4329. F11 = ferment_status.Ferment_Tank_11
  4330. F12 = ferment_status.Ferment_Tank_12
  4331. FO1 = ferment_status.Ferment_Output_1
  4332. FO2 = ferment_status.Ferment_Output_2
  4333. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  4334. PO1 = clean_status.Peel_Output_1 # PO_Waiting # PO_OutputtingBean
  4335. PO2 = clean_status.Peel_Output_2
  4336. F_UP_tanklist = [F1, F2, F3, F4, F5, F6]
  4337. F_DOWN_tanklist = [F7, F8, F9, F10, F11, F12]
  4338. FOutputtingBean_Tank = '' # 這是給出料儲豆槽判斷目前出豆的桶槽
  4339. # 目前發酵槽 F1~F6 正在入豆、入水的桶槽數量 (應小於一桶)
  4340. FermentUp_Waiting_number = int(F_UP_tanklist.count('F_Waiting'))
  4341. FermentUp_InputtingBean_number = int(F_UP_tanklist.count('F_InputtingBean'))
  4342. FermentUp_InputtingBeanPause_number = int(F_UP_tanklist.count('F_InputtingBean_Pause'))
  4343. FermentUp_InputtingBeanFinish_number = int(F_UP_tanklist.count('F_InputtingBean_Finish'))
  4344. FermentUp_InputtingWater_number = int(F_UP_tanklist.count('F_InputtingWater'))
  4345. # -- 取得發酵 入料儲豆槽 FI1~FI2 / 桶槽 F1~F6 / 出料 FO1~FO2 桶內高度 UltraSonic start -------------
  4346. FI_UP_UltraSoniclist = []
  4347. for i in range(1, 3, 1):
  4348. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  4349. # UltraSonic = float("{:.2f}".format(34.6 - float(input_UltraSonic.UltraSonic)))
  4350. UltraSonic = float(input_UltraSonic.UltraSonic)
  4351. FI_UP_UltraSoniclist.append(UltraSonic)
  4352. print('FI_UP_UltraSoniclist: ', FI_UP_UltraSoniclist)
  4353. F_UP_UltraSoniclist = []
  4354. for i in range(1, 7, 1):
  4355. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  4356. UltraSonic = (float(tank_UltraSonic.UltraSonic))
  4357. F_UP_UltraSoniclist.append(UltraSonic)
  4358. print('F_UP_UltraSoniclist: ', F_UP_UltraSoniclist)
  4359. FO_UP_UltraSoniclist = []
  4360. for i in range(1, 3, 1):
  4361. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO' + str(i)).order_by(text('datetime desc')).first()
  4362. UltraSonic = float(output_UltraSonic.UltraSonic)
  4363. FO_UP_UltraSoniclist.append(UltraSonic)
  4364. print('FO_UP_UltraSoniclist: ', FO_UP_UltraSoniclist)
  4365. # -- 取得發酵 入料儲豆槽 FI1~FI2 / 桶槽 F1~F6 / 出料 FO1~FO2 桶內高度 UltraSonic end -------------
  4366. # -- 取得發酵桶槽 F1~F6 夾層水位高度 WaterLevel start -------------
  4367. F_UP_tank_WaterLevel = []
  4368. for i in range(1, 7, 1):
  4369. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  4370. WaterLevel = float(tank_WaterLevel.WaterLevel)
  4371. F_UP_tank_WaterLevel.append(WaterLevel)
  4372. print('F_UP_tank_WaterLevel: ', F_UP_tank_WaterLevel)
  4373. # -- 取得發酵桶槽 F1~F6 夾層水位高度 WaterLevel end -------------
  4374. # -- 取得發酵桶槽 F1~F6 pH -------------
  4375. F_UP_tank_PH = []
  4376. for i in range(1, 7, 1):
  4377. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  4378. PH = float(tank_PH.PH)
  4379. F_UP_tank_PH.append(PH)
  4380. print('F_UP_tank_PH: ', F_UP_tank_PH)
  4381. # -- 取得發酵桶槽 F1~F6 pH -------------
  4382. # -- 取得發酵桶槽 F1~F6 SHT11_TEMP -------------
  4383. F_UP_tank_SHT11_Temp = []
  4384. for i in range(1, 7, 1):
  4385. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  4386. SHT11_Temp = float(tank_SHT11.SHT11_Temp)
  4387. F_UP_tank_SHT11_Temp.append(SHT11_Temp)
  4388. print('F_UP_tank_SHT11_Temp: ', F_UP_tank_SHT11_Temp)
  4389. # -- 取得發酵桶槽 F1~F6 SHT11_TEMP -------------
  4390. # ----- 發酵排程動作 start ------------------------------------------------------------------
  4391. # FI1 == 'FI_InputtingBean' AND if (FI_UP_UltraSoniclist[0] >= Ferment_Input_bean_height):
  4392. def FIInputtingBean_filled(tid):
  4393. # [致動器] 入料真空吸料機 OFF
  4394. data = { "tank_num": tid, "command": "input_vacuum_status", "value": "off" }
  4395. print('data: ', data)
  4396. # mqtt_f(data)
  4397. print('------- ', tid, ' 狀態更新:可出豆 -------')
  4398. # FI1 == 'FI_InputtingBean' AND elif (FI_UP_UltraSoniclist[0] < Ferment_Input_bean_height) and PO1 == 'PO_OutputtingBean':
  4399. def FIInputtingBean_AND_notfilled(tid):
  4400. # [致動器] 入料真空吸料機 ON
  4401. data = { "tank_num": tid, "command": "input_vacuum_status", "value": "on" }
  4402. print('data: ', data)
  4403. # mqtt_f(data)
  4404. # 暫停 (指定吸料時間) 秒
  4405. time.sleep(Ferment_Input_vacuumON_time)
  4406. # [致動器] 入料真空吸料機 OFF
  4407. data = { "tank_num": tid, "command": "input_vacuum_status", "value": "off" }
  4408. print('data: ', data)
  4409. # mqtt_f(data)
  4410. # 暫停 (指定放料時間) 秒
  4411. time.sleep(Ferment_Input_vacuumOFF_time)
  4412. # F1 == 'F_InputtingBean' AND (F_UP_UltraSoniclist[0] >= Ferment_Tank_bean_height):
  4413. def FInputtingBean_TO_FInputtingBeanFinish(tid):
  4414. # [致動器] 真空吸料機 OFF
  4415. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  4416. print('data: ', data)
  4417. # mqtt_f(data)
  4418. # [致動器] 馬達 0
  4419. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  4420. print('data: ', data)
  4421. # mqtt_f(data)
  4422. # [致動器] 入料三通閥 ON排氣
  4423. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "on" }
  4424. print('data: ', data)
  4425. # mqtt_f(data)
  4426. print('------- ', tid,' 狀態更新:入料完成 -------')
  4427. # (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height) AND FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height):
  4428. def FInputtingBean_AND_notfilled(tid):
  4429. # [致動器] 入料三通閥 OFF入豆
  4430. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  4431. print('data: ', data)
  4432. # mqtt_f(data)
  4433. # [致動器] 真空吸料機 ON
  4434. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "on" }
  4435. print('data: ', data)
  4436. # mqtt_f(data)
  4437. # 暫停 (指定吸料時間) 秒
  4438. time.sleep(Ferment_Tank_vacuumON_time)
  4439. # [致動器] 入料真空吸料機 OFF
  4440. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  4441. print('data: ', data)
  4442. # mqtt_f(data)
  4443. # 暫停 (指定吸料時間) 秒
  4444. time.sleep(Ferment_Tank_vacuumOFF_time)
  4445. # # [致動器] 真空吸料機 ON
  4446. # data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "on" }
  4447. # print('data: ', data)
  4448. # # mqtt_f(data)
  4449. # timer = time.time()
  4450. # while True:
  4451. # if (time.time() - timer) > Ferment_Tank_vacuumON_time:
  4452. # # [致動器] 入料真空吸料機 OFF
  4453. # data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  4454. # print('data: ', data)
  4455. # # mqtt_f(data)
  4456. # timer = time.time()
  4457. # break
  4458. # while True:
  4459. # if (time.time() - timer) > Ferment_Tank_vacuumOFF_time:
  4460. # break
  4461. # (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height) AND FI1 != 'FI_OutputtingBean'
  4462. def FInputtingBean_TO_FInputtingBeanPause(tid):
  4463. # [致動器] 真空吸料機 OFF
  4464. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  4465. print('data: ', data)
  4466. # mqtt_f(data)
  4467. # [致動器] 入料三通閥 OFF入豆
  4468. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  4469. print('data: ', data)
  4470. # mqtt_f(data)
  4471. # [致動器] 馬達 0
  4472. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  4473. print('data: ', data)
  4474. # mqtt_f(data)
  4475. print('------- ', tid,' 狀態更新:入豆暫停 -------')
  4476. # FermentUp_InputtingBeanPause_number == 1 and FI1 == 'FI_OutputtingBean'
  4477. # if F1 == 'F_InputtingBean_Pause' AND FI1 == 'FI_OutputtingBean'
  4478. def FInputtingBeanPause_AND_FIOutputtingBean(tid):
  4479. # [致動器] 入料三通閥 OFF入豆
  4480. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  4481. print('data: ', data)
  4482. # mqtt_f(data)
  4483. # [致動器] 馬達 5
  4484. data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
  4485. print('data: ', data)
  4486. # mqtt_f(data)
  4487. print('------- ', tid, ' 狀態更新:入料中 -------')
  4488. # elif FermentUp_InputtingBean_number == 0 and FermentUp_InputtingBeanPause_number == 0 and FI1 == 'FI_OutputtingBean' and FermentUp_Waiting_number >= 1
  4489. def FWaiting_TO_FInputtingBean(tid):
  4490. # [致動器] 入料三通閥 OFF入豆
  4491. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  4492. print('data: ', data)
  4493. # mqtt_f(data)
  4494. # [致動器] 馬達 5
  4495. data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
  4496. print('data: ', data)
  4497. # mqtt_f(data)
  4498. print('------- ', tid, ' 狀態更新:入料中 -------')
  4499. # elif FermentUp_InputtingWater_number == 0 and FermentUp_InputtingBeanFinish_number >= 1:
  4500. def FInputtingBeanFinish_TO_FInputtingWater_UP(tid, sn):
  4501. print('------- ', tid,' 狀態更新:入水中 -------')
  4502. # [致動器] 浮選三通閥 ON
  4503. data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "on" }
  4504. print('data: ', data)
  4505. # mqtt_f(data)
  4506. if (F_UP_tank_WaterLevel[sn] == 0):
  4507. # [致動器] 桶外進水電磁閥 ON
  4508. data = { "tank_num": tid, "command": "outer_solenoid_water_status", "value": "on" }
  4509. print('data: ', data)
  4510. # mqtt_f(data)
  4511. if (F_UP_UltraSoniclist[sn] < Ferment_Tank_water_height):
  4512. # 桶內高度若低於水位指定高度, [致動器] 桶內進水電磁閥 ON
  4513. data = { "tank_num": tid, "command": "tank_solenoid_water_in_status", "value": "on" }
  4514. print('data: ', data)
  4515. # mqtt_f(data)
  4516. # elif FermentUp_InputtingWater_number == 1:
  4517. # 'F_InputtingWater' if (F_UP_tank_WaterLevel[0] == 1) and (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height):
  4518. def FInputtingWater_TO_FFermenting(tid):
  4519. # 若夾層入水達水位計高度 且 桶內入水達指定水位高度, 狀態轉換為發酵中
  4520. # 桶外水位高度高於水位計高度, [致動器] 桶外進水電磁閥 OFF
  4521. data = { "tank_num": tid, "command": "outer_solenoid_water_status", "value": "off" }
  4522. print('data: ', data)
  4523. # mqtt_f(data)
  4524. # 桶內高度若高於水位指定高度, [致動器] 桶內進水電磁閥 OFF
  4525. data = { "tank_num": tid, "command": "tank_solenoid_water_in_status", "value": "off" }
  4526. print('data: ', data)
  4527. # mqtt_f(data)
  4528. print('------- ', tid, ' 狀態更新:發酵中 -------')
  4529. # 若勾選 發酵時桶內抽真空?
  4530. if Ferment_cb_vacuum == 'true':
  4531. # [致動器] 入料三通閥 ON排氣
  4532. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "on" }
  4533. print('data: ', data)
  4534. # mqtt_f(data)
  4535. # [致動器] 外桶浮選三通閥 OFF
  4536. data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "off" }
  4537. print('data: ', data)
  4538. # mqtt_f(data)
  4539. # [致動器] 真空吸料機 ON
  4540. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "on" }
  4541. print('data: ', data)
  4542. # mqtt_f(data)
  4543. # 暫停 (桶內抽氣時間) 秒
  4544. print(tid, '真空發酵, 桶槽抽氣 ' , Ferment_cb_vacuum_time, ' 秒')
  4545. time.sleep(Ferment_cb_vacuum_time)
  4546. # timer = time.time()
  4547. # while True:
  4548. # if (time.time() - timer) > Ferment_cb_vacuum_time:
  4549. # # [致動器] 入料真空吸料機 OFF
  4550. # data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  4551. # print('data: ', data)
  4552. # # mqtt_f(data)
  4553. # break
  4554. # [致動器] 馬達 (指定轉速)
  4555. data = { "tank_num": tid, "command": "tank_motor_status", "value": Ferment_Tank_motor_rpm }
  4556. print('data: ', data)
  4557. # mqtt_f(data)
  4558. # [致動器] 溫控開關 ON
  4559. # data = { "tank_num": tid, "command": "tank_temp_enable", "value": "on", "duration": Ferment_Tank_fermenting_time}
  4560. # print('data: ', data)
  4561. # # mqtt_f(data)
  4562. # [致動器] 設定溫度、持溫時間
  4563. # [致動器] 加熱器 1 ON
  4564. data = { "tank_num": tid, "command": "tank_heater1_status", "value": "on" }
  4565. print('data: ', data)
  4566. # mqtt_f(data)
  4567. # [致動器] 加熱器 2 ON
  4568. data = { "tank_num": tid, "command": "tank_heater2_status", "value": "on" }
  4569. print('data: ', data)
  4570. # mqtt_f(data)
  4571. # [致動器] 雙核薄膜泵 水質檢測 ON
  4572. data = { "tank_num": tid, "command": "tank_pump_sensor_status", "value": "on"}
  4573. print('data: ', data)
  4574. # mqtt_f(data)
  4575. # TODO 增加發酵條件等
  4576. # 'F_InputtingWater' AND (F_UP_tank_WaterLevel[0] == 1)
  4577. def FInputtingWater_AND_WaterLevel1(tid):
  4578. # [致動器] 桶外進水電磁閥 OFF
  4579. data = { "tank_num": tid, "command": "outer_solenoid_water_status", "value": "off" }
  4580. print('data: ', data)
  4581. # mqtt_f(data)
  4582. # 'F_InputtingWater' AND (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height)
  4583. def FInputtingWater_AND_tankwaterfilled(tid):
  4584. # 桶內高度若高於水位指定高度, [致動器] 桶內進水電磁閥 OFF
  4585. data = { "tank_num": tid, "command": "tank_solenoid_water_in_status", "value": "off" }
  4586. print('data: ', data)
  4587. # mqtt_f(data)
  4588. # else
  4589. # F1 == 'F_Fermenting' and F_UP_tank_SHT11_Temp[0] >= Ferment_Tank_fermenting_temp and F_UP_tank_PH[0] <= Ferment_Tank_fermenting_pH:
  4590. def FFermenting_TO_FOutputtingBean(tid):
  4591. # 暫停 (桶內抽氣時間) 秒
  4592. print(tid, ' 發酵等待 ', Ferment_Tank_fermenting_time, ' 秒')
  4593. time.sleep(Ferment_Tank_fermenting_time)
  4594. # [致動器] 外桶浮選三通閥 OFF
  4595. data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "off" }
  4596. print('data: ', data)
  4597. # mqtt_f(data)
  4598. # [致動器] 馬達 0
  4599. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  4600. print('data: ', data)
  4601. # mqtt_f(data)
  4602. # [致動器] 設定溫度 0
  4603. data = { "tank_num": tid, "command": "tank_temp", "value": "0" }
  4604. print('data: ', data)
  4605. # mqtt_f(data)
  4606. # [致動器] 溫控開關 OFF
  4607. # data = { "tank_num": tid, "command": "tank_temp_enable", "value": "off" }
  4608. # print('data: ', data)
  4609. # # mqtt_f(data)
  4610. # [致動器] 加熱器 1 OFF
  4611. data = { "tank_num": tid, "command": "tank_heater1_status", "value": "off" }
  4612. print('data: ', data)
  4613. # mqtt_f(data)
  4614. # [致動器] 加熱器 2 OFF
  4615. data = { "tank_num": tid, "command": "tank_heater2_status", "value": "off" }
  4616. print('data: ', data)
  4617. # mqtt_f(data)
  4618. # [致動器] 雙核薄膜泵 水質檢測 OFF
  4619. data = { "tank_num": tid, "command": "tank_pump_sensor_status", "value": "off"}
  4620. print('data: ', data)
  4621. # mqtt_f(data)
  4622. # timer = time.time()
  4623. # while True:
  4624. # if (time.time() - timer) > Ferment_Tank_fermenting_time :
  4625. # # [致動器] 外桶浮選三通閥 OFF
  4626. # data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "off" }
  4627. # print('data: ', data)
  4628. # # mqtt_f(data)
  4629. # # [致動器] 馬達 0
  4630. # data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  4631. # print('data: ', data)
  4632. # # mqtt_f(data)
  4633. # # [致動器] 設定溫度 0
  4634. # data = { "tank_num": tid, "command": "tank_temp", "value": "0" }
  4635. # print('data: ', data)
  4636. # # mqtt_f(data)
  4637. # # [致動器] 溫控開關 OFF
  4638. # # data = { "tank_num": tid, "command": "tank_temp_enable", "value": "off" }
  4639. # # print('data: ', data)
  4640. # # # mqtt_f(data)
  4641. # # [致動器] 加熱器 1 OFF
  4642. # data = { "tank_num": tid, "command": "tank_heater1_status", "value": "off" }
  4643. # print('data: ', data)
  4644. # # mqtt_f(data)
  4645. # # [致動器] 加熱器 2 OFF
  4646. # data = { "tank_num": tid, "command": "tank_heater2_status", "value": "off" }
  4647. # print('data: ', data)
  4648. # # mqtt_f(data)
  4649. # # [致動器] 雙核薄膜泵 水質檢測 OFF
  4650. # data = { "tank_num": tid, "command": "tank_pump_sensor_status", "value": "off"}
  4651. # print('data: ', data)
  4652. # # mqtt_f(data)
  4653. # # TODO 增加發酵條件等
  4654. # break
  4655. # [致動器] 廢水排水閥 (桶內) ON
  4656. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "on" }
  4657. print('data: ', data)
  4658. # mqtt_f(data)
  4659. # 暫停 (桶內抽氣時間) 秒
  4660. print(tid, '桶內廢水排水 ', Ferment_Tank_WaterOut_time, ' 秒')
  4661. time.sleep(Ferment_Tank_WaterOut_time)
  4662. # [致動器] 廢水排水閥 (桶內) OFF
  4663. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  4664. print('data: ', data)
  4665. # mqtt_f(data)
  4666. # timer = time.time()
  4667. # while True:
  4668. # if (time.time() - timer) > Ferment_Tank_WaterOut_time:
  4669. # # [致動器] 廢水排水閥 (桶內) OFF
  4670. # data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  4671. # print('data: ', data)
  4672. # # mqtt_f(data)
  4673. # break
  4674. print('------- ', tid, ' 狀態更新:可出豆 -------')
  4675. # else: if F1 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[0] <= Ferment_Tank_bean_empty):
  4676. def FOutputtingBean_TO_FWaiting(tid):
  4677. # [致動器] F1 蝴蝶閥 ON
  4678. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "on" }
  4679. print('data: ', data)
  4680. # mqtt_f(data)
  4681. # F_Cleaning
  4682. def FCleaning(tid):
  4683. # [致動器] 浮選三通閥 OFF
  4684. data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "off" }
  4685. print('data: ', data)
  4686. # mqtt_f(data)
  4687. # [致動器] 逆洗雙核薄膜泵電磁閥 ON
  4688. data = { "tank_num": tid, "command": "solenoid_tank_pump_status", "value": "on" }
  4689. print('data: ', data)
  4690. # mqtt_f(data)
  4691. # [致動器] 馬達 10
  4692. data = { "tank_num": tid, "command": "tank_motor_status", "value": "10" }
  4693. print('data: ', data)
  4694. # mqtt_f(data)
  4695. # [致動器] 消毒電磁閥 ON
  4696. data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "on" }
  4697. print('data: ', data)
  4698. # mqtt_f(data)
  4699. # [致動器] 消毒抽水 Pump ON TODO
  4700. # 暫停 (消毒時間) 秒
  4701. print(tid, ' 桶內消毒 ', Ferment_Tank_Disinfect_time, ' 秒')
  4702. time.sleep(Ferment_Tank_Disinfect_time)
  4703. # [致動器] 消毒電磁閥 OFF
  4704. data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "off" }
  4705. print('data: ', data)
  4706. # mqtt_f(data)
  4707. # timer = time.time()
  4708. # while True:
  4709. # if (time.time() - timer) > Ferment_Tank_Disinfect_time :
  4710. # # [致動器] 消毒電磁閥 OFF
  4711. # data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "off" }
  4712. # print('data: ', data)
  4713. # # mqtt_f(data)
  4714. # break
  4715. # [致動器] 消毒抽水 Pump OFF TODO
  4716. # [致動器] 馬達 0
  4717. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  4718. print('data: ', data)
  4719. # mqtt_f(data)
  4720. # [致動器] 浮選三通閥 ON
  4721. data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "on" }
  4722. print('data: ', data)
  4723. # mqtt_f(data)
  4724. # [致動器] 逆洗雙核薄膜泵電磁閥 OFF
  4725. data = { "tank_num": tid, "command": "solenoid_tank_pump_status", "value": "off" }
  4726. print('data: ', data)
  4727. # mqtt_f(data)
  4728. # [致動器] 消毒電磁閥 OFF
  4729. data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "off" }
  4730. print('data: ', data)
  4731. # mqtt_f(data)
  4732. # [致動器] 廢水排水閥 (桶內) ON
  4733. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "on" }
  4734. print('data: ', data)
  4735. # mqtt_f(data)
  4736. print(tid, ' 桶內廢水排水 ', Ferment_Tank_WaterOut_time, ' 秒')
  4737. time.sleep(Ferment_Tank_WaterOut_time)
  4738. # [致動器] 廢水排水閥 (桶內) OFF
  4739. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  4740. print('data: ', data)
  4741. # mqtt_f(data)
  4742. # timer = time.time()
  4743. # while True:
  4744. # if (time.time() - timer) > Ferment_Tank_WaterOut_time:
  4745. # # [致動器] 廢水排水閥 (桶內) OFF
  4746. # data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  4747. # print('data: ', data)
  4748. # # mqtt_f(data)
  4749. # break
  4750. print('------- ', tid, ' 狀態更新:空桶等待 -------')
  4751. # elif FO1 == 'FO_InputtingBean' and FOutputtingBean_Tank != '': AND elif FO_UP_UltraSoniclist[0] < Ferment_Output_bean_height:
  4752. def FOInputtingBean_filled(tid):
  4753. # [致動器] 出料真空吸料機 ON
  4754. data = { "tank_num": FOutputtingBean_Tank, "command": "input_vacuum_status", "value": "on" }
  4755. print('data: ', data)
  4756. # mqtt_f(data)
  4757. # 暫停 (指定吸料時間) 秒
  4758. time.sleep(Ferment_Output_vacuumON_time)
  4759. # [致動器] 出料真空吸料機 OFF
  4760. data = { "tank_num": FOutputtingBean_Tank, "command": "input_vacuum_status", "value": "off" }
  4761. print('data: ', data)
  4762. # mqtt_f(data)
  4763. # 暫停 (指定放料時間) 秒
  4764. time.sleep(Ferment_Output_vacuumOFF_time)
  4765. # # [致動器] 出料真空吸料機 ON
  4766. # data = { "tank_num": FOutputtingBean_Tank, "command": "input_vacuum_status", "value": "on" }
  4767. # print('data: ', data)
  4768. # # mqtt_f(data)
  4769. # timer = time.time()
  4770. # while True:
  4771. # if (time.time() - timer) > Ferment_Output_vacuumON_time:
  4772. # # [致動器] 出料真空吸料機 OFF
  4773. # data = { "tank_num": FOutputtingBean_Tank, "command": "input_vacuum_status", "value": "off" }
  4774. # print('data: ', data)
  4775. # # mqtt_f(data)
  4776. # timer = time.time()
  4777. # break
  4778. # while True:
  4779. # if (time.time() - timer) > Ferment_Output_vacuumOFF_time:
  4780. # break
  4781. # ----- 發酵排程動作 end ------------------------------------------------------------------
  4782. # ----- 發酵入料儲豆槽 FI1~FI2 入豆→可出豆判斷 ------------------------------
  4783. # 入料儲豆槽等待中、且脫皮機儲豆槽可出豆時, 入料儲豆槽入豆
  4784. if FI1 == 'FI_Waiting' and PO1 == 'PO_OutputtingBean':
  4785. FI1 = 'FI_InputtingBean'
  4786. print('------- FI1 狀態更新:入豆中 -------')
  4787. # 入料儲豆槽入豆時
  4788. elif FI1 == 'FI_InputtingBean':
  4789. # 桶槽內達指定生豆高度時, 入料儲豆槽狀態轉為 可出豆
  4790. if (FI_UP_UltraSoniclist[0] >= Ferment_Input_bean_height):
  4791. FIInputtingBean_filled("FI1")
  4792. FI1 = 'FI_OutputtingBean'
  4793. # 桶槽內未達指定生豆高度, 且 前方 PO1 可出豆, 就執行入料動作
  4794. elif (FI_UP_UltraSoniclist[0] < Ferment_Input_bean_height) and PO1 == 'PO_OutputtingBean':
  4795. FI1_thread = threading.Thread(target=FIInputtingBean_AND_notfilled, args=["FI1"])
  4796. FI1_thread.start()
  4797. # 桶槽內大於空桶高度, 且 前方 PO1 非可出豆, 將狀態轉為可出豆
  4798. elif (FI_UP_UltraSoniclist[0] > Ferment_Input_bean_empty) and PO1 != 'PO_OutputtingBean':
  4799. FI1 = 'FI_OutputtingBean'
  4800. print('------- FI1 狀態更新:可出豆 -------')
  4801. # 桶槽內小於空桶高度, 且 前方 PO1 非可出豆, 將狀態轉為空桶等待
  4802. elif (FI_UP_UltraSoniclist[0] <= Ferment_Input_bean_empty) and PO1 != 'PO_OutputtingBean':
  4803. FI1 = 'FI_Waiting'
  4804. print('------- FI1 狀態更新:空桶等待 -------')
  4805. # 入料儲豆槽出豆時, 桶槽高度為 空桶高度時, 狀態轉為 空桶等待
  4806. elif FI1 == 'FI_OutputtingBean' and (FI_UP_UltraSoniclist[0] <= Ferment_Input_bean_empty):
  4807. FI1 = 'FI_Waiting'
  4808. print('------- FI1 狀態更新:空桶等待 -------')
  4809. # [介面] 若啟用 發酵 狀態
  4810. if Ferment_btn:
  4811. # ----- 發酵桶槽 F1~F6 入料桶槽優先入料判斷 ------------------------------
  4812. # 若 F1~F6 桶槽中有一個桶槽入豆中
  4813. if FermentUp_InputtingBean_number == 1:
  4814. # 若 F1 桶槽為入豆中
  4815. if F1 == 'F_InputtingBean':
  4816. if (F_UP_UltraSoniclist[0] >= Ferment_Tank_bean_height):
  4817. FInputtingBean_TO_FInputtingBeanFinish("F1")
  4818. F1 = 'F_InputtingBean_Finish'
  4819. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height):
  4820. F1_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F1"])
  4821. F1_thread.start()
  4822. elif FI1 != 'FI_OutputtingBean':
  4823. FInputtingBean_TO_FInputtingBeanPause("F1")
  4824. F1 = 'F_InputtingBean_Pause'
  4825. elif F2 == 'F_InputtingBean':
  4826. if (F_UP_UltraSoniclist[1] >= Ferment_Tank_bean_height):
  4827. FInputtingBean_TO_FInputtingBeanFinish("F2")
  4828. F2 = 'F_InputtingBean_Finish'
  4829. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[1] < Ferment_Tank_bean_height):
  4830. F2_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F2"])
  4831. F2_thread.start()
  4832. elif FI1 != 'FI_OutputtingBean':
  4833. FInputtingBean_TO_FInputtingBeanPause("F2")
  4834. F2 = 'F_InputtingBean_Pause'
  4835. elif F3 == 'F_InputtingBean':
  4836. if (F_UP_UltraSoniclist[2] >= Ferment_Tank_bean_height):
  4837. FInputtingBean_TO_FInputtingBeanFinish("F3")
  4838. F3 = 'F_InputtingBean_Finish'
  4839. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[2] < Ferment_Tank_bean_height):
  4840. F3_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F3"])
  4841. F3_thread.start()
  4842. elif FI1 != 'FI_OutputtingBean':
  4843. FInputtingBean_TO_FInputtingBeanPause("F3")
  4844. F3 = 'F_InputtingBean_Pause'
  4845. elif F4 == 'F_InputtingBean':
  4846. if (F_UP_UltraSoniclist[3] >= Ferment_Tank_bean_height):
  4847. FInputtingBean_TO_FInputtingBeanFinish("F4")
  4848. F4 = 'F_InputtingBean_Finish'
  4849. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[3] < Ferment_Tank_bean_height):
  4850. F4_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F4"])
  4851. F4_thread.start()
  4852. elif FI1 != 'FI_OutputtingBean':
  4853. FInputtingBean_TO_FInputtingBeanPause("F4")
  4854. F4 = 'F_InputtingBean_Pause'
  4855. elif F5 == 'F_InputtingBean':
  4856. if (F_UP_UltraSoniclist[4] >= Ferment_Tank_bean_height):
  4857. FInputtingBean_TO_FInputtingBeanFinish("F5")
  4858. F5 = 'F_InputtingBean_Finish'
  4859. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[4] < Ferment_Tank_bean_height):
  4860. F5_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F5"])
  4861. F5_thread.start()
  4862. elif FI1 != 'FI_OutputtingBean':
  4863. FInputtingBean_TO_FInputtingBeanPause("F5")
  4864. F5 = 'F_InputtingBean_Pause'
  4865. elif F6 == 'F_InputtingBean':
  4866. if (F_UP_UltraSoniclist[5] >= Ferment_Tank_bean_height):
  4867. FInputtingBean_TO_FInputtingBeanFinish("F6")
  4868. F6 = 'F_InputtingBean_Finish'
  4869. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[5] < Ferment_Tank_bean_height):
  4870. F6_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F6"])
  4871. F6_thread.start()
  4872. elif FI1 != 'FI_OutputtingBean':
  4873. FInputtingBean_TO_FInputtingBeanPause("F6")
  4874. F6 = 'F_InputtingBean_Pause'
  4875. # 若 F1~F6 桶槽中有一個桶槽入豆暫停中, 且 FI1 可出豆
  4876. elif FermentUp_InputtingBeanPause_number == 1 and FI1 == 'FI_OutputtingBean':
  4877. # 若 F1 桶槽為入豆暫停 且 FI1 可出料
  4878. if F1 == 'F_InputtingBean_Pause':
  4879. FInputtingBeanPause_AND_FIOutputtingBean("F1")
  4880. F1 = 'F_InputtingBean'
  4881. elif F2 == 'F_InputtingBean_Pause':
  4882. FInputtingBeanPause_AND_FIOutputtingBean("F2")
  4883. F2 = 'F_InputtingBean'
  4884. elif F3 == 'F_InputtingBean_Pause':
  4885. FInputtingBeanPause_AND_FIOutputtingBean("F3")
  4886. F3 = 'F_InputtingBean'
  4887. elif F4 == 'F_InputtingBean_Pause':
  4888. FInputtingBeanPause_AND_FIOutputtingBean("F4")
  4889. F4 = 'F_InputtingBean'
  4890. elif F5 == 'F_InputtingBean_Pause':
  4891. FInputtingBeanPause_AND_FIOutputtingBean("F5")
  4892. F5 = 'F_InputtingBean'
  4893. elif F6 == 'F_InputtingBean_Pause':
  4894. FInputtingBeanPause_AND_FIOutputtingBean("F6")
  4895. F6 = 'F_InputtingBean'
  4896. # 若 F1~F6 桶槽中, 兩個桶槽皆為 入料中, 則桶號小者優先入料
  4897. elif FermentUp_InputtingBean_number >= 2:
  4898. if F1 == 'F_InputtingBean':
  4899. if (F_UP_UltraSoniclist[0] >= Ferment_Tank_bean_height):
  4900. FInputtingBean_TO_FInputtingBeanFinish("F1")
  4901. F1 = 'F_InputtingBean_Finish'
  4902. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height):
  4903. F1_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F1"])
  4904. F1_thread.start()
  4905. elif FI1 != 'FI_OutputtingBean':
  4906. FInputtingBean_TO_FInputtingBeanPause("F1")
  4907. F1 = 'F_InputtingBean_Pause'
  4908. elif F2 == 'F_InputtingBean':
  4909. if (F_UP_UltraSoniclist[1] >= Ferment_Tank_bean_height):
  4910. FInputtingBean_TO_FInputtingBeanFinish("F2")
  4911. F2 = 'F_InputtingBean_Finish'
  4912. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[1] < Ferment_Tank_bean_height):
  4913. F2_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F2"])
  4914. F2_thread.start()
  4915. elif FI1 != 'FI_OutputtingBean':
  4916. FInputtingBean_TO_FInputtingBeanPause("F2")
  4917. F2 = 'F_InputtingBean_Pause'
  4918. elif F3 == 'F_InputtingBean':
  4919. if (F_UP_UltraSoniclist[2] >= Ferment_Tank_bean_height):
  4920. FInputtingBean_TO_FInputtingBeanFinish("F3")
  4921. F3 = 'F_InputtingBean_Finish'
  4922. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[2] < Ferment_Tank_bean_height):
  4923. F3_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F3"])
  4924. F3_thread.start()
  4925. elif FI1 != 'FI_OutputtingBean':
  4926. FInputtingBean_TO_FInputtingBeanPause("F3")
  4927. F3 = 'F_InputtingBean_Pause'
  4928. elif F4 == 'F_InputtingBean':
  4929. if (F_UP_UltraSoniclist[3] >= Ferment_Tank_bean_height):
  4930. FInputtingBean_TO_FInputtingBeanFinish("F4")
  4931. F4 = 'F_InputtingBean_Finish'
  4932. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[3] < Ferment_Tank_bean_height):
  4933. F4_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F4"])
  4934. F4_thread.start()
  4935. elif FI1 != 'FI_OutputtingBean':
  4936. FInputtingBean_TO_FInputtingBeanPause("F4")
  4937. F4 = 'F_InputtingBean_Pause'
  4938. elif F5 == 'F_InputtingBean':
  4939. if (F_UP_UltraSoniclist[4] >= Ferment_Tank_bean_height):
  4940. FInputtingBean_TO_FInputtingBeanFinish("F5")
  4941. F5 = 'F_InputtingBean_Finish'
  4942. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[4] < Ferment_Tank_bean_height):
  4943. F5_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F5"])
  4944. F5_thread.start()
  4945. elif FI1 != 'FI_OutputtingBean':
  4946. FInputtingBean_TO_FInputtingBeanPause("F5")
  4947. F5 = 'F_InputtingBean_Pause'
  4948. elif F6 == 'F_InputtingBean':
  4949. if (F_UP_UltraSoniclist[5] >= Ferment_Tank_bean_height):
  4950. FInputtingBean_TO_FInputtingBeanFinish("F6")
  4951. F6 = 'F_InputtingBean_Finish'
  4952. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[5] < Ferment_Tank_bean_height):
  4953. F6_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F6"])
  4954. F6_thread.start()
  4955. elif FI1 != 'FI_OutputtingBean':
  4956. FInputtingBean_TO_FInputtingBeanPause("F6")
  4957. F6 = 'F_InputtingBean_Pause'
  4958. # 若 F1~F6 桶槽中, 兩個桶槽皆為 入料暫停中, 則桶號小者優先入料
  4959. elif FermentUp_InputtingBeanPause_number >= 2 and FI1 == 'FI_OutputtingBean':
  4960. # 若 F1 桶槽為入豆暫停 且 FI1 可出料
  4961. if F1 == 'F_InputtingBean_Pause':
  4962. FInputtingBeanPause_AND_FIOutputtingBean("F1")
  4963. F1 = 'F_InputtingBean'
  4964. elif F2 == 'F_InputtingBean_Pause':
  4965. FInputtingBeanPause_AND_FIOutputtingBean("F2")
  4966. F2 = 'F_InputtingBean'
  4967. elif F3 == 'F_InputtingBean_Pause':
  4968. FInputtingBeanPause_AND_FIOutputtingBean("F3")
  4969. F3 = 'F_InputtingBean'
  4970. elif F4 == 'F_InputtingBean_Pause':
  4971. FInputtingBeanPause_AND_FIOutputtingBean("F4")
  4972. F4 = 'F_InputtingBean'
  4973. elif F5 == 'F_InputtingBean_Pause':
  4974. FInputtingBeanPause_AND_FIOutputtingBean("F5")
  4975. F5 = 'F_InputtingBean'
  4976. elif F6 == 'F_InputtingBean_Pause':
  4977. FInputtingBeanPause_AND_FIOutputtingBean("F6")
  4978. F6 = 'F_InputtingBean'
  4979. # 若 F1~F6 桶槽中 無桶槽正在入料或入料等待, 且 FI1 可出豆時
  4980. elif FermentUp_InputtingBean_number == 0 and FermentUp_InputtingBeanPause_number == 0 and FI1 == 'FI_OutputtingBean' and FermentUp_Waiting_number >= 1:
  4981. if F1 == 'F_Waiting':
  4982. FWaiting_TO_FInputtingBean("F1")
  4983. F1 = 'F_InputtingBean'
  4984. elif F2 == 'F_Waiting':
  4985. FWaiting_TO_FInputtingBean("F2")
  4986. F2 = 'F_InputtingBean'
  4987. elif F3 == 'F_Waiting':
  4988. FWaiting_TO_FInputtingBean("F3")
  4989. F3 = 'F_InputtingBean'
  4990. elif F4 == 'F_Waiting':
  4991. FWaiting_TO_FInputtingBean("F4")
  4992. F4 = 'F_InputtingBean'
  4993. elif F5 == 'F_Waiting':
  4994. FWaiting_TO_FInputtingBean("F5")
  4995. F5 = 'F_InputtingBean'
  4996. elif F6 == 'F_Waiting':
  4997. FWaiting_TO_FInputtingBean("F6")
  4998. F6 = 'F_InputtingBean'
  4999. # 若 F1~F6 桶槽中 無桶槽正在入水, 則入豆完成者轉換狀態 開始入水
  5000. if FermentUp_InputtingWater_number == 0 and FermentUp_InputtingBeanFinish_number >= 1:
  5001. if F1 == 'F_InputtingBean_Finish':
  5002. F1 = 'F_InputtingWater'
  5003. FInputtingBeanFinish_TO_FInputtingWater_UP("F1", 0)
  5004. elif F2 == 'F_InputtingBean_Finish':
  5005. F2 = 'F_InputtingWater'
  5006. FInputtingBeanFinish_TO_FInputtingWater_UP("F2", 1)
  5007. elif F3 == 'F_InputtingBean_Finish':
  5008. F3 = 'F_InputtingWater'
  5009. FInputtingBeanFinish_TO_FInputtingWater_UP("F3", 2)
  5010. elif F4 == 'F_InputtingBean_Finish':
  5011. F4 = 'F_InputtingWater'
  5012. FInputtingBeanFinish_TO_FInputtingWater_UP("F4", 3)
  5013. elif F5 == 'F_InputtingBean_Finish':
  5014. F5 = 'F_InputtingWater'
  5015. FInputtingBeanFinish_TO_FInputtingWater_UP("F5", 4)
  5016. elif F6 == 'F_InputtingBean_Finish':
  5017. F6 = 'F_InputtingWater'
  5018. FInputtingBeanFinish_TO_FInputtingWater_UP("F6", 5)
  5019. # 若 F1~F6 桶槽中 無桶槽正在入水, 則入豆完成者轉換狀態 開始入水
  5020. if FermentUp_InputtingWater_number == 1:
  5021. if F1 == 'F_InputtingWater':
  5022. if (F_UP_tank_WaterLevel[0] == 1) and (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height):
  5023. F1 = 'F_Fermenting'
  5024. F1_thread = threading.Thread(target=FInputtingWater_TO_FFermenting, args=["F1"])
  5025. F1_thread.start()
  5026. elif (F_UP_tank_WaterLevel[0] == 1):
  5027. FInputtingWater_AND_WaterLevel1("F1")
  5028. elif (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height):
  5029. FInputtingWater_AND_tankwaterfilled("F1")
  5030. elif F2 == 'F_InputtingWater':
  5031. if (F_UP_tank_WaterLevel[1] == 1) and (F_UP_UltraSoniclist[1] >= Ferment_Tank_water_height):
  5032. F2 = 'F_Fermenting'
  5033. F2_thread = threading.Thread(target=FInputtingWater_TO_FFermenting, args=["F2"])
  5034. F2_thread.start()
  5035. elif (F_UP_tank_WaterLevel[1] == 1):
  5036. FInputtingWater_AND_WaterLevel1("F2")
  5037. elif (F_UP_UltraSoniclist[1] >= Ferment_Tank_water_height):
  5038. FInputtingWater_AND_tankwaterfilled("F2")
  5039. elif F3 == 'F_InputtingWater':
  5040. if (F_UP_tank_WaterLevel[2] == 1) and (F_UP_UltraSoniclist[2] >= Ferment_Tank_water_height):
  5041. F3 = 'F_Fermenting'
  5042. F3_thread = threading.Thread(target=FInputtingWater_TO_FFermenting, args=["F3"])
  5043. F3_thread.start()
  5044. elif (F_UP_tank_WaterLevel[2] == 1):
  5045. FInputtingWater_AND_WaterLevel1("F3")
  5046. elif (F_UP_UltraSoniclist[2] >= Ferment_Tank_water_height):
  5047. FInputtingWater_AND_tankwaterfilled("F3")
  5048. elif F4 == 'F_InputtingWater':
  5049. if (F_UP_tank_WaterLevel[3] == 1) and (F_UP_UltraSoniclist[3] >= Ferment_Tank_water_height):
  5050. F4 = 'F_Fermenting'
  5051. F4_thread = threading.Thread(target=FInputtingWater_TO_FFermenting, args=["F4"])
  5052. F4_thread.start()
  5053. elif (F_UP_tank_WaterLevel[3] == 1):
  5054. FInputtingWater_AND_WaterLevel1("F4")
  5055. elif (F_UP_UltraSoniclist[3] >= Ferment_Tank_water_height):
  5056. FInputtingWater_AND_tankwaterfilled("F4")
  5057. elif F5 == 'F_InputtingWater':
  5058. if (F_UP_tank_WaterLevel[4] == 1) and (F_UP_UltraSoniclist[4] >= Ferment_Tank_water_height):
  5059. F5 = 'F_Fermenting'
  5060. F5_thread = threading.Thread(target=FInputtingWater_TO_FFermenting, args=["F5"])
  5061. F5_thread.start()
  5062. elif (F_UP_tank_WaterLevel[0] == 1):
  5063. FInputtingWater_AND_WaterLevel1("F5")
  5064. elif (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height):
  5065. FInputtingWater_AND_tankwaterfilled("F5")
  5066. elif F6 == 'F_InputtingWater':
  5067. if (F_UP_tank_WaterLevel[5] == 1) and (F_UP_UltraSoniclist[5] >= Ferment_Tank_water_height):
  5068. F6 = 'F_Fermenting'
  5069. F6_thread = threading.Thread(target=FInputtingWater_TO_FFermenting, args=["F6"])
  5070. F6_thread.start()
  5071. elif (F_UP_tank_WaterLevel[5] == 1):
  5072. FInputtingWater_AND_WaterLevel1("F6")
  5073. elif (F_UP_UltraSoniclist[5] >= Ferment_Tank_water_height):
  5074. FInputtingWater_AND_tankwaterfilled("F6")
  5075. else:
  5076. print("else ---------------------------- ")
  5077. if F1 == 'F_Fermenting' and F_UP_tank_SHT11_Temp[0] >= Ferment_Tank_fermenting_temp and F_UP_tank_PH[0] <= Ferment_Tank_fermenting_pH:
  5078. F1_thread = threading.Thread(target=FFermenting_TO_FOutputtingBean, args=["F1"])
  5079. F1_thread.start()
  5080. F1 = 'F_OutputtingBean'
  5081. # 將可出豆桶槽賦值
  5082. if FOutputtingBean_Tank == '': FOutputtingBean_Tank = 'F1'
  5083. if F2 == 'F_Fermenting':
  5084. F2_thread = threading.Thread(target=FFermenting_TO_FOutputtingBean, args=["F2"])
  5085. F2_thread.start()
  5086. F2 = 'F_OutputtingBean'
  5087. if FOutputtingBean_Tank == '': FOutputtingBean_Tank = 'F2'
  5088. if F3 == 'F_Fermenting':
  5089. F3_thread = threading.Thread(target=FFermenting_TO_FOutputtingBean, args=["F3"])
  5090. F3_thread.start()
  5091. F3 = 'F_OutputtingBean'
  5092. if FOutputtingBean_Tank == '': FOutputtingBean_Tank = 'F3'
  5093. if F4 == 'F_Fermenting':
  5094. F4_thread = threading.Thread(target=FFermenting_TO_FOutputtingBean, args=["F4"])
  5095. F4_thread.start()
  5096. F4 = 'F_OutputtingBean'
  5097. if FOutputtingBean_Tank == '': FOutputtingBean_Tank = 'F4'
  5098. if F5 == 'F_Fermenting':
  5099. F5_thread = threading.Thread(target=FFermenting_TO_FOutputtingBean, args=["F5"])
  5100. F5_thread.start()
  5101. F5 = 'F_OutputtingBean'
  5102. if FOutputtingBean_Tank == '': FOutputtingBean_Tank = 'F5'
  5103. if F6 == 'F_Fermenting':
  5104. F6_thread = threading.Thread(target=FFermenting_TO_FOutputtingBean, args=["F6"])
  5105. F6_thread.start()
  5106. F6 = 'F_OutputtingBean'
  5107. if FOutputtingBean_Tank == '': FOutputtingBean_Tank = 'F6'
  5108. # 若桶槽 F1~F6 可出豆 且 桶槽內為空桶 且 有指定清洗排程, 進行清洗桶槽
  5109. # TODO 發酵次數計算、消毒次數、校正
  5110. if F1 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[0] <= Ferment_Tank_bean_empty):
  5111. if FOutputtingBean_Tank == 'F1':
  5112. FOutputtingBean_TO_FWaiting('F1')
  5113. FOutputtingBean_Tank = ''
  5114. if (FermentAuto_cleaning == 0): F1 = 'F_Waiting'
  5115. elif (FermentAuto_cleaning != 0): F1 = 'F_Cleaning'
  5116. if F2 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[1] <= Ferment_Tank_bean_empty):
  5117. if FOutputtingBean_Tank == 'F2':
  5118. FOutputtingBean_TO_FWaiting('F2')
  5119. FOutputtingBean_Tank = ''
  5120. if (FermentAuto_cleaning == 0): F2 = 'F_Waiting'
  5121. elif (FermentAuto_cleaning != 0): F2 = 'F_Cleaning'
  5122. if F3 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[2] <= Ferment_Tank_bean_empty):
  5123. if FOutputtingBean_Tank == 'F3':
  5124. FOutputtingBean_TO_FWaiting('F3')
  5125. FOutputtingBean_Tank = ''
  5126. if (FermentAuto_cleaning == 0): F3 = 'F_Waiting'
  5127. elif (FermentAuto_cleaning != 0): F3 = 'F_Cleaning'
  5128. if F4 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[3] <= Ferment_Tank_bean_empty):
  5129. if FOutputtingBean_Tank == 'F4':
  5130. FOutputtingBean_TO_FWaiting('F4')
  5131. FOutputtingBean_Tank = ''
  5132. if (FermentAuto_cleaning == 0): F4 = 'F_Waiting'
  5133. elif (FermentAuto_cleaning != 0): F4 = 'F_Cleaning'
  5134. if F5 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[4] <= Ferment_Tank_bean_empty):
  5135. if FOutputtingBean_Tank == 'F5':
  5136. FOutputtingBean_TO_FWaiting('F5')
  5137. FOutputtingBean_Tank = ''
  5138. if (FermentAuto_cleaning == 0): F5 = 'F_Waiting'
  5139. elif (FermentAuto_cleaning != 0): F5 = 'F_Cleaning'
  5140. if F6 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[5] <= Ferment_Tank_bean_empty):
  5141. if FOutputtingBean_Tank == 'F6':
  5142. FOutputtingBean_TO_FWaiting('F6')
  5143. FOutputtingBean_Tank = ''
  5144. if (FermentAuto_cleaning == 0): F6 = 'F_Waiting'
  5145. elif (FermentAuto_cleaning != 0): F6 = 'F_Cleaning'
  5146. # 避免桶槽可出豆時未賦值
  5147. if FOutputtingBean_Tank == '':
  5148. if F1 == 'F_OutputtingBean': FOutputtingBean_Tank = 'F1'
  5149. elif F2 == 'F_OutputtingBean': FOutputtingBean_Tank = 'F2'
  5150. elif F3 == 'F_OutputtingBean': FOutputtingBean_Tank = 'F3'
  5151. elif F4 == 'F_OutputtingBean': FOutputtingBean_Tank = 'F4'
  5152. elif F5 == 'F_OutputtingBean': FOutputtingBean_Tank = 'F5'
  5153. elif F6 == 'F_OutputtingBean': FOutputtingBean_Tank = 'F6'
  5154. # 若桶槽 F1~F6 為清洗中
  5155. if F1 == 'F_Cleaning':
  5156. F1_thread = threading.Thread(target=FCleaning, args=["F1"])
  5157. F1_thread.start()
  5158. F1 = 'F_Waiting'
  5159. if F2 == 'F_Cleaning':
  5160. F2_thread = threading.Thread(target=FCleaning, args=["F2"])
  5161. F2_thread.start()
  5162. F2 = 'F_Waiting'
  5163. if F3 == 'F_Cleaning':
  5164. F3_thread = threading.Thread(target=FCleaning, args=["F3"])
  5165. F3_thread.start()
  5166. F3 = 'F_Waiting'
  5167. if F4 == 'F_Cleaning':
  5168. F4_thread = threading.Thread(target=FCleaning, args=["F4"])
  5169. F4_thread.start()
  5170. F4 = 'F_Waiting'
  5171. if F5 == 'F_Cleaning':
  5172. F5_thread = threading.Thread(target=FCleaning, args=["F5"])
  5173. F5_thread.start()
  5174. F5 = 'F_Waiting'
  5175. if F6 == 'F_Cleaning':
  5176. F6_thread = threading.Thread(target=FCleaning, args=["F6"])
  5177. F6_thread.start()
  5178. F6 = 'F_Waiting'
  5179. # # ----- [測試用] !!!!! F1~F6 入料完成→可出豆 判斷 ------------------------------
  5180. # if F1 == 'F_InputtingBean_Finish': F1 = 'F_OutputtingBean'
  5181. # if F2 == 'F_InputtingBean_Finish': F2 = 'F_OutputtingBean'
  5182. # if F3 == 'F_InputtingBean_Finish': F3 = 'F_OutputtingBean'
  5183. # if F4 == 'F_InputtingBean_Finish': F4 = 'F_OutputtingBean'
  5184. # if F5 == 'F_InputtingBean_Finish': F5 = 'F_OutputtingBean'
  5185. # if F6 == 'F_InputtingBean_Finish': F6 = 'F_OutputtingBean'
  5186. # # ----- [測試用] !!!!! F1~F6 入料完成→可出豆 判斷 ------------------------------
  5187. else:
  5188. # [介面] 若未啟用 發酵 狀態
  5189. print('未啟用發酵流程')
  5190. # ----- 發酵出料儲豆槽 FO1~FO2 入豆→可出豆判斷 ------------------------------
  5191. # 目前發酵槽 F1~F6 正在入豆、入水的桶槽數量 (應小於一桶)
  5192. # Ferment_OutputtingBean_number = int(F_UP_tanklist.count('F_OutputtingBean'))
  5193. # 若出料儲豆槽狀態為 空桶等待 且 桶槽狀態為 F_OutputtingBean 可出豆, 與 FO1 配合開始出豆
  5194. if FO1 == 'FO_Waiting' and FOutputtingBean_Tank != '':
  5195. # 判斷要對應出料的桶槽為何, 設定成 FOutputtingBean_Tank = 'F1', 待出完料再把 FOutputtingBean_Tank = ''
  5196. FO1 = 'FO_InputtingBean'
  5197. print('------- ' + FOutputtingBean_Tank + ' 狀態更新:出豆中 -------')
  5198. print('------- FO1 狀態更新:入豆中 -------')
  5199. # [致動器] F1 蝴蝶閥 ON
  5200. data = { "tank_num": FOutputtingBean_Tank, "command": "tank_diskvalve_status", "value": "on" }
  5201. print('data: ', data)
  5202. # mqtt_f(data)
  5203. elif FO1 == 'FO_InputtingBean' and FOutputtingBean_Tank != '':
  5204. if FO_UP_UltraSoniclist[0] >= Ferment_Output_bean_height:
  5205. # [致動器] 出料真空吸料機 OFF
  5206. data = { "tank_num": FOutputtingBean_Tank, "command": "input_vacuum_status", "value": "off" }
  5207. print('data: ', data)
  5208. # mqtt_f(data)
  5209. # [致動器] F1 蝴蝶閥 OFF
  5210. data = { "tank_num": FOutputtingBean_Tank, "command": "tank_diskvalve_status", "value": "off" }
  5211. print('data: ', data)
  5212. # mqtt_f(data)
  5213. FO1 = 'FO_OutputtingBean'
  5214. print('------- FO1 狀態更新:出豆中 -------')
  5215. elif FO_UP_UltraSoniclist[0] < Ferment_Output_bean_height:
  5216. FO1_thread = threading.Thread(target=FOInputtingBean_filled, args=["FO1"])
  5217. FO1_thread.start()
  5218. # 若是無桶槽可入豆, 出料儲豆槽判斷是否可出豆或空桶等待入豆
  5219. elif FOutputtingBean_Tank == '':
  5220. if FO_UP_UltraSoniclist[0] > Ferment_Output_bean_empty:
  5221. FO1 = 'FO_OutputtingBean'
  5222. print('------- FO1 狀態更新:可出豆 -------')
  5223. elif FO_UP_UltraSoniclist[0] <= Ferment_Output_bean_empty:
  5224. FO1 = 'FO_Waiting'
  5225. print('------- FO1 狀態更新:空桶等待 -------')
  5226. elif FO1 == 'FO_OutputtingBean' and FO_UP_UltraSoniclist[0] <= Ferment_Output_bean_empty:
  5227. FO1 = 'FO_Waiting'
  5228. print('------- FO1 狀態更新:空桶等待 -------')
  5229. # ----- 等待 thread 多執行緒執行完成 --------
  5230. # 若 FI1_thread 有被定義, 則執行 FI1_thread.join() 等待執行完成 (當入料儲豆槽入料時)
  5231. # 若 FI1_thread 有被定義, 會出現 UnboundLocalError: local variable 'FO1_thread' referenced before assignment 錯誤訊息
  5232. # (非入料儲豆槽入料時) 此時就不進行任何處理
  5233. try:
  5234. FI1_thread.join()
  5235. print("-- FI1_thread complete! --")
  5236. except UnboundLocalError:
  5237. pass
  5238. try:
  5239. F1_thread.join()
  5240. print("-- F1_thread complete! --")
  5241. except UnboundLocalError:
  5242. pass
  5243. try:
  5244. F2_thread.join()
  5245. print("-- F2_thread complete! --")
  5246. except UnboundLocalError:
  5247. pass
  5248. try:
  5249. F3_thread.join()
  5250. print("-- F3_thread complete! --")
  5251. except UnboundLocalError:
  5252. pass
  5253. try:
  5254. F4_thread.join()
  5255. print("-- F4_thread complete! --")
  5256. except UnboundLocalError:
  5257. pass
  5258. try:
  5259. F5_thread.join()
  5260. print("-- F5_thread complete! --")
  5261. except UnboundLocalError:
  5262. pass
  5263. try:
  5264. F6_thread.join()
  5265. print("-- F6_thread complete! --")
  5266. except UnboundLocalError:
  5267. pass
  5268. try:
  5269. FO1_thread.join()
  5270. print("-- FO1_thread complete! --")
  5271. except UnboundLocalError:
  5272. pass
  5273. # ----- 將狀態寫入資料庫 ------------------------------
  5274. # 獲取文本框的值並賦值給user實體對象
  5275. F_status = ferment_container_status()
  5276. F_status.Ferment_Input_1 = FI1
  5277. F_status.Ferment_Input_2 = FI2
  5278. F_status.Ferment_Tank_1 = F1
  5279. F_status.Ferment_Tank_2 = F2
  5280. F_status.Ferment_Tank_3 = F3
  5281. F_status.Ferment_Tank_4 = F4
  5282. F_status.Ferment_Tank_5 = F5
  5283. F_status.Ferment_Tank_6 = F6
  5284. F_status.Ferment_Tank_7 = F7
  5285. F_status.Ferment_Tank_8 = F8
  5286. F_status.Ferment_Tank_9 = F9
  5287. F_status.Ferment_Tank_10 = F10
  5288. F_status.Ferment_Tank_11 = F11
  5289. F_status.Ferment_Tank_12 = F12
  5290. F_status.Ferment_Output_1 = FO1
  5291. F_status.Ferment_Output_2 = FO2
  5292. #將數據保存進資料庫
  5293. db.session.add(F_status)
  5294. # 手動提交
  5295. db.session.commit()
  5296. # ----- 將狀態寫入資料庫 ------------------------------
  5297. return jsonify({"Peel_Output_1":PO1,
  5298. "Ferment_Input_1":FI1,
  5299. "Ferment_Tank_1":F1,
  5300. "Ferment_Tank_2":F2,
  5301. "Ferment_Tank_3":F3,
  5302. "Ferment_Tank_4":F4,
  5303. "Ferment_Tank_5":F5,
  5304. "Ferment_Tank_6":F6,
  5305. "Ferment_Output_1":FO1
  5306. })
  5307. # 1026 以流程圖判斷, 改寫 def ferment_auto_test, 以下為原備份
  5308. @main.route('/ferment_auto_test_1026backup')
  5309. def ferment_auto_test_1026backup():
  5310. info = request.args.to_dict()
  5311. # 從介面取得 指定生豆高度/發酵桶槽排程:發酵、清洗、校正 EC、校正攪拌棒
  5312. Ferment_Input_bean_empty = 2
  5313. Ferment_Tank_bean_empty = 2
  5314. Ferment_Output_bean_empty = 2
  5315. FermentAuto_fermenting = int(info['FermentAuto_fermenting'])
  5316. FermentAuto_cleaning = int(info['FermentAuto_cleaning'])
  5317. FermentAuto_calibratingEC = int(info['FermentAuto_calibratingEC'])
  5318. FermentAuto_calibratingSTIR = int(info['FermentAuto_calibratingSTIR'])
  5319. Ferment_Input_bean_height = float(info['Ferment_Input_bean_height'])
  5320. Ferment_Input_vacuumON_time = float(info['Ferment_Input_vacuumON_time'])
  5321. Ferment_Input_vacuumOFF_time = float(info['Ferment_Input_vacuumOFF_time'])
  5322. Ferment_Tank_bean_height = float(info['Ferment_Tank_bean_height'])
  5323. Ferment_Tank_vacuumON_time = float(info['Ferment_Tank_vacuumON_time'])
  5324. Ferment_Tank_vacuumOFF_time = float(info['Ferment_Tank_vacuumOFF_time'])
  5325. Ferment_Tank_water_height = float(info['Ferment_Tank_water_height'])
  5326. Ferment_Tank_fermenting_temp = float(info['Ferment_Tank_fermenting_temp'])
  5327. Ferment_Tank_fermenting_time = float(info['Ferment_Tank_fermenting_time'])
  5328. Ferment_Tank_motor_rpm = float(info['Ferment_Tank_motor_rpm'])
  5329. Ferment_Tank_motor_time = float(info['Ferment_Tank_motor_time'])
  5330. Ferment_Tank_fermenting_pH = float(info['Ferment_Tank_fermenting_pH'])
  5331. Ferment_Output_bean_height = float(info['Ferment_Output_bean_height'])
  5332. Ferment_Output_vacuumON_time = float(info['Ferment_Output_vacuumON_time'])
  5333. Ferment_Output_vacuumOFF_time = float(info['Ferment_Output_vacuumOFF_time'])
  5334. Ferment_Tank_WaterOut_time = float(info['Ferment_Tank_WaterOut_time'])
  5335. Ferment_Tank_Disinfect_time = float(info['Ferment_Tank_Disinfect_time'])
  5336. # print('發酵自動化_指定生豆高度: ', Ferment_Tank_bean_height)
  5337. # print('發酵自動化_發酵排程: ', FermentAuto_fermenting, type(FermentAuto_fermenting))
  5338. # print('發酵自動化_清洗排程: ', FermentAuto_cleaning, type(FermentAuto_cleaning))
  5339. # print('發酵自動化_校正 EC 排程: ', FermentAuto_calibratingEC, type(FermentAuto_calibratingEC))
  5340. # print('發酵自動化_校正攪拌棒排程: ', FermentAuto_calibratingSTIR, type(FermentAuto_calibratingSTIR))
  5341. # [介面] 讓使用者可以選擇排程內有發酵/清洗/校正, 此處預設為 True
  5342. Ferment_btn = FermentAuto_fermenting # Ferment_btn = True
  5343. # 從資料庫資料表中取得最新狀態
  5344. ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  5345. FI1 = ferment_status.Ferment_Input_1
  5346. FI2 = ferment_status.Ferment_Input_2
  5347. F1 = ferment_status.Ferment_Tank_1
  5348. F2 = ferment_status.Ferment_Tank_2
  5349. F3 = ferment_status.Ferment_Tank_3
  5350. F4 = ferment_status.Ferment_Tank_4
  5351. F5 = ferment_status.Ferment_Tank_5
  5352. F6 = ferment_status.Ferment_Tank_6
  5353. F7 = ferment_status.Ferment_Tank_7
  5354. F8 = ferment_status.Ferment_Tank_8
  5355. F9 = ferment_status.Ferment_Tank_9
  5356. F10 = ferment_status.Ferment_Tank_10
  5357. F11 = ferment_status.Ferment_Tank_11
  5358. F12 = ferment_status.Ferment_Tank_12
  5359. FO1 = ferment_status.Ferment_Output_1
  5360. FO2 = ferment_status.Ferment_Output_2
  5361. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  5362. PO1 = clean_status.Peel_Output_1 # PO_Waiting # PO_OutputtingBean
  5363. PO2 = clean_status.Peel_Output_2
  5364. F_UP_tanklist = [F1, F2, F3, F4, F5, F6]
  5365. F_DOWN_tanklist = [F7, F8, F9, F10, F11, F12]
  5366. # ----- 發酵入料儲豆槽 FI1~FI2 入豆→可出豆判斷 ------------------------------
  5367. # 目前發酵槽 F1~F6 正在入豆的桶槽數量 (應小於一桶)
  5368. FermentUp_InputtingBean_number = int(F_UP_tanklist.count('F_InputtingBean'))
  5369. FermentUp_InputtingBeanPause_number = int(F_UP_tanklist.count('F_InputtingBean_Pause'))
  5370. # -- 取得發酵入料儲豆槽 FI1~FI2 桶內高度 UltraSonic -------------
  5371. FI_UP_UltraSoniclist = []
  5372. for i in range(1, 3, 1):
  5373. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  5374. # UltraSonic = float("{:.2f}".format(34.6 - float(input_UltraSonic.UltraSonic)))
  5375. UltraSonic = float(input_UltraSonic.UltraSonic)
  5376. FI_UP_UltraSoniclist.append(UltraSonic)
  5377. print('FI_UP_UltraSoniclist: ', FI_UP_UltraSoniclist)
  5378. # -- 取得發酵入料儲豆槽 FI1~FI2 桶內高度 UltraSonic -------------
  5379. # 入料儲豆槽等待中、且脫皮機儲豆槽可出豆時, 入料儲豆槽入豆
  5380. if FI1 == 'FI_Waiting' and PO1 == 'PO_OutputtingBean':
  5381. FI1 = 'FI_InputtingBean'
  5382. print('------- FI1 狀態更新:入豆中 -------')
  5383. # [致動器] 入料真空吸料機 ON
  5384. data = { "tank_num": "F1", "command": "input_vacuum_status", "value": "on" }
  5385. print('data: ', data)
  5386. # mqtt_f(data)
  5387. timer = time.time()
  5388. while True:
  5389. if (time.time() - timer) > Ferment_Input_vacuumON_time:
  5390. # [致動器] 入料真空吸料機 OFF
  5391. data = { "tank_num": "F1", "command": "input_vacuum_status", "value": "off" }
  5392. print('data: ', data)
  5393. # mqtt_f(data)
  5394. timer = time.time()
  5395. break
  5396. while True:
  5397. if (time.time() - timer) > Ferment_Input_vacuumOFF_time:
  5398. break
  5399. # 入料儲豆槽入豆時
  5400. elif FI1 == 'FI_InputtingBean':
  5401. # 桶槽內未達指定生豆高度, 且 前方 PO1 可出豆, 就執行入料動作
  5402. if (FI_UP_UltraSoniclist[0] < Ferment_Input_bean_height) and PO1 == 'PO_OutputtingBean':
  5403. # [致動器] 入料真空吸料機 ON
  5404. data = { "tank_num": "F1", "command": "input_vacuum_status", "value": "on" }
  5405. print('data: ', data)
  5406. # mqtt_f(data)
  5407. timer = time.time()
  5408. while True:
  5409. if (time.time() - timer) > Ferment_Input_vacuumON_time:
  5410. # [致動器] 入料真空吸料機 OFF
  5411. data = { "tank_num": "F1", "command": "input_vacuum_status", "value": "off" }
  5412. print('data: ', data)
  5413. # mqtt_f(data)
  5414. timer = time.time()
  5415. break
  5416. while True:
  5417. if (time.time() - timer) > Ferment_Input_vacuumOFF_time:
  5418. break
  5419. # 桶槽內達指定生豆高度時, 入料儲豆槽狀態轉為 可出豆
  5420. if (FI_UP_UltraSoniclist[0] >= Ferment_Input_bean_height):
  5421. FI1 = 'FI_OutputtingBean'
  5422. print('------- FI1 狀態更新:可出豆 -------')
  5423. # 入料儲豆槽出豆時, 桶槽高度為 空桶高度時, 狀態轉為 空桶等待
  5424. elif FI1 == 'FI_OutputtingBean' and (FI_UP_UltraSoniclist[0] <= Ferment_Input_bean_empty):
  5425. FI1 = 'FI_Waiting'
  5426. print('------- FI1 狀態更新:空桶等待 -------')
  5427. # [1012 刪除, 避免混豆]若入料儲豆槽可出豆 且 儲豆槽內高度低於 40 且 前方脫皮機儲豆槽可出豆 且 目前無桶槽需入料時
  5428. # elif FI1 == 'FI_OutputtingBean' and (FI_UP_UltraSoniclist[0] < 40) and PO1 == 'PO_OutputtingBean' and FermentUp_InputtingBean_number == 0 and FermentUp_InputtingBeanPause_number == 0:
  5429. # FI1 = 'FI_InputtingBean'
  5430. # print('------- FI1 狀態更新:入豆中 -------')
  5431. # if FI2 == 'FI_Waiting' and PO2 == 'PO_OutputtingBean':
  5432. # FI2 = 'FI_InputtingBean'
  5433. # print('------- FI2 狀態更新:入豆中 -------')
  5434. # elif FI2 == 'FI_InputtingBean' and ((FI_UP_UltraSoniclist[1] >= 35) or (PO2 != 'PO_OutputtingBean')) :
  5435. # FI2 = 'FI_OutputtingBean'
  5436. # print('------- FI2 狀態更新:可出豆 -------')
  5437. # elif FI2 == 'FI_OutputtingBean' and (FI_UP_UltraSoniclist[1] < 40) and PO2 == 'PO_OutputtingBean' and FermentUp_InputtingBean_number == 0 and FermentUp_InputtingBeanPause_number == 0:
  5438. # FI2 = 'FI_InputtingBean'
  5439. # print('------- FI2 狀態更新:入豆中 -------')
  5440. # ----- 發酵桶槽 F1~F6 入料暫停→入料判斷 ------------------------------
  5441. ### 移到入料
  5442. # ----- 發酵桶槽 F1~F6 等待→入料判斷 ------------------------------
  5443. # -- 取得發酵桶槽 F1~F6 桶內高度 UltraSonic -------------
  5444. F_UP_UltraSoniclist = []
  5445. for i in range(1, 7, 1):
  5446. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  5447. UltraSonic = (float(tank_UltraSonic.UltraSonic))
  5448. F_UP_UltraSoniclist.append(UltraSonic)
  5449. print('F_UP_UltraSoniclist: ', F_UP_UltraSoniclist)
  5450. # -- 取得發酵桶槽 F1~F6 桶內高度 UltraSonic -------------
  5451. # [介面] 若啟用 發酵 狀態
  5452. if Ferment_btn:
  5453. # 若入料儲豆槽可出料狀態
  5454. if FI1 == 'FI_OutputtingBean':
  5455. # 若 F1~F6 發酵桶槽為 入豆中, 繼續入豆, 當高度 > 指定生豆高度 時入豆完成
  5456. if F1 == 'F_InputtingBean':
  5457. if (F_UP_UltraSoniclist[0] >= Ferment_Tank_bean_height):
  5458. F1 = 'F_InputtingBean_Finish'
  5459. print('------- F1 狀態更新:入料完成 -------')
  5460. # [致動器] 入料三通閥 ON排氣
  5461. data = { "tank_num": "F1", "command": "tank_threewayvalve_input_status", "value": "on" }
  5462. print('data: ', data)
  5463. # mqtt_f(data)
  5464. # [致動器] 馬達 0
  5465. data = { "tank_num": "F1", "command": "tank_motor_status", "value": "0" }
  5466. print('data: ', data)
  5467. # mqtt_f(data)
  5468. # [致動器] 真空吸料機 OFF
  5469. data = { "tank_num": "F1", "command": "tank_vacuum_status", "value": "off" }
  5470. print('data: ', data)
  5471. # mqtt_f(data)
  5472. else:
  5473. # [致動器] 真空吸料機 ON
  5474. data = { "tank_num": "F1", "command": "tank_vacuum_status", "value": "on" }
  5475. print('data: ', data)
  5476. # mqtt_f(data)
  5477. timer = time.time()
  5478. while True:
  5479. if (time.time() - timer) > Ferment_Tank_vacuumON_time:
  5480. # [致動器] 入料真空吸料機 OFF
  5481. data = { "tank_num": "F1", "command": "tank_vacuum_status", "value": "off" }
  5482. print('data: ', data)
  5483. # mqtt_f(data)
  5484. timer = time.time()
  5485. break
  5486. while True:
  5487. if (time.time() - timer) > Ferment_Tank_vacuumOFF_time:
  5488. break
  5489. if F2 == 'F_InputtingBean' and (F_UP_UltraSoniclist[1] >= Ferment_Tank_bean_height):
  5490. F2 = 'F_InputtingBean_Finish'
  5491. print('------- F2 狀態更新:入料完成 -------')
  5492. if F3 == 'F_InputtingBean' and (F_UP_UltraSoniclist[2] >= Ferment_Tank_bean_height):
  5493. F3 = 'F_InputtingBean_Finish'
  5494. print('------- F3 狀態更新:入料完成 -------')
  5495. if F4 == 'F_InputtingBean' and (F_UP_UltraSoniclist[3] >= Ferment_Tank_bean_height):
  5496. F4 = 'F_InputtingBean_Finish'
  5497. print('------- F4 狀態更新:入料完成 -------')
  5498. if F5 == 'F_InputtingBean' and (F_UP_UltraSoniclist[4] >= Ferment_Tank_bean_height):
  5499. F5 = 'F_InputtingBean_Finish'
  5500. print('------- F5 狀態更新:入料完成 -------')
  5501. if F6 == 'F_InputtingBean' and (F_UP_UltraSoniclist[5] >= Ferment_Tank_bean_height):
  5502. F6 = 'F_InputtingBean_Finish'
  5503. print('------- F6 狀態更新:入料完成 -------')
  5504. # 若有兩個以上桶槽入料中, 則桶號最小者優先入料 ←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←← 1021 優先入豆判斷
  5505. if FermentUp_InputtingBean_number == 1:
  5506. if F1 == 'F_InputtingBean':
  5507. # [致動器] 桶槽真空吸料機 ON
  5508. data = { "tank_num": "F1", "command": "tank_vacuum_status", "value": "on" }
  5509. print('data: ', data)
  5510. # mqtt_f(data)
  5511. timer = time.time()
  5512. while True:
  5513. if (time.time() - timer) > Ferment_Tank_vacuumON_time:
  5514. # [致動器] 桶槽真空吸料機 OFF
  5515. data = { "tank_num": "F1", "command": "tank_vacuum_status", "value": "off" }
  5516. print('data: ', data)
  5517. # mqtt_f(data)
  5518. timer = time.time()
  5519. break
  5520. while True:
  5521. if (time.time() - timer) > Ferment_Tank_vacuumOFF_time:
  5522. break
  5523. # else if F2 == ''...
  5524. # 若 F1~F6 發酵桶槽為 入豆暫停, 則狀態改為優先入豆 ←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←← 1021 優先入豆判斷
  5525. elif FermentUp_InputtingBeanPause_number >= 1:
  5526. if F1 == 'F_InputtingBean_Pause':
  5527. F1 = 'F_InputtingBean'
  5528. print('------- F1 狀態更新:入料中 -------')
  5529. # [致動器] 桶槽真空吸料機 ON
  5530. data = { "tank_num": "F1", "command": "tank_vacuum_status", "value": "on" }
  5531. print('data: ', data)
  5532. # mqtt_f(data)
  5533. timer = time.time()
  5534. while True:
  5535. if (time.time() - timer) > Ferment_Tank_vacuumON_time:
  5536. # [致動器] 桶槽真空吸料機 OFF
  5537. data = { "tank_num": "F1", "command": "tank_vacuum_status", "value": "off" }
  5538. print('data: ', data)
  5539. # mqtt_f(data)
  5540. timer = time.time()
  5541. break
  5542. while True:
  5543. if (time.time() - timer) > Ferment_Tank_vacuumOFF_time:
  5544. break
  5545. elif F2 == 'F_InputtingBean_Pause':
  5546. F2 = 'F_InputtingBean'
  5547. print('------- F2 狀態更新:入料中 -------')
  5548. elif F3 == 'F_InputtingBean_Pause':
  5549. F3 = 'F_InputtingBean'
  5550. print('------- F3 狀態更新:入料中 -------')
  5551. elif F4 == 'F_InputtingBean_Pause':
  5552. F4 = 'F_InputtingBean'
  5553. print('------- F4 狀態更新:入料中 -------')
  5554. elif F5 == 'F_InputtingBean_Pause':
  5555. F5 = 'F_InputtingBean'
  5556. print('------- F5 狀態更新:入料中 -------')
  5557. elif F6 == 'F_InputtingBean_Pause':
  5558. F6 = 'F_InputtingBean'
  5559. print('------- F6 狀態更新:入料中 -------')
  5560. # 若 F1~F6 皆無入豆 無入豆暫停, 則桶號最小者開始入豆
  5561. elif FermentUp_InputtingBean_number == 0 and FermentUp_InputtingBeanPause_number == 0:
  5562. if F1 == 'F_Waiting':
  5563. F1 = 'F_InputtingBean'
  5564. print('------- F1 狀態更新:入料中 -------')
  5565. # [致動器] 入料入料三通閥 OFF入豆
  5566. data = { "tank_num": "F1", "command": "tank_threewayvalve_input_status", "value": "off" }
  5567. print('data: ', data)
  5568. # mqtt_f(data)
  5569. # [致動器] 馬達 5
  5570. data = { "tank_num": "F1", "command": "tank_motor_status", "value": "5" }
  5571. print('data: ', data)
  5572. # mqtt_f(data)
  5573. # [致動器] 桶槽真空吸料機 ON
  5574. data = { "tank_num": "F1", "command": "tank_vacuum_status", "value": "on" }
  5575. print('data: ', data)
  5576. # mqtt_f(data)
  5577. timer = time.time()
  5578. while True:
  5579. if (time.time() - timer) > Ferment_Tank_vacuumON_time:
  5580. # [致動器] 桶槽真空吸料機 OFF
  5581. data = { "tank_num": "F1", "command": "tank_vacuum_status", "value": "off" }
  5582. print('data: ', data)
  5583. # mqtt_f(data)
  5584. timer = time.time()
  5585. break
  5586. while True:
  5587. if (time.time() - timer) > Ferment_Tank_vacuumON_time:
  5588. break
  5589. elif F2 == 'F_Waiting':
  5590. F2 = 'F_InputtingBean'
  5591. print('------- F2 狀態更新:入料中 -------')
  5592. elif F3 == 'F_Waiting':
  5593. F3 = 'F_InputtingBean'
  5594. print('------- F3 狀態更新:入料中 -------')
  5595. elif F4 == 'F_Waiting':
  5596. F4 = 'F_InputtingBean'
  5597. print('------- F4 狀態更新:入料中 -------')
  5598. elif F5 == 'F_Waiting':
  5599. F5 = 'F_InputtingBean'
  5600. print('------- F5 狀態更新:入料中 -------')
  5601. elif F6 == 'F_Waiting':
  5602. F6 = 'F_InputtingBean'
  5603. print('------- F6 狀態更新:入料中 -------')
  5604. # 若入料儲豆槽非可出豆, 且 F1~F6 其中有桶槽入料中, 若桶槽未滿則入料暫停
  5605. elif FI1 != 'FI_InputtingBean' and FermentUp_InputtingBean_number >= 1:
  5606. if F1 == 'F_InputtingBean' and F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height:
  5607. F1 = 'F_InputtingBean_Pause'
  5608. print('------- F1 狀態更新:入料暫停 -------')
  5609. # [致動器] 桶槽真空吸料機 OFF
  5610. data = { "tank_num": "F1", "command": "tank_vacuum_status", "value": "off" }
  5611. print('data: ', data)
  5612. # mqtt_f(data)
  5613. elif F1 == 'F_InputtingBean' and F_UP_UltraSoniclist[0] >= Ferment_Tank_bean_height:
  5614. F1 = 'F_InputtingBean_Finish'
  5615. print('------- F1 狀態更新:入料完成 -------')
  5616. # [致動器] 入料三通閥 ON排氣
  5617. data = { "tank_num": "F1", "command": "tank_threewayvalve_input_status", "value": "on" }
  5618. print('data: ', data)
  5619. # mqtt_f(data)
  5620. # [致動器] 馬達 0
  5621. data = { "tank_num": "F1", "command": "tank_motor_status", "value": "0" }
  5622. print('data: ', data)
  5623. # mqtt_f(data)
  5624. # [致動器] 入料真空吸料機 OFF
  5625. data = { "tank_num": "F1", "command": "input_vacuum_status", "value": "off" }
  5626. print('data: ', data)
  5627. # mqtt_f(data)
  5628. if F2 == 'F_InputtingBean' and F_UP_UltraSoniclist[1] < Ferment_Tank_bean_height:
  5629. F2 = 'F_InputtingBean_Pause'
  5630. print('------- F2 狀態更新:入料暫停 -------')
  5631. elif F2 == 'F_InputtingBean' and F_UP_UltraSoniclist[1] >= Ferment_Tank_bean_height:
  5632. F2 = 'F_InputtingBean_Finish'
  5633. print('------- F2 狀態更新:入料完成 -------')
  5634. if F3 == 'F_InputtingBean' and F_UP_UltraSoniclist[2] < Ferment_Tank_bean_height:
  5635. F3 = 'F_InputtingBean_Pause'
  5636. print('------- F3 狀態更新:入料暫停 -------')
  5637. elif F3 == 'F_InputtingBean' and F_UP_UltraSoniclist[2] >= Ferment_Tank_bean_height:
  5638. F3 = 'F_InputtingBean_Finish'
  5639. print('------- F3 狀態更新:入料完成 -------')
  5640. if F4 == 'F_InputtingBean' and F_UP_UltraSoniclist[3] < Ferment_Tank_bean_height:
  5641. F4 = 'F_InputtingBean_Pause'
  5642. print('------- F4 狀態更新:入料暫停 -------')
  5643. elif F4 == 'F_InputtingBean' and F_UP_UltraSoniclist[3] >= Ferment_Tank_bean_height:
  5644. F4 = 'F_InputtingBean_Finish'
  5645. print('------- F4 狀態更新:入料完成 -------')
  5646. if F5 == 'F_InputtingBean' and F_UP_UltraSoniclist[4] < Ferment_Tank_bean_height:
  5647. F5 = 'F_InputtingBean_Pause'
  5648. print('------- F5 狀態更新:入料暫停 -------')
  5649. elif F5 == 'F_InputtingBean' and F_UP_UltraSoniclist[4] >= Ferment_Tank_bean_height:
  5650. F5 = 'F_InputtingBean_Finish'
  5651. print('------- F5 狀態更新:入料完成 -------')
  5652. if F6 == 'F_InputtingBean' and F_UP_UltraSoniclist[5] < Ferment_Tank_bean_height:
  5653. F6 = 'F_InputtingBean_Pause'
  5654. print('------- F6 狀態更新:入料暫停 -------')
  5655. elif F6 == 'F_InputtingBean' and F_UP_UltraSoniclist[5] >= Ferment_Tank_bean_height:
  5656. F6 = 'F_InputtingBean_Finish'
  5657. print('------- F6 狀態更新:入料完成 -------')
  5658. else:
  5659. # 若入料儲豆槽非可出料狀態
  5660. print('發酵入料儲豆槽空, 桶槽無法入料')
  5661. else:
  5662. # [介面] 若未啟用 發酵 狀態
  5663. print('未啟用發酵流程')
  5664. # ----- 10/07 --------------------------------------------------------------------------------------------------------------------------------
  5665. # ----- 發酵桶槽 F1~F6 入料→入料暫停判斷 ------------------------------
  5666. ### 移到入料
  5667. # ----- 發酵桶槽 F1~F6 入料→入水判斷 ------------------------------
  5668. # -- 取得發酵桶槽 F1~F6 夾層水位高度 WaterLevel -------------
  5669. F_UP_tank_WaterLevel = []
  5670. for i in range(1, 7, 1):
  5671. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  5672. WaterLevel = float(tank_WaterLevel.WaterLevel)
  5673. F_UP_tank_WaterLevel.append(WaterLevel)
  5674. print('F_UP_tank_WaterLevel: ', F_UP_tank_WaterLevel)
  5675. # -- 取得發酵桶槽 F1~F6 夾層水位高度 WaterLevel -------------
  5676. Ferment_InputtingBeanFinish_number = int(F_UP_tanklist.count('F_InputtingBean_Finish'))
  5677. Ferment_InputtingWater_number = int(F_UP_tanklist.count('F_InputtingWater'))
  5678. # 入水條件:當前桶槽入豆 + 沒有其他桶槽入水
  5679. if Ferment_InputtingBeanFinish_number >= 1 and Ferment_InputtingWater_number == 0:
  5680. # 當入豆到指定高度時, 狀態轉換為入水 (桶槽編號小者優先)
  5681. # !!! 發酵槽 F_InputtingBean_Finish 狀態應該請硬體判斷
  5682. # !!! 若狀態為 F_InputtingBean 且 超音波值>指定生豆高度, 狀態改為 F_InputtingBean_Finish 並等待入水 F_InputtingWater
  5683. # 這邊是考慮一次僅一個桶槽入水, 多桶入水會不會速度變慢?
  5684. if F1 == 'F_InputtingBean_Finish':
  5685. F1 = 'F_InputtingWater'
  5686. print('------- F1 狀態更新:入水中 -------')
  5687. # [致動器] 外桶浮選三通閥 ON
  5688. data = { "tank_num": "F1", "command": "outer_threewayvalve_float_status", "value": "on" }
  5689. print('data: ', data)
  5690. # mqtt_f(data)
  5691. # 桶內高度若低於水位指定高度, [致動器] 桶內進水電磁閥 ON
  5692. if F_UP_UltraSoniclist[0] < Ferment_Tank_water_height:
  5693. data = { "tank_num": "F1", "command": "tank_solenoid_water_in_status", "value": "on" }
  5694. print('data: ', data)
  5695. # mqtt_f(data)
  5696. # [致動器] 桶內進水電磁閥 OFF
  5697. else:
  5698. data = { "tank_num": "F1", "command": "tank_solenoid_water_in_status", "value": "off" }
  5699. print('data: ', data)
  5700. # mqtt_f(data)
  5701. # 桶外水位高度若低於水位計高度, [致動器] 桶外進水電磁閥 ON
  5702. if F_UP_tank_WaterLevel[0] != 1:
  5703. data = { "tank_num": "F1", "command": "outer_solenoid_water_status", "value": "on" }
  5704. print('data: ', data)
  5705. # mqtt_f(data)
  5706. # [致動器] 桶外進水電磁閥 OFF
  5707. else:
  5708. data = { "tank_num": "F1", "command": "outer_solenoid_water_status", "value": "off" }
  5709. print('data: ', data)
  5710. # mqtt_f(data)
  5711. elif F2 == 'F_InputtingBean_Finish':
  5712. F2 = 'F_InputtingWater'
  5713. print('------- F2 狀態更新:入水中 -------')
  5714. elif F3 == 'F_InputtingBean_Finish':
  5715. F3 = 'F_InputtingWater'
  5716. print('------- F3 狀態更新:入水中 -------')
  5717. elif F4 == 'F_InputtingBean_Finish':
  5718. F4 = 'F_InputtingWater'
  5719. print('------- F4 狀態更新:入水中 -------')
  5720. elif F5 == 'F_InputtingBean_Finish':
  5721. F5 = 'F_InputtingWater'
  5722. print('------- F5 狀態更新:入水中 -------')
  5723. elif F6 == 'F_InputtingBean_Finish':
  5724. F6 = 'F_InputtingWater'
  5725. print('------- F6 狀態更新:入水中 -------')
  5726. # ----- 發酵桶槽 F1~F6 入水→發酵判斷 ------------------------------
  5727. # !!! 發酵槽 F_Fermenting 狀態應該請硬體判斷
  5728. # !!! 若狀態為 F_InputtingWater 且 超音波值>指定水位高度 且 夾層水位計 == 1, 狀態改為 F_Fermenting 發酵
  5729. if F1 == 'F_InputtingWater':
  5730. if F_UP_tank_WaterLevel[0] == 1 and F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height:
  5731. # 桶外水位高度高於水位計高度, [致動器] 桶外進水電磁閥 OFF
  5732. data = { "tank_num": "F1", "command": "outer_solenoid_water_status", "value": "off" }
  5733. print('data: ', data)
  5734. # mqtt_f(data)
  5735. # 桶內高度若高於水位指定高度, [致動器] 桶內進水電磁閥 OFF
  5736. data = { "tank_num": "F1", "command": "tank_solenoid_water_in_status", "value": "off" }
  5737. print('data: ', data)
  5738. # mqtt_f(data)
  5739. F1 = 'F_Fermenting'
  5740. print('------- F1 狀態更新:發酵中 -------')
  5741. # [致動器] 馬達 (指定轉速)
  5742. data = { "tank_num": "F1", "command": "tank_motor_status", "value": Ferment_Tank_motor_rpm }
  5743. print('data: ', data)
  5744. # mqtt_f(data)
  5745. # [致動器] 溫控開關 ON
  5746. # data = { "tank_num": "F1", "command": "tank_temp_enable", "value": "on" }
  5747. # print('data: ', data)
  5748. # # mqtt_f(data)
  5749. # [致動器] 設定溫度、持溫時間
  5750. # [致動器] 加熱器 1 ON
  5751. data = { "tank_num": "F1", "command": "tank_heater1_status", "value": "on" }
  5752. print('data: ', data)
  5753. # mqtt_f(data)
  5754. elif F_UP_tank_WaterLevel[0] == 1:
  5755. # 桶外水位高度高於水位計高度, [致動器] 桶外進水電磁閥 OFF
  5756. data = { "tank_num": "F1", "command": "outer_solenoid_water_status", "value": "off" }
  5757. print('data: ', data)
  5758. # mqtt_f(data)
  5759. elif F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height:
  5760. # 桶內高度若高於水位指定高度, [致動器] 桶內進水電磁閥 OFF
  5761. data = { "tank_num": "F1", "command": "tank_solenoid_water_in_status", "value": "off" }
  5762. print('data: ', data)
  5763. # mqtt_f(data)
  5764. if F2 == 'F_InputtingWater' and F_UP_tank_WaterLevel[1] == 1 and F_UP_UltraSoniclist[1] >= Ferment_Tank_water_height:
  5765. F2 = 'F_Fermenting'
  5766. print('------- F2 狀態更新:發酵中 -------')
  5767. if F3 == 'F_InputtingWater' and F_UP_tank_WaterLevel[2] == 1 and F_UP_UltraSoniclist[2] >= Ferment_Tank_water_height:
  5768. F3 = 'F_Fermenting'
  5769. print('------- F3 狀態更新:發酵中 -------')
  5770. if F4 == 'F_InputtingWater' and F_UP_tank_WaterLevel[3] == 1 and F_UP_UltraSoniclist[3] >= Ferment_Tank_water_height:
  5771. F4 = 'F_Fermenting'
  5772. print('------- F4 狀態更新:發酵中 -------')
  5773. if F5 == 'F_InputtingWater' and F_UP_tank_WaterLevel[4] == 1 and F_UP_UltraSoniclist[4] >= Ferment_Tank_water_height:
  5774. F5 = 'F_Fermenting'
  5775. print('------- F5 狀態更新:發酵中 -------')
  5776. if F6 == 'F_InputtingWater' and F_UP_tank_WaterLevel[5] == 1 and F_UP_UltraSoniclist[5] >= Ferment_Tank_water_height:
  5777. F6 = 'F_Fermenting'
  5778. print('------- F6 狀態更新:發酵中 -------')
  5779. # ----- 發酵桶槽 F1~F6 發酵→可出豆 判斷 ------------------------------
  5780. # TODO
  5781. # !!! 發酵槽 F_Fermenting 狀態應該請硬體判斷
  5782. # !!! 若狀態為 F_InputtingWater 且 超音波值>指定水位高度 且 夾層水位計 == 1, 狀態改為 F_Fermenting 發酵
  5783. # 可以多桶各自執行發酵排程
  5784. # -- 取得發酵桶槽 F1~F6 pH -------------
  5785. F_UP_tank_PH = []
  5786. for i in range(1, 7, 1):
  5787. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  5788. PH = float(tank_PH.PH)
  5789. F_UP_tank_PH.append(PH)
  5790. print('F_UP_tank_PH: ', F_UP_tank_PH)
  5791. # -- 取得發酵桶槽 F1~F6 pH -------------
  5792. # -- 取得發酵桶槽 F1~F6 SHT11_TEMP -------------
  5793. F_UP_tank_SHT11_Temp = []
  5794. for i in range(1, 7, 1):
  5795. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  5796. SHT11_Temp = float(tank_SHT11.SHT11_Temp)
  5797. F_UP_tank_SHT11_Temp.append(SHT11_Temp)
  5798. print('F_UP_tank_SHT11_Temp: ', F_UP_tank_SHT11_Temp)
  5799. # -- 取得發酵桶槽 F1~F6 SHT11_TEMP -------------
  5800. #
  5801. if F1 == 'F_Fermenting' and F_UP_tank_SHT11_Temp[0] >= Ferment_Tank_fermenting_temp and F_UP_tank_PH[0] <= Ferment_Tank_fermenting_pH:
  5802. print('發酵等待 ', Ferment_Tank_fermenting_time, ' 秒')
  5803. timer = time.time()
  5804. while True:
  5805. if (time.time() - timer) > Ferment_Tank_fermenting_time :
  5806. # [致動器] 外桶浮選三通閥 OFF
  5807. data = { "tank_num": "F1", "command": "outer_threewayvalve_float_status", "value": "off" }
  5808. print('data: ', data)
  5809. # mqtt_f(data)
  5810. # [致動器] 馬達 0
  5811. data = { "tank_num": "F1", "command": "tank_motor_status", "value": "0" }
  5812. print('data: ', data)
  5813. # mqtt_f(data)
  5814. # [致動器] 溫控開關 OFF
  5815. # data = { "tank_num": "F1", "command": "tank_temp_enable", "value": "off" }
  5816. # print('data: ', data)
  5817. # # mqtt_f(data)
  5818. # [致動器] 加熱器 1 OFF
  5819. data = { "tank_num": "F1", "command": "tank_heater1_status", "value": "off" }
  5820. print('data: ', data)
  5821. # mqtt_f(data)
  5822. break
  5823. # [致動器] 廢水排水閥 (桶內) ON
  5824. data = { "tank_num": "F1", "command": "tank_solenoid_water_out_status", "value": "on" }
  5825. print('data: ', data)
  5826. # mqtt_f(data)
  5827. print('桶內廢水排水 ', Ferment_Tank_WaterOut_time, ' 秒')
  5828. timer = time.time()
  5829. while True:
  5830. if (time.time() - timer) > Ferment_Tank_WaterOut_time:
  5831. # [致動器] 廢水排水閥 (桶內) OFF
  5832. data = { "tank_num": "F1", "command": "tank_solenoid_water_out_status", "value": "off" }
  5833. print('data: ', data)
  5834. # mqtt_f(data)
  5835. break
  5836. F1 = 'F_OutputtingBean'
  5837. print('------- F1 狀態更新:可出豆 -------')
  5838. if F2 == 'F_Fermenting' and F_UP_tank_SHT11_Temp[1] >= Ferment_Tank_fermenting_temp and F_UP_tank_PH[1] <= Ferment_Tank_fermenting_pH:
  5839. F2 = 'F_OutputtingBean'
  5840. print('------- F2 狀態更新:可出豆 -------')
  5841. if F3 == 'F_Fermenting' and F_UP_tank_PH[2] <= Ferment_Tank_fermenting_pH:
  5842. F3 = 'F_OutputtingBean'
  5843. print('------- F3 狀態更新:可出豆 -------')
  5844. if F4 == 'F_Fermenting' and F_UP_tank_PH[3] <= Ferment_Tank_fermenting_pH:
  5845. F4 = 'F_OutputtingBean'
  5846. print('------- F4 狀態更新:可出豆 -------')
  5847. if F5 == 'F_Fermenting' and F_UP_tank_PH[4] <= Ferment_Tank_fermenting_pH:
  5848. F5 = 'F_OutputtingBean'
  5849. print('------- F5 狀態更新:可出豆 -------')
  5850. if F6 == 'F_Fermenting' and F_UP_tank_PH[5] <= Ferment_Tank_fermenting_pH:
  5851. F6 = 'F_OutputtingBean'
  5852. print('------- F6 狀態更新:可出豆 -------')
  5853. if F1 == 'F_OutputtingBean' and F_UP_UltraSoniclist[0] < Ferment_Tank_bean_empty:
  5854. # 增加消毒電磁閥開關
  5855. # [致動器] 消毒電磁閥 ON
  5856. data = { "tank_num": "F1", "command": "tank_solenoid_disinfect_status", "value": "on" }
  5857. print('data: ', data)
  5858. # mqtt_f(data)
  5859. # 暫停 (消毒時間) 秒
  5860. timer = time.time()
  5861. while True:
  5862. if (time.time() - timer) > Ferment_Tank_Disinfect_time :
  5863. # [致動器] 消毒電磁閥 OFF
  5864. data = { "tank_num": "F1", "command": "tank_solenoid_disinfect_status", "value": "off" }
  5865. print('data: ', data)
  5866. # mqtt_f(data)
  5867. break
  5868. print('------- F1 狀態更新:空桶等待 -------')
  5869. F1 = 'F_Waiting'
  5870. # # ----- [測試用] !!!!! F1~F6 入料完成→可出豆 判斷 ------------------------------
  5871. # if F1 == 'F_InputtingBean_Finish': F1 = 'F_OutputtingBean'
  5872. # if F2 == 'F_InputtingBean_Finish': F2 = 'F_OutputtingBean'
  5873. # if F3 == 'F_InputtingBean_Finish': F3 = 'F_OutputtingBean'
  5874. # if F4 == 'F_InputtingBean_Finish': F4 = 'F_OutputtingBean'
  5875. # if F5 == 'F_InputtingBean_Finish': F5 = 'F_OutputtingBean'
  5876. # if F6 == 'F_InputtingBean_Finish': F6 = 'F_OutputtingBean'
  5877. # # ----- [測試用] !!!!! F1~F6 入料完成→可出豆 判斷 ------------------------------
  5878. # ----- 發酵桶槽 F1~F6 可出豆→出料儲豆槽 FO1 判斷 ------------------------------
  5879. # ----- 發酵出料儲豆槽 FO1~FO2 入豆→可出豆判斷 ------------------------------
  5880. # -- 取得發酵出料儲豆槽 FO1~FO2 桶內高度 UltraSonic -------------
  5881. FO_UP_UltraSoniclist = []
  5882. for i in range(1, 3, 1):
  5883. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO' + str(i)).order_by(text('datetime desc')).first()
  5884. UltraSonic = float(output_UltraSonic.UltraSonic)
  5885. FO_UP_UltraSoniclist.append(UltraSonic)
  5886. print('FO_UP_UltraSoniclist: ', FO_UP_UltraSoniclist)
  5887. # 桶槽可出豆, 且出料儲豆槽等待時, 出料儲豆槽入豆
  5888. # 參考 -- 發酵桶槽 F1~F6 可出豆→出料儲豆槽 FO1 判斷 --
  5889. Ferment_OutputtingBean_number = int(F_UP_tanklist.count('F_OutputtingBean'))
  5890. # !!! 若出料儲豆槽狀態為 FO_Waiting(空桶等待) 且 桶槽狀態為 F_OutputtingBean 可出豆, 與 FO1 配合開始出豆
  5891. if FO1 == 'FO_Waiting' and Ferment_OutputtingBean_number >= 1:
  5892. if F1 == 'F_OutputtingBean':
  5893. FO1 = 'FO_InputtingBean'
  5894. print('------- F1 狀態更新:出豆中 -------')
  5895. print('------- FO1 狀態更新:入豆中 -------')
  5896. # [致動器] 出料真空吸料機 ON
  5897. data = { "tank_num": "F1", "command": "input_vacuum_status", "value": "on" }
  5898. print('data: ', data)
  5899. # mqtt_f(data)
  5900. # 暫停 3 秒
  5901. timer = time.time()
  5902. while True:
  5903. if (time.time() - timer) > 3 :
  5904. # [致動器] 蝴蝶閥 ON
  5905. data = { "tank_num": "F1", "command": "tank_diskvalve_status", "value": "on" }
  5906. print('data: ', data)
  5907. # mqtt_f(data)
  5908. break
  5909. timer = time.time()
  5910. while True:
  5911. if (time.time() - timer) > Ferment_Output_vacuumON_time:
  5912. # [致動器] 出料真空吸料機 OFF
  5913. data = { "tank_num": "F1", "command": "input_vacuum_status", "value": "off" }
  5914. print('data: ', data)
  5915. # mqtt_f(data)
  5916. timer = time.time()
  5917. break
  5918. while True:
  5919. if (time.time() - timer) > Ferment_Output_vacuumOFF_time:
  5920. break
  5921. elif F2 == 'F_OutputtingBean':
  5922. FO1 = 'FO_InputtingBean'
  5923. print('------- F2 狀態更新:出豆中 -------')
  5924. print('------- FO1 狀態更新:入豆中 -------')
  5925. elif F3 == 'F_OutputtingBean':
  5926. FO1 = 'FO_InputtingBean'
  5927. print('------- F3 狀態更新:出豆中 -------')
  5928. print('------- FO1 狀態更新:入豆中 -------')
  5929. elif F4 == 'F_OutputtingBean':
  5930. FO1 = 'FO_InputtingBean'
  5931. print('------- F4 狀態更新:出豆中 -------')
  5932. print('------- FO1 狀態更新:入豆中 -------')
  5933. elif F5 == 'F_OutputtingBean':
  5934. FO1 = 'FO_InputtingBean'
  5935. print('------- F5 狀態更新:出豆中 -------')
  5936. print('------- FO1 狀態更新:入豆中 -------')
  5937. elif F6 == 'F_OutputtingBean':
  5938. FO1 = 'FO_InputtingBean'
  5939. print('------- F6 狀態更新:出豆中 -------')
  5940. print('------- FO1 狀態更新:入豆中 -------')
  5941. # 出料儲豆槽入料滿時, 出料儲豆槽狀態改為可出豆 (需判斷是哪個桶槽, 好關閉蝴蝶閥)
  5942. elif FO1 == 'FO_InputtingBean' and FO_UP_UltraSoniclist[0] >= Ferment_Output_bean_height:
  5943. if F1 == 'F_OutputtingBean':
  5944. FO1 = 'FO_OutputtingBean'
  5945. print('------- FO1 狀態更新:可出豆 -------')
  5946. # [致動器] 出料真空吸料機 OFF
  5947. data = { "tank_num": "F1", "command": "input_vacuum_status", "value": "off" }
  5948. print('data: ', data)
  5949. # mqtt_f(data)
  5950. # [致動器] 蝴蝶閥 OFF
  5951. data = { "tank_num": "F1", "command": "tank_diskvalve_status", "value": "off" }
  5952. print('data: ', data)
  5953. # mqtt_f(data)
  5954. elif F2 == 'F_OutputtingBean':
  5955. pass # TODO ←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←← 1020 TODO
  5956. # 出料儲豆槽入料時, 桶槽已空, 則桶槽回到空桶等待, 出料儲豆槽可出豆 ←←←←←←←←←←←←←←←←←←←←←←←←←← 1012 這段怪怪的
  5957. elif FO1 == 'FO_InputtingBean' and Ferment_OutputtingBean_number == 1:
  5958. if F1 == 'F_OutputtingBean':
  5959. if F_UP_UltraSoniclist[0] < Ferment_Tank_bean_empty:
  5960. FO1 = 'FO_OutputtingBean'
  5961. print('------- FO1 狀態更新:可出豆 -------')
  5962. # 增加消毒電磁閥開關
  5963. # [致動器] 消毒電磁閥 ON
  5964. data = { "tank_num": "F1", "command": "tank_solenoid_disinfect_status", "value": "on" }
  5965. print('data: ', data)
  5966. # mqtt_f(data)
  5967. # 暫停 (消毒時間) 秒
  5968. timer = time.time()
  5969. while True:
  5970. if (time.time() - timer) > Ferment_Tank_Disinfect_time :
  5971. # [致動器] 消毒電磁閥 OFF
  5972. data = { "tank_num": "F1", "command": "tank_solenoid_disinfect_status", "value": "off" }
  5973. print('data: ', data)
  5974. # mqtt_f(data)
  5975. break
  5976. print('------- F1 狀態更新:空桶等待 -------')
  5977. F1 = 'F_Waiting'
  5978. else:
  5979. # [致動器] 出料真空吸料機 ON
  5980. data = { "tank_num": "F1", "command": "input_vacuum_status", "value": "on" }
  5981. print('data: ', data)
  5982. # mqtt_f(data)
  5983. # 暫停 3 秒
  5984. timer = time.time()
  5985. while True:
  5986. if (time.time() - timer) > 3 :
  5987. # [致動器] 蝴蝶閥 ON
  5988. data = { "tank_num": "F1", "command": "tank_diskvalve_status", "value": "on" }
  5989. print('data: ', data)
  5990. # mqtt_f(data)
  5991. break
  5992. timer = time.time()
  5993. while True:
  5994. if (time.time() - timer) > Ferment_Output_vacuumON_time:
  5995. # [致動器] 出料真空吸料機 OFF
  5996. data = { "tank_num": "F1", "command": "input_vacuum_status", "value": "off" }
  5997. print('data: ', data)
  5998. # mqtt_f(data)
  5999. timer = time.time()
  6000. break
  6001. while True:
  6002. if (time.time() - timer) > Ferment_Output_vacuumOFF_time:
  6003. break
  6004. elif F2 == 'F_OutputtingBean' and F_UP_UltraSoniclist[1] < 5:
  6005. F2 = 'F_Waiting'
  6006. FO1 = 'FO_OutputtingBean'
  6007. print('------- F2 狀態更新:空桶等待 -------')
  6008. print('------- FO1 狀態更新:可出豆 -------')
  6009. elif F3 == 'F_OutputtingBean' and F_UP_UltraSoniclist[2] < 5:
  6010. F3 = 'F_Waiting'
  6011. FO1 = 'FO_OutputtingBean'
  6012. print('------- F3 狀態更新:空桶等待 -------')
  6013. print('------- FO1 狀態更新:可出豆 -------')
  6014. elif F4 == 'F_OutputtingBean' and F_UP_UltraSoniclist[3] < 5:
  6015. F4 = 'F_Waiting'
  6016. FO1 = 'FO_OutputtingBean'
  6017. print('------- F4 狀態更新:空桶等待 -------')
  6018. print('------- FO1 狀態更新:可出豆 -------')
  6019. elif F5 == 'F_OutputtingBean' and F_UP_UltraSoniclist[4] < 5:
  6020. F5 = 'F_Waiting'
  6021. FO1 = 'FO_OutputtingBean'
  6022. print('------- F5 狀態更新:空桶等待 -------')
  6023. print('------- FO1 狀態更新:可出豆 -------')
  6024. elif F6 == 'F_OutputtingBean' and F_UP_UltraSoniclist[5] < 5:
  6025. F6 = 'F_Waiting'
  6026. FO1 = 'FO_OutputtingBean'
  6027. print('------- F6 狀態更新:空桶等待 -------')
  6028. print('------- FO1 狀態更新:可出豆 -------')
  6029. # 出料儲豆槽出料 且 儲豆槽內高度低於 5 , 為空桶等待
  6030. elif FO1 == 'FO_OutputtingBean' and FO_UP_UltraSoniclist[0] < Ferment_Output_bean_empty:
  6031. FO1 = 'FO_Waiting'
  6032. # ----- 發酵入料儲豆槽 FI1~FI2 入豆→可出豆判斷 ------------------------------
  6033. # 1008 移到桶槽前面
  6034. # ----- 發酵出料儲豆槽 FO1~FO2 入豆→可出豆判斷 ------------------------------
  6035. # 1012 移到桶槽可出豆內
  6036. # ----- 將狀態寫入資料庫 ------------------------------
  6037. # 獲取文本框的值並賦值給user實體對象
  6038. F_status = ferment_container_status()
  6039. F_status.Ferment_Input_1 = FI1
  6040. F_status.Ferment_Input_2 = FI2
  6041. F_status.Ferment_Tank_1 = F1
  6042. F_status.Ferment_Tank_2 = F2
  6043. F_status.Ferment_Tank_3 = F3
  6044. F_status.Ferment_Tank_4 = F4
  6045. F_status.Ferment_Tank_5 = F5
  6046. F_status.Ferment_Tank_6 = F6
  6047. F_status.Ferment_Tank_7 = F7
  6048. F_status.Ferment_Tank_8 = F8
  6049. F_status.Ferment_Tank_9 = F9
  6050. F_status.Ferment_Tank_10 = F10
  6051. F_status.Ferment_Tank_11 = F11
  6052. F_status.Ferment_Tank_12 = F12
  6053. F_status.Ferment_Output_1 = FO1
  6054. F_status.Ferment_Output_2 = FO2
  6055. #將數據保存進資料庫
  6056. db.session.add(F_status)
  6057. # 手動提交
  6058. db.session.commit()
  6059. # ----- 將狀態寫入資料庫 ------------------------------
  6060. return jsonify({"Peel_Output_1":PO1,
  6061. "Ferment_Input_1":FI1,
  6062. "Ferment_Tank_1":F1,
  6063. "Ferment_Tank_2":F2,
  6064. "Ferment_Tank_3":F3,
  6065. "Ferment_Tank_4":F4,
  6066. "Ferment_Tank_5":F5,
  6067. "Ferment_Tank_6":F6,
  6068. "Ferment_Output_1":FO1
  6069. })
  6070. '''
  6071. return jsonify({"Ferment_Input_1":FI1,
  6072. "Ferment_Input_2":FI2,
  6073. "Ferment_Tank_1":F1,
  6074. "Ferment_Tank_2":F2,
  6075. "Ferment_Tank_3":F3,
  6076. "Ferment_Tank_4":F4,
  6077. "Ferment_Tank_5":F5,
  6078. "Ferment_Tank_6":F6,
  6079. "Ferment_Tank_7":F7,
  6080. "Ferment_Tank_8":F8,
  6081. "Ferment_Tank_9":F9,
  6082. "Ferment_Tank_10":F10,
  6083. "Ferment_Tank_11":F11,
  6084. "Ferment_Tank_12":F12,
  6085. "Ferment_Output_1":FO1,
  6086. "Ferment_Output_2":FO2
  6087. })
  6088. '''
  6089. # 1026 以流程圖判斷, 改寫 def ferment_auto_test, 以上為原備份
  6090. # 舊有 video 介面
  6091. @main.route('/video')
  6092. def main_video():
  6093. # 獲取登入信息
  6094. if 'id' in session and 'uname' in session and 'status' in session:
  6095. username = session['uname']
  6096. status = session['status']
  6097. if status == 9:
  6098. return render_template('signin_disable.html')
  6099. elif status == 8:
  6100. return render_template('signin_new.html')
  6101. return render_template('video.html', params=locals())
  6102. else:
  6103. return render_template('sign_in.html')
  6104. @main.route('/sitemap')
  6105. def sitemap():
  6106. if request.method == 'GET':
  6107. if 'id' in session and 'uname' in session and 'status' in session:
  6108. username = session['uname']
  6109. status = session['status']
  6110. print('username: ', username)
  6111. print('status: ', status)
  6112. if status == 9:
  6113. return render_template('signin_disable.html', **locals())
  6114. elif status == 8:
  6115. return render_template('signin_new.html', **locals())
  6116. return render_template('sitemap.html', **locals())
  6117. else:
  6118. return render_template('sign_in.html')
  6119. @main.route('/index_navbar', methods=['GET'])
  6120. def index_navbar():
  6121. return render_template('index_navbar.html')
  6122. @main.route('/camera_dry', methods=['GET', 'POST'])
  6123. def camera_dry():
  6124. if request.method == 'GET':
  6125. if 'id' in session and 'uname' in session and 'status' in session:
  6126. username = session['uname']
  6127. status = session['status']
  6128. if status == 9:
  6129. return render_template('signin_disable.html')
  6130. elif status == 8:
  6131. return render_template('signin_new.html')
  6132. return render_template('camera_dry.html', title='乾燥貨櫃攝影機', **locals())
  6133. else:
  6134. return render_template('sign_in.html')
  6135. @main.route('/camera_ferment', methods=['GET', 'POST'])
  6136. def camera_ferment():
  6137. if request.method == 'GET':
  6138. if 'id' in session and 'uname' in session and 'status' in session:
  6139. username = session['uname']
  6140. status = session['status']
  6141. if status == 9:
  6142. return render_template('signin_disable.html')
  6143. elif status == 8:
  6144. return render_template('signin_new.html')
  6145. return render_template('camera_ferment.html', title='發酵貨櫃攝影機', **locals())
  6146. else:
  6147. return render_template('sign_in.html')
  6148. @main.route('/camera_clean', methods=['GET', 'POST'])
  6149. def camera_clean():
  6150. if request.method == 'GET':
  6151. if 'id' in session and 'uname' in session and 'status' in session:
  6152. username = session['uname']
  6153. status = session['status']
  6154. if status == 9:
  6155. return render_template('signin_disable.html')
  6156. elif status == 8:
  6157. return render_template('signin_new.html')
  6158. return render_template('camera_clean.html', title='清洗貨櫃攝影機', **locals())
  6159. else:
  6160. return render_template('sign_in.html')
  6161. @main.route('/camera_dry_1', methods=['GET', 'POST'])
  6162. def camera_dry_2():
  6163. if request.method == 'GET':
  6164. return render_template('camera_dry_1.html', title='乾燥貨櫃攝影機', **locals())
  6165. @main.route('/camera_<tid>', methods=['GET', 'POST'])
  6166. def camera(tid):
  6167. if request.method == 'GET':
  6168. if 'id' in session and 'uname' in session and 'status' in session:
  6169. username = session['uname']
  6170. status = session['status']
  6171. if status == 9:
  6172. return render_template('signin_disable.html')
  6173. elif status == 8:
  6174. return render_template('signin_new.html')
  6175. if tid == 'CCargo_in':
  6176. WS_URL = 'ws:///60.250.156.230:1111'
  6177. camera_title = '清洗貨櫃內部'
  6178. return render_template('camera.html', title='[畫面]' + camera_title, **locals())
  6179. elif tid == 'CCargo_out':
  6180. WS_URL = 'ws:///60.250.156.230:1111'
  6181. camera_title = '清洗貨櫃外部'
  6182. return render_template('camera.html', title='[畫面]' + camera_title, **locals())
  6183. elif tid == 'FCargo_in':
  6184. WS_URL = 'ws:///60.250.156.230:1111'
  6185. camera_title = '發酵貨櫃內部'
  6186. return render_template('camera.html', title='[畫面]' + camera_title, **locals())
  6187. elif tid == 'FCargo_out':
  6188. WS_URL = 'ws:///60.250.156.230:1111'
  6189. camera_title = '發酵貨櫃外部'
  6190. return render_template('camera.html', title='[畫面]' + camera_title, **locals())
  6191. elif tid == 'DCargo_in':
  6192. WS_URL = 'ws:///60.250.156.230:1111'
  6193. camera_title = '乾燥貨櫃內部'
  6194. return render_template('camera.html', title='[畫面]' + camera_title, **locals())
  6195. elif tid == 'DCargo_out':
  6196. WS_URL = 'ws:///60.250.156.230:1111'
  6197. camera_title = '乾燥貨櫃外部'
  6198. return render_template('camera.html', title='[畫面]' + camera_title, **locals())
  6199. elif tid[:2] == 'DO':
  6200. WS_URL_list = ['ws:///60.250.156.230:1111',
  6201. 'ws:///60.250.156.230:2222'
  6202. ]
  6203. WS_URL = WS_URL_list[int(tid[2:])-1]
  6204. camera_title = '乾燥出料儲豆槽'
  6205. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  6206. elif tid[:2] == 'DI':
  6207. WS_URL_list = ['ws:///60.250.156.230:1111',
  6208. 'ws:///60.250.156.230:2222'
  6209. ]
  6210. WS_URL = WS_URL_list[int(tid[2:])-1]
  6211. camera_title = '乾燥入料儲豆槽'
  6212. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  6213. elif tid[:1] == 'D':
  6214. WS_URL_list = ['ws:///60.250.156.230:8093', # D1 攝影機已安裝
  6215. 'ws:///60.250.156.230:2222',
  6216. 'ws:///60.250.156.230:3333',
  6217. 'ws:///60.250.156.230:4444',
  6218. 'ws:///60.250.156.230:5555',
  6219. 'ws:///60.250.156.230:6666',
  6220. 'ws:///60.250.156.230:7777',
  6221. 'ws:///60.250.156.230:8888',
  6222. 'ws:///60.250.156.230:9999',
  6223. 'ws:///60.250.156.230:1010',
  6224. 'ws:///60.250.156.230:1111',
  6225. 'ws:///60.250.156.230:1212'
  6226. ]
  6227. WS_URL = WS_URL_list[int(tid[1:])-1]
  6228. camera_title = '乾燥槽'
  6229. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  6230. elif tid[:2] == 'FO':
  6231. WS_URL_list = ['ws:///60.250.156.230:1111',
  6232. 'ws:///60.250.156.230:2222'
  6233. ]
  6234. WS_URL = WS_URL_list[int(tid[2:])-1]
  6235. camera_title = '發酵出料儲豆槽'
  6236. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  6237. elif tid[:2] == 'FI':
  6238. WS_URL_list = ['ws:///60.250.156.230:1111',
  6239. 'ws:///60.250.156.230:2222'
  6240. ]
  6241. WS_URL = WS_URL_list[int(tid[2:])-1]
  6242. camera_title = '發酵入料儲豆槽'
  6243. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  6244. elif tid[:1] == 'F':
  6245. WS_URL_list = ['ws:///60.250.156.230:8089', # F1 攝影機已安裝
  6246. 'ws:///60.250.156.230:2222',
  6247. 'ws:///60.250.156.230:3333',
  6248. 'ws:///60.250.156.230:4444',
  6249. 'ws:///60.250.156.230:5555',
  6250. 'ws:///60.250.156.230:6666',
  6251. 'ws:///60.250.156.230:7777',
  6252. 'ws:///60.250.156.230:8888',
  6253. 'ws:///60.250.156.230:9999',
  6254. 'ws:///60.250.156.230:1010',
  6255. 'ws:///60.250.156.230:1111',
  6256. 'ws:///60.250.156.230:1212'
  6257. ]
  6258. WS_URL = WS_URL_list[int(tid[1:])-1]
  6259. camera_title = '發酵槽'
  6260. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  6261. elif tid[:2] == 'CO':
  6262. WS_URL_list = ['ws:///60.250.156.230:1111',
  6263. 'ws:///60.250.156.230:2222'
  6264. ]
  6265. WS_URL = WS_URL_list[int(tid[2:])-1]
  6266. camera_title = '清洗浮選出料儲豆槽'
  6267. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  6268. elif tid[:1] == 'C':
  6269. WS_URL_list = ['ws:///60.250.156.230:8088', # C1 攝影機已安裝
  6270. 'ws:///60.250.156.230:2222',
  6271. 'ws:///60.250.156.230:3333',
  6272. 'ws:///60.250.156.230:4444'
  6273. ]
  6274. WS_URL = WS_URL_list[int(tid[1:])-1]
  6275. camera_title = '清洗浮選槽'
  6276. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  6277. elif tid[:2] == 'SO':
  6278. WS_URL_list = ['ws:///60.250.156.230:1111',
  6279. 'ws:///60.250.156.230:2222'
  6280. ]
  6281. WS_URL = WS_URL_list[int(tid[2:])-1]
  6282. camera_title = '色選機出料儲豆槽'
  6283. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  6284. elif tid[:1] == 'S':
  6285. WS_URL_list = ['ws:///60.250.156.230:1111',
  6286. 'ws:///60.250.156.230:2222'
  6287. ]
  6288. WS_URL = WS_URL_list[int(tid[1:])-1]
  6289. camera_title = '色選機'
  6290. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  6291. elif tid[:2] == 'PO':
  6292. WS_URL_list = ['ws:///60.250.156.230:1111',
  6293. 'ws:///60.250.156.230:2222'
  6294. ]
  6295. WS_URL = WS_URL_list[int(tid[2:])-1]
  6296. camera_title = '脫皮機出料儲豆槽'
  6297. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  6298. elif tid[:1] == 'P':
  6299. WS_URL_list = ['ws:///60.250.156.230:1111',
  6300. 'ws:///60.250.156.230:2222'
  6301. ]
  6302. WS_URL = WS_URL_list[int(tid[1:])-1]
  6303. camera_title = '脫皮機'
  6304. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  6305. elif tid[:1] == 'R':
  6306. WS_URL_list = ['ws:///60.250.156.230:1111'
  6307. ]
  6308. WS_URL = WS_URL_list[int(tid[1:])-1]
  6309. camera_title = '中水桶'
  6310. return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
  6311. else:
  6312. return render_template('sign_in.html')
  6313. else:
  6314. pass
  6315. @main.route('/dry_SHT11_<dtid>', methods=['GET', 'POST'])
  6316. def dry_SHT11(dtid):
  6317. if request.method == 'GET':
  6318. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D' + dtid).order_by(text('datetime desc')).first()
  6319. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D' + dtid).order_by(text('datetime desc')).first()
  6320. SHT11_Temp = tank_SHT11.SHT11_Temp
  6321. SHT11_Humidity = tank_SHT11.SHT11_Humidity
  6322. Soil_Temp = tank_Soil.soil_Temp
  6323. return jsonify({"SHT11_Temp":SHT11_Temp,
  6324. "SHT11_Humidity":SHT11_Humidity,
  6325. "Soil_Temp":Soil_Temp
  6326. })
  6327. else:
  6328. pass
  6329. @main.route('/dry_UltraSonic_<dtid>', methods=['GET', 'POST'])
  6330. def dry_UltraSonic(dtid):
  6331. if request.method == 'GET':
  6332. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D' + dtid).order_by(text('datetime desc')).first()
  6333. UltraSonic = tank_UltraSonic.UltraSonic
  6334. return jsonify({"UltraSonic":UltraSonic
  6335. })
  6336. else:
  6337. pass
  6338. @main.route('/dry_input_UltraSonic_<dtid>', methods=['GET', 'POST'])
  6339. def dry_input_UltraSonic(dtid):
  6340. if request.method == 'GET':
  6341. input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI' + dtid).order_by(text('datetime desc')).first()
  6342. UltraSonic = input_UltraSonic.UltraSonic
  6343. return jsonify({"UltraSonic":UltraSonic
  6344. })
  6345. else:
  6346. pass
  6347. @main.route('/dry_output_UltraSonic_<dtid>', methods=['GET', 'POST'])
  6348. def dry_output_UltraSonic(dtid):
  6349. if request.method == 'GET':
  6350. output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO' + dtid).order_by(text('datetime desc')).first()
  6351. UltraSonic = output_UltraSonic.UltraSonic
  6352. return jsonify({"UltraSonic":UltraSonic
  6353. })
  6354. else:
  6355. pass
  6356. @main.route('/ferment_SHT11_<ftid>', methods=['GET', 'POST'])
  6357. def ferment_SHT11(ftid):
  6358. if request.method == 'GET':
  6359. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  6360. SHT11_Temp = tank_SHT11.SHT11_Temp
  6361. return jsonify({"SHT11_Temp":SHT11_Temp
  6362. })
  6363. else:
  6364. pass
  6365. @main.route('/ferment_WaterLevel_<ftid>', methods=['GET', 'POST'])
  6366. def ferment_WaterLevel(ftid):
  6367. if request.method == 'GET':
  6368. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  6369. WaterLevel = tank_WaterLevel.WaterLevel
  6370. return jsonify({"WaterLevel":WaterLevel
  6371. })
  6372. else:
  6373. pass
  6374. @main.route('/ferment_WaterIn_<ftid>', methods=['GET', 'POST'])
  6375. def ferment_WaterIn(ftid):
  6376. if request.method == 'GET':
  6377. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  6378. UltraSonic = (float(tank_UltraSonic.UltraSonic))
  6379. # tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  6380. # PressureWaterLevel = '{:.2f}'.format((float(tank_PressureWaterLevel.PressureWaterLevel) -15 -90.278)/9.4214)
  6381. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  6382. WaterLevel = tank_WaterLevel.WaterLevel
  6383. return jsonify({"UltraSonic":UltraSonic,
  6384. "WaterLevel":WaterLevel
  6385. })
  6386. else:
  6387. pass
  6388. @main.route('/ferment_UltraSonic_<ftid>', methods=['GET', 'POST'])
  6389. def ferment_UltraSonic(ftid):
  6390. if request.method == 'GET':
  6391. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  6392. UltraSonic = (float(tank_UltraSonic.UltraSonic))
  6393. return jsonify({"UltraSonic":UltraSonic
  6394. })
  6395. else:
  6396. pass
  6397. '''
  6398. @main.route('/ferment_LiDAR_<ftid>', methods=['GET', 'POST'])
  6399. def ferment_LiDAR(ftid):
  6400. if request.method == 'GET':
  6401. tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  6402. LiDAR = tank_LiDAR.LiDAR
  6403. return jsonify({"LiDAR":LiDAR
  6404. })
  6405. else:
  6406. pass
  6407. '''
  6408. @main.route('/ferment_input_UltraSonic_<ftid>', methods=['GET', 'POST'])
  6409. def ferment_input_UltraSonic_(ftid):
  6410. if request.method == 'GET':
  6411. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI' + ftid).order_by(text('datetime desc')).first()
  6412. UltraSonic = input_UltraSonic.UltraSonic
  6413. return jsonify({"UltraSonic":UltraSonic
  6414. })
  6415. else:
  6416. pass
  6417. @main.route('/ferment_output_UltraSonic_<ftid>', methods=['GET', 'POST'])
  6418. def ferment_output_UltraSonic_(ftid):
  6419. if request.method == 'GET':
  6420. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO' + ftid).order_by(text('datetime desc')).first()
  6421. UltraSonic = output_UltraSonic.UltraSonic
  6422. return jsonify({"UltraSonic":UltraSonic
  6423. })
  6424. else:
  6425. pass
  6426. @main.route('/ferment_watertesting_<tid>', methods=['GET', 'POST'])
  6427. def ferment_watertesting(tid):
  6428. if request.method == 'GET':
  6429. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  6430. tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  6431. tank_DO = ferment_tank_DO.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  6432. tank_EC = ferment_tank_EC.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  6433. PH = tank_PH.PH
  6434. ORP = tank_ORP.ORP
  6435. DO = tank_DO.DO
  6436. EC = tank_EC.EC
  6437. return jsonify({"PH":PH,
  6438. "ORP":ORP,
  6439. "DO":DO,
  6440. "EC":EC,
  6441. })
  6442. '''
  6443. @main.route('/ferment_PressureWaterLevel_<ftid>', methods=['GET', 'POST'])
  6444. def ferment_PressureWaterLevel(ftid):
  6445. if request.method == 'GET':
  6446. tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  6447. PressureWaterLevel = float(tank_PressureWaterLevel.PressureWaterLevel)
  6448. #PressureWaterLevel = '{:.2f}'.format((float(tank_PressureWaterLevel.PressureWaterLevel) -15 -90.278)/9.4214)
  6449. print("PressureWaterLevel_start: ", PressureWaterLevel)
  6450. return jsonify({"PressureWaterLevel":PressureWaterLevel
  6451. })
  6452. # 此段刪除
  6453. while int(PressureWaterLevel) < int(testing_water_height):
  6454. tank_water_status = 'NO'
  6455. time.sleep(3)
  6456. # print(ferment_water_height(testing_water_height))
  6457. # [目前桶內水位高度]發酵槽_感測器_壓力式水位計
  6458. tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
  6459. PressureWaterLevel = tank_PressureWaterLevel.PressureWaterLevel
  6460. print("-- MySQL --")
  6461. print("tank_PressureWaterLevel: ", tank_PressureWaterLevel)
  6462. # tank_water_height()
  6463. # print("PressureWaterLevel_while: ", PressureWaterLevel)
  6464. ferment_water_height(testing_water_height)
  6465. return jsonify({"testing_water_height":testing_water_height,
  6466. "tank_water_status":tank_water_status
  6467. })
  6468. else:
  6469. tank_water_status = 'OK'
  6470. print("PressureWaterLevel_else: ", PressureWaterLevel)
  6471. return jsonify({"testing_water_height":testing_water_height,
  6472. "tank_water_status":tank_water_status
  6473. })
  6474. '''
  6475. '''
  6476. def tank_water_height():
  6477. tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
  6478. PressureWaterLevel = tank_PressureWaterLevel.PressureWaterLevel
  6479. print("tank_water_height", PressureWaterLevel)
  6480. return PressureWaterLevel
  6481. '''
  6482. @main.route('/loading/R<rtid>', methods=['GET', 'POST'])
  6483. def R_loading(rtid):
  6484. if request.method == 'GET':
  6485. # 致動器_中水桶
  6486. tank_actuator = reclaimed_tank_actuator.query.filter_by(tank_num='R'+rtid).order_by(text('datetime desc')).first()
  6487. tank_solenoid_water_in = tank_actuator.solenoid_water_in
  6488. tank_solenoid_reclaimed_out = tank_actuator.solenoid_reclaimed_out
  6489. tank_solenoid_water_out = tank_actuator.solenoid_water_out
  6490. tank_pump_reclaimed_out = tank_actuator.pump_reclaimed_out
  6491. return jsonify({"tank_solenoid_water_in":tank_solenoid_water_in,
  6492. "tank_solenoid_reclaimed_out":tank_solenoid_reclaimed_out,
  6493. "tank_solenoid_water_out":tank_solenoid_water_out,
  6494. "tank_pump_reclaimed_out":tank_pump_reclaimed_out
  6495. })
  6496. else:
  6497. pass
  6498. @main.route('/loading/SO<sotid>', methods=['GET', 'POST'])
  6499. def SO_loading(sotid):
  6500. if request.method == 'GET':
  6501. # 致動器_脫皮機_ALL
  6502. output_actuator = colorselect_output_actuator.query.filter_by(tank_num='SO'+sotid).order_by(text('datetime desc')).first()
  6503. output_vacuum = output_actuator.vacuum
  6504. return jsonify({"output_vacuum":output_vacuum
  6505. })
  6506. else:
  6507. pass
  6508. @main.route('/loading/S<stid>', methods=['GET', 'POST'])
  6509. def S_loading(stid):
  6510. if request.method == 'GET':
  6511. # 致動器_色選機
  6512. tank_actuator = colorselect_tank_actuator.query.filter_by(tank_num='S'+stid).order_by(text('datetime desc')).first()
  6513. tank_vacuum = tank_actuator.vacuum
  6514. tank_motor = tank_actuator.motor
  6515. tank_nozzle = tank_actuator.nozzle
  6516. # 致動器_超音波感測器colorselect_tank_UltraSonic
  6517. tank_UltraSonic = colorselect_tank_UltraSonic.query.filter_by(tank_num='S'+stid).order_by(text('datetime desc')).first()
  6518. UltraSonic = tank_UltraSonic.UltraSonic
  6519. # 致動器_顏色感測器
  6520. tank_color = colorselect_tank_color.query.filter_by(tank_num='S'+stid).order_by(text('datetime desc')).first()
  6521. color = tank_color.color
  6522. return jsonify({"tank_vacuum":tank_vacuum,
  6523. "tank_motor":tank_motor,
  6524. "tank_nozzle":tank_nozzle,
  6525. "UltraSonic":UltraSonic,
  6526. "color":color
  6527. })
  6528. else:
  6529. pass
  6530. @main.route('/loading/PO<potid>', methods=['GET', 'POST'])
  6531. def PO_loading(potid):
  6532. if request.method == 'GET':
  6533. # 致動器_脫皮機_ALL
  6534. output_actuator = peel_output_actuator.query.filter_by(tank_num='PO'+potid).order_by(text('datetime desc')).first()
  6535. output_vacuum = output_actuator.vacuum
  6536. return jsonify({"output_vacuum":output_vacuum
  6537. })
  6538. else:
  6539. pass
  6540. @main.route('/loading/P<ptid>', methods=['GET', 'POST'])
  6541. def P_loading(ptid):
  6542. if request.method == 'GET':
  6543. # 致動器_脫皮機_ALL
  6544. tank_actuator = peel_tank_actuator.query.filter_by(tank_num='P'+ptid).order_by(text('datetime desc')).first()
  6545. tank_vacuum = tank_actuator.vacuum
  6546. tank_motor = tank_actuator.motor
  6547. return jsonify({"tank_vacuum":tank_vacuum,
  6548. "tank_motor":tank_motor})
  6549. else:
  6550. pass
  6551. @main.route('/loading/CO<cotid>', methods=['GET', 'POST'])
  6552. def CO_loading(cotid):
  6553. if request.method == 'GET':
  6554. output_actuator = clean_output_actuator.query.filter_by(tank_num='CO'+cotid).order_by(text('datetime desc')).first()
  6555. output_vacuum = output_actuator.vacuum
  6556. return jsonify({"output_vacuum":output_vacuum
  6557. })
  6558. else:
  6559. pass
  6560. @main.route('/loading/C<ctid>', methods=['GET', 'POST'])
  6561. def C_loading(ctid):
  6562. if request.method == 'GET':
  6563. # 致動器_浮選清洗_ALL
  6564. tank_actuator = cleann_tank_actuator.query.filter_by(tank_num='C'+str(ctid)).order_by(text('datetime desc')).first()
  6565. tank_vacuum = tank_actuator.vacuum
  6566. tank_threewayvalve_input = tank_actuator.threewayvalve_input
  6567. tank_motor = tank_actuator.motor
  6568. tank_solenoid_reclaimed_in = tank_actuator.solenoid_reclaimed_in
  6569. tank_solenoid_water_in = tank_actuator.solenoid_water_in
  6570. tank_pump_water_in = tank_actuator.pump_water_in
  6571. tank_solenoid_water_out = tank_actuator.solenoid_water_out
  6572. tank_solenoid_reclaimed_out = tank_actuator.solenoid_reclaimed_out
  6573. tank_solenoid_disinfect = tank_actuator.solenoid_disinfect
  6574. tank_pump_disinfect = tank_actuator.pump_disinfect
  6575. tank_diskvalve = tank_actuator.diskvalve
  6576. # 感測器_浮選清洗_超音波感測器
  6577. tank_UltraSonic = clean_tank_UltraSonic.query.filter_by(tank_num='C'+str(ctid)).order_by(text('datetime desc')).first()
  6578. UltraSonic = tank_UltraSonic.UltraSonic
  6579. tank_Encoder = clean_tank_Encoder.query.filter_by(tank_num='C'+str(ctid)).order_by(text('datetime desc')).first()
  6580. Encoder = tank_Encoder.Encoder
  6581. tank_Turbidity = clean_tank_Turbidity.query.filter_by(tank_num='C'+str(ctid)).order_by(text('datetime desc')).first()
  6582. tankTurbidity = tank_Turbidity.tankTurbidity
  6583. filter_Turbidity = clean_filter_Turbidity.query.filter_by(tank_num='C'+str(ctid)).order_by(text('datetime desc')).first()
  6584. filterTurbidity = filter_Turbidity.filterTurbidity
  6585. # tank_pump_waterInput = tank_actuator.pump_waterInput
  6586. # tank_pump_waterL2L3 = tank_actuator.pump_waterL2L3
  6587. # tank_pump_waterL4L5 = tank_actuator.pump_waterL4L5
  6588. # tank_solenoid_waterL2L3 = tank_actuator.solenoid_waterL2L3
  6589. # tank_solenoid_waterL4L5 = tank_actuator.solenoid_waterL4L5
  6590. # tank_stepping_motor = tank_actuator.stepping_motor
  6591. return jsonify({"UltraSonic":UltraSonic,
  6592. "Encoder":Encoder,
  6593. "tankTurbidity":tankTurbidity,
  6594. "filterTurbidity":filterTurbidity,
  6595. "tank_vacuum":tank_vacuum,
  6596. "tank_threewayvalve_input":tank_threewayvalve_input,
  6597. "tank_motor":tank_motor,
  6598. "tank_solenoid_reclaimed_in":tank_solenoid_reclaimed_in,
  6599. "tank_solenoid_water_in":tank_solenoid_water_in,
  6600. "tank_pump_water_in":tank_pump_water_in,
  6601. "tank_solenoid_water_out":tank_solenoid_water_out,
  6602. "tank_solenoid_reclaimed_out":tank_solenoid_reclaimed_out,
  6603. "tank_solenoid_disinfect":tank_solenoid_disinfect,
  6604. "tank_pump_disinfect":tank_pump_disinfect,
  6605. "tank_diskvalve":tank_diskvalve
  6606. })
  6607. else:
  6608. pass
  6609. @main.route('/loading/F<ftid>', methods=['GET', 'POST'])
  6610. def F_loading(ftid):
  6611. if request.method == 'GET':
  6612. # 致動器_發酵槽_ALL
  6613. tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6614. tank_vacuum = tank_actuator.vacuum
  6615. tank_threewayvalve_input = tank_actuator.threewayvalve_input
  6616. tank_diskvalve = tank_actuator.diskvalve
  6617. solenoid_tank_pump = tank_actuator.solenoid_tank_pump
  6618. tank_solenoid_disinfect = tank_actuator.solenoid_tank_disinfect
  6619. outer_solenoid_water = tank_actuator.solenoid_outer_water
  6620. tank_solenoid_water_in = tank_actuator.solenoid_tank_water_in
  6621. tank_solenoid_water_out = tank_actuator.solenoid_tank_water_out
  6622. tank_pump_sensor = tank_actuator.pump_sensor
  6623. outer_threewayvalve_float = tank_actuator.threewayvalve_outer_float
  6624. tank_motor = tank_actuator.motor
  6625. tank_heater1 = tank_actuator.heater1
  6626. tank_heater2 = tank_actuator.heater2
  6627. tank_temp_enable = tank_actuator.temp_enable
  6628. tank_temp = tank_actuator.temp
  6629. # 感測器_發酵桶_SHT11
  6630. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6631. SHT11_Temp = float(tank_SHT11.SHT11_Temp)
  6632. SHT11_Humidity = float(tank_SHT11.SHT11_Humidity)
  6633. # 感測器_發酵桶_二氧化碳
  6634. tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6635. CO2 = float(tank_CO2.CO2)
  6636. # 感測器_發酵桶_酸鹼值
  6637. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6638. tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6639. tank_DO = ferment_tank_DO.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6640. tank_EC = ferment_tank_EC.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6641. PH = float(tank_PH.PH)
  6642. ORP = float(tank_ORP.ORP)
  6643. DO = float(tank_DO.DO)
  6644. EC = float(tank_EC.EC)
  6645. # 感測器_發酵桶_氣壓
  6646. tank_PA = ferment_tank_PA.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6647. PA = float(tank_PA.PA)
  6648. # 感測器_發酵桶_超音波感測器
  6649. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6650. UltraSonic= (float(tank_UltraSonic.UltraSonic))
  6651. # 感測器_發酵桶_保溫夾層水位計
  6652. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6653. WaterLevel = tank_WaterLevel.WaterLevel
  6654. # 感測器_發酵桶_咖啡生豆高度
  6655. # tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6656. # LiDAR = tank_LiDAR.LiDAR
  6657. # 感測器_發酵桶_水位高度
  6658. # tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6659. # PressureWaterLevel = '{:.2f}'.format((float(tank_PressureWaterLevel.PressureWaterLevel) -15 -90.278)/9.4214)
  6660. # 感測器_發酵桶_馬達編碼器
  6661. tank_motorEncoder = ferment_tank_motorEncoder.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6662. motorEncoder = tank_motorEncoder.motorEncoder
  6663. return jsonify({"SHT11_Temp": SHT11_Temp,
  6664. "SHT11_Humidity":SHT11_Humidity,
  6665. "CO2":CO2,
  6666. "PH":PH,
  6667. "ORP":ORP,
  6668. "DO":DO,
  6669. "EC":EC,
  6670. "PA":PA,
  6671. "WaterLevel":WaterLevel,
  6672. "UltraSonic":UltraSonic,
  6673. "motorEncoder":motorEncoder,
  6674. "tank_vacuum":tank_vacuum,
  6675. "tank_threewayvalve_input":tank_threewayvalve_input,
  6676. "tank_diskvalve":tank_diskvalve,
  6677. "solenoid_tank_pump":solenoid_tank_pump,
  6678. "tank_solenoid_disinfect":tank_solenoid_disinfect,
  6679. "outer_solenoid_water":outer_solenoid_water,
  6680. "tank_solenoid_water_in":tank_solenoid_water_in,
  6681. "tank_solenoid_water_out":tank_solenoid_water_out,
  6682. "tank_pump_sensor":tank_pump_sensor,
  6683. "outer_threewayvalve_float":outer_threewayvalve_float,
  6684. "tank_motor":tank_motor,
  6685. "tank_heater1":tank_heater1,
  6686. "tank_heater2":tank_heater2,
  6687. "tank_temp_enable":tank_temp_enable,
  6688. "tank_temp":tank_temp
  6689. })
  6690. else:
  6691. pass
  6692. @main.route('/loading/FI<fitid>', methods=['GET', 'POST'])
  6693. def FI_loading(fitid):
  6694. if request.method == 'GET':
  6695. input_actuator = ferment_input_actuator.query.filter_by(tank_num='F'+fitid).order_by(text('datetime desc')).first()
  6696. input_vacuum = input_actuator.vacuum
  6697. input_sensor = ferment_input_UltraSonic.query.filter_by(tank_num='F'+fitid).order_by(text('datetime desc')).first()
  6698. # input_UltraSonic = float("{:.2f}".format(34.6 - float(input_sensor.UltraSonic)))
  6699. input_UltraSonic = float(input_sensor.UltraSonic)
  6700. return jsonify({"input_UltraSonic":input_UltraSonic,
  6701. "input_vacuum":input_vacuum
  6702. })
  6703. else:
  6704. pass
  6705. @main.route('/loading/FO<fotid>', methods=['GET', 'POST'])
  6706. def FO_loading(fotid):
  6707. if request.method == 'GET':
  6708. output_actuator = ferment_output_actuator.query.filter_by(tank_num='FO'+fotid).order_by(text('datetime desc')).first()
  6709. output_vacuum = output_actuator.vacuum
  6710. output_sensor = ferment_output_UltraSonic.query.filter_by(tank_num='FO'+fotid).order_by(text('datetime desc')).first()
  6711. output_UltraSonic = output_sensor.UltraSonic
  6712. tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+fotid).order_by(text('datetime desc')).first()
  6713. LiDAR = tank_LiDAR.LiDAR
  6714. return jsonify({"output_UltraSonic":output_UltraSonic,
  6715. "output_vacuum":output_vacuum,
  6716. "LiDAR":LiDAR
  6717. })
  6718. else:
  6719. pass
  6720. @main.route('/loading/DI<ditid>', methods=['GET', 'POST'])
  6721. def DI_loading(ditid):
  6722. if request.method == 'GET':
  6723. input_actuator = dry_input_brake.query.filter_by(tank_num='DI'+ditid).order_by(text('datetime desc')).first()
  6724. input_vacuum = input_actuator.vacuum
  6725. input_sensor = dry_input_sensor.query.filter_by(tank_num='DI'+ditid).order_by(text('datetime desc')).first()
  6726. input_UltraSonic = input_sensor.UltraSonic
  6727. return jsonify({"input_UltraSonic":input_UltraSonic,
  6728. "input_vacuum":input_vacuum
  6729. })
  6730. else:
  6731. pass
  6732. @main.route('/loading/DO<dotid>', methods=['GET', 'POST'])
  6733. def DO_loading(dotid):
  6734. if request.method == 'GET':
  6735. output_actuator = dry_output_brake.query.filter_by(tank_num='DO'+dotid).order_by(text('datetime desc')).first()
  6736. output_vacuum = output_actuator.vacuum
  6737. output_sensor = dry_output_sensor.query.filter_by(tank_num='DO'+dotid).order_by(text('datetime desc')).first()
  6738. output_UltraSonic = output_sensor.UltraSonic
  6739. return jsonify({"output_vacuum":output_vacuum,
  6740. "output_UltraSonic":output_UltraSonic
  6741. })
  6742. else:
  6743. pass
  6744. @main.route('/loading/D<dtid>', methods=['GET', 'POST'])
  6745. def D_loading(dtid):
  6746. if request.method == 'GET':
  6747. # 感測器_乾燥桶_超音波感測器
  6748. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  6749. UltraSonic = tank_UltraSonic.UltraSonic
  6750. # 感測器_乾燥桶_SHT11
  6751. tonow = dt.now()
  6752. # 感測器_乾燥桶_SHT11
  6753. print("tonow: ", tonow)
  6754. time_del = timedelta(minutes=-60)
  6755. bias_date_time = tonow + time_del
  6756. # print(dt.now() >= dt(2021,11,29,17,35,36))
  6757. # bias_min = tonow.minute + 3
  6758. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(dtid))\
  6759. .filter(dry_tank_SHT11.datetime >= bias_date_time)\
  6760. .order_by(text('datetime desc')).first()
  6761. print("tank_SHT11: ", tank_SHT11, type(tank_SHT11)) # tank_SHT11: <dry_tank_SHT11 2021-12-03 15:39:16> <class 'app.models.dry_tank_SHT11'>
  6762. print("hasattr tank_SHT11: ", hasattr(object, 'tank_SHT11'))
  6763. print("hasattr tank_SHT11.SHT11_Temp: ", hasattr(object, 'tank_SHT11.SHT11_Temp'))
  6764. try:
  6765. SHT11_Temp = tank_SHT11.SHT11_Temp
  6766. SHT11_Humidity = tank_SHT11.SHT11_Humidity
  6767. except AttributeError:
  6768. SHT11_Temp = " — "
  6769. SHT11_Humidity = " — "
  6770. # if not hasattr(object, 'tank_SHT11.SHT11_Temp'):
  6771. # SHT11_Temp = " — "
  6772. # SHT11_Humidity = " — "
  6773. # else:
  6774. # SHT11_Temp = tank_SHT11.SHT11_Temp
  6775. # SHT11_Humidity = tank_SHT11.SHT11_Humidity
  6776. # tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  6777. # SHT11_Temp = tank_SHT11.SHT11_Temp
  6778. # SHT11_Humidity = tank_SHT11.SHT11_Humidity
  6779. # 感測器_乾燥桶_土壤三合一
  6780. tank_Soil = dry_tank_Soil.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  6781. soil_Temp = tank_Soil.soil_Temp
  6782. soil_Humidity = tank_Soil.soil_Humidity
  6783. soil_EC = tank_Soil.soil_EC
  6784. # 感測器_乾燥桶_氣壓
  6785. tank_PA = dry_tank_PA.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  6786. PA = tank_PA.PA
  6787. # 致動器_乾燥桶_ALL
  6788. tank_brake = dry_tank_brake.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  6789. # tank_vacuum = 'ON' if i<100 else 2 if i>100 else 0
  6790. tank_vacuum = tank_brake.vacuum
  6791. tank_threewayvalve_input = tank_brake.threewayvalve_input
  6792. tank_threewayvalve_bean = tank_brake.threewayvalve_bean
  6793. tank_diskvalve = tank_brake.diskvalve
  6794. tank_solenoid_disinfect = tank_brake.solenoid_disinfect
  6795. tank_solenoid_water = tank_brake.solenoid_water
  6796. tank_solenoid_outer_water = tank_brake.solenoid_outer_water
  6797. tank_motor = tank_brake.motor
  6798. tank_blower = tank_brake.blower
  6799. tank_heater1 = tank_brake.heater1
  6800. tank_heater2 = tank_brake.heater2
  6801. tank_temp1_enable = tank_brake.temp1_enable
  6802. tank_temp1 = tank_brake.temp1
  6803. #return jsonify({"peeling": peeling_rpm})
  6804. '''
  6805. info = psutil.virtual_memory()
  6806. print('記憶體使用: ', psutil.Process(os.getpid()).memory_info().rss)
  6807. # print('總記憶體: ', info.total)
  6808. print('記憶體占比: ', info.percent)
  6809. print('cpu 個數: ', psutil.cpu_count())
  6810. '''
  6811. print("SHT11_Temp", SHT11_Temp)
  6812. return jsonify({"UltraSonic":UltraSonic,
  6813. "SHT11_Temp": SHT11_Temp,
  6814. "SHT11_Humidity":SHT11_Humidity,
  6815. "soil_Temp":soil_Temp,
  6816. "soil_Humidity":soil_Humidity,
  6817. "soil_EC":soil_EC,
  6818. "PA":PA,
  6819. "tank_vacuum":tank_vacuum,
  6820. "tank_threewayvalve_input":tank_threewayvalve_input,
  6821. "tank_threewayvalve_bean":tank_threewayvalve_bean,
  6822. "tank_diskvalve":tank_diskvalve,
  6823. "tank_solenoid_disinfect":tank_solenoid_disinfect,
  6824. "tank_solenoid_water":tank_solenoid_water,
  6825. "tank_solenoid_outer_water":tank_solenoid_outer_water,
  6826. "tank_motor":tank_motor,
  6827. "tank_blower":tank_blower,
  6828. "tank_heater1":tank_heater1,
  6829. "tank_heater2":tank_heater2,
  6830. "tank_temp1_enable":tank_temp1_enable,
  6831. "tank_temp1":tank_temp1
  6832. })
  6833. else:
  6834. pass
  6835. @main.route('/index_new')
  6836. def index_new():
  6837. if 'id' in session and 'uname' in session and 'status' in session:
  6838. username = session['uname']
  6839. status = session['status']
  6840. if status == 9:
  6841. return render_template('signin_disable.html', **locals())
  6842. elif status == 8:
  6843. return render_template('signin_new.html', **locals())
  6844. else:
  6845. return render_template('oops.html', **locals())
  6846. return render_template('index_new.html', title='Smart Coffee', **locals())
  6847. @main.route('/user/<name>')
  6848. def user(name):
  6849. return render_template('hello.html', name=name)
  6850. '''
  6851. @main.route('/plot.png')
  6852. def plot():
  6853. # 重新整理會有問題
  6854. # 圖的寬和高
  6855. fig = plt.figure()
  6856. # 在圖中新增子圖, 通常多個圖才會用到?
  6857. axis = fig.add_subplot(1, 1, 1)
  6858. # x、 軸資料
  6859. xs = range(100)
  6860. ys = [random.randint(1, 50) for x in xs]
  6861. axis.plot(xs, ys)
  6862. canvas = FigureCanvas(fig)
  6863. output = io.BytesIO()
  6864. canvas.print_png(output)
  6865. response = make_response(output.getvalue())
  6866. response.mimetype = 'image/png'
  6867. return response
  6868. '''
  6869. @main.route('/chart_<tank>/<sensor_name>/<tid>', methods=['GET', 'POST'])
  6870. def chart_D(tank, sensor_name, tid):
  6871. if request.method == 'GET':
  6872. if 'id' in session and 'uname' in session and 'status' in session:
  6873. username = session['uname']
  6874. status = session['status']
  6875. if status == 9:
  6876. return render_template('signin_disable.html')
  6877. elif status == 8:
  6878. return render_template('signin_new.html')
  6879. else:
  6880. return render_template('oops.html')
  6881. if tank == 'DI':
  6882. return render_template('sensor_chart_DI.html', title='[圖表]' + tank + tid + '乾燥入料儲豆槽', **locals())
  6883. elif tank == 'DO':
  6884. return render_template('sensor_chart_DO.html', title='[圖表]' + tank + tid + '乾燥出料儲豆槽', **locals())
  6885. elif tank == 'FI':
  6886. return render_template('sensor_chart_FI.html', title='[圖表]' + tank + tid + '發酵入料儲豆槽', **locals())
  6887. elif tank == 'FO':
  6888. return render_template('sensor_chart_FO.html', title='[圖表]' + tank + tid + '發酵出料儲豆槽', **locals())
  6889. elif tank == 'F':
  6890. return render_template('sensor_chart_F.html', title='[圖表]' + tank + tid + '發酵槽', **locals())
  6891. else:
  6892. return render_template('sensor_chart_D.html', title='[圖表]' + tank + tid + '乾燥槽', **locals())
  6893. elif request.method == 'POST':
  6894. if 'id' in session and 'uname' in session and 'status' in session:
  6895. username = session['uname']
  6896. status = session['status']
  6897. if status == 9:
  6898. return render_template('signin_disable.html', **locals())
  6899. elif status == 8:
  6900. return render_template('signin_new.html', **locals())
  6901. else:
  6902. return render_template('oops.html', **locals())
  6903. starttime = request.values['sensor_starttime'] # 2021-07-19T09:00
  6904. endtime = request.values['sensor_endtime'] # 2021-07-19T12:00
  6905. sensor_name = request.values['sensors']
  6906. print('sensor_name:', sensor_name)
  6907. # 判斷資料索取區間 起<迄
  6908. if starttime < endtime :
  6909. # print('starttime endtime:', starttime, endtime)
  6910. # print('TF:', starttime<endtime ) # 可以比較 起<迄
  6911. # [html]2021-07-19T09:00 轉換成 [python]datetime.datetime(2021, 07, 19, 09, 00, 00)
  6912. start_YY = starttime[:4] # '2021'
  6913. start_MM = starttime[6:7] if starttime[5:7][:1] == '0' else starttime[5:7] # '07'
  6914. start_DD = starttime[9:10] if starttime[8:10][:1] == '0' else starttime[8:10] # '19'
  6915. start_hh = starttime[12:13] if starttime[11:13][:1] == '0' else starttime[11:13] # '09'
  6916. start_mm = starttime[15:] if starttime[14:][:1] == '0' else starttime[14:] # '00'
  6917. start_ss = 0
  6918. end_YY = endtime[:4] # '2021'
  6919. end_MM = endtime[6:7] if endtime[5:7][:1] == '0' else endtime[5:7] # '07'
  6920. end_DD = endtime[9:10] if endtime[8:10][:1] == '0' else endtime[8:10] # '19'
  6921. end_hh = endtime[12:13] if endtime[11:13][:1] == '0' else endtime[11:13] # '09'
  6922. end_mm = endtime[15:] if endtime[14:][:1] == '0' else endtime[14:] # '00'
  6923. end_ss = 0
  6924. time_range = []
  6925. temp_range = []
  6926. # 拿掉會 Error, 要使用沒有 GUI 的 matplotlib
  6927. plt.switch_backend('agg')
  6928. plt.figure()
  6929. if tank == 'DI':
  6930. print('DI')
  6931. if sensor_name == 'UltraSonic':
  6932. for d in db.session.query(dry_input_sensor) \
  6933. .filter_by(tank_num='DI' + tid) \
  6934. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_input_sensor.datetime) \
  6935. .filter(dry_input_sensor.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  6936. .order_by(dry_input_sensor.datetime):
  6937. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  6938. time_range.append(str(d.datetime))
  6939. temp_range.append(float(d.UltraSonic))
  6940. print('time_range:', time_range)
  6941. print('temp_range:', temp_range)
  6942. return render_template('sensor_chart_DI.html', **locals())
  6943. elif tank == 'DO':
  6944. print('DO')
  6945. if sensor_name == 'UltraSonic':
  6946. for d in db.session.query(dry_output_sensor) \
  6947. .filter_by(tank_num='DO' + tid) \
  6948. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_output_sensor.datetime) \
  6949. .filter(dry_output_sensor.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  6950. .order_by(dry_output_sensor.datetime):
  6951. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  6952. time_range.append(str(d.datetime))
  6953. temp_range.append(float(d.UltraSonic))
  6954. print('time_range:', time_range)
  6955. print('temp_range:', temp_range)
  6956. return render_template('sensor_chart_DO.html', **locals())
  6957. elif tank == 'D':
  6958. print('D')
  6959. if sensor_name == 'SHT11_Temp':
  6960. for d in db.session.query(dry_tank_SHT11) \
  6961. .filter_by(tank_num='D' + tid) \
  6962. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_SHT11.datetime) \
  6963. .filter(dry_tank_SHT11.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  6964. .order_by(dry_tank_SHT11.datetime):
  6965. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  6966. time_range.append(str(d.datetime))
  6967. temp_range.append(float(d.SHT11_Temp))
  6968. # 畫出 x 軸基準線
  6969. # plt.axhline(28.5, color= 'r')
  6970. elif sensor_name == 'SHT11_Humidity':
  6971. for d in db.session.query(dry_tank_SHT11) \
  6972. .filter_by(tank_num='D' + tid) \
  6973. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_SHT11.datetime) \
  6974. .filter(dry_tank_SHT11.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  6975. .order_by(dry_tank_SHT11.datetime):
  6976. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  6977. time_range.append(str(d.datetime))
  6978. temp_range.append(float(d.SHT11_Humidity))
  6979. elif sensor_name == 'UltraSonic':
  6980. for d in db.session.query(dry_tank_UltraSonic) \
  6981. .filter_by(tank_num='D' + tid) \
  6982. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_UltraSonic.datetime) \
  6983. .filter(dry_tank_UltraSonic.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  6984. .order_by(dry_tank_UltraSonic.datetime):
  6985. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  6986. time_range.append(str(d.datetime))
  6987. temp_range.append(float(d.UltraSonic))
  6988. elif sensor_name == 'PA':
  6989. for d in db.session.query(dry_tank_PA) \
  6990. .filter_by(tank_num='D' + tid) \
  6991. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_PA.datetime) \
  6992. .filter(dry_tank_PA.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  6993. .order_by(dry_tank_PA.datetime):
  6994. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  6995. time_range.append(str(d.datetime))
  6996. temp_range.append(float(d.PA))
  6997. elif sensor_name == 'soil_Temp':
  6998. for d in db.session.query(dry_tank_Soil) \
  6999. .filter_by(tank_num='D' + tid) \
  7000. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_Soil.datetime) \
  7001. .filter(dry_tank_Soil.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  7002. .order_by(dry_tank_Soil.datetime):
  7003. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  7004. time_range.append(str(d.datetime))
  7005. temp_range.append(float(d.soil_Temp))
  7006. # 畫出 x 軸基準線
  7007. plt.axhline(28.5, color= 'r')
  7008. elif sensor_name == 'soil_Humidity':
  7009. for d in db.session.query(dry_tank_Soil) \
  7010. .filter_by(tank_num='D' + tid) \
  7011. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_Soil.datetime) \
  7012. .filter(dry_tank_Soil.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  7013. .order_by(dry_tank_Soil.datetime):
  7014. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  7015. time_range.append(str(d.datetime))
  7016. temp_range.append(float(d.soil_Humidity))
  7017. elif sensor_name == 'soil_EC':
  7018. for d in db.session.query(dry_tank_Soil) \
  7019. .filter_by(tank_num='D' + tid) \
  7020. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_Soil.datetime) \
  7021. .filter(dry_tank_Soil.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  7022. .order_by(dry_tank_Soil.datetime):
  7023. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  7024. time_range.append(str(d.datetime))
  7025. temp_range.append(float(d.soil_EC))
  7026. print('time_range:', time_range)
  7027. print('temp_range:', temp_range)
  7028. return render_template('sensor_chart_D.html', **locals())
  7029. elif tank == 'FI':
  7030. print('FI')
  7031. if sensor_name == 'UltraSonic':
  7032. for d in db.session.query(ferment_input_UltraSonic) \
  7033. .filter_by(tank_num='FI' + tid) \
  7034. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_input_UltraSonic.datetime) \
  7035. .filter(ferment_input_UltraSonic.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  7036. .order_by(ferment_input_UltraSonic.datetime):
  7037. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  7038. time_range.append(str(d.datetime))
  7039. temp_range.append(float(d.UltraSonic))
  7040. print('time_range:', time_range)
  7041. print('temp_range:', temp_range)
  7042. return render_template('sensor_chart_FI.html', **locals())
  7043. elif tank == 'FO':
  7044. print('FO')
  7045. if sensor_name == 'UltraSonic':
  7046. for d in db.session.query(ferment_output_UltraSonic) \
  7047. .filter_by(tank_num='FO' + tid) \
  7048. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_output_UltraSonic.datetime) \
  7049. .filter(ferment_output_UltraSonic.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  7050. .order_by(ferment_output_UltraSonic.datetime):
  7051. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  7052. time_range.append(str(d.datetime))
  7053. temp_range.append(float(d.UltraSonic))
  7054. print('time_range:', time_range)
  7055. print('temp_range:', temp_range)
  7056. return render_template('sensor_chart_FO.html', **locals())
  7057. elif tank == 'F':
  7058. print('F')
  7059. if sensor_name == 'LiDAR':
  7060. for d in db.session.query(ferment_tank_LiDAR) \
  7061. .filter_by(tank_num='F' + tid) \
  7062. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_LiDAR.datetime) \
  7063. .filter(ferment_tank_LiDAR.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  7064. .order_by(ferment_tank_LiDAR.datetime):
  7065. time_range.append(str(d.datetime))
  7066. temp_range.append(float(d.LiDAR))
  7067. elif sensor_name == 'motorEncoder':
  7068. print('sensor_name == motorEncoder')
  7069. for d in db.session.query(ferment_tank_motorEncoder) \
  7070. .filter_by(tank_num='F' + tid) \
  7071. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_motorEncoder.datetime) \
  7072. .filter(ferment_tank_motorEncoder.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  7073. .order_by(ferment_tank_motorEncoder.datetime):
  7074. time_range.append(str(d.datetime))
  7075. temp_range.append(float(d.motorEncoder))
  7076. print('time_range: ' + time_range)
  7077. print('temp_range: ' + temp_range)
  7078. elif sensor_name == 'PressureWaterLevel':
  7079. for d in db.session.query(ferment_tank_PressureWaterLevel) \
  7080. .filter_by(tank_num='F' + tid) \
  7081. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_PressureWaterLevel.datetime) \
  7082. .filter(ferment_tank_PressureWaterLevel.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  7083. .order_by(ferment_tank_PressureWaterLevel.datetime):
  7084. time_range.append(str(d.datetime))
  7085. temp_range.append('{:.2f}'.format(float(d.PressureWaterLevel)))
  7086. elif sensor_name == 'SHT11_Temp':
  7087. for d in db.session.query(ferment_tank_SHT11) \
  7088. .filter_by(tank_num='F' + tid) \
  7089. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_PressureWaterLevel.datetime) \
  7090. .filter(ferment_tank_SHT11.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  7091. .order_by(ferment_tank_SHT11.datetime):
  7092. time_range.append(str(d.datetime))
  7093. temp_range.append(float(d.SHT11_Temp))
  7094. elif sensor_name == 'SHT11_Humidity':
  7095. for d in db.session.query(ferment_tank_SHT11) \
  7096. .filter_by(tank_num='F' + tid) \
  7097. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_SHT11.datetime) \
  7098. .filter(ferment_tank_SHT11.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  7099. .order_by(ferment_tank_SHT11.datetime):
  7100. time_range.append(str(d.datetime))
  7101. temp_range.append(float(d.SHT11_Humidity))
  7102. elif sensor_name == 'CO2':
  7103. for d in db.session.query(ferment_tank_CO2) \
  7104. .filter_by(tank_num='F' + tid) \
  7105. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_CO2.datetime) \
  7106. .filter(ferment_tank_CO2.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  7107. .order_by(ferment_tank_CO2.datetime):
  7108. time_range.append(str(d.datetime))
  7109. temp_range.append(float(d.CO2))
  7110. elif sensor_name == 'PH':
  7111. for d in db.session.query(ferment_tank_PH) \
  7112. .filter_by(tank_num='F' + tid) \
  7113. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_PH.datetime) \
  7114. .filter(ferment_tank_PH.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  7115. .order_by(ferment_tank_PH.datetime):
  7116. time_range.append(str(d.datetime))
  7117. temp_range.append(float(d.PH))
  7118. elif sensor_name == 'ORP':
  7119. for d in db.session.query(ferment_tank_ORP) \
  7120. .filter_by(tank_num='F' + tid) \
  7121. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_ORP.datetime) \
  7122. .filter(ferment_tank_ORP.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  7123. .order_by(ferment_tank_ORP.datetime):
  7124. time_range.append(str(d.datetime))
  7125. temp_range.append(float(d.ORP))
  7126. elif sensor_name == 'DO':
  7127. for d in db.session.query(ferment_tank_DO) \
  7128. .filter_by(tank_num='F' + tid) \
  7129. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_DO.datetime) \
  7130. .filter(ferment_tank_DO.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  7131. .order_by(ferment_tank_DO.datetime):
  7132. time_range.append(str(d.datetime))
  7133. temp_range.append(float(d.DO))
  7134. elif sensor_name == 'EC':
  7135. for d in db.session.query(ferment_tank_EC) \
  7136. .filter_by(tank_num='F' + tid) \
  7137. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_EC.datetime) \
  7138. .filter(ferment_tank_EC.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  7139. .order_by(ferment_tank_EC.datetime):
  7140. time_range.append(str(d.datetime))
  7141. temp_range.append(float(d.EC))
  7142. elif sensor_name == 'PA':
  7143. for d in db.session.query(ferment_tank_PA) \
  7144. .filter_by(tank_num='F' + tid) \
  7145. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_PA.datetime) \
  7146. .filter(ferment_tank_PA.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  7147. .order_by(ferment_tank_PA.datetime):
  7148. time_range.append(str(d.datetime))
  7149. temp_range.append(float(d.PA))
  7150. print('time_range:', time_range)
  7151. print('temp_range:', temp_range)
  7152. return render_template('sensor_chart_F.html', **locals())
  7153. '''
  7154. # 設定 x 軸資料、y 軸資料、折線顏色
  7155. plt.plot(time_range, temp_range, 'bo')
  7156. # x 軸標題 (中文無法顯示)
  7157. # plt.xlabel('time')
  7158. # plt.ylabel(sensor_name)
  7159. # x 軸 label 和垂直顯示, rotation='vertical'
  7160. plt.xticks(time_range, rotation='vertical' )
  7161. # 設定圖表標題
  7162. plt.title(sensor_name)
  7163. # 調整圖片與周圍的間距
  7164. plt.tight_layout()
  7165. # plt.show()
  7166. # 儲存圖片 應改為相對路徑
  7167. plt.savefig('C:/Users/USER/Rita/Coffee/CoffeeProject/app/static/img/new_plot.png')
  7168. '''
  7169. # 判斷資料索取區間 起>迄
  7170. else:
  7171. return render_template('sensor_chart_D.html', **locals())
  7172. '''
  7173. @main.route('/chart_DI/<sensor_name>/<tid>', methods=['GET', 'POST'])
  7174. def chart_DI(sensor_name, tid):
  7175. if request.method == 'GET':
  7176. return render_template('sensor_chart_DI.html', **locals())
  7177. elif request.method == 'POST':
  7178. starttime = request.values['sensor_starttime'] # 2021-07-19T09:00
  7179. endtime = request.values['sensor_endtime'] # 2021-07-19T12:00
  7180. sensor_name = request.values['sensors']
  7181. print('sensor_name:', sensor_name)
  7182. # 判斷資料索取區間 起<迄
  7183. if starttime < endtime :
  7184. start_YY = starttime[:4] # '2021'
  7185. start_MM = starttime[6:7] if starttime[5:7][:1] == '0' else starttime[5:7] # '07'
  7186. start_DD = starttime[9:10] if starttime[8:10][:1] == '0' else starttime[8:10] # '19'
  7187. start_hh = starttime[12:13] if starttime[11:13][:1] == '0' else starttime[11:13] # '09'
  7188. start_mm = starttime[15:] if starttime[14:][:1] == '0' else starttime[14:] # '00'
  7189. start_ss = 0
  7190. end_YY = endtime[:4] # '2021'
  7191. end_MM = endtime[6:7] if endtime[5:7][:1] == '0' else endtime[5:7] # '07'
  7192. end_DD = endtime[9:10] if endtime[8:10][:1] == '0' else endtime[8:10] # '19'
  7193. end_hh = endtime[12:13] if endtime[11:13][:1] == '0' else endtime[11:13] # '09'
  7194. end_mm = endtime[15:] if endtime[14:][:1] == '0' else endtime[14:] # '00'
  7195. end_ss = 0
  7196. time_range = []
  7197. temp_range = []
  7198. # 拿掉會 Error, 要使用沒有 GUI 的 matplotlib
  7199. plt.switch_backend('agg')
  7200. plt.figure()
  7201. if sensor_name == 'UltraSonic':
  7202. for d in db.session.query(dry_input_sensor) \
  7203. .filter_by(tank_num='DI' + tid) \
  7204. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_UltraSonic.datetime) \
  7205. .filter(dry_tank_UltraSonic.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  7206. .order_by(dry_tank_UltraSonic.datetime):
  7207. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  7208. time_range.append(str(d.datetime))
  7209. temp_range.append(float(d.UltraSonic))
  7210. # 畫出 x 軸基準線
  7211. # plt.axhline(28.5, color= 'r')
  7212. print('time_range:', time_range)
  7213. print('temp_range:', temp_range)
  7214. return render_template('sensor_chart_DI.html', **locals())
  7215. # 判斷資料索取區間 起>迄
  7216. else:
  7217. return render_template('sensor_chart_DI.html', **locals())
  7218. @main.route('/chart_DO/<sensor_name>/<tid>', methods=['GET', 'POST'])
  7219. def chart_DO(sensor_name, tid):
  7220. if request.method == 'GET':
  7221. return render_template('sensor_chart_DO.html', **locals())
  7222. elif request.method == 'POST':
  7223. starttime = request.values['sensor_starttime'] # 2021-07-19T09:00
  7224. endtime = request.values['sensor_endtime'] # 2021-07-19T12:00
  7225. sensor_name = request.values['sensors']
  7226. print('sensor_name:', sensor_name)
  7227. # 判斷資料索取區間 起<迄
  7228. if starttime < endtime :
  7229. start_YY = starttime[:4] # '2021'
  7230. start_MM = starttime[6:7] if starttime[5:7][:1] == '0' else starttime[5:7] # '07'
  7231. start_DD = starttime[9:10] if starttime[8:10][:1] == '0' else starttime[8:10] # '19'
  7232. start_hh = starttime[12:13] if starttime[11:13][:1] == '0' else starttime[11:13] # '09'
  7233. start_mm = starttime[15:] if starttime[14:][:1] == '0' else starttime[14:] # '00'
  7234. start_ss = 0
  7235. end_YY = endtime[:4] # '2021'
  7236. end_MM = endtime[6:7] if endtime[5:7][:1] == '0' else endtime[5:7] # '07'
  7237. end_DD = endtime[9:10] if endtime[8:10][:1] == '0' else endtime[8:10] # '19'
  7238. end_hh = endtime[12:13] if endtime[11:13][:1] == '0' else endtime[11:13] # '09'
  7239. end_mm = endtime[15:] if endtime[14:][:1] == '0' else endtime[14:] # '00'
  7240. end_ss = 0
  7241. time_range = []
  7242. temp_range = []
  7243. # 拿掉會 Error, 要使用沒有 GUI 的 matplotlib
  7244. plt.switch_backend('agg')
  7245. plt.figure()
  7246. if sensor_name == 'UltraSonic':
  7247. for d in db.session.query(dry_input_sensor) \
  7248. .filter_by(tank_num='DO' + tid) \
  7249. .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_UltraSonic.datetime) \
  7250. .filter(dry_tank_UltraSonic.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
  7251. .order_by(dry_tank_UltraSonic.datetime):
  7252. # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
  7253. time_range.append(str(d.datetime))
  7254. temp_range.append(float(d.UltraSonic))
  7255. # 畫出 x 軸基準線
  7256. # plt.axhline(28.5, color= 'r')
  7257. print('time_range:', time_range)
  7258. print('temp_range:', temp_range)
  7259. return render_template('sensor_chart_DO.html', **locals())
  7260. # 判斷資料索取區間 起>迄
  7261. else:
  7262. return render_template('sensor_chart_DO.html', **locals())
  7263. '''
  7264. # Rita 測試
  7265. # 乾燥桶感測器/致動器測試
  7266. # Rita 須加上 <tid> 區分桶號 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  7267. @main.route('/dry_tank/1', methods=['GET'])
  7268. def dry_tank():
  7269. if request.method == 'GET':
  7270. return render_template('dry_tank.html')
  7271. @main.route('/clean', methods=['GET'])
  7272. def clean():
  7273. if 'id' in session and 'uname' in session and 'status' in session:
  7274. username = session['uname']
  7275. status = session['status']
  7276. if status == 9:
  7277. return render_template('signin_disable.html')
  7278. elif status == 8:
  7279. return render_template('signin_new.html')
  7280. else:
  7281. return render_template('oops.html')
  7282. return render_template('clean.html', title='清洗貨櫃', **locals())
  7283. @main.route('/ferment', methods=['GET'])
  7284. def ferment():
  7285. if 'id' in session and 'uname' in session and 'status' in session:
  7286. username = session['uname']
  7287. status = session['status']
  7288. if status == 9:
  7289. return render_template('signin_disable.html')
  7290. elif status == 8:
  7291. return render_template('signin_new.html')
  7292. else:
  7293. return render_template('oops.html')
  7294. return render_template('ferment.html', title='發酵貨櫃', **locals())
  7295. @main.route('/dry', methods=['GET'])
  7296. def dry():
  7297. if request.method == 'GET':
  7298. if 'id' in session and 'uname' in session and 'status' in session:
  7299. username = session['uname']
  7300. status = session['status']
  7301. if status == 9:
  7302. return render_template('signin_disable.html')
  7303. elif status == 8:
  7304. return render_template('signin_new.html')
  7305. else:
  7306. return render_template('oops.html')
  7307. return render_template('dry.html', title='乾燥貨櫃', **locals())
  7308. @main.route('/reclaimedwater_tank/<tid>', methods=['GET', 'POST'])
  7309. def reclaimedwater_tank(tid):
  7310. if request.method == 'GET':
  7311. if 'id' in session and 'uname' in session and 'status' in session:
  7312. username = session['uname']
  7313. status = session['status']
  7314. if status == 9:
  7315. return render_template('signin_disable.html')
  7316. elif status == 8:
  7317. return render_template('signin_new.html')
  7318. else:
  7319. return render_template('oops.html')
  7320. # 致動器_中水桶
  7321. tank_actuator = reclaimed_tank_actuator.query.filter_by(tank_num='R'+tid).order_by(text('datetime desc')).first()
  7322. tank_solenoid_water_in = tank_actuator.solenoid_water_in
  7323. tank_solenoid_reclaimed_out = tank_actuator.solenoid_reclaimed_out
  7324. tank_solenoid_water_out = tank_actuator.solenoid_water_out
  7325. tank_pump_reclaimed_out = tank_actuator.pump_reclaimed_out
  7326. return render_template('reclaimedwater_tank.html', title='[操作] 中水桶操作介面', **locals())
  7327. elif request.method == 'POST':
  7328. pass
  7329. @main.route('/colorselect_container_tank/<tid>', methods=['GET', 'POST'])
  7330. def colorselect_container_tank(tid):
  7331. if request.method == 'GET':
  7332. if 'id' in session and 'uname' in session and 'status' in session:
  7333. username = session['uname']
  7334. status = session['status']
  7335. if status == 9:
  7336. return render_template('signin_disable.html')
  7337. elif status == 8:
  7338. return render_template('signin_new.html')
  7339. else:
  7340. return render_template('oops.html')
  7341. # 致動器_色選機
  7342. tank_actuator = colorselect_tank_actuator.query.filter_by(tank_num='S'+tid).order_by(text('datetime desc')).first()
  7343. tank_vacuum = tank_actuator.vacuum
  7344. tank_motor = tank_actuator.motor
  7345. tank_nozzle = tank_actuator.nozzle
  7346. # 致動器_超音波感測器colorselect_tank_UltraSonic
  7347. tank_UltraSonic = colorselect_tank_UltraSonic.query.filter_by(tank_num='S'+tid).order_by(text('datetime desc')).first()
  7348. # 致動器_顏色感測器
  7349. tank_color = colorselect_tank_color.query.filter_by(tank_num='S'+tid).order_by(text('datetime desc')).first()
  7350. return render_template('colorselect_container_tank.html', title='[操作] S' + tid + ' 色選機操作介面', **locals())
  7351. elif request.method == 'POST':
  7352. pass
  7353. @main.route('/peel_container_tank/<tid>', methods=['GET', 'POST'])
  7354. def peel_container_tank(tid):
  7355. if request.method == 'GET':
  7356. if 'id' in session and 'uname' in session and 'status' in session:
  7357. username = session['uname']
  7358. status = session['status']
  7359. if status == 9:
  7360. return render_template('signin_disable.html')
  7361. elif status == 8:
  7362. return render_template('signin_new.html')
  7363. else:
  7364. return render_template('oops.html')
  7365. # 致動器_脫皮機_ALL
  7366. # tank_num='P'+str(tid)
  7367. tank_actuator = peel_tank_actuator.query.filter_by(tank_num='P'+str(tid)).order_by(text('datetime desc')).first()
  7368. tank_vacuum = tank_actuator.vacuum
  7369. tank_motor = tank_actuator.motor
  7370. # 感測器_脫皮機出料儲豆槽_超音波高度
  7371. tank_UltraSonic = peel_output_UltraSonic.query.filter_by(tank_num='P'+str(tid)).order_by(text('datetime desc')).first()
  7372. # 感測器_脫皮機出料儲豆槽_馬達編碼器
  7373. tank_motorEncoder = peel_output_motorEncoder.query.filter_by(tank_num='P'+str(tid)).order_by(text('datetime desc')).first()
  7374. return render_template('peel_container_tank.html', title='[操作] P' + tid + ' 脫皮機操作介面', **locals())
  7375. elif request.method == 'POST':
  7376. pass
  7377. @main.route('/peel_container/<tid>', methods=['GET', 'POST'])
  7378. def peel_container(tid):
  7379. if request.method == 'GET':
  7380. if 'id' in session and 'uname' in session and 'status' in session:
  7381. username = session['uname']
  7382. status = session['status']
  7383. if status == 9:
  7384. return render_template('signin_disable.html')
  7385. elif status == 8:
  7386. return render_template('signin_new.html')
  7387. else:
  7388. return render_template('oops.html')
  7389. # 致動器_入料儲豆槽_真空吸料機
  7390. input_vacuum = peel_input_actuator.query.filter_by(tank_num='P'+str(tid)).order_by(text('datetime desc')).first()
  7391. input_vacuum = input_vacuum.vacuum
  7392. # 致動器_脫皮機_ALL
  7393. tank_actuator = peel_tank_actuator.query.filter_by(tank_num='P'+str(tid)).order_by(text('datetime desc')).first()
  7394. tank_vacuum = tank_actuator.vacuum
  7395. tank_motor = tank_actuator.motor
  7396. # 致動器_出料儲豆槽_真空吸料機
  7397. output_vacuum = peel_output_actuator.query.filter_by(tank_num='P'+str(tid)).order_by(text('datetime desc')).first()
  7398. output_vacuum = output_vacuum.vacuum
  7399. return render_template('peel_container.html', title='脫皮機P' + tid + '總操作介面', **locals())
  7400. elif request.method == 'POST':
  7401. pass
  7402. @main.route('/clean_container/<tid>', methods=['GET', 'POST'])
  7403. def clean_container(tid):
  7404. if request.method == 'GET':
  7405. if 'id' in session and 'uname' in session and 'status' in session:
  7406. username = session['uname']
  7407. status = session['status']
  7408. if status == 9:
  7409. return render_template('signin_disable.html')
  7410. elif status == 8:
  7411. return render_template('signin_new.html')
  7412. else:
  7413. return render_template('oops.html')
  7414. # 致動器_入料儲豆槽_真空吸料機
  7415. input_vacuum = clean_input_actuator.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  7416. input_vacuum = 'ON' if (input_vacuum.vacuum == 1) else 'OFF'
  7417. # 致動器_浮選清洗_ALL
  7418. tank_actuator = clean_tank_actuator.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  7419. tank_vacuum = 'ON' if tank_actuator.vacuum == 1 else 'OFF'
  7420. tank_pump_waterInput = 'ON' if tank_actuator.pump_waterInput == 1 else 'OFF'
  7421. tank_pump_waterL2L3 = 'ON' if tank_actuator.pump_waterL2L3 == 1 else 'OFF'
  7422. tank_pump_waterL4L5 = 'ON' if tank_actuator.pump_waterL4L5 == 1 else 'OFF'
  7423. tank_solenoid_waterL2L3 = 'ON' if tank_actuator.solenoid_waterL2L3 == 1 else 'OFF'
  7424. tank_solenoid_waterL4L5 = 'ON' if tank_actuator.solenoid_waterL4L5 == 1 else 'OFF'
  7425. tank_stepping_motor = tank_actuator.stepping_motor
  7426. # 致動器_出料儲豆槽_真空吸料機
  7427. output_vacuum = clean_output_actuator.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  7428. output_vacuum = 'ON' if (output_vacuum.vacuum == 1) else 'OFF'
  7429. # 感測器_浮選清洗_超音波感測器
  7430. tank_UltraSonic = clean_tank_UltraSonic.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  7431. return render_template('clean_container.html', title='[操作] C' + tid + ' 清洗浮選槽操作介面', **locals())
  7432. elif request.method == 'POST':
  7433. pass
  7434. @main.route('/clean_container_tank/<tid>', methods=['GET', 'POST'])
  7435. def clean_container_tank(tid):
  7436. if request.method == 'GET':
  7437. if 'id' in session and 'uname' in session and 'status' in session:
  7438. username = session['uname']
  7439. status = session['status']
  7440. if status == 9:
  7441. return render_template('signin_disable.html')
  7442. elif status == 8:
  7443. return render_template('signin_new.html')
  7444. else:
  7445. return render_template('oops.html')
  7446. # 致動器_浮選清洗_ALL
  7447. tank_actuator = cleann_tank_actuator.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  7448. try:
  7449. tank_vacuum = tank_actuator.vacuum
  7450. except AttributeError:
  7451. tank_vacuum = 'noValue'
  7452. try:
  7453. tank_threewayvalve_input = tank_actuator.threewayvalve_input
  7454. except AttributeError:
  7455. tank_threewayvalve_input = 'noValue'
  7456. try:
  7457. tank_motor = tank_actuator.motor
  7458. except AttributeError:
  7459. tank_motor = 'noValue'
  7460. try:
  7461. tank_solenoid_reclaimed_in = tank_actuator.solenoid_reclaimed_in
  7462. except AttributeError:
  7463. tank_solenoid_reclaimed_in = 'noValue'
  7464. try:
  7465. tank_solenoid_water_in = tank_actuator.solenoid_water_in
  7466. except AttributeError:
  7467. tank_solenoid_water_in = 'noValue'
  7468. try:
  7469. tank_pump_water_in = tank_actuator.pump_water_in
  7470. except AttributeError:
  7471. tank_pump_water_in = 'noValue'
  7472. try:
  7473. tank_solenoid_water_out = tank_actuator.solenoid_water_out
  7474. except AttributeError:
  7475. tank_solenoid_water_out = 'noValue'
  7476. try:
  7477. tank_solenoid_reclaimed_out = tank_actuator.solenoid_reclaimed_out
  7478. except AttributeError:
  7479. tank_solenoid_reclaimed_out = 'noValue'
  7480. try:
  7481. tank_solenoid_disinfect = tank_actuator.solenoid_disinfect
  7482. except AttributeError:
  7483. tank_solenoid_disinfect = 'noValue'
  7484. try:
  7485. tank_pump_disinfect = tank_actuator.pump_disinfect
  7486. except AttributeError:
  7487. tank_pump_disinfect = 'noValue'
  7488. try:
  7489. tank_diskvalve = tank_actuator.diskvalve
  7490. except AttributeError:
  7491. tank_diskvalve = 'noValue'
  7492. # tank_pump_waterInput = 'ON' if tank_actuator.pump_waterInput == 1 else 'OFF'
  7493. # tank_pump_waterL2L3 = 'ON' if tank_actuator.pump_waterL2L3 == 1 else 'OFF'
  7494. # tank_pump_waterL4L5 = 'ON' if tank_actuator.pump_waterL4L5 == 1 else 'OFF'
  7495. # tank_solenoid_waterL2L3 = 'ON' if tank_actuator.solenoid_waterL2L3 == 1 else 'OFF'
  7496. # tank_solenoid_waterL4L5 = 'ON' if tank_actuator.solenoid_waterL4L5 == 1 else 'OFF'
  7497. # tank_stepping_motor = tank_actuator.stepping_motor
  7498. # 感測器_浮選清洗_超音波感測器
  7499. tank_UltraSonic = clean_tank_UltraSonic.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  7500. try:
  7501. UltraSonic = tank_UltraSonic.UltraSonic
  7502. except AttributeError:
  7503. UltraSonic = 'noValue'
  7504. tank_Encoder = clean_tank_Encoder.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  7505. try:
  7506. Encoder = tank_Encoder.Encoder
  7507. except AttributeError:
  7508. Encoder = 'noValue'
  7509. tank_Turbidity = clean_tank_Turbidity.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  7510. try:
  7511. tankTurbidity = tank_Turbidity.tankTurbidity
  7512. except AttributeError:
  7513. tankTurbidity = 'noValue'
  7514. filter_Turbidity = clean_filter_Turbidity.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  7515. try:
  7516. filterTurbidity = filter_Turbidity.filterTurbidity
  7517. except AttributeError:
  7518. filterTurbidity = 'noValue'
  7519. return render_template('clean_container_tank.html', title='[操作] C' + tid + ' 清洗浮選槽操作介面', **locals())
  7520. elif request.method == 'POST':
  7521. pass
  7522. @main.route('/ferment_container/<tid>', methods=['GET', 'POST'])
  7523. def ferment_container(tid):
  7524. if request.method == 'GET':
  7525. if 'id' in session and 'uname' in session and 'status' in session:
  7526. username = session['uname']
  7527. status = session['status']
  7528. if status == 9:
  7529. return render_template('signin_disable.html')
  7530. elif status == 8:
  7531. return render_template('signin_new.html')
  7532. else:
  7533. return render_template('oops.html')
  7534. # 致動器_發酵槽_ALL
  7535. tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7536. tank_vacuum = 'ON' if tank_actuator.vacuum == 1 else 'OFF'
  7537. tank_threewayvalve_input = 'ON' if tank_actuator.threewayvalve_input == 1 else 'OFF'
  7538. tank_diskvalve = 'ON' if tank_actuator.diskvalve == 1 else 'OFF'
  7539. tank_solenoid_water_total = 'ON' if tank_actuator.solenoid_tank_water_total == 1 else 'OFF'
  7540. tank_solenoid_disinfect = 'ON' if tank_actuator.solenoid_tank_disinfect == 1 else 'OFF'
  7541. outer_solenoid_water = 'ON' if tank_actuator.solenoid_outer_water == 1 else 'OFF'
  7542. tank_solenoid_water_in = 'ON' if tank_actuator.solenoid_tank_water_in == 1 else 'OFF'
  7543. tank_pump_sensor = 'ON' if tank_actuator.pump_sensor == 1 else 'OFF'
  7544. tank_threewayvalve_bean = 'ON' if tank_actuator.threewayvalve_bean == 1 else 'OFF'
  7545. outer_threewayvalve_float = 'ON' if tank_actuator.threewayvalve_outer_float == 1 else 'OFF'
  7546. tank_motor = tank_actuator.motor
  7547. tank_heater1 = 'ON' if tank_actuator.heater1 == 1 else 'OFF'
  7548. tank_heater2 = 'ON' if tank_actuator.heater2 == 1 else 'OFF'
  7549. tank_temp_enable = 'ON' if tank_actuator.temp_enable == 1 else 'OFF'
  7550. tank_temp = tank_actuator.temp
  7551. # 感測器_發酵桶_SHT11
  7552. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7553. # 感測器_發酵桶_二氧化碳
  7554. tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7555. # 感測器_發酵桶_酸鹼值
  7556. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7557. tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7558. tank_DO = ferment_tank_DO.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7559. tank_EC = ferment_tank_EC.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7560. # 感測器_發酵桶_氣壓
  7561. tank_PA = ferment_tank_PA.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7562. # 感測器_發酵桶_超音波感測器
  7563. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7564. # 感測器_發酵桶_水位計
  7565. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7566. num_tank_WaterLevel = float(tank_WaterLevel.WaterLevel)
  7567. print('tank_WaterLevel', tank_WaterLevel.WaterLevel)
  7568. if tank_WaterLevel.WaterLevel == '1':
  7569. WaterLevel = '滿'
  7570. elif tank_WaterLevel.WaterLevel == '0':
  7571. WaterLevel = '未達滿水高度'
  7572. else:
  7573. WaterLevel = 'ERROR'
  7574. # 感測器_發酵桶_咖啡生豆高度
  7575. tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7576. LiDAR = tank_LiDAR.LiDAR
  7577. # 感測器_發酵桶_水位高度
  7578. tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7579. PressureWaterLevel = '{:.2f}'.format((float(tank_PressureWaterLevel.PressureWaterLevel) -15 -90.278)/9.4214)
  7580. if tid in ['1', '2', '3', '4', '5', '6']:
  7581. # print("1")
  7582. # 感測器_入料儲豆槽_超音波感測器
  7583. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI1').order_by(text('datetime desc')).first()
  7584. # 致動器_入料儲豆槽_真空吸引機
  7585. input_vacuum = ferment_input_actuator.query.filter_by(tank_num='FI1').order_by(text('datetime desc')).first()
  7586. input_vacuum = input_vacuum.vacuum
  7587. # 感測器_出料儲豆槽_超音波感測器
  7588. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO1').order_by(text('datetime desc')).first()
  7589. # 致動器_出料儲豆槽_真空吸引機
  7590. output_vacuum = ferment_output_actuator.query.filter_by(tank_num='FO1').order_by(text('datetime desc')).first()
  7591. output_vacuum = output_vacuum.vacuum
  7592. elif tid in ['7', '8', '9', '10', '11', '12']:
  7593. # print("2")
  7594. # 感測器_入料儲豆槽_超音波感測器
  7595. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI2').order_by(text('datetime desc')).first()
  7596. # 致動器_入料儲豆槽_真空吸引機
  7597. input_vacuum = ferment_input_actuator.query.filter_by(tank_num='FI2').order_by(text('datetime desc')).first()
  7598. input_vacuum = input_vacuum.vacuum
  7599. print("input_vacuum", input_vacuum)
  7600. # 感測器_出料儲豆槽_超音波感測器
  7601. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO2').order_by(text('datetime desc')).first()
  7602. # 致動器_出料儲豆槽_真空吸引機
  7603. output_vacuum = ferment_output_actuator.query.filter_by(tank_num='FO2').order_by(text('datetime desc')).first()
  7604. output_vacuum = output_vacuum.vacuum
  7605. print("output_vacuum", output_vacuum)
  7606. return render_template('ferment_container.html', title='發酵槽F' + tid + '總操作介面' , **locals())
  7607. elif request.method == 'POST':
  7608. pass
  7609. @main.route('/ferment_container_tank/<tid>', methods=['GET', 'POST'])
  7610. def ferment_container_tank(tid):
  7611. if request.method == 'GET':
  7612. if 'id' in session and 'uname' in session and 'status' in session:
  7613. username = session['uname']
  7614. status = session['status']
  7615. if status == 9:
  7616. return render_template('signin_disable.html')
  7617. elif status == 8:
  7618. return render_template('signin_new.html')
  7619. else:
  7620. return render_template('oops.html')
  7621. # 致動器_發酵槽_ALL
  7622. tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7623. tank_vacuum = 'ON' if tank_actuator.vacuum == 1 else 'OFF'
  7624. tank_threewayvalve_input = 'ON' if tank_actuator.threewayvalve_input == 1 else 'OFF'
  7625. tank_diskvalve = 'ON' if tank_actuator.diskvalve == 1 else 'OFF'
  7626. solenoid_tank_pump = 'ON' if tank_actuator.solenoid_tank_pump == 1 else 'OFF'
  7627. tank_solenoid_disinfect = 'ON' if tank_actuator.solenoid_tank_disinfect == 1 else 'OFF'
  7628. outer_solenoid_water = 'ON' if tank_actuator.solenoid_outer_water == 1 else 'OFF'
  7629. tank_solenoid_water_in = 'ON' if tank_actuator.solenoid_tank_water_in == 1 else 'OFF'
  7630. tank_solenoid_water_out = 'ON' if tank_actuator.solenoid_tank_water_out == 1 else 'OFF'
  7631. tank_pump_sensor = 'ON' if tank_actuator.pump_sensor == 1 else 'OFF'
  7632. outer_threewayvalve_float = 'ON' if tank_actuator.threewayvalve_outer_float == 1 else 'OFF'
  7633. tank_motor = tank_actuator.motor
  7634. tank_heater1 = 'ON' if tank_actuator.heater1 == 1 else 'OFF'
  7635. tank_heater2 = 'ON' if tank_actuator.heater2 == 1 else 'OFF'
  7636. tank_temp_enable = 'ON' if tank_actuator.temp_enable == 1 else 'OFF'
  7637. tank_temp = tank_actuator.temp
  7638. # 感測器_發酵桶_SHT11
  7639. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7640. # 感測器_發酵桶_二氧化碳
  7641. tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7642. # 感測器_發酵桶_酸鹼值
  7643. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7644. tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7645. tank_DO = ferment_tank_DO.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7646. tank_EC = ferment_tank_EC.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7647. # 感測器_發酵桶_氣壓
  7648. tank_PA = ferment_tank_PA.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7649. # 感測器_發酵桶_超音波感測器
  7650. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7651. # 感測器_發酵桶_水位計
  7652. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7653. num_tank_WaterLevel = float(tank_WaterLevel.WaterLevel)
  7654. if tank_WaterLevel.WaterLevel == '1':
  7655. WaterLevel = '滿'
  7656. elif tank_WaterLevel.WaterLevel == '0':
  7657. WaterLevel = '未達滿水高度'
  7658. else:
  7659. WaterLevel = 'ERROR'
  7660. # 感測器_發酵桶_咖啡生豆高度
  7661. #tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7662. #LiDAR = tank_LiDAR.LiDAR
  7663. # 感測器_發酵桶_水位高度
  7664. #tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7665. #PressureWaterLevel = '{:.2f}'.format((float(tank_PressureWaterLevel.PressureWaterLevel) -15 -90.278)/9.4214)
  7666. # 感測器_發酵桶_馬達編碼器
  7667. tank_motorEncoder = ferment_tank_motorEncoder.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7668. return render_template('ferment_container_tank.html', title='[操作] F' + tid + ' 發酵槽操作介面', **locals())
  7669. elif request.method == 'POST':
  7670. pass
  7671. @main.route('/ferment_container_input/<tid>', methods=['GET', 'POST'])
  7672. def ferment_container_input(tid):
  7673. if request.method == 'GET':
  7674. if 'id' in session and 'uname' in session and 'status' in session:
  7675. username = session['uname']
  7676. status = session['status']
  7677. if status == 9:
  7678. return render_template('signin_disable.html')
  7679. elif status == 8:
  7680. return render_template('signin_new.html')
  7681. else:
  7682. return render_template('oops.html')
  7683. # 感測器_入料儲豆槽_超音波感測器
  7684. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI' + tid).order_by(text('datetime desc')).first()
  7685. # 致動器_入料儲豆槽_真空吸引機
  7686. input_vacuum = ferment_input_actuator.query.filter_by(tank_num='FI' + tid).order_by(text('datetime desc')).first()
  7687. input_vacuum = input_vacuum.vacuum
  7688. return render_template('ferment_container_input.html', title='[操作] FI' + tid + ' 發酵入料儲豆槽操作介面', **locals())
  7689. elif request.method == 'POST':
  7690. pass
  7691. @main.route('/ferment_container_output/<tid>', methods=['GET', 'POST'])
  7692. def ferment_container_output(tid):
  7693. if request.method == 'GET':
  7694. if 'id' in session and 'uname' in session and 'status' in session:
  7695. username = session['uname']
  7696. status = session['status']
  7697. if status == 9:
  7698. return render_template('signin_disable.html')
  7699. elif status == 8:
  7700. return render_template('signin_new.html')
  7701. else:
  7702. return render_template('oops.html')
  7703. # 感測器_出料儲豆槽_超音波感測器
  7704. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO' + tid).order_by(text('datetime desc')).first()
  7705. # 致動器_出料儲豆槽_真空吸引機
  7706. output_vacuum = ferment_output_actuator.query.filter_by(tank_num='FO' + tid).order_by(text('datetime desc')).first()
  7707. output_vacuum = output_vacuum.vacuum
  7708. tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7709. LiDAR = tank_LiDAR.LiDAR
  7710. return render_template('ferment_container_output.html', title='[操作] FO' + tid + ' 發酵出料儲豆槽操作介面', **locals())
  7711. elif request.method == 'POST':
  7712. pass
  7713. @main.route('/dry_container_schedule', methods=['GET', 'POST'])
  7714. def dry_container_schedule():
  7715. if request.method == 'GET':
  7716. if 'id' in session and 'uname' in session:
  7717. username = session['uname']
  7718. # 感測器_入料儲豆槽_超音波感測器
  7719. input_UltraSonic = dry_input_sensor.query.order_by(text('datetime desc')).first()
  7720. # 感測器_乾燥桶_超音波感測器
  7721. tank_UltraSonic = dry_tank_UltraSonic.query.order_by(text('datetime desc')).first()
  7722. return render_template('dry_container_schedule.html', title='dry_container_schedule', **locals())
  7723. elif request.method == 'POST':
  7724. pass
  7725. @main.route('/dry_block', methods=['GET', 'POST'])
  7726. def dry_block():
  7727. if request.method == 'GET':
  7728. if 'id' in session and 'uname' in session:
  7729. username = session['uname']
  7730. DBW = dry_block_waiting.query.order_by(text('datetime desc')).first()
  7731. pin_data = coffee1_0_pin.query.order_by(text('datetime desc')).first()
  7732. return render_template('dry_block.html', title='積木設定_乾燥空桶等待', **locals())
  7733. elif request.method == 'POST':
  7734. pass
  7735. @main.route('/dry_block_empty', methods=['GET', 'POST'])
  7736. def dry_block_empty():
  7737. if request.method == 'GET':
  7738. if 'id' in session and 'uname' in session:
  7739. username = session['uname']
  7740. return render_template('dry_block_empty.html', title='積木設定空白_乾燥空桶等待', **locals())
  7741. elif request.method == 'POST':
  7742. pass
  7743. # 0323 積木程式 格式調整
  7744. @main.route('/dry_block_format', methods=['GET', 'POST'])
  7745. def dry_block_format():
  7746. if request.method == 'GET':
  7747. info = request.args.to_dict()
  7748. # print("info: ", info)
  7749. # info = {'cond_z1_1': 'if', 'cond_tank1_1': 'D1', 'cond_a1_1': 'tank_soil_Temp', 'cond_b1_1': 'Equal', 'cond_c1_1': '11', 'cond_d1_2': 'and', 'cond_a1_2': 'tank_soil_Humidity', 'cond_b1_2': 'Equal', 'cond_c1_2': '12', 'cond_d1_3': 'and', 'cond_a1_3': 'tank_soil_EC', 'cond_b1_3': 'Equal', 'cond_c1_3': '13', 'do_obj1_1': 'tank_heater1_status', 'do_act1_1': 'on', 'do_obj1_2': 'tank_heater2_status', 'do_act1_2': 'on'}
  7750. tank_num_data = info['tank_num'] # 桶槽編號:D1
  7751. mainLength_data = int(info['mainLength'])+1 # 總條件數量
  7752. addLength_data = int(info['addLength'])+1 # 子條件數量
  7753. comLength_data = int(info['comLength'])+1 # 子物件數量
  7754. cond_main_all_list = []
  7755. for z in range(1,mainLength_data):
  7756. # 初始
  7757. cond_main_all_dict = {}
  7758. cond_add_list = [] # 附加條件 List
  7759. cond_com_list = [] # 物件動作 List
  7760. # cond_main_dict_all = {}
  7761. # cond_add_dict_all = {}
  7762. # cond_com_dict_all = {}
  7763. # print(z)
  7764. # 總條件
  7765. try:
  7766. cond_main_all_dict['cond_main'] = info['cond_main' + str(z)]
  7767. except(KeyError):
  7768. pass
  7769. # print("cond_main_dict: ", cond_main_dict)
  7770. # 附加條件
  7771. for x in range(1,addLength_data):
  7772. try:
  7773. cond_add_list.append(info['cond_add' + str(z) + '_' + str(x)])
  7774. except(KeyError):
  7775. pass
  7776. # print("cond_add_list: ", cond_add_list)
  7777. cond_main_all_dict['cond_add'] = cond_add_list
  7778. # print("cond_main_dict: ", cond_main_dict)
  7779. # 物件動作
  7780. for y in range(1,comLength_data):
  7781. try:
  7782. cond_com_list.append(info['cond_com' + str(z) + '_' + str(y)])
  7783. except(KeyError):
  7784. pass
  7785. # print("cond_com_list: ", cond_com_list)
  7786. cond_main_all_dict['cond_com'] = cond_com_list
  7787. # print("cond_main_dict: ", cond_main_dict)
  7788. if cond_com_list != []:
  7789. cond_main_all_list.append(cond_main_all_dict)
  7790. # cond_main_all_list.append(cond_add_dict_all)
  7791. # cond_main_all_list.append(cond_com_dict_all)
  7792. print("cond_main_all_list: ", cond_main_all_list)
  7793. # cond_main_all_list: [{'cond_main': 'if D1 tank_UltraSonic >= 30', 'cond_add': ['and tank_PA <= 1', 'and tank_soil_Temp <= 30'], 'cond_com': ['tank_vacuum_status on', 'tank_motor_status 15']}]
  7794. dry_block_sehedule = {'command':'Dry_OTA', 'tank_num':tank_num_data, 'cond':cond_main_all_list}
  7795. print('dry_block_sehedule:', dry_block_sehedule)
  7796. # dry_block_sehedule: {'command': 'Dry_OTA', 'cond': [{'cond_main': 'if D1 tank_UltraSonic >= 30', 'cond_add': ['and tank_PA <= 1', 'and tank_soil_Temp <= 30'], 'cond_com': ['tank_vacuum_status on', 'tank_motor_status 15']}]}
  7797. topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
  7798. print('=========================================================')
  7799. print("json.dumps(dry_block_sehedule):", json.dumps(dry_block_sehedule))
  7800. # json.dumps(dry_block_sehedule): {"command": "Dry_OTA", "cond": [{"cond_main": "if D1 tank_UltraSonic >= 30", "cond_add": ["and tank_PA <= 1", "and tank_soil_Temp <= 30"], "cond_com": ["tank_vacuum_status on", "tank_motor_status 15"]}]}
  7801. print('=========================================================')
  7802. # mqtt.publish(topic, json.dumps(dry_block_sehedule))
  7803. return jsonify({"response":dry_block_sehedule})
  7804. # 積木程式
  7805. @main.route('/dry_block_set', methods=['GET', 'POST'])
  7806. def dry_block_set():
  7807. if request.method == 'GET':
  7808. if 'id' in session and 'uname' in session:
  7809. username = session['uname']
  7810. info = request.args.to_dict()
  7811. # print("info: ", info, type(info)) # dict
  7812. # 傳回 總條件物件動作 數量
  7813. condition = int(info['condition'])
  7814. # 傳回 子條件 數量
  7815. cond_add_child = int(info['cond_add_child'])
  7816. # 傳回 子物件動作 數量
  7817. act_add_child = int(info['act_add_child'])
  7818. # 傳回 指令
  7819. set_Schedule = eval(info['set_Schedule']) # 字串轉成字典
  7820. # print("set_Schedule: ", set_Schedule, type(set_Schedule)) # dict
  7821. cond_data = ''
  7822. # mqtt_data("D1", "block_command_test", "condition=" + str(condition)) # 0321 TEST
  7823. # ----- 0321 註解測試 -----
  7824. # # 拆解條件 / 物件 / 動作
  7825. # # # 條件物件取值
  7826. # for z in range(1, condition+1, 1):
  7827. # # 放要執行的判斷式
  7828. # # # if / while
  7829. # cond_data = ''
  7830. # try:
  7831. # z_num = 'cond_z' + str(z) + '_1'
  7832. # # print("cond_z_value[z_num]: ", set_Schedule[z_num]) # if
  7833. # cond_data += set_Schedule[z_num]
  7834. # except KeyError:
  7835. # pass
  7836. # # # 桶槽號取值
  7837. # try:
  7838. # tank_num = 'cond_tank' + str(z) + '_1'
  7839. # except KeyError:
  7840. # pass
  7841. # # # 子條件取值
  7842. # for x in range(1, cond_add_child+1, 1):
  7843. # # d
  7844. # try:
  7845. # x_num_d = 'cond_d' + str(z) + '_' + str(x)
  7846. # # print("cond_d_value[x_num_d]: ", set_Schedule[x_num_d])
  7847. # cond_data += ' ' + set_Schedule[x_num_d]
  7848. # except KeyError:
  7849. # pass
  7850. # # a
  7851. # x_num_a = 'cond_a' + str(z) + '_' + str(x)
  7852. # try:
  7853. # x_num_a = 'cond_a' + str(z) + '_' + str(x)
  7854. # # print("cond_a_value[x_num_a]: ", set_Schedule[x_num_a])
  7855. # cond_data += ' ' + set_Schedule[x_num_a]
  7856. # if set_Schedule[x_num_a] == 'input_vacuum_status':
  7857. # input_vacuum_status = dry_input_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().vacuum
  7858. # print("input_vacuum_status: ", input_vacuum_status)
  7859. # elif set_Schedule[x_num_a] == 'tank_vacuum_status':
  7860. # tank_vacuum_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().vacuum
  7861. # print("tank_vacuum_status: ", tank_vacuum_status)
  7862. # elif set_Schedule[x_num_a] == 'tank_threewayvalve_input_status':
  7863. # tank_threewayvalve_input_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().threewayvalve_input
  7864. # print("tank_threewayvalve_input_status: ", tank_threewayvalve_input_status)
  7865. # elif set_Schedule[x_num_a] == 'tank_motor_status':
  7866. # tank_motor_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().motor
  7867. # print("tank_motor_status: ", tank_motor_status)
  7868. # elif set_Schedule[x_num_a] == 'tank_blower_status':
  7869. # tank_blower_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().blower
  7870. # print("tank_blower_status: ", tank_blower_status)
  7871. # elif set_Schedule[x_num_a] == 'tank_heater1_status':
  7872. # tank_heater1_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().heater1
  7873. # print("tank_heater1_status: ", tank_heater1_status)
  7874. # elif set_Schedule[x_num_a] == 'tank_heater2_status':
  7875. # tank_heater2_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().heater2
  7876. # print("tank_heater2_status: ", tank_heater2_status)
  7877. # elif set_Schedule[x_num_a] == 'tank_diskvalve_status':
  7878. # tank_diskvalve_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().diskvalve
  7879. # print("tank_diskvalve_status: ", tank_diskvalve_status)
  7880. # elif set_Schedule[x_num_a] == 'tank_solenoid_disinfect_status':
  7881. # tank_solenoid_disinfect_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().solenoid_disinfect
  7882. # print("tank_solenoid_disinfect_status: ", tank_solenoid_disinfect_status)
  7883. # elif set_Schedule[x_num_a] == 'tank_solenoid_water_out_status':
  7884. # tank_solenoid_water_out_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().solenoid_water
  7885. # print("tank_solenoid_water_out_status: ", tank_solenoid_water_out_status)
  7886. # elif set_Schedule[x_num_a] == 'outer_solenoid_water_status':
  7887. # outer_solenoid_water_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().solenoid_outer_water
  7888. # print("outer_solenoid_water_status: ", outer_solenoid_water_status)
  7889. # elif set_Schedule[x_num_a] == 'tank_temp_enable':
  7890. # tank_temp_enable = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().temp1_enable
  7891. # print("tank_temp_enable: ", tank_temp_enable)
  7892. # elif set_Schedule[x_num_a] == 'tank_temp':
  7893. # tank_temp = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().temp1
  7894. # print("tank_temp: ", tank_temp)
  7895. # elif set_Schedule[x_num_a] == 'output_vacuum':
  7896. # output_vacuum = dry_output_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().vacuum
  7897. # print("output_vacuum: ", output_vacuum)
  7898. # elif set_Schedule[x_num_a] == 'input_UltraSonic':
  7899. # input_UltraSonic = float(dry_input_sensor.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().UltraSonic)
  7900. # print("input_UltraSonic: ", input_UltraSonic)
  7901. # elif set_Schedule[x_num_a] == 'tank_UltraSonic':
  7902. # tank_UltraSonic = float(dry_tank_UltraSonic.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().UltraSonic)
  7903. # print("tank_UltraSonic: ", tank_UltraSonic)
  7904. # elif set_Schedule[x_num_a] == 'tank_SHT11_Temp':
  7905. # tank_SHT11_Temp = float(dry_tank_SHT11.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().SHT11_Temp)
  7906. # print("tank_SHT11_Temp: ", tank_SHT11_Temp)
  7907. # elif set_Schedule[x_num_a] == 'tank_SHT11_Humidity':
  7908. # tank_SHT11_Humidity = float(dry_tank_SHT11.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().SHT11_Humidity)
  7909. # print("tank_SHT11_Humidity: ", tank_SHT11_Humidity)
  7910. # elif set_Schedule[x_num_a] == 'tank_soil_Temp':
  7911. # tank_soil_Temp = float(dry_tank_Soil.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().soil_Temp)
  7912. # print("tank_soil_Temp: ", tank_soil_Temp)
  7913. # elif set_Schedule[x_num_a] == 'tank_soil_Humidity':
  7914. # tank_soil_Humidity = float(dry_tank_Soil.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().soil_Humidity)
  7915. # print("tank_soil_Humidity: ", tank_soil_Temp)
  7916. # elif set_Schedule[x_num_a] == 'tank_soil_EC':
  7917. # tank_soil_EC = float(dry_tank_Soil.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().soil_EC)
  7918. # print("tank_soil_EC: ", tank_soil_EC)
  7919. # elif set_Schedule[x_num_a] == 'tank_PA':
  7920. # tank_PA = float(dry_tank_PA.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().PA)
  7921. # print("tank_PA: ", tank_PA)
  7922. # elif set_Schedule[x_num_a] == 'output_UltraSonic':
  7923. # output_UltraSonic = float(dry_output_sensor.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().UltraSonic)
  7924. # print("output_UltraSonic: ", output_UltraSonic)
  7925. # except KeyError:
  7926. # pass
  7927. # # b
  7928. # try:
  7929. # x_num_b = 'cond_b' + str(z) + '_' + str(x)
  7930. # # print("cond_b_value[x_num_b]: ", set_Schedule[x_num_b])
  7931. # cond_b_dict = {'morethan': ' >= ', 'lessthan': ' <= ', 'equal':' == '}
  7932. # cond_data += cond_b_dict[set_Schedule[x_num_b]] # cond_b_dict['equal'] 會輸出 ' == '
  7933. # except KeyError:
  7934. # pass
  7935. # # c
  7936. # try:
  7937. # x_num_c = 'cond_c' + str(z) + '_' + str(x)
  7938. # # print("cond_c_value[x_num_c]: ", set_Schedule[x_num_c])
  7939. # if set_Schedule[x_num_c] == 'on':
  7940. # cond_data += '1'
  7941. # elif set_Schedule[x_num_c] == 'off':
  7942. # cond_data += '0'
  7943. # else:
  7944. # cond_data += set_Schedule[x_num_c]
  7945. # except KeyError:
  7946. # pass
  7947. # if x == cond_add_child:
  7948. # cond_data += ': '
  7949. # # 子物件動作取值
  7950. # for y in range(1, act_add_child+1, 1):
  7951. # # do_obj
  7952. # try:
  7953. # y_num_obj = "do_obj" + str(z) + "_" + str(y)
  7954. # # print("y_num_obj[y_num_obj]: ", set_Schedule[y_num_obj])
  7955. # # cond_data += 'print(\'' + 'mqtt_data("D1", "' + str(set_Schedule[y_num_obj]) + '", '
  7956. # if set_Schedule[y_num_obj] == 'time.sleep':
  7957. # cond_data += '''
  7958. # time.sleep('''
  7959. # else:
  7960. # cond_data += '''
  7961. # mqtt_data('''
  7962. # cond_data += '"' + set_Schedule[tank_num] + '", "' + str(set_Schedule[y_num_obj]) + '", '
  7963. # except KeyError:
  7964. # pass
  7965. # try:
  7966. # y_num_act = "do_act" + str(z) + "_" + str(y)
  7967. # # print("y_num_act[y_num_act]: ", set_Schedule[y_num_act])
  7968. # if set_Schedule[y_num_obj] == 'time.sleep':
  7969. # cond_data += set_Schedule[y_num_act] + ')'
  7970. # else:
  7971. # cond_data += '"' + str(set_Schedule[y_num_act]) + '") '
  7972. # cond_data += '''
  7973. # time.sleep(0.5)'''
  7974. # except KeyError:
  7975. # pass
  7976. # # TODO
  7977. # # set_Schedule[z_num] → if / while
  7978. # # set_Schedule[x_num_a] → actuator / sensor
  7979. # # set_Schedule[x_num_b] → morethan / equal / lessthan
  7980. # # set_Schedule[x_num_c] → 數值 / on / off
  7981. # # set_Schedule[x_num_d] → or / and
  7982. # # set_Schedule[y_num_obj] → actuator
  7983. # # set_Schedule[y_num_act] → on / off / 對應數值
  7984. # print("cond_data: ", cond_data)
  7985. # if cond_data != ': ':
  7986. # # exec(cond_data)
  7987. # # 01/17 新增, 格式待修改
  7988. # mqtt_data("D1", "command_test", "exec(" + cond_data + ")")
  7989. return jsonify({"response":"OK"
  7990. })
  7991. elif request.method == 'POST':
  7992. pass
  7993. # 乾燥貨櫃_各致動器控制
  7994. @main.route('/ctrl_DI_<actuator>/<tid>', methods=['GET', 'POST'])
  7995. def ctrl_DI(actuator, tid):
  7996. if request.method == 'GET':
  7997. if actuator == 'Vacuum':
  7998. if 'id' in session and 'uname' in session and 'status' in session:
  7999. username = session['uname']
  8000. status = session['status']
  8001. if status == 9:
  8002. return render_template('signin_disable.html')
  8003. elif status == 8:
  8004. return render_template('signin_new.html')
  8005. else:
  8006. return render_template('oops.html')
  8007. input_brake = dry_input_brake.query.filter_by(tank_num='DI'+str(tid)).order_by(text('datetime desc')).first()
  8008. input_vacuum = input_brake.vacuum
  8009. tank_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI'+str(tid)).order_by(text('datetime desc')).first()
  8010. UltraSonic = tank_UltraSonic.UltraSonic
  8011. return render_template('ctrl_DI_Vacuum.html', title='[操作]DI' + tid + '乾燥槽入料_真空吸料機', **locals())
  8012. elif request.method == 'POST':
  8013. pass
  8014. @main.route('/ctrl_DO_<actuator>/<tid>', methods=['GET', 'POST'])
  8015. def ctrl_DO(actuator, tid):
  8016. if request.method == 'GET':
  8017. if 'id' in session and 'uname' in session and 'status' in session:
  8018. username = session['uname']
  8019. status = session['status']
  8020. if status == 9:
  8021. return render_template('signin_disable.html')
  8022. elif status == 8:
  8023. return render_template('signin_new.html')
  8024. else:
  8025. return render_template('oops.html')
  8026. if actuator == 'Vacuum':
  8027. tank_brake = dry_output_brake.query.filter_by(tank_num='DO'+str(tid)).order_by(text('datetime desc')).first()
  8028. tank_vacuum = tank_brake.vacuum
  8029. tank_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO'+str(tid)).order_by(text('datetime desc')).first()
  8030. UltraSonic = tank_UltraSonic.UltraSonic
  8031. return render_template('ctrl_DO_Vacuum.html', title='[操作]DI' + tid + '乾燥槽出料_真空吸料機', **locals())
  8032. elif request.method == 'POST':
  8033. pass
  8034. @main.route('/ctrl_D_<actuator>/<tid>', methods=['GET', 'POST'])
  8035. def ctrl_D(actuator, tid):
  8036. if request.method == 'GET':
  8037. if 'id' in session and 'uname' in session and 'status' in session:
  8038. username = session['uname']
  8039. status = session['status']
  8040. if status == 9:
  8041. return render_template('signin_disable.html')
  8042. elif status == 8:
  8043. return render_template('signin_new.html')
  8044. else:
  8045. return render_template('oops.html')
  8046. tank_brake = dry_tank_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8047. if actuator == 'Vacuum':
  8048. tank_vacuum = tank_brake.vacuum
  8049. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8050. UltraSonic = tank_UltraSonic.UltraSonic
  8051. return render_template('ctrl_D_Vacuum.html', title='[操作]D' + tid + '乾燥槽_真空吸料機', **locals())
  8052. elif actuator == 'ThreeWayValveInput':
  8053. tank_threewayvalve_input = tank_brake.threewayvalve_input
  8054. return render_template('ctrl_D_ThreeWayValveInput.html', title='[操作]D' + tid + '乾燥槽_入料三通閥', **locals())
  8055. elif actuator == 'ThreeWayValveBean':
  8056. tank_threewayvalve_bean = tank_brake.threewayvalve_bean
  8057. return render_template('ctrl_D_ThreeWayValveBean.html', title='[操作]D' + tid + '乾燥槽_測豆三通閥', **locals())
  8058. elif actuator == 'DiskValve':
  8059. tank_diskvalve = tank_brake.diskvalve
  8060. return render_template('ctrl_D_DiskValve.html', title='[操作]D' + tid + '乾燥槽_蝴蝶閥', **locals())
  8061. elif actuator == 'SolenoidDisinfect':
  8062. tank_solenoid_disinfect = tank_brake.solenoid_disinfect
  8063. return render_template('ctrl_D_SolenoidDisinfect.html', title='[操作]D' + tid + '乾燥槽_消毒電磁閥', **locals())
  8064. elif actuator == 'SolenoidWater':
  8065. tank_solenoid_water = tank_brake.solenoid_water
  8066. return render_template('ctrl_D_SolenoidWater.html', title='[操作]D' + tid + '乾燥槽_排水電磁閥', **locals())
  8067. elif actuator == 'Motor':
  8068. tank_motor = tank_brake.motor
  8069. return render_template('ctrl_D_Motor.html', title='[操作]D' + tid + '乾燥槽_馬達', **locals())
  8070. elif actuator == 'Blower':
  8071. tank_blower = tank_brake.blower
  8072. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8073. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8074. return render_template('ctrl_D_Blower.html', title='[操作]D' + tid + '乾燥槽_鼓風機', **locals())
  8075. elif actuator == 'Heater1':
  8076. tank_heater1 = tank_brake.heater1
  8077. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8078. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8079. return render_template('ctrl_D_Heater1.html', title='[操作]D' + tid + '乾燥槽_加熱器 1', **locals())
  8080. elif actuator == 'Heater2':
  8081. tank_heater2 = tank_brake.heater2
  8082. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8083. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8084. return render_template('ctrl_D_Heater2.html', title='[操作]D' + tid + '乾燥槽_加熱器 2', **locals())
  8085. elif actuator == 'TempEnable':
  8086. tank_temp1_enable = tank_brake.temp1_enable
  8087. return render_template('ctrl_D_TempEnable.html', title='[操作]D' + tid + '乾燥槽_溫控開關', **locals())
  8088. elif actuator == 'Temp':
  8089. tank_temp1_enable = tank_brake.temp1_enable
  8090. tank_temp1 = tank_brake.temp1
  8091. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8092. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8093. return render_template('ctrl_D_Temp.html', title='[操作]D' + tid + '乾燥槽_設定溫度', **locals())
  8094. elif request.method == 'POST':
  8095. pass
  8096. # 發酵貨櫃_各致動器控制
  8097. @main.route('/ctrl_FI_<actuator>/<tid>', methods=['GET', 'POST'])
  8098. def ctrl_FI(actuator, tid):
  8099. if request.method == 'GET':
  8100. if 'id' in session and 'uname' in session and 'status' in session:
  8101. username = session['uname']
  8102. status = session['status']
  8103. if status == 9:
  8104. return render_template('signin_disable.html')
  8105. elif status == 8:
  8106. return render_template('signin_new.html')
  8107. else:
  8108. return render_template('oops.html')
  8109. if actuator == 'Vacuum':
  8110. if 'id' in session and 'uname' in session and 'status' in session:
  8111. username = session['uname']
  8112. status = session['status']
  8113. if status == 9:
  8114. return render_template('signin_disable.html')
  8115. elif status == 8:
  8116. return render_template('signin_new.html')
  8117. else:
  8118. return render_template('oops.html')
  8119. tank_actuator = ferment_input_actuator.query.filter_by(tank_num='FI'+str(tid)).order_by(text('datetime desc')).first()
  8120. tank_vacuum = tank_actuator.vacuum
  8121. tank_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI'+str(tid)).order_by(text('datetime desc')).first()
  8122. UltraSonic = tank_UltraSonic.UltraSonic
  8123. return render_template('ctrl_FI_Vacuum.html', title='[操作]FI' + tid + '發酵入料儲豆槽_真空吸料機', **locals())
  8124. elif request.method == 'POST':
  8125. pass
  8126. @main.route('/ctrl_FO_<actuator>/<tid>', methods=['GET', 'POST'])
  8127. def ctrl_FO(actuator, tid):
  8128. if request.method == 'GET':
  8129. if 'id' in session and 'uname' in session and 'status' in session:
  8130. username = session['uname']
  8131. status = session['status']
  8132. if status == 9:
  8133. return render_template('signin_disable.html')
  8134. elif status == 8:
  8135. return render_template('signin_new.html')
  8136. else:
  8137. return render_template('oops.html')
  8138. if actuator == 'Vacuum':
  8139. tank_actuator = ferment_output_actuator.query.filter_by(tank_num='FO'+str(tid)).order_by(text('datetime desc')).first()
  8140. tank_vacuum = tank_actuator.vacuum
  8141. tank_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO'+str(tid)).order_by(text('datetime desc')).first()
  8142. UltraSonic = tank_UltraSonic.UltraSonic
  8143. return render_template('ctrl_FO_Vacuum.html', title='[操作]FO' + tid + '發酵出料儲豆槽_真空吸料機', **locals())
  8144. elif request.method == 'POST':
  8145. pass
  8146. @main.route('/ctrl_F_<actuator>/<tid>', methods=['GET', 'POST'])
  8147. def ctrl_F(actuator, tid):
  8148. if request.method == 'GET':
  8149. if 'id' in session and 'uname' in session and 'status' in session:
  8150. username = session['uname']
  8151. status = session['status']
  8152. if status == 9:
  8153. return render_template('signin_disable.html')
  8154. elif status == 8:
  8155. return render_template('signin_new.html')
  8156. else:
  8157. return render_template('oops.html')
  8158. tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  8159. if actuator == 'Vacuum':
  8160. tank_vacuum = tank_actuator.vacuum
  8161. tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  8162. LiDAR = tank_LiDAR.LiDAR
  8163. return render_template('ctrl_F_Vacuum.html', title='[操作]F' + tid + '發酵槽_真空吸料機', **locals())
  8164. elif actuator == 'ThreeWayValveInput':
  8165. tank_threewayvalveinput = tank_actuator.threewayvalve_input
  8166. return render_template('ctrl_F_ThreeWayValveInput.html', title='[操作]F' + tid + '發酵槽_入料三通閥', **locals())
  8167. elif actuator == 'SolenoidWaterTotal':
  8168. tank_solenoid_tank_water_total = tank_actuator.solenoid_tank_water_total
  8169. return render_template('ctrl_F_SolenoidWaterTotal.html', title='[操作]F' + tid + '發酵槽_總進水電磁閥', **locals())
  8170. elif actuator == 'SolenoidOuterWater':
  8171. tank_solenoid_outer_water = tank_actuator.solenoid_outer_water
  8172. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  8173. WaterLevel = tank_WaterLevel.WaterLevel
  8174. return render_template('ctrl_F_SolenoidOuterWater.html', title='[操作]F' + tid + '發酵槽_保溫夾層進水電磁閥', **locals())
  8175. elif actuator == 'SolenoidWaterIn':
  8176. tank_solenoid_tank_water_in = tank_actuator.solenoid_tank_water_in
  8177. tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  8178. PressureWaterLevel = tank_PressureWaterLevel.PressureWaterLevel
  8179. return render_template('ctrl_F_SolenoidWaterIn.html', title='[操作]F' + tid + '發酵槽_桶內進水電磁閥', **locals())
  8180. elif actuator == 'PumpSensor':
  8181. tank_pump_sensor = tank_actuator.pump_sensor
  8182. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  8183. tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  8184. tank_DO = ferment_tank_DO.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  8185. tank_EC = ferment_tank_EC.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  8186. PH = tank_PH.PH
  8187. ORP = tank_ORP.ORP
  8188. DO = tank_DO.DO
  8189. EC = tank_EC.EC
  8190. return render_template('ctrl_F_PumpSensor.html', title='[操作]F' + tid + '發酵槽_感測器抽水雙核隔膜泵', **locals())
  8191. elif actuator == 'ThreeWayValveBean':
  8192. tank_threewayvalve_bean = tank_actuator.threewayvalve_bean
  8193. return render_template('ctrl_F_ThreeWayValveBean.html', title='[操作]F' + tid + '發酵槽_感測模組下豆三通閥', **locals())
  8194. elif actuator == 'ThreeWayValveFloat':
  8195. tank_threewayvalve_outer_float = tank_actuator.threewayvalve_outer_float
  8196. return render_template('ctrl_F_ThreeWayValveFloat.html', title='[操作]F' + tid + '發酵槽_外桶浮選三通閥', **locals())
  8197. elif actuator == 'SolenoidDisinfect':
  8198. tank_solenoid_tank_disinfect = tank_actuator.solenoid_tank_disinfect
  8199. return render_template('ctrl_F_SolenoidDisinfect.html', title='[操作]F' + tid + '發酵槽_桶內消毒電磁閥', **locals())
  8200. elif actuator == 'Motor':
  8201. tank_motor = tank_actuator.motor
  8202. return render_template('ctrl_F_Motor.html', title='[操作]F' + tid + '發酵槽_馬達', **locals())
  8203. elif actuator == 'Heater1':
  8204. tank_heater1 = tank_actuator.heater1
  8205. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  8206. return render_template('ctrl_F_Heater1.html', title='[操作]F' + tid + '發酵槽_加熱器 1', **locals())
  8207. elif actuator == 'Heater2':
  8208. tank_heater2 = tank_actuator.heater2
  8209. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  8210. return render_template('ctrl_F_Heater2.html', title='[操作]F' + tid + '發酵槽_加熱器 2', **locals())
  8211. elif actuator == 'TempEnable':
  8212. tank_temp_enable = tank_actuator.temp_enable
  8213. return render_template('ctrl_F_TempEnable.html', title='[操作]F' + tid + '發酵槽_溫控開關', **locals())
  8214. elif actuator == 'Temp':
  8215. tank_temp = tank_actuator.temp
  8216. tank_temp_enable = tank_actuator.temp_enable
  8217. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  8218. return render_template('ctrl_F_Temp.html', title='[操作]F' + tid + '發酵槽_溫度設定', **locals())
  8219. elif actuator == 'DiskValve':
  8220. tank_diskvalve = tank_actuator.diskvalve
  8221. return render_template('ctrl_F_DiskValve.html', title='[操作]F' + tid + '發酵槽_蝴蝶閥', **locals())
  8222. @main.route('/dry_Temp/<tid>/<Temp_Weights_SHT11>/<Temp_Weights_Soil>/<temp_data>', methods=['GET', 'POST'])
  8223. def dry_Temp(tid, Temp_Weights_SHT11, Temp_Weights_Soil, temp_data):
  8224. if request.method == 'GET':
  8225. if 'id' in session and 'uname' in session and 'status' in session:
  8226. username = session['uname']
  8227. status = session['status']
  8228. if status == 9:
  8229. return render_template('signin_disable.html')
  8230. elif status == 8:
  8231. return render_template('signin_new.html')
  8232. else:
  8233. return render_template('oops.html')
  8234. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8235. SHT11_Temp = float(tank_SHT11.SHT11_Temp)
  8236. SHT11_Humidity = tank_SHT11.SHT11_Humidity
  8237. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8238. Soil_Temp = float(tank_Soil.soil_Temp)
  8239. Soil_Humidity = tank_Soil.soil_Humidity
  8240. Temp_Weights_SHT11= float(Temp_Weights_SHT11)
  8241. Temp_Weights_Soil = float(Temp_Weights_Soil)
  8242. temp_data = float(temp_data)
  8243. present_temp = math.ceil( (SHT11_Temp*Temp_Weights_SHT11 + Soil_Temp*Temp_Weights_Soil)/(Temp_Weights_SHT11+Temp_Weights_Soil) )
  8244. # Math.round((present_SHT11_Temp*Temp_Weights_SHT11 + present_SOIL_Temp*Temp_Weights_Soil)/(Temp_Weights_SHT11+Temp_Weights_Soil)*100) / 100
  8245. target_temp = math.ceil(temp_data)
  8246. TempUp = {
  8247. 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
  8248. }
  8249. if target_temp in TempUp and present_temp in TempUp:
  8250. TempUpTime = ', 預計 ' + str(TempUp[target_temp] - TempUp[present_temp]) + ' 秒達到指定溫度'
  8251. elif target_temp < 22 or present_temp < 22 :
  8252. TempUpTime = '℃, 指定溫度過低, 持續升溫中'
  8253. elif target_temp > 44 or present_temp > 44 :
  8254. TempUpTime = '℃, 指定溫度過高, 持續升溫中'
  8255. return jsonify({"SHT11_Temp":SHT11_Temp,
  8256. "SHT11_Humidity":SHT11_Humidity,
  8257. "Soil_Temp":Soil_Temp,
  8258. "Soil_Humidity":Soil_Humidity,
  8259. "present_temp":present_temp,
  8260. "TempUpTime":TempUpTime
  8261. })
  8262. else:
  8263. pass
  8264. @main.route('/dry_container_tank/<tid>', methods=['GET', 'POST'])
  8265. def dry_container_tank(tid):
  8266. if request.method == 'GET':
  8267. if 'id' in session and 'uname' in session and 'status' in session:
  8268. username = session['uname']
  8269. status = session['status']
  8270. if status == 9:
  8271. return render_template('signin_disable.html')
  8272. elif status == 8:
  8273. return render_template('signin_new.html')
  8274. else:
  8275. return render_template('oops.html')
  8276. tonow = dt.now()
  8277. print("tonow: ", tonow)
  8278. time_del = timedelta(minutes=-60)
  8279. bias_date_time = tonow + time_del
  8280. # print(dt.now() >= dt(2021,11,29,17,35,36))
  8281. # bias_min = tonow.minute + 3
  8282. # 感測器_乾燥桶_SHT11
  8283. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid))\
  8284. .filter(dry_tank_SHT11.datetime >= bias_date_time)\
  8285. .order_by(text('datetime desc')).first()
  8286. # print("tank_SHT11: ", tank_SHT11, type(tank_SHT11)) # tank_SHT11: <dry_tank_SHT11 2021-12-03 15:39:16> <class 'app.models.dry_tank_SHT11'>
  8287. if not hasattr(object, 'tank_SHT11'):
  8288. tank_SHT11 = {"SHT11_Temp":" — ", "SHT11_Humidity":" — "}
  8289. print(tank_SHT11["SHT11_Temp"])
  8290. # 感測器_乾燥桶_土壤三合一
  8291. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8292. if not hasattr(object, 'tank_Soil'):
  8293. tank_Soil = {"soil_Temp":" — ", "soil_Humidity":" — ", "soil_EC":" — "}
  8294. # 感測器_乾燥桶_氣壓
  8295. tank_PA = dry_tank_PA.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8296. if not hasattr(object, 'tank_PA'):
  8297. tank_PA = {"PA":" — "}
  8298. # 感測器_乾燥桶_超音波感測器
  8299. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8300. if not hasattr(object, 'tank_UltraSonic'):
  8301. tank_UltraSonic = {"UltraSonic":" — "}
  8302. # 致動器_乾燥桶_ALL
  8303. tank_brake = dry_tank_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8304. tank_vacuum = tank_brake.vacuum
  8305. tank_threewayvalve_input = tank_brake.threewayvalve_input
  8306. tank_threewayvalve_bean = tank_brake.threewayvalve_bean
  8307. tank_diskvalve = tank_brake.diskvalve
  8308. tank_solenoid_disinfect = tank_brake.solenoid_disinfect
  8309. tank_solenoid_water = tank_brake.solenoid_water
  8310. tank_solenoid_outer_water = tank_brake.solenoid_outer_water
  8311. tank_motor = tank_brake.motor
  8312. tank_blower = tank_brake.blower
  8313. tank_heater1 = tank_brake.heater1
  8314. tank_heater2 = tank_brake.heater2
  8315. tank_temp1_enable = tank_brake.temp1_enable
  8316. tank_temp1 = tank_brake.temp1
  8317. # Temp_weight = num_SHT11_temp * 0.5 + num_Soil_temp * 0.5
  8318. return render_template('dry_container_tank.html', title='[操作] D' + tid + ' 乾燥槽操作介面', **locals())
  8319. elif request.method == 'POST':
  8320. pass
  8321. @main.route('/dry_container_input/<tid>', methods=['GET', 'POST'])
  8322. def dry_container_input(tid):
  8323. if request.method == 'GET':
  8324. if 'id' in session and 'uname' in session and 'status' in session:
  8325. username = session['uname']
  8326. status = session['status']
  8327. if status == 9:
  8328. return render_template('signin_disable.html')
  8329. elif status == 8:
  8330. return render_template('signin_new.html')
  8331. else:
  8332. return render_template('oops.html')
  8333. input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI'+str(tid)).order_by(text('datetime desc')).first()
  8334. input_vacuum = dry_input_brake.query.filter_by(tank_num='DI'+str(tid)).order_by(text('datetime desc')).first()
  8335. input_vacuum = input_vacuum.vacuum
  8336. return render_template('dry_container_input.html', title='[操作] DI' + tid + ' 乾燥入料儲豆槽操作介面', **locals())
  8337. elif request.method == 'POST':
  8338. pass
  8339. @main.route('/dry_container_output/<tid>', methods=['GET', 'POST'])
  8340. def dry_container_output(tid):
  8341. if request.method == 'GET':
  8342. if 'id' in session and 'uname' in session and 'status' in session:
  8343. username = session['uname']
  8344. status = session['status']
  8345. if status == 9:
  8346. return render_template('signin_disable.html')
  8347. elif status == 8:
  8348. return render_template('signin_new.html')
  8349. else:
  8350. return render_template('oops.html')
  8351. output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO'+str(tid)).order_by(text('datetime desc')).first()
  8352. output_vacuum = dry_output_brake.query.filter_by(tank_num='DO'+str(tid)).order_by(text('datetime desc')).first()
  8353. output_vacuum = output_vacuum.vacuum
  8354. return render_template('dry_container_output.html', title='[操作] DO' + tid + ' 乾燥出料儲豆槽操作介面', **locals())
  8355. elif request.method == 'POST':
  8356. pass
  8357. # 原本的乾燥貨櫃控制, 備份用
  8358. @main.route('/dry_container/<tid>', methods=['GET', 'POST'])
  8359. def dry_container(tid):
  8360. if request.method == 'GET':
  8361. if 'id' in session and 'uname' in session and 'status' in session:
  8362. username = session['uname']
  8363. status = session['status']
  8364. if status == 9:
  8365. return render_template('signin_disable.html')
  8366. elif status == 8:
  8367. return render_template('signin_new.html')
  8368. else:
  8369. return render_template('oops.html')
  8370. # Rita 參數 params 是用來取得參數的 locals=() 所有參數
  8371. '''
  8372. # 開啟本機 coffeetest 資料庫
  8373. # mydb = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='g53743001', database='coffeetest', charset='utf8')
  8374. mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffee',
  8375. password='skyeye', database='Coffee', charset='utf8')
  8376. mycursor = mydb.cursor()
  8377. '''
  8378. # 感測器_乾燥桶_SHT11
  8379. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8380. num_SHT11_temp = float(tank_SHT11.SHT11_Temp)
  8381. # 感測器_乾燥桶_土壤三合一
  8382. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8383. num_Soil_temp = float(tank_Soil.soil_Temp)
  8384. # 感測器_乾燥桶_氣壓
  8385. tank_PA = dry_tank_PA.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8386. # 感測器_乾燥桶_超音波感測器
  8387. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8388. # 感測器_出料儲豆槽_超音波感測器
  8389. output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8390. # 致動器_乾燥桶_ALL
  8391. tank_brake = dry_tank_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8392. tank_vacuum = tank_brake.vacuum
  8393. tank_threewayvalve_input = tank_brake.threewayvalve_input
  8394. tank_threewayvalve_bean = tank_brake.threewayvalve_bean
  8395. tank_diskvalve = tank_brake.diskvalve
  8396. tank_solenoid_disinfect = tank_brake.solenoid_disinfect
  8397. tank_solenoid_water = tank_brake.solenoid_water
  8398. tank_motor = tank_brake.motor
  8399. tank_blower = tank_brake.blower
  8400. tank_heater1 = tank_brake.heater1
  8401. tank_heater2 = tank_brake.heater2
  8402. tank_temp1_enable = tank_brake.temp1_enable
  8403. tank_temp1 = tank_brake.temp1
  8404. '''
  8405. tank_vacuum = 'ON' if tank_brake.vacuum == 1 else 'OFF'
  8406. tank_threewayvalve = 'ON' if tank_brake.threewayvalve == 1 else 'OFF'
  8407. tank_diskvalve = 'ON' if tank_brake.diskvalve == 1 else 'OFF'
  8408. tank_solenoid_disinfect = 'ON' if tank_brake.solenoid_disinfect == 1 else 'OFF'
  8409. tank_solenoid_water = 'ON' if tank_brake.solenoid_water == 1 else 'OFF'
  8410. tank_motor = tank_brake.motor
  8411. tank_blower = 'ON' if tank_brake.blower == 1 else 'OFF'
  8412. tank_heater1 = 'ON' if tank_brake.heater1 == 1 else 'OFF'
  8413. tank_heater2 = 'ON' if tank_brake.heater2 == 1 else 'OFF'
  8414. tank_temp1_enable = 'ON' if tank_brake.temp1_enable == 1 else 'OFF'
  8415. tank_temp1 = tank_brake.temp1
  8416. '''
  8417. '''
  8418. data = mycursor.execute(
  8419. 'SELECT * FROM dry_tank_brake ORDER BY datetime DESC;')
  8420. data = mycursor.fetchone()
  8421. '''
  8422. if tid in ['1', '2', '3', '4', '5', '6']:
  8423. # print("1")
  8424. # 感測器_入料儲豆槽_超音波感測器
  8425. input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI1').order_by(text('datetime desc')).first()
  8426. # 致動器_入料儲豆槽_真空吸引機
  8427. input_vacuum = dry_input_brake.query.filter_by(tank_num='DI1').order_by(text('datetime desc')).first()
  8428. input_vacuum = input_vacuum.vacuum
  8429. # 感測器_出料儲豆槽_超音波感測器
  8430. output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO1').order_by(text('datetime desc')).first()
  8431. # 致動器_出料儲豆槽_真空吸引機
  8432. output_vacuum = dry_output_brake.query.filter_by(tank_num='DO1').order_by(text('datetime desc')).first()
  8433. output_vacuum = output_vacuum.vacuum
  8434. elif tid in ['7', '8', '9', '10', '11', '12']:
  8435. print("2")
  8436. # 感測器_入料儲豆槽_超音波感測器
  8437. input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI2').order_by(text('datetime desc')).first()
  8438. # 致動器_入料儲豆槽_真空吸引機
  8439. input_vacuum = dry_input_brake.query.filter_by(tank_num='DI2').order_by(text('datetime desc')).first()
  8440. input_vacuum = input_vacuum.vacuum
  8441. # 感測器_出料儲豆槽_超音波感測器
  8442. output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO2').order_by(text('datetime desc')).first()
  8443. # 致動器_出料儲豆槽_真空吸引機
  8444. output_vacuum = dry_output_brake.query.filter_by(tank_num='DO2').order_by(text('datetime desc')).first()
  8445. output_vacuum = output_vacuum.vacuum
  8446. '''
  8447. # 感測器_入料儲豆槽_超音波感測器
  8448. input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8449. # 致動器_入料儲豆槽_真空吸引機
  8450. input_vacuum = dry_input_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8451. # print("input_vacuum:", input_vacuum)
  8452. input_vacuum = input_vacuum.vacuum
  8453. #print('input_vacuum:', input_vacuum.vacuum)
  8454. # 致動器_出料儲豆槽_真空吸引機
  8455. output_vacuum = dry_output_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  8456. #print('output_vacuum.vacuum: ', output_vacuum.vacuum)
  8457. output_vacuum = 'ON' if (output_vacuum.vacuum == 1) else 'OFF'
  8458. #print('output_vacuum: ', output_vacuum)
  8459. '''
  8460. # 傳 MQTT 給阿超, 阿超讓硬體動作, 將資料儲存到資料庫
  8461. input_data = set_dry_input.query.order_by(text('datetime desc')).first()
  8462. schedule_input_height = input_data.input_height
  8463. schedule_input_entertime = input_data.input_entertime
  8464. schedule_input_exittime = input_data.input_exittime
  8465. schedule_tank_height = input_data.tank_height
  8466. return render_template('dry_container.html', title='dry_container', **locals())
  8467. elif request.method == 'POST':
  8468. # 表單輸入處
  8469. print('/dry_input_setting POST')
  8470. set = set_dry_input()
  8471. set.input_height = request.form['schedule_input_height']
  8472. set.input_entertime = request.form['schedule_input_entertime']
  8473. set.input_exittime = request.form['schedule_input_exittime']
  8474. set.tank_height = request.form['schedule_tank_height']
  8475. #將數據保存進資料庫 - 註冊
  8476. db.session.add(set)
  8477. # 手動提交,目的是為了獲取提交後的user的id
  8478. db.session.commit()
  8479. # 當user成功插入進資料庫之後,程序會自動將所有信息取出來在賦值給user
  8480. # 完成登入的操作
  8481. # setting = Set_dry_input.query.order_by(text('datetime desc')).first()
  8482. #session['id'] = set.userID
  8483. #session['uname'] = set.username
  8484. return redirect('/dry_container')
  8485. # 登入頁面的訪問路徑
  8486. @main.route('/login', methods=['GET', 'POST'])
  8487. def login_views():
  8488. if request.method == 'GET':
  8489. if 'id' in session and 'uname' in session and 'status' in session:
  8490. return redirect('/')
  8491. else:
  8492. return render_template('sign_in.html')
  8493. else:
  8494. # 接收前端傳過來的資料
  8495. username = request.form['username']
  8496. password = request.form['password']
  8497. # 使用接收的用戶和密碼到資料庫中查詢
  8498. user = User.query.filter_by(
  8499. username=username, password=password).first()
  8500. # 如果用戶存在,將信息保存置session並重定向回首頁,否則重定向回登入頁
  8501. if user:
  8502. resp = redirect('/')
  8503. # 判斷是否有記住密碼
  8504. if 'rem' in request.form:
  8505. userID = str(user.userID)
  8506. max_age = 60*60*24*365
  8507. status = str(user.status)
  8508. print('status: ', status)
  8509. # Rita 以秒為單位, 一年
  8510. # Rita 功能和 expires 很像,但此參數並非所有瀏覽器均支持,所以建議使用 expires 參數。
  8511. # Rita expires:指定 Cookie 的有效日期, 當過了有效日期後就不會儲存在瀏覽器
  8512. resp.set_cookie("username", username, max_age=max_age)
  8513. resp.set_cookie("userID", userID, max_age=max_age)
  8514. resp.set_cookie("status", status, max_age=max_age)
  8515. session['uname'] = user.username
  8516. session['id'] = user.userID
  8517. session['status'] = user.status
  8518. return resp
  8519. else:
  8520. errMsg = "Wrong login or password"
  8521. return render_template('sign_in.html', errMsg=errMsg)
  8522. # 登入重設密碼的頁面
  8523. # Rita reset_pwd1 - Email
  8524. # Rita reset_pwd2 - New password / Confirm password
  8525. @main.route('/reset_password', methods=['POST', 'GET'])
  8526. def reset_password_views():
  8527. if request.method == 'GET':
  8528. if 'mail' in session:
  8529. del session['mail']
  8530. return render_template('reset_pwd1.html')
  8531. else:
  8532. # POST
  8533. # 如果有id在session裡,代表從reset_pwd2過來的 ? 對, reset_pwd2 POST (但也有其他可能)
  8534. if "mail" in session:
  8535. new_pwd = request.form['new_pwd']
  8536. confirm_pwd = request.form['confirm_pwd']
  8537. # 判斷密碼是否一致
  8538. if new_pwd == confirm_pwd:
  8539. mail = session['mail']
  8540. user = User.query.filter_by(mail=mail).first()
  8541. print("user: ", user)
  8542. print("user.password_before: ", user.password)
  8543. print("new_pwd: ", new_pwd)
  8544. user.password = new_pwd
  8545. print("user.password_after: ", user.password)
  8546. db.session.add(user)
  8547. db.session.commit()
  8548. del session['mail']
  8549. # 修改完後回登入頁
  8550. return redirect('/login')
  8551. else:
  8552. # Rita errMsg 是指網頁上的 {{errMsg}} 位置
  8553. errMsg = "Passwords does not match"
  8554. return render_template('reset_pwd2.html', errMsg=errMsg)
  8555. email = request.form['email']
  8556. user = User.query.filter_by(mail=email).first()
  8557. if user: # Rita 有找到對應 email
  8558. session['mail'] = user.mail
  8559. return render_template('reset_pwd2.html')
  8560. else:
  8561. errMsg = "Wrong email.Please try again"
  8562. return render_template('reset_pwd1.html', errMsg=errMsg)
  8563. # 註冊頁面的訪問路徑
  8564. @main.route('/register', methods=['POST', "GET"])
  8565. def register_views():
  8566. if request.method == 'GET':
  8567. return render_template('registration.html')
  8568. else:
  8569. # 獲取文本框的值並賦值給user實體對象
  8570. user = User()
  8571. user.firstname = request.form['firstname']
  8572. user.lastname = request.form['lastname']
  8573. user.mail = request.form['email']
  8574. user.phone = request.form['phone']
  8575. user.username = request.form['username']
  8576. user.password = request.form['password']
  8577. user.status = 8 # Rita app\models.py 設定 0:admin;1:new;9:disable [0906 更新] 0:admin;1:superuser;2:enduser;8:new;9:disable
  8578. #將數據保存進資料庫 - 註冊
  8579. db.session.add(user)
  8580. # 手動提交,目的是為了獲取提交後的user的id
  8581. db.session.commit()
  8582. # 當user成功插入進資料庫之後,程序會自動將所有信息取出來在賦值給user
  8583. # 完成登入的操作
  8584. user = User.query.filter_by(username=user.username).first()
  8585. session['status'] = user.status
  8586. session['id'] = user.userID
  8587. session['uname'] = user.username
  8588. return redirect('/')
  8589. # 驗證email訪問路徑
  8590. @main.route('/check_email')
  8591. def check_email_views():
  8592. email = request.args['email']
  8593. user = User.query.filter_by(mail=email).first()
  8594. if user:
  8595. # Rita email 錯誤時會顯示 Incorrect email address
  8596. result = {"errMsg": " "}
  8597. else:
  8598. result = {"pass": " "}
  8599. return json.dumps(result)
  8600. # 驗證username訪問路徑
  8601. @main.route('/check_username')
  8602. def check_username_views():
  8603. username = request.args['username']
  8604. user = User.query.filter_by(username=username).first()
  8605. if user:
  8606. result = {"errMsg": " "}
  8607. else:
  8608. result = {"pass": " "}
  8609. return json.dumps(result)
  8610. # 咖啡貨櫃的訪問路徑
  8611. @main.route('/cargo_list', methods=['GET', 'POST'])
  8612. def cargo_list_views():
  8613. username = session['uname']
  8614. if request.method == 'GET':
  8615. return render_template('cargo_list.html', params=locals())
  8616. else:
  8617. pass
  8618. # 貨櫃1的訪問路徑
  8619. @main.route('/cargo1', methods=['GET', 'POST'])
  8620. def cargo1_views():
  8621. username = session['uname']
  8622. if request.method == 'GET':
  8623. return render_template('cargo1.html', params=locals())
  8624. else:
  8625. pass
  8626. # 貨櫃1排程的訪問路徑
  8627. @main.route('/cargo1_schedule', methods=['GET', 'POST'])
  8628. def cargo1_schedule_views():
  8629. username = session['uname']
  8630. if request.method == 'GET':
  8631. # 將已儲存的排程資料傳給前端
  8632. # 進豆閥
  8633. try:
  8634. bean = BeanValve.query.order_by(text('datetime desc')).first()
  8635. datetime = bean.datetime
  8636. beans = BeanValve.query.filter_by(
  8637. datetime=datetime).all()
  8638. except Exception as e:
  8639. pass
  8640. # 清洗機
  8641. try:
  8642. wash = WashMachine.query.order_by(text('datetime desc')).first()
  8643. datetime = wash.datetime
  8644. washes = WashMachine.query.filter_by(datetime=datetime).all()
  8645. except Exception as e:
  8646. pass
  8647. # 輸送帶1
  8648. try:
  8649. belt1 = ConveyorBelt1.query.order_by(text('datetime desc')).first()
  8650. datetime = belt1.datetime
  8651. belts1 = ConveyorBelt1.query.filter_by(datetime=datetime).all()
  8652. except Exception as e:
  8653. pass
  8654. # ///////////////////////////////////////////////////////////////////////////////////////////
  8655. # 消毒機
  8656. try:
  8657. disinfect = Cargo1Disinfect.query.order_by(
  8658. text('datetime desc')).first()
  8659. datetime = disinfect.datetime
  8660. disinfects = Cargo1Disinfect.query.filter_by(
  8661. datetime=datetime).all()
  8662. except Exception as e:
  8663. pass
  8664. # 色選機
  8665. try:
  8666. color = ColorMachine.query.order_by(text('datetime desc')).first()
  8667. datetime = color.datetime
  8668. colors = ColorMachine.query.filter_by(datetime=datetime).all()
  8669. except Exception as e:
  8670. pass
  8671. # 輸送帶2
  8672. try:
  8673. belt2 = ConveyorBelt2.query.order_by(text('datetime desc')).first()
  8674. datetime = belt2.datetime
  8675. belts2 = ConveyorBelt2.query.filter_by(datetime=datetime).all()
  8676. except Exception as e:
  8677. pass
  8678. # 去皮機
  8679. try:
  8680. peeling = PeelingMachine.query.order_by(
  8681. text('datetime desc')).first()
  8682. datetime = peeling.datetime
  8683. peelings = PeelingMachine.query.filter_by(datetime=datetime).all()
  8684. except Exception as e:
  8685. pass
  8686. # 輸送帶3
  8687. try:
  8688. belt3 = ConveyorBelt3.query.order_by(text('datetime desc')).first()
  8689. datetime = belt3.datetime
  8690. belts3 = ConveyorBelt3.query.filter_by(datetime=datetime).all()
  8691. except Exception as e:
  8692. pass
  8693. return render_template('cargo1_schedule.html', params=locals())
  8694. else:
  8695. current_time = dt.now()
  8696. # 循環從前端提交過來的資料
  8697. for i in request.form:
  8698. # 進豆閥
  8699. if i[:10] == 'inletValve':
  8700. if i[:19] == 'inletValve_duration':
  8701. bean = BeanValve()
  8702. bean.duration = request.form[i]
  8703. elif i[:18] == 'inletValve_from_hr':
  8704. iv_from_hr = request.form[i]
  8705. elif i[:19] == 'inletValve_from_min':
  8706. iv_from_min = request.form[i]
  8707. bean.start = iv_from_hr + ":" + iv_from_min
  8708. elif i[:16] == 'inletValve_to_hr':
  8709. iv_to_hr = request.form[i]
  8710. elif i[:17] == 'inletValve_to_min':
  8711. iv_to_min = request.form[i]
  8712. bean.end = iv_to_hr + ":" + iv_to_min
  8713. bean.datetime = current_time
  8714. db.session.add(bean)
  8715. db.session.commit()
  8716. # 清洗機
  8717. elif i[:4] == 'wash':
  8718. if i[:13] == 'wash_duration':
  8719. wash = WashMachine()
  8720. wash.duration = request.form[i]
  8721. elif i[:12] == 'wash_from_hr':
  8722. wash_from_hr = request.form[i]
  8723. elif i[:13] == 'wash_from_min':
  8724. wash_from_min = request.form[i]
  8725. wash.start = wash_from_hr + ":" + wash_from_min
  8726. elif i[:10] == 'wash_to_hr':
  8727. wash_to_hr = request.form[i]
  8728. elif i[:11] == 'wash_to_min':
  8729. wash_to_min = request.form[i]
  8730. wash.end = wash_to_hr + ":" + wash_to_min
  8731. wash.datetime = current_time
  8732. db.session.add(wash)
  8733. db.session.commit()
  8734. # 輸送帶1
  8735. elif i[:5] == 'belt1':
  8736. if i[:14] == 'belt1_duration':
  8737. belt1 = ConveyorBelt1()
  8738. belt1.duration = request.form[i]
  8739. elif i[:13] == 'belt1_from_hr':
  8740. belt1_from_hr = request.form[i]
  8741. elif i[:14] == 'belt1_from_min':
  8742. belt1_from_min = request.form[i]
  8743. belt1.start = belt1_from_hr + ":" + belt1_from_min
  8744. elif i[:11] == 'belt1_to_hr':
  8745. belt1_to_hr = request.form[i]
  8746. elif i[:12] == 'belt1_to_min':
  8747. belt1_to_min = request.form[i]
  8748. belt1.end = belt1_to_hr + ":" + belt1_to_min
  8749. belt1.datetime = current_time
  8750. db.session.add(belt1)
  8751. db.session.commit()
  8752. # 消毒
  8753. elif i[:9] == 'disinfect':
  8754. if i[:18] == 'disinfect_duration':
  8755. disinfect = Cargo1Disinfect()
  8756. disinfect.duration = request.form[i]
  8757. elif i[:17] == 'disinfect_from_hr':
  8758. di_from_hr = request.form[i]
  8759. elif i[:18] == 'disinfect_from_min':
  8760. di_from_min = request.form[i]
  8761. disinfect.start = di_from_hr + ":" + di_from_min
  8762. elif i[:15] == 'disinfect_to_hr':
  8763. di_to_hr = request.form[i]
  8764. elif i[:16] == 'disinfect_to_min':
  8765. di_to_min = request.form[i]
  8766. disinfect.end = di_to_hr + ":" + di_to_min
  8767. disinfect.datetime = current_time
  8768. db.session.add(disinfect)
  8769. db.session.commit()
  8770. # 色選機
  8771. elif i[:5] == 'color':
  8772. if i[:14] == 'color_duration':
  8773. color = ColorMachine()
  8774. color.duration = request.form[i]
  8775. elif i[:13] == 'color_from_hr':
  8776. color_from_hr = request.form[i]
  8777. elif i[:14] == 'color_from_min':
  8778. color_from_min = request.form[i]
  8779. color.start = color_from_hr + ":" + color_from_min
  8780. elif i[:11] == 'color_to_hr':
  8781. color_to_hr = request.form[i]
  8782. elif i[:12] == 'color_to_min':
  8783. color_to_min = request.form[i]
  8784. color.end = color_to_hr + ":" + color_to_min
  8785. color.datetime = current_time
  8786. db.session.add(color)
  8787. db.session.commit()
  8788. # 輸送帶2
  8789. elif i[:5] == 'belt2':
  8790. if i[:14] == 'belt2_duration':
  8791. belt2 = ConveyorBelt2()
  8792. belt2.duration = request.form[i]
  8793. elif i[:13] == 'belt2_from_hr':
  8794. belt2_from_hr = request.form[i]
  8795. elif i[:14] == 'belt2_from_min':
  8796. belt2_from_min = request.form[i]
  8797. belt2.start = belt2_from_hr + ":" + belt2_from_min
  8798. elif i[:11] == 'belt2_to_hr':
  8799. belt2_to_hr = request.form[i]
  8800. elif i[:12] == 'belt2_to_min':
  8801. belt2_to_min = request.form[i]
  8802. belt2.end = belt2_to_hr + ":" + belt2_to_min
  8803. belt2.datetime = current_time
  8804. db.session.add(belt2)
  8805. db.session.commit()
  8806. # 去皮機
  8807. elif i[:6] == 'peeled':
  8808. if i[:15] == 'peeled_duration':
  8809. peeling = PeelingMachine()
  8810. peeling.duration = request.form[i]
  8811. elif i[:14] == 'peeled_from_hr':
  8812. peeled_from_hr = request.form[i]
  8813. elif i[:15] == 'peeled_from_min':
  8814. peeled_from_min = request.form[i]
  8815. peeling.start = peeled_from_hr + ":" + peeled_from_min
  8816. elif i[:12] == 'peeled_to_hr':
  8817. peeled_to_hr = request.form[i]
  8818. elif i[:13] == 'peeled_to_min':
  8819. peeled_to_min = request.form[i]
  8820. peeling.end = peeled_to_hr + ":" + peeled_to_min
  8821. peeling.datetime = current_time
  8822. db.session.add(peeling)
  8823. db.session.commit()
  8824. # 輸送帶3
  8825. elif i[:5] == 'belt3':
  8826. if i[:14] == 'belt3_duration':
  8827. belt3 = ConveyorBelt3()
  8828. belt3.duration = request.form[i]
  8829. elif i[:13] == 'belt3_from_hr':
  8830. belt3_from_hr = request.form[i]
  8831. elif i[:14] == 'belt3_from_min':
  8832. belt3_from_min = request.form[i]
  8833. belt3.start = belt3_from_hr + ":" + belt3_from_min
  8834. elif i[:11] == 'belt3_to_hr':
  8835. belt3_to_hr = request.form[i]
  8836. elif i[:12] == 'belt3_to_min':
  8837. belt3_to_min = request.form[i]
  8838. belt3.end = belt3_to_hr + ":" + belt3_to_min
  8839. belt3.datetime = current_time
  8840. db.session.add(belt3)
  8841. db.session.commit()
  8842. return render_template('cargo1.html', params=locals())
  8843. # 貨櫃2的訪問路徑
  8844. @main.route('/cargo2', methods=['GET', 'POST'])
  8845. def cargo2_views():
  8846. username = session['uname']
  8847. if request.method == 'GET':
  8848. return render_template('cargo2.html', params=locals())
  8849. else:
  8850. pass
  8851. # 貨櫃2排程的發酵槽訪問路徑
  8852. @main.route('/cargo2_schedule_tanks', methods=['GET', 'POST'])
  8853. def cargo2_schedule_tanks_views():
  8854. username = session['uname']
  8855. if request.method == 'GET':
  8856. return render_template('cargo2_schedule_tanks.html', params=locals())
  8857. else:
  8858. pass
  8859. # 貨櫃2排程發酵槽的清單訪問路徑
  8860. @main.route('/cargo2_schedule/<tid>', methods=['GET', 'POST'])
  8861. def cargo2_schedule_views(tid):
  8862. username = session['uname']
  8863. if request.method == 'GET':
  8864. # 將已儲存的排程資料傳給前端
  8865. # 打菌
  8866. try:
  8867. bacteria = Bacteria.query.filter_by(tank_num=int(
  8868. tid)).order_by(text('datetime desc')).first()
  8869. datetime = bacteria.datetime
  8870. bacterias = Bacteria.query.filter_by(datetime=datetime).all()
  8871. except Exception as e:
  8872. pass
  8873. # 消毒
  8874. try:
  8875. disinfect = Cargo2Disinfect.query.filter_by(
  8876. tank_num=int(tid)).order_by(text('datetime desc')).first()
  8877. datetime = disinfect.datetime
  8878. disinfects = Cargo2Disinfect.query.filter_by(
  8879. datetime=datetime).all()
  8880. except Exception as e:
  8881. pass
  8882. # 加熱
  8883. try:
  8884. heating = Heating.query.filter_by(tank_num=int(
  8885. tid)).order_by(text('datetime desc')).first()
  8886. datetime = heating.datetime
  8887. heatings = Heating.query.filter_by(datetime=datetime).all()
  8888. except Exception as e:
  8889. pass
  8890. # 攪拌
  8891. try:
  8892. stir = Stir.query.filter_by(tank_num=int(tid)).order_by(
  8893. text('datetime desc')).first()
  8894. datetime = stir.datetime
  8895. stirs = Stir.query.filter_by(datetime=datetime).all()
  8896. except Exception as e:
  8897. pass
  8898. # 注水
  8899. try:
  8900. water = WaterInjection.query.filter_by(
  8901. tank_num=int(tid)).order_by(text('datetime desc')).first()
  8902. datetime = water.datetime
  8903. waters = WaterInjection.query.filter_by(datetime=datetime).all()
  8904. except Exception as e:
  8905. pass
  8906. # 開上閥
  8907. try:
  8908. top = TopValve.query.filter_by(tank_num=int(
  8909. tid)).order_by(text('datetime desc')).first()
  8910. datetime = top.datetime
  8911. tops = TopValve.query.filter_by(datetime=datetime).all()
  8912. except Exception as e:
  8913. pass
  8914. # 開下閥
  8915. try:
  8916. bottom = BottomValve.query.filter_by(tank_num=int(
  8917. tid)).order_by(text('datetime desc')).first()
  8918. datetime = bottom.datetime
  8919. bottoms = BottomValve.query.filter_by(datetime=datetime).all()
  8920. except Exception as e:
  8921. pass
  8922. # 溫度
  8923. try:
  8924. tem = Temperature.query.filter_by(tank_num=int(
  8925. tid)).order_by(text('datetime desc')).first()
  8926. datetime = tem.datetime
  8927. tems = Temperature.query.filter_by(datetime=datetime).all()
  8928. except Exception as e:
  8929. pass
  8930. return render_template('cargo2_schedule.html', params=locals())
  8931. else:
  8932. current_time = dt.now()
  8933. # 循環從前端提交過來的資料
  8934. for i in request.form:
  8935. # 打菌
  8936. if i[:8] == 'bacteria':
  8937. if i[:17] == 'bacteria_duration':
  8938. bacteria = Bacteria()
  8939. bacteria.duration = request.form[i]
  8940. elif i[:16] == 'bacteria_from_hr':
  8941. bac_from_hr = request.form[i]
  8942. elif i[:17] == 'bacteria_from_min':
  8943. bac_from_min = request.form[i]
  8944. bacteria.start = bac_from_hr + ":" + bac_from_min
  8945. elif i[:14] == 'bacteria_to_hr':
  8946. bac_to_hr = request.form[i]
  8947. elif i[:15] == 'bacteria_to_min':
  8948. bac_to_min = request.form[i]
  8949. bacteria.end = bac_to_hr + ":" + bac_to_min
  8950. bacteria.datetime = current_time
  8951. bacteria.tank_num = int(tid)
  8952. db.session.add(bacteria)
  8953. db.session.commit()
  8954. # 消毒
  8955. elif i[:9] == 'disinfect':
  8956. if i[:18] == 'disinfect_duration':
  8957. disinfect = Cargo2Disinfect()
  8958. disinfect.duration = request.form[i]
  8959. elif i[:17] == 'disinfect_from_hr':
  8960. di_from_hr = request.form[i]
  8961. elif i[:18] == 'disinfect_from_min':
  8962. di_from_min = request.form[i]
  8963. disinfect.start = di_from_hr + ":" + di_from_min
  8964. elif i[:15] == 'disinfect_to_hr':
  8965. di_to_hr = request.form[i]
  8966. elif i[:16] == 'disinfect_to_min':
  8967. di_to_min = request.form[i]
  8968. disinfect.end = di_to_hr + ":" + di_to_min
  8969. disinfect.datetime = current_time
  8970. disinfect.tank_num = int(tid)
  8971. db.session.add(disinfect)
  8972. db.session.commit()
  8973. # 加熱
  8974. elif i[:7] == 'heating':
  8975. if i[:16] == 'heating_duration':
  8976. heating = Heating()
  8977. heating.duration = request.form[i]
  8978. elif i[:15] == 'heating_from_hr':
  8979. heat_from_hr = request.form[i]
  8980. elif i[:16] == 'heating_from_min':
  8981. heat_from_min = request.form[i]
  8982. heating.start = heat_from_hr + ":" + heat_from_min
  8983. elif i[:13] == 'heating_to_hr':
  8984. heat_to_hr = request.form[i]
  8985. elif i[:14] == 'heating_to_min':
  8986. heat_to_min = request.form[i]
  8987. heating.end = heat_to_hr + ":" + heat_to_min
  8988. heating.datetime = current_time
  8989. heating.tank_num = int(tid)
  8990. db.session.add(heating)
  8991. db.session.commit()
  8992. # 攪拌
  8993. elif i[:4] == 'stir':
  8994. if i[:13] == 'stir_duration':
  8995. stir = Stir()
  8996. stir.duration = request.form[i]
  8997. elif i[:12] == 'stir_from_hr':
  8998. stir_from_hr = request.form[i]
  8999. elif i[:13] == 'stir_from_min':
  9000. stir_from_min = request.form[i]
  9001. stir.start = stir_from_hr + ":" + stir_from_min
  9002. elif i[:10] == 'stir_to_hr':
  9003. stir_to_hr = request.form[i]
  9004. elif i[:11] == 'stir_to_min':
  9005. stir_to_min = request.form[i]
  9006. stir.end = stir_to_hr + ":" + stir_to_min
  9007. stir.datetime = current_time
  9008. stir.tank_num = int(tid)
  9009. db.session.add(stir)
  9010. db.session.commit()
  9011. # 注水
  9012. elif i[:5] == 'water':
  9013. if i[:14] == 'water_duration':
  9014. water = WaterInjection()
  9015. water.duration = request.form[i]
  9016. elif i[:13] == 'water_from_hr':
  9017. water_from_hr = request.form[i]
  9018. elif i[:14] == 'water_from_min':
  9019. water_from_min = request.form[i]
  9020. water.start = water_from_hr + ":" + water_from_min
  9021. elif i[:11] == 'water_to_hr':
  9022. water_to_hr = request.form[i]
  9023. elif i[:12] == 'water_to_min':
  9024. water_to_min = request.form[i]
  9025. water.end = water_to_hr + ":" + water_to_min
  9026. water.datetime = current_time
  9027. water.tank_num = int(tid)
  9028. db.session.add(water)
  9029. db.session.commit()
  9030. # 開上閥
  9031. elif i[:9] == 'highValve':
  9032. if i[:18] == 'highValve_duration':
  9033. top = TopValve()
  9034. top.duration = request.form[i]
  9035. elif i[:17] == 'highValve_from_hr':
  9036. h_valve_from_hr = request.form[i]
  9037. elif i[:18] == 'highValve_from_min':
  9038. h_valve_from_min = request.form[i]
  9039. top.start = h_valve_from_hr + ":" + h_valve_from_min
  9040. elif i[:15] == 'highValve_to_hr':
  9041. h_valve_to_hr = request.form[i]
  9042. elif i[:16] == 'highValve_to_min':
  9043. h_valve_to_min = request.form[i]
  9044. top.end = h_valve_to_hr + ":" + h_valve_to_min
  9045. top.datetime = current_time
  9046. top.tank_num = int(tid)
  9047. db.session.add(top)
  9048. db.session.commit()
  9049. # 開下閥
  9050. elif i[:8] == 'lowValve':
  9051. if i[:17] == 'lowValve_duration':
  9052. bottom = BottomValve()
  9053. bottom.duration = request.form[i]
  9054. elif i[:16] == 'lowValve_from_hr':
  9055. l_valve_from_hr = request.form[i]
  9056. elif i[:17] == 'lowValve_from_min':
  9057. l_valve_from_min = request.form[i]
  9058. bottom.start = l_valve_from_hr + ":" + l_valve_from_min
  9059. elif i[:14] == 'lowValve_to_hr':
  9060. l_valve_to_hr = request.form[i]
  9061. elif i[:15] == 'lowValve_to_min':
  9062. l_valve_to_min = request.form[i]
  9063. bottom.end = l_valve_to_hr + ":" + l_valve_to_min
  9064. bottom.datetime = current_time
  9065. bottom.tank_num = int(tid)
  9066. db.session.add(bottom)
  9067. db.session.commit()
  9068. # 溫度
  9069. elif i[:3] == 'tem':
  9070. if i[:12] == 'tem_duration':
  9071. tem = Temperature()
  9072. tem.duration = request.form[i]
  9073. elif i[:11] == 'tem_from_hr':
  9074. tem_from_hr = request.form[i]
  9075. elif i[:12] == 'tem_from_min':
  9076. tem_from_min = request.form[i]
  9077. tem.start = tem_from_hr + ":" + tem_from_min
  9078. elif i[:9] == 'tem_to_hr':
  9079. tem_to_hr = request.form[i]
  9080. elif i[:10] == 'tem_to_min':
  9081. tem_to_min = request.form[i]
  9082. tem.end = tem_to_hr + ":" + tem_to_min
  9083. tem.datetime = current_time
  9084. tem.tank_num = int(tid)
  9085. db.session.add(tem)
  9086. db.session.commit()
  9087. return render_template('cargo2.html', params=locals())
  9088. # 貨櫃2感測器的發酵槽訪問路徑
  9089. @main.route('/cargo2_sensor_tanks', methods=['GET', 'POST'])
  9090. def cargo2_sensor_tanks_views():
  9091. username = session['uname']
  9092. if request.method == 'GET':
  9093. return render_template('cargo2_sensor_tanks.html', params=locals())
  9094. else:
  9095. pass
  9096. # 貨櫃2感測器發酵槽的清單訪問路徑
  9097. @main.route('/cargo2_sensor/<tid>', methods=['GET', 'POST'])
  9098. def s_tank_views(tid):
  9099. # 判斷用戶是否已關閉瀏覽器或登出後,在訪問這個route,如果沒有session就回登入頁
  9100. try:
  9101. username = session['uname']
  9102. except KeyError:
  9103. return redirect('/')
  9104. if request.method == 'GET':
  9105. # Rita 網頁端 params.tank_tem.tem
  9106. # Coffee/CoffeeProject/app/templates/cargo2_sensor.html
  9107. tank_tem = TankTemSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
  9108. tank_ph = TankPHSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
  9109. tank_ec = TankECSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
  9110. tank_sonic = TankSonicSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
  9111. return render_template('cargo2_sensor.html', params=locals())
  9112. else:
  9113. pass
  9114. # 貨櫃2感測器發酵槽歷史數據的訪問路徑
  9115. @main.route('/history_data', methods=['GET', 'POST'])
  9116. def history_data_views():
  9117. if request.method == 'GET':
  9118. # json
  9119. # tid:tid_D1
  9120. # sensor_name:soil_Temp
  9121. # avg:1
  9122. # max:1
  9123. # min:1
  9124. # time-interval:month
  9125. # date-start:2021-07-01
  9126. # date-end:2021-07-28
  9127. info = request.args.to_dict()
  9128. evt = info['evt']
  9129. avg = int(info['avg'])
  9130. max = int(info['max'])
  9131. min = int(info['min'])
  9132. time_interval = info['time-interval']
  9133. print(info)
  9134. # Rita {'evt': '1-溫濕度', 'avg': '1', 'max': '0', 'min': '0', 'time-interval': 'month',
  9135. # 'date-start': '2021-05-04', 'date-end': '2021-05-18'} {'all': [], 'avg': []}
  9136. # print(info)
  9137. # {'evt': '1-溫濕度', 'avg': '1', 'max': '0', 'min': '0', 'time-interval': 'hour', 'date-start': '2021-01-01', 'date-end': '2021-07-27'}
  9138. # print(D)
  9139. # {'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']],
  9140. # 'avg': [['2021-02-19 16:00:00', '24.5'], ['2021-02-19 18:00:00', '25.3']]}
  9141. # 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 -
  9142. date_start = info['date-start']
  9143. date_end_list = info['date-end'].split('-') # 先把 'date-end' 的 '2021-05-18' 拆成 ['2021', '05', '18']
  9144. date_end_list[2] = str(int(date_end_list[2]) + 1) # 18 + 1 = 19 再轉成 str → '19'
  9145. date_end = '-'.join(date_end_list) # '2021-05-19'
  9146. tank_num = evt.split('-')[0] # 1
  9147. sensor = evt.split('-')[1] # 溫濕度
  9148. L = []
  9149. D = {}
  9150. maxData = []
  9151. minData = []
  9152. avgData = []
  9153. def sensorData(data_name): # data_name = "tem"
  9154. def dataResample(time_interval, how, data_name): # dataResample('month', how???, "tem") # 下方 "hour"
  9155. interval = 0
  9156. # 設置resample的第一個參數,要按照逐月、逐日或逐時
  9157. if time_interval == 'month':
  9158. interval = "M" # interval = "M"
  9159. elif time_interval == 'day':
  9160. interval = "D"
  9161. elif time_interval == 'hour':
  9162. interval = "H"
  9163. if how == "max":
  9164. # data = df.resample(interval, how={data_name:how})
  9165. # 最新版的pandas
  9166. data = df.resample(interval).max() # 取樣頻率 "H"
  9167. # 刪除有 NaN 的列, any 任何一欄位為空則刪 (all 全部欄位為空值才刪)
  9168. data = data.dropna(axis=0, how='any')
  9169. if time_interval == ('hour' or 'day'):
  9170. data.index = pd.to_datetime(
  9171. data.index, format='%Y-%b-%d_%H:%M:%S') # 将数据类型转换为日期类型
  9172. for a in range(0, len(data.index)):
  9173. l = []
  9174. # 如果是逐時,才顯示小時分秒
  9175. if time_interval == 'hour':
  9176. l.append(str(data.index[a]))
  9177. else:
  9178. l.append(str(data.index[a]).split(' ')[0])
  9179. l.append(str(data[data_name][a]))
  9180. maxData.append(l)
  9181. D['max'] = maxData
  9182. elif how == "mean":
  9183. # data = df.resample(interval, how={data_name:how})
  9184. # 最新版的pandas
  9185. data = df.resample(interval).mean()
  9186. # 刪除具有NaN的值
  9187. data = data.dropna(axis=0, how='any')
  9188. # 將平均數取自小數1位
  9189. data = data.round({data_name: 1})
  9190. for a in range(0, len(data.index)):
  9191. l = []
  9192. # 如果是逐時,才顯示小時分秒
  9193. if time_interval == 'hour':
  9194. l.append(str(data.index[a]))
  9195. else:
  9196. l.append(str(data.index[a]).split(' ')[0])
  9197. l.append(str(data[data_name][a]))
  9198. avgData.append(l)
  9199. D['avg'] = avgData
  9200. elif how == "min":
  9201. # data = df.resample(interval, how={data_name:how})
  9202. # 最新版的pandas
  9203. data = df.resample(interval).min()
  9204. # 刪除具有NaN的值
  9205. data = data.dropna(axis=0, how='any')
  9206. for a in range(0, len(data.index)):
  9207. # print(data.index[a])
  9208. l = []
  9209. # 如果是逐時,才顯示小時分秒
  9210. if time_interval == 'hour':
  9211. l.append(str(data.index[a]))
  9212. else:
  9213. l.append(str(data.index[a]).split(' ')[0])
  9214. l.append(str(data[data_name][a]))
  9215. minData.append(l)
  9216. D['min'] = minData
  9217. df = pd.DataFrame(L, columns=["datetime", data_name]) # 指定欄標籤名稱 為 ["datetime", "tem"]
  9218. df['datetime'] = pd.to_datetime(
  9219. df['datetime'], format='%Y-%b-%d_%H:%M:%S') # 将数据类型转换为日期类型
  9220. # print(df['datetime']) # 0 2021-02-19 16:46:10
  9221. # 1 2021-02-19 16:46:20
  9222. # 2 2021-02-19 16:46:30
  9223. # 3 2021-02-19 16:46:41
  9224. df[data_name] = df[data_name].astype(float)
  9225. df = df.set_index('datetime') # 将datetime设置为index
  9226. # print(df) # datetime tem
  9227. # 2021-02-19 16:46:10 24.4
  9228. # 2021-02-19 16:46:20 24.4
  9229. if time_interval == 'month':
  9230. if max:
  9231. dataResample(time_interval, "max", data_name)
  9232. if avg:
  9233. dataResample(time_interval, "mean", data_name)
  9234. if min:
  9235. dataResample(time_interval, "min", data_name)
  9236. elif time_interval == 'day':
  9237. if max:
  9238. dataResample(time_interval, "max", data_name)
  9239. if avg:
  9240. dataResample(time_interval, "mean", data_name)
  9241. if min:
  9242. dataResample(time_interval, "min", data_name)
  9243. elif time_interval == 'hour':
  9244. if max:
  9245. dataResample(time_interval, "max", data_name)
  9246. if avg:
  9247. dataResample(time_interval, "mean", data_name)
  9248. if min:
  9249. dataResample(time_interval, "min", data_name)
  9250. if sensor == '溫濕度':
  9251. # tank_tem = TankTemSensor.query.filter_by(tank_num=int(tank_num)).order_by(text('datetime desc')).all()
  9252. # [7/27 Benson] tank_tem = TankTemSensor.query.filter_by(tank_num=int(tank_num)).filter(TankTemSensor.datetime.between(date_start, date_end)).all()
  9253. tank_tem = dry_tank_SHT11.query.filter(dry_tank_SHT11.datetime.between(date_start, date_end)).all()
  9254. # .filter_by(tank_num="D"+tank_num)
  9255. for tem in tank_tem:
  9256. l = [] # l = []
  9257. time = dt.strftime(tem.datetime, '%Y-%b-%d_%H:%M:%S') # time = '2021-Feb-19_16:46:10' 轉換時間格式
  9258. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  9259. l.append(time) # l = ['2021-Feb-19_16:46:10']
  9260. #l.append(tem.tem) # l = ['2021-Feb-19_16:46:10', '24.4']
  9261. l.append(tem.SHT11_Temp)
  9262. L.append(l) # L = [['2021-Feb-19_16:46:10', '24.4']]
  9263. # print(L)
  9264. D['all'] = L # D = {'all': [['2021-Feb-19_16:46:10', '24.4']]} # all 所有符合數據
  9265. sensorData("tem")
  9266. elif sensor == '酸鹼值':
  9267. tank_ph = TankPHSensor.query.filter_by(tank_num=int(tank_num)).filter(
  9268. TankPHSensor.datetime.between(date_start, date_end)).all()
  9269. for ph in tank_ph:
  9270. l = []
  9271. time = dt.strftime(ph.datetime, '%Y-%b-%d_%H:%M:%S')
  9272. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  9273. l.append(time)
  9274. l.append(ph.ph)
  9275. L.append(l)
  9276. # print(L)
  9277. D['all'] = L
  9278. sensorData("ph")
  9279. elif sensor == 'EC值':
  9280. tank_ec = TankECSensor.query.filter_by(tank_num=int(tank_num)).filter(
  9281. TankECSensor.datetime.between(date_start, date_end)).all()
  9282. for ec in tank_ec:
  9283. l = []
  9284. time = dt.strftime(ec.datetime, '%Y-%b-%d_%H:%M:%S')
  9285. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  9286. l.append(time)
  9287. l.append(ec.ec)
  9288. L.append(l)
  9289. # print(L)
  9290. D['all'] = L
  9291. sensorData("ec")
  9292. elif sensor == '超音波':
  9293. tank_sonic = TankSonicSensor.query.filter_by(tank_num=int(tank_num)).filter(
  9294. TankSonicSensor.datetime.between(date_start, date_end)).all()
  9295. for sonic in tank_sonic:
  9296. l = []
  9297. time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
  9298. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  9299. l.append(time)
  9300. l.append(sonic.sonic)
  9301. L.append(l)
  9302. # print(L)
  9303. D['all'] = L
  9304. sensorData("sonic")
  9305. print(D)
  9306. return json.dumps(D)
  9307. else:
  9308. pass
  9309. # Rita 改寫
  9310. @main.route('/history_data_new', methods=['GET', 'POST'])
  9311. def history_data_new_views():
  9312. if request.method == 'GET':
  9313. # json
  9314. # tid:tid_D1
  9315. # sensor_name:soil_Temp
  9316. # avg:1
  9317. # max:1
  9318. # min:1
  9319. # time-interval:month
  9320. # date-start:2021-07-01
  9321. # date-end:2021-07-28
  9322. info = request.args.to_dict()
  9323. # evt = info['evt']
  9324. tid = info['tid']
  9325. sensor_name = info['sensor_name']
  9326. avg = int(info['avg'])
  9327. max = int(info['max'])
  9328. min = int(info['min'])
  9329. time_interval = info['time-interval']
  9330. print("info:", info)
  9331. # Rita {'evt': '1-溫濕度', 'avg': '1', 'max': '0', 'min': '0', 'time-interval': 'month',
  9332. # 'date-start': '2021-05-04', 'date-end': '2021-05-18'} {'all': [], 'avg': []}
  9333. # print(info)
  9334. # {'evt': '1-溫濕度', 'avg': '1', 'max': '0', 'min': '0', 'time-interval': 'hour', 'date-start': '2021-01-01', 'date-end': '2021-07-27'}
  9335. # print(D)
  9336. # {'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']],
  9337. # 'avg': [['2021-02-19 16:00:00', '24.5'], ['2021-02-19 18:00:00', '25.3']]}
  9338. # 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 -
  9339. date_start = info['date-start']
  9340. date_end_list = info['date-end'].split('-') # 先把 'date-end' 的 '2021-05-18' 拆成 ['2021', '05', '18']
  9341. date_end_list[2] = str(int(date_end_list[2]) + 1) # 18 + 1 = 19 再轉成 str → '19'
  9342. date_end = '-'.join(date_end_list) # '2021-05-19'
  9343. # tank_num = evt.split('-')[0] # 1
  9344. # sensor = evt.split('-')[1] # 溫濕度
  9345. tank_num = tid # D1
  9346. sensor = sensor_name # soil_Temp
  9347. L = []
  9348. D = {}
  9349. maxData = []
  9350. minData = []
  9351. avgData = []
  9352. def sensorData(data_name): # data_name = "tem"
  9353. def dataResample(time_interval, how, data_name): # dataResample('month', how???, "tem") # 下方 "hour"
  9354. interval = 0
  9355. # 設置resample的第一個參數,要按照逐月、逐日或逐時
  9356. if time_interval == 'month':
  9357. interval = "M" # interval = "M"
  9358. elif time_interval == 'day':
  9359. interval = "D"
  9360. elif time_interval == 'hour':
  9361. interval = "H"
  9362. if how == "max":
  9363. # data = df.resample(interval, how={data_name:how})
  9364. # 最新版的pandas
  9365. data = df.resample(interval).max() # 取樣頻率 'H'
  9366. # 刪除有 NaN 的列, any 任何一欄位為空則刪 (all 全部欄位為空值才刪)
  9367. data = data.dropna(axis=0, how='any')
  9368. if time_interval == ('hour' or 'day'):
  9369. data.index = pd.to_datetime(
  9370. data.index, format='%Y-%b-%d_%H:%M:%S') # 将数据类型转换为日期类型
  9371. for a in range(0, len(data.index)):
  9372. l = []
  9373. # 如果是逐時,才顯示小時分秒
  9374. if time_interval == 'hour':
  9375. l.append(str(data.index[a]))
  9376. else:
  9377. l.append(str(data.index[a]).split(' ')[0])
  9378. l.append(str(data[data_name][a]))
  9379. maxData.append(l)
  9380. D['max'] = maxData
  9381. elif how == "mean":
  9382. # data = df.resample(interval, how={data_name:how})
  9383. # 最新版的pandas
  9384. data = df.resample(interval).mean()
  9385. # 刪除具有NaN的值
  9386. data = data.dropna(axis=0, how='any')
  9387. # 將平均數取自小數1位
  9388. data = data.round({data_name: 1})
  9389. for a in range(0, len(data.index)):
  9390. l = []
  9391. # 如果是逐時,才顯示小時分秒
  9392. if time_interval == 'hour':
  9393. l.append(str(data.index[a]))
  9394. else:
  9395. l.append(str(data.index[a]).split(' ')[0])
  9396. l.append(str(data[data_name][a]))
  9397. avgData.append(l)
  9398. D['avg'] = avgData
  9399. elif how == "min":
  9400. # data = df.resample(interval, how={data_name:how})
  9401. # 最新版的pandas
  9402. data = df.resample(interval).min()
  9403. # 刪除具有NaN的值
  9404. data = data.dropna(axis=0, how='any')
  9405. for a in range(0, len(data.index)):
  9406. # print(data.index[a])
  9407. l = []
  9408. # 如果是逐時,才顯示小時分秒
  9409. if time_interval == 'hour':
  9410. l.append(str(data.index[a]))
  9411. else:
  9412. l.append(str(data.index[a]).split(' ')[0])
  9413. l.append(str(data[data_name][a]))
  9414. minData.append(l)
  9415. D['min'] = minData
  9416. df = pd.DataFrame(L, columns=["datetime", data_name]) # 指定欄標籤名稱 為 ["datetime", "tem"]
  9417. df['datetime'] = pd.to_datetime(
  9418. df['datetime'], format='%Y-%b-%d_%H:%M:%S') # 将数据类型转换为日期类型
  9419. # print(df['datetime']) # 0 2021-02-19 16:46:10
  9420. # 1 2021-02-19 16:46:20
  9421. # 2 2021-02-19 16:46:30
  9422. # 3 2021-02-19 16:46:41
  9423. df[data_name] = df[data_name].astype(float)
  9424. df = df.set_index('datetime') # 将datetime设置为index
  9425. # print(df) # datetime tem
  9426. # 2021-02-19 16:46:10 24.4
  9427. # 2021-02-19 16:46:20 24.4
  9428. if time_interval == 'month':
  9429. if max:
  9430. dataResample(time_interval, "max", data_name)
  9431. if avg:
  9432. dataResample(time_interval, "mean", data_name)
  9433. if min:
  9434. dataResample(time_interval, "min", data_name)
  9435. elif time_interval == 'day':
  9436. if max:
  9437. dataResample(time_interval, "max", data_name)
  9438. if avg:
  9439. dataResample(time_interval, "mean", data_name)
  9440. if min:
  9441. dataResample(time_interval, "min", data_name)
  9442. elif time_interval == 'hour':
  9443. if max:
  9444. dataResample(time_interval, "max", data_name)
  9445. if avg:
  9446. dataResample(time_interval, "mean", data_name)
  9447. if min:
  9448. dataResample(time_interval, "min", data_name)
  9449. if tank_num[:2] == 'DI':
  9450. # 乾燥入料儲豆槽
  9451. if sensor == 'UltraSonic':
  9452. tank_UltraSonic = dry_input_sensor.query.filter_by(tank_num=tank_num).filter(dry_input_sensor.datetime.between(date_start, date_end)).all()
  9453. for sonic in tank_UltraSonic:
  9454. l = []
  9455. time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
  9456. l.append(time)
  9457. l.append(sonic.UltraSonic)
  9458. L.append(l)
  9459. D['all'] = L
  9460. sensorData("UltraSonic")
  9461. elif tank_num[:2] == 'DO':
  9462. # 乾燥出料儲豆槽
  9463. if sensor == 'UltraSonic':
  9464. tank_UltraSonic = dry_output_sensor.query.filter_by(tank_num=tank_num).filter(dry_output_sensor.datetime.between(date_start, date_end)).all()
  9465. for sonic in tank_UltraSonic:
  9466. l = []
  9467. time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
  9468. l.append(time)
  9469. l.append(sonic.UltraSonic)
  9470. L.append(l)
  9471. D['all'] = L
  9472. sensorData("UltraSonic")
  9473. elif tank_num[:1] == 'D':
  9474. # 乾燥槽
  9475. if sensor == 'SHT11_Temp':
  9476. tank_tem = dry_tank_SHT11.query.filter_by(tank_num=tank_num).filter(dry_tank_SHT11.datetime.between(date_start, date_end)).all()
  9477. for tem in tank_tem:
  9478. l = [] # l = []
  9479. time = dt.strftime(tem.datetime, '%Y-%b-%d_%H:%M:%S') # time = '2021-Feb-19_16:46:10' 轉換時間格式
  9480. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  9481. l.append(time) # l = ['2021-Feb-19_16:46:10']
  9482. #l.append(tem.tem) # l = ['2021-Feb-19_16:46:10', '24.4']
  9483. l.append(tem.SHT11_Temp)
  9484. L.append(l) # L = [['2021-Feb-19_16:46:10', '24.4']]
  9485. # print(L)
  9486. D['all'] = L # D = {'all': [['2021-Feb-19_16:46:10', '24.4']]} # all 所有符合數據
  9487. sensorData("SHT11_Temp")
  9488. elif sensor == 'SHT11_Humidity':
  9489. tank_hum = dry_tank_SHT11.query.filter_by(tank_num=tank_num).filter(dry_tank_SHT11.datetime.between(date_start, date_end)).all()
  9490. for hum in tank_hum:
  9491. l = []
  9492. time = dt.strftime(hum.datetime, '%Y-%b-%d_%H:%M:%S')
  9493. l.append(time)
  9494. l.append(hum.SHT11_Humidity)
  9495. L.append(l)
  9496. D['all'] = L
  9497. sensorData("SHT11_Humidity")
  9498. elif sensor == 'UltraSonic':
  9499. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num=tank_num).filter(dry_tank_UltraSonic.datetime.between(date_start, date_end)).all()
  9500. for sonic in tank_UltraSonic:
  9501. l = []
  9502. time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
  9503. l.append(time)
  9504. l.append(sonic.UltraSonic)
  9505. L.append(l)
  9506. D['all'] = L
  9507. sensorData("UltraSonic")
  9508. elif sensor == 'PA':
  9509. tank_PA = dry_tank_PA.query.filter_by(tank_num=tank_num).filter(dry_tank_PA.datetime.between(date_start, date_end)).all()
  9510. for pa in tank_PA:
  9511. l = []
  9512. time = dt.strftime(pa.datetime, '%Y-%b-%d_%H:%M:%S')
  9513. l.append(time)
  9514. l.append(pa.PA)
  9515. L.append(l)
  9516. D['all'] = L
  9517. sensorData("PA")
  9518. elif sensor == 'soil_Temp':
  9519. tank_soiltemp = dry_tank_Soil.query.filter_by(tank_num=tank_num).filter(dry_tank_Soil.datetime.between(date_start, date_end)).all()
  9520. for temp in tank_soiltemp:
  9521. l = []
  9522. time = dt.strftime(temp.datetime, '%Y-%b-%d_%H:%M:%S')
  9523. l.append(time)
  9524. l.append(temp.soil_Temp)
  9525. L.append(l)
  9526. D['all'] = L
  9527. sensorData("soil_Temp")
  9528. elif sensor == 'soil_Humidity':
  9529. tank_soilHum = dry_tank_Soil.query.filter_by(tank_num=tank_num).filter(dry_tank_Soil.datetime.between(date_start, date_end)).all()
  9530. for hum in tank_soilHum:
  9531. l = []
  9532. time = dt.strftime(hum.datetime, '%Y-%b-%d_%H:%M:%S')
  9533. l.append(time)
  9534. l.append(hum.soil_EC)
  9535. L.append(l)
  9536. D['all'] = L
  9537. sensorData("soil_Humidity")
  9538. elif sensor == 'soil_EC':
  9539. tank_soilec = dry_tank_Soil.query.filter_by(tank_num=tank_num).filter(dry_tank_Soil.datetime.between(date_start, date_end)).all()
  9540. for ec in tank_soilec:
  9541. l = []
  9542. time = dt.strftime(ec.datetime, '%Y-%b-%d_%H:%M:%S')
  9543. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  9544. l.append(time)
  9545. l.append(ec.soil_EC)
  9546. L.append(l)
  9547. D['all'] = L
  9548. sensorData("soil_EC")
  9549. elif tank_num[:2] == 'FI':
  9550. if sensor == 'UltraSonic':
  9551. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num=tank_num).filter(ferment_input_UltraSonic.datetime.between(date_start, date_end)).all()
  9552. for UltraSonic in input_UltraSonic:
  9553. l = []
  9554. time = dt.strftime(UltraSonic.datetime, '%Y-%b-%d_%H:%M:%S')
  9555. l.append(time)
  9556. l.append(UltraSonic.UltraSonic)
  9557. L.append(l)
  9558. D['all'] = L
  9559. sensorData("UltraSonic")
  9560. elif tank_num[:2] == 'FO':
  9561. if sensor == 'UltraSonic':
  9562. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num=tank_num).filter(ferment_output_UltraSonic.datetime.between(date_start, date_end)).all()
  9563. for UltraSonic in output_UltraSonic:
  9564. l = []
  9565. time = dt.strftime(UltraSonic.datetime, '%Y-%b-%d_%H:%M:%S')
  9566. l.append(time)
  9567. l.append(UltraSonic.UltraSonic)
  9568. L.append(l)
  9569. D['all'] = L
  9570. sensorData("UltraSonic")
  9571. elif tank_num[:1] == 'F':
  9572. if sensor == 'LiDAR':
  9573. tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num = tank_num)\
  9574. .filter(ferment_tank_LiDAR.datetime.between(date_start, date_end)).all()
  9575. for LiDAR in tank_LiDAR:
  9576. l = []
  9577. time = dt.strftime(LiDAR.datetime, '%Y-%b-%d_%H:%M:%S')
  9578. l.append(time)
  9579. l.append(LiDAR.LiDAR)
  9580. L.append(l)
  9581. D['all'] = L
  9582. sensorData("LiDAR")
  9583. elif sensor == 'motorEncoder':
  9584. tank_motorEncoder = ferment_tank_motorEncoder.query.filter_by(tank_num = tank_num)\
  9585. .filter(ferment_tank_motorEncoder.datetime.between(date_start, date_end)).all()
  9586. for motorEncoder in tank_motorEncoder:
  9587. l = []
  9588. time = dt.strftime(motorEncoder.datetime, '%Y-%b-%d_%H:%M:%S')
  9589. l.append(time)
  9590. l.append(motorEncoder.motorEncoder)
  9591. L.append(l)
  9592. D['all'] = L
  9593. sensorData("motorEncoder")
  9594. elif sensor == 'PressureWaterLevel':
  9595. tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num = tank_num)\
  9596. .filter(ferment_tank_PressureWaterLevel.datetime.between(date_start, date_end)).all()
  9597. for PressureWaterLevel in tank_PressureWaterLevel:
  9598. l = []
  9599. time = dt.strftime(PressureWaterLevel.datetime, '%Y-%b-%d_%H:%M:%S')
  9600. l.append(time)
  9601. l.append(PressureWaterLevel.PressureWaterLevel)
  9602. l.append('{:.2f}'.format(float(PressureWaterLevel.PressureWaterLevel)))
  9603. L.append(l)
  9604. D['all'] = L
  9605. sensorData("PressureWaterLevel")
  9606. elif sensor == 'SHT11_Temp':
  9607. tank_Temp = ferment_tank_SHT11.query.filter_by(tank_num = tank_num)\
  9608. .filter(ferment_tank_SHT11.datetime.between(date_start, date_end)).all()
  9609. for Temp in tank_Temp:
  9610. l = []
  9611. time = dt.strftime(Temp.datetime, '%Y-%b-%d_%H:%M:%S')
  9612. l.append(time)
  9613. l.append(Temp.SHT11_Temp)
  9614. L.append(l)
  9615. D['all'] = L
  9616. sensorData("SHT11_Temp")
  9617. elif sensor == 'SHT11_Humidity':
  9618. tank_Humidity = ferment_tank_SHT11.query.filter_by(tank_num = tank_num)\
  9619. .filter(ferment_tank_SHT11.datetime.between(date_start, date_end)).all()
  9620. for Humidity in tank_Humidity:
  9621. l = []
  9622. time = dt.strftime(Humidity.datetime, '%Y-%b-%d_%H:%M:%S')
  9623. l.append(time)
  9624. l.append(Humidity.SHT11_Humidity)
  9625. L.append(l)
  9626. D['all'] = L
  9627. sensorData("SHT11_Humidity")
  9628. elif sensor == 'CO2':
  9629. tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num = tank_num)\
  9630. .filter(ferment_tank_CO2.datetime.between(date_start, date_end)).all()
  9631. for CO2 in tank_CO2:
  9632. l = []
  9633. time = dt.strftime(CO2.datetime, '%Y-%b-%d_%H:%M:%S')
  9634. l.append(time)
  9635. l.append(CO2.CO2)
  9636. L.append(l)
  9637. D['all'] = L
  9638. sensorData("CO2")
  9639. elif sensor == 'PH':
  9640. tank_PH = ferment_tank_PH.query.filter_by(tank_num = tank_num)\
  9641. .filter(ferment_tank_PH.datetime.between(date_start, date_end)).all()
  9642. for PH in tank_PH:
  9643. l = []
  9644. time = dt.strftime(PH.datetime, '%Y-%b-%d_%H:%M:%S')
  9645. l.append(time)
  9646. l.append(PH.PH)
  9647. L.append(l)
  9648. D['all'] = L
  9649. sensorData("PH")
  9650. elif sensor == 'ORP':
  9651. tank_ORP = ferment_tank_ORP.query.filter_by(tank_num = tank_num)\
  9652. .filter(ferment_tank_ORP.datetime.between(date_start, date_end)).all()
  9653. for ORP in tank_ORP:
  9654. l = []
  9655. time = dt.strftime(ORP.datetime, '%Y-%b-%d_%H:%M:%S')
  9656. l.append(time)
  9657. l.append(ORP.ORP)
  9658. L.append(l)
  9659. D['all'] = L
  9660. sensorData("ORP")
  9661. elif sensor == 'DO':
  9662. tank_DO = ferment_tank_DO.query.filter_by(tank_num = tank_num)\
  9663. .filter(ferment_tank_DO.datetime.between(date_start, date_end)).all()
  9664. for DO in tank_DO:
  9665. l = []
  9666. time = dt.strftime(DO.datetime, '%Y-%b-%d_%H:%M:%S')
  9667. l.append(time)
  9668. l.append(DO.DO)
  9669. L.append(l)
  9670. D['all'] = L
  9671. sensorData("DO")
  9672. elif sensor == 'EC':
  9673. tank_EC = ferment_tank_EC.query.filter_by(tank_num = tank_num)\
  9674. .filter(ferment_tank_EC.datetime.between(date_start, date_end)).all()
  9675. for EC in tank_EC:
  9676. l = []
  9677. time = dt.strftime(EC.datetime, '%Y-%b-%d_%H:%M:%S')
  9678. l.append(time)
  9679. l.append(EC.EC)
  9680. L.append(l)
  9681. D['all'] = L
  9682. sensorData("EC")
  9683. elif sensor == 'PA':
  9684. tank_PA = ferment_tank_PA.query.filter_by(tank_num = tank_num)\
  9685. .filter(ferment_tank_PA.datetime.between(date_start, date_end)).all()
  9686. for PA in tank_PA:
  9687. l = []
  9688. time = dt.strftime(PA.datetime, '%Y-%b-%d_%H:%M:%S')
  9689. l.append(time)
  9690. l.append(PA.PA)
  9691. L.append(l)
  9692. D['all'] = L
  9693. sensorData("PA")
  9694. print(D)
  9695. return json.dumps(D)
  9696. else:
  9697. pass
  9698. # 貨櫃2致動器的發酵槽訪問路徑
  9699. @main.route('/cargo2_actuator_tanks', methods=['GET', 'POST'])
  9700. def cargo2_actuator_tanks_views():
  9701. username = session['uname']
  9702. if request.method == 'GET':
  9703. return render_template('cargo2_actuator_tanks.html', params=locals())
  9704. else:
  9705. pass
  9706. # 貨櫃2致動器發酵槽的清單訪問路徑
  9707. @main.route('/cargo2_actuator/<tid>', methods=['GET', 'POST'])
  9708. def cargo2_actuator_views(tid):
  9709. username = session['uname']
  9710. if request.method == 'GET':
  9711. return render_template('cargo2_actuator.html', params=locals())
  9712. else:
  9713. pass
  9714. # 貨櫃3的訪問路徑
  9715. @main.route('/cargo3', methods=['GET', 'POST'])
  9716. def cargo3_views():
  9717. username = session['uname']
  9718. if request.method == 'GET':
  9719. return render_template('cargo3.html', params=locals())
  9720. else:
  9721. pass
  9722. # 貨櫃3排程的訪問路徑
  9723. @main.route('/cargo3_schedule', methods=['GET', 'POST'])
  9724. def cargo3_schedule_views():
  9725. username = session['uname']
  9726. if request.method == 'GET':
  9727. # 將已儲存的排程資料傳給前端
  9728. # 提升機
  9729. try:
  9730. hoist = Hoist.query.order_by(text('datetime desc')).first()
  9731. datetime = hoist.datetime
  9732. hoists = Hoist.query.filter_by(datetime=datetime).all()
  9733. except Exception as e:
  9734. pass
  9735. # 烘乾機
  9736. try:
  9737. dryer = Dryer.query.order_by(text('datetime desc')).first()
  9738. datetime = dryer.datetime
  9739. dryers = Dryer.query.filter_by(datetime=datetime).all()
  9740. except Exception as e:
  9741. pass
  9742. return render_template('cargo3_schedule.html', params=locals())
  9743. else:
  9744. # Rita: "POST /b_cargo3 HTTP/1.1" 404 -
  9745. current_time = dt.now()
  9746. # 循環從前端提交過來的資料
  9747. for i in request.form:
  9748. print('Rita test i :', i)
  9749. # 堤升機
  9750. if i[:5] == 'hoist':
  9751. if i[:14] == 'hoist_duration':
  9752. hoist = Hoist()
  9753. hoist.duration = request.form[i]
  9754. elif i[:13] == 'hoist_from_hr':
  9755. ho_from_hr = request.form[i]
  9756. elif i[:14] == 'hoist_from_min':
  9757. ho_from_min = request.form[i]
  9758. hoist.start = ho_from_hr + ":" + ho_from_min
  9759. elif i[:11] == 'hoist_to_hr':
  9760. ho_to_hr = request.form[i]
  9761. elif i[:12] == 'hoist_to_min':
  9762. ho_to_min = request.form[i]
  9763. hoist.end = ho_to_hr + ":" + ho_to_min
  9764. hoist.datetime = current_time
  9765. db.session.add(hoist)
  9766. db.session.commit()
  9767. # 烘乾機
  9768. elif i[:5] == 'dryer':
  9769. if i[:14] == 'dryer_duration':
  9770. dryer = Dryer()
  9771. dryer.duration = request.form[i]
  9772. elif i[:13] == 'dryer_from_hr':
  9773. dry_from_hr = request.form[i]
  9774. elif i[:14] == 'dryer_from_min':
  9775. dry_from_min = request.form[i]
  9776. dryer.start = dry_from_hr + ":" + dry_from_min
  9777. elif i[:11] == 'dryer_to_hr':
  9778. dry_to_hr = request.form[i]
  9779. elif i[:12] == 'dryer_to_min':
  9780. dry_to_min = request.form[i]
  9781. dryer.end = dry_to_hr + ":" + dry_to_min
  9782. dryer.datetime = current_time
  9783. db.session.add(dryer)
  9784. db.session.commit()
  9785. return render_template('cargo3.html', params=locals())
  9786. # 影像串流的訪問路徑
  9787. @main.route('/video', methods=['GET', 'POST'])
  9788. def video_views():
  9789. username = session['uname']
  9790. if request.method == 'GET':
  9791. return render_template('video.html', params=locals())
  9792. else:
  9793. pass
  9794. # 影像的訪問路徑
  9795. @main.route('/learn', methods=['GET', 'POST'])
  9796. def learn_views():
  9797. username = session['uname']
  9798. if request.method == 'GET':
  9799. return render_template('learn.html', params=locals())
  9800. else:
  9801. pass
  9802. # 獲取relay狀態路徑
  9803. @main.route('/relay', methods=['GET', 'POST'])
  9804. def relay_views():
  9805. if request.method == 'GET':
  9806. relay = Relay.query.order_by(text('datetime desc')).first()
  9807. relay_status = relay.status
  9808. return jsonify({"relay": relay_status})
  9809. else:
  9810. pass
  9811. # 獲取脫皮機狀態路徑
  9812. @main.route('/peel', methods=['GET', 'POST'])
  9813. def peeling_views():
  9814. if request.method == 'GET':
  9815. peeling = PeelingMachineRPM.query.order_by(text('datetime desc')).first()
  9816. peeling_rpm = peeling.rpm
  9817. return jsonify({"peeling": peeling_rpm})
  9818. else:
  9819. pass
  9820. # 退出的訪問路徑
  9821. @main.route('/logout')
  9822. def logout_views():
  9823. if 'id' in session and 'uname' in session:
  9824. del session['id']
  9825. del session['uname']
  9826. return redirect('/')
  9827. @main.route("/udp_client", methods=['POST', 'GET'])
  9828. def udp_views():
  9829. # sl(0.5)
  9830. global c_sock
  9831. if request.method == 'GET':
  9832. # def close():
  9833. # global c_sock
  9834. # sl(600)
  9835. # c_sock.close()
  9836. # c_sock = 0
  9837. # print("c_sock is closing")
  9838. max_length = 65000
  9839. # max_length = 95000
  9840. # lab1的IP
  9841. host = "192.168.50.65"
  9842. # lab2的IP
  9843. # host = "192.168.51.160"
  9844. port = 8000
  9845. c_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  9846. # t = threading.Thread(target=close)
  9847. # t.daemon = True
  9848. # t.start()
  9849. print("test")
  9850. # dict = request.args.to_dict()
  9851. # nr = int(dict['nr'])
  9852. # if nr == 1:
  9853. # camara = 0
  9854. # elif nr == 2:
  9855. # camara = 'rtsp://admin:admin@192.168.50.182/av2_0'
  9856. # elif nr == 3:
  9857. # camara = 'rtsp://admin:abcd1234@192.168.51.101/av2_0'
  9858. # 地下室小兵
  9859. # cap = cv2.VideoCapture('rtsp://admin:abcd1234@192.168.51.48/av2_0')
  9860. # 主機攝像頭
  9861. # cap = cv2.VideoCapture(0)
  9862. # 外面小兵
  9863. # cap = cv2.VideoCapture('rtsp://admin:admin@192.168.50.182/av2_0')
  9864. cap = cv2.VideoCapture('rtsp://192.168.50.182/av0_0')
  9865. # cap = cv2.VideoCapture(0)
  9866. # cap = cv2.VideoCapture(camara)
  9867. ret, frame = cap.read()
  9868. while ret:
  9869. # compress frame
  9870. frame = cv2.resize(frame, (550, 400), interpolation=cv2.INTER_AREA)
  9871. retval, buffer = cv2.imencode(".jpg", frame)
  9872. if retval:
  9873. # convert to byte array
  9874. buffer = buffer.tobytes()
  9875. # get size of the frame
  9876. buffer_size = len(buffer)
  9877. num_of_packs = 1
  9878. if buffer_size > max_length:
  9879. num_of_packs = math.ceil(buffer_size / max_length)
  9880. frame_info = {"packs": num_of_packs}
  9881. # send the number of packs to be expected
  9882. # print("Number of packs:", num_of_packs)
  9883. c_sock.sendto(pickle.dumps(frame_info), (host, port))
  9884. left = 0
  9885. right = max_length
  9886. for i in range(num_of_packs):
  9887. # print("left:", left)
  9888. # print("right:", right)
  9889. # truncate data to send
  9890. data = buffer[left:right]
  9891. left = right
  9892. right += max_length
  9893. # send the frames accordingly
  9894. c_sock.sendto(data, (host, port))
  9895. ret, frame = cap.read()
  9896. print("done")
  9897. return "done"
  9898. else:
  9899. c_sock.shutdown(2)
  9900. c_sock.close()
  9901. c_sock = 0
  9902. print("c_sock is closing")
  9903. # 影像串流的路徑
  9904. @main.route("/video_feed", methods=['POST', 'GET'])
  9905. def video_feed_views():
  9906. print("test2")
  9907. global s_sock
  9908. if request.method == 'GET':
  9909. # 於10分鐘之後,自動關閉socket server
  9910. # if s_sock == 0:
  9911. # def socket_server_views():
  9912. # global s_sock
  9913. # print("test")
  9914. # print(s_sock)
  9915. # sl(600)
  9916. # if s_sock != 0:
  9917. # s_sock.close()
  9918. # s_sock = 0
  9919. # print('s_sock is closed')
  9920. #
  9921. # pool.submit(socket_server_views)
  9922. host = "192.168.50.65"
  9923. port = 8000
  9924. max_length = 65540
  9925. # max_length = 95540
  9926. s_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  9927. s_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  9928. s_sock.bind((host, port))
  9929. frame_info = None
  9930. buffer = None
  9931. frame = None
  9932. encodedImage = None
  9933. print("-> waiting for connection")
  9934. # 影像生成器函數,將影像以jpg格式傳給前端
  9935. def generate():
  9936. while True:
  9937. with lock:
  9938. global s_sock, frame_info, buffer, frame, encodedImage
  9939. if s_sock == 0:
  9940. break
  9941. data, address = s_sock.recvfrom(max_length)
  9942. if len(data) < 100:
  9943. frame_info = pickle.loads(data)
  9944. if frame_info:
  9945. nums_of_packs = frame_info["packs"]
  9946. for i in range(nums_of_packs):
  9947. if s_sock == 0:
  9948. break
  9949. data, address = s_sock.recvfrom(max_length)
  9950. if i == 0:
  9951. buffer = data
  9952. else:
  9953. buffer += data
  9954. frame = np.frombuffer(buffer, dtype=np.uint8)
  9955. frame = frame.reshape(frame.shape[0], 1)
  9956. frame = cv2.imdecode(frame, cv2.IMREAD_UNCHANGED)
  9957. # print(frame)
  9958. # 如果frame為None就跳過
  9959. if frame is None:
  9960. continue
  9961. frame = cv2.resize(
  9962. frame, (640, 360), interpolation=cv2.INTER_AREA)
  9963. # encode the frame in JPEG format
  9964. (flag, encodedImage) = cv2.imencode(".jpg", frame)
  9965. # ensure the frame was successfully encoded
  9966. if not flag:
  9967. continue
  9968. # yield the output frame in the byte format
  9969. yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' +
  9970. bytearray(encodedImage) + b'\r\n')
  9971. # return the response generated along with the specific media
  9972. # type (mime type)
  9973. return Response(generate(), mimetype="multipart/x-mixed-replace; boundary=frame")
  9974. else:
  9975. if s_sock != 0:
  9976. s_sock.close()
  9977. s_sock = 0
  9978. print('s_sock is closed')
  9979. return "s_sock is closed"
  9980. print("test")
  9981. return "s_sock is closed"
  9982. D = {"input_vacuum_status": "0",
  9983. "tank_vacuum_status": "0",
  9984. "tank_threewayvalve_input_status": "0",
  9985. "tank_threewayvalve_bean_status": "0",
  9986. "tank_solenoid_disinfect_status": "0",
  9987. "tank_pump_disinfect_status": "0",
  9988. "outer_threewayvalve_float_status": "0",
  9989. "tank_motor_status": 'none',
  9990. "tank_pump_water_in_status": "0",
  9991. "tank_pump_cleanwater_in_status": "0",
  9992. "outer_solenoid_water_status": "0",
  9993. "tank_solenoid_reclaimed_in_status": "0",
  9994. "tank_solenoid_water_in_status": "0",
  9995. "tank_solenoid_water_out_status": "0",
  9996. "tank_solenoid_reclaimed_out_status": "0",
  9997. "tank_pump_sensor_status": "0",
  9998. "solenoid_tank_pump_status": "0",
  9999. "tank_nozzle_status": "0",
  10000. "tank_blower_status": "0",
  10001. "tank_heater1_status": "0",
  10002. "tank_heater2_status": "0",
  10003. "temp1_enable": "0",
  10004. "temp1": "0",
  10005. "tank_diskvalve_status": "0",
  10006. "output_vacuum_status": "0",
  10007. "tank_temp_enable_status": "0",
  10008. "tank_temp_status": "0",
  10009. # "tank_pump_waterFloat_status": "0",
  10010. # "tank_pump_waterL2_status": "0",
  10011. # "tank_pump_waterL4_status": "0",
  10012. # "tank_solenoid_waterL3_status": "0",
  10013. # "tank_solenoid_waterL5_status": "0",
  10014. # "tank_stepping_motor_status": 'none',
  10015. }
  10016. # pub_topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
  10017. # sub_topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78/Log'
  10018. # mqttObj = MQTT('aisky-client', 'aiskyc', '60.250.156.234', 1883, 60, sub_topic)
  10019. mqttObj = MQTT()
  10020. @main.route('/mqtt_block', methods=['POST'])
  10021. def mqtt_block():
  10022. import json
  10023. dict = request.form.to_dict() # 將表單轉換成字典
  10024. print('dict:', dict)
  10025. # print('dict.keys():', dict.keys())
  10026. # dict = {
  10027. # "command":"Dry_OTA",
  10028. # "cond": [
  10029. # {
  10030. # "cond_main": "if D1 tank_SHT11_Temp == 30",
  10031. # "cond_add": ["and tank_soil_Humidity == 25","and tank_soil_Humidity == 25",],
  10032. # "cond_com": ["tank_motor_status 10", "tank_motor_status 10"]
  10033. # },
  10034. # {
  10035. # "cond_main": "if D1 tank_SHT11_Temp == 30",
  10036. # "cond_add": ["and tank_soil_Humidity == 25","and tank_soil_Humidity == 25",],
  10037. # "cond_com": ["tank_motor_status 10", "tank_motor_status 10"]
  10038. # }
  10039. # ]
  10040. # }
  10041. # dict = {"command": "Dry_OTA", "cond": "'cond_main':'if D1 tank_soil_Temp == 11', 'cond_add':['and tank_soil_Humidity == 12', 'and tank_soil_EC == 13'], 'cond_com':['tank_heater1_status on', 'tank_heater2_status on']], ['cond_main':'if D2 tank_solenoid_disinfect_status == 21', 'cond_add':['and tank_solenoid_water_out_status == 22', 'and outer_solenoid_water_status == 23'], 'cond_com':['tank_heater1_status on', 'tank_heater2_status on']"}
  10042. json = json.dumps(dict)
  10043. # json: {"command": "Dry_OTA", "cond": [{"cond_main": "if D1 tank_SHT11_Temp == 30", "cond_add": ["and tank_soil_Humidity == 25", "and tank_soil_Humidity == 25"], "cond_com": ["tank_motor_status 10", "tank_motor_status 10"]}, {"cond_main": "if D1 tank_SHT11_Temp == 30", "cond_add": ["and tank_soil_Humidity == 25", "and tank_soil_Humidity == 25"], "cond_com": ["tank_motor_status 10", "tank_motor_status 10"]}]}
  10044. print('json:', json)
  10045. # dict: {'command': 'Dry_OTA', 'cond': [{'cond_main': 'if D1 tank_SHT11_Temp == 30', 'cond_add': ['and tank_soil_Humidity == 25', 'and tank_soil_Humidity == 25'], 'cond_com': ['tank_motor_status 10', 'tank_motor_status 10']}, {'cond_main': 'if D1 tank_SHT11_Temp == 30', 'cond_add': ['and tank_soil_Humidity == 25', 'and tank_soil_Humidity == 25'], 'cond_com': ['tank_motor_status 10', 'tank_motor_status 10']}]}
  10046. topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
  10047. mqtt.publish(topic, json)
  10048. return 'OK'
  10049. # mqtt發布
  10050. # @main.route('/mqtt/<tid>', methods=['POST'])
  10051. @main.route('/mqtt/<tid>', methods=['POST'])
  10052. def mqtt_views(tid):
  10053. import json
  10054. dict = request.form.to_dict() # 將表單轉換成字典
  10055. json = json.dumps(dict)
  10056. # print('dict:', dict) # dict: {'tank-number': '1', 'command': 'tank_vacuum_status', 'value': 'on'}
  10057. # print('json:', json) # json: {"tank-number": "1", "command": "tank_vacuum_status", "value": "on"}
  10058. topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
  10059. # res = mqttObj.mqttPublish(pub_topic, json)
  10060. # print(res)
  10061. # sl(2)
  10062. # print(mqttObj.res)
  10063. #
  10064. # print('test')
  10065. mqtt.publish(topic, json)
  10066. # 入料儲豆槽真空吸料機(ON吸料/OFF排氣)
  10067. if dict['command'] == 'input_vacuum_status':
  10068. time.sleep(1)
  10069. # D[input_vacuum_status]: "0"
  10070. print('D[input_vacuum_status]:', D['input_vacuum_status'])
  10071. if D['input_vacuum_status'] == 'on':
  10072. return 'on'
  10073. elif D['input_vacuum_status'] == 'off':
  10074. return 'off'
  10075. else:
  10076. return "input_vacuum_status signal was not received"
  10077. # 真空吸料機
  10078. elif dict['command'] == 'tank_vacuum_status':
  10079. time.sleep(1)
  10080. if D['tank_vacuum_status'] == 'on':
  10081. return 'on'
  10082. elif D['tank_vacuum_status'] == 'off':
  10083. return 'off'
  10084. else:
  10085. return "tank_vacuum_status signal was not received"
  10086. # 入料三通閥(ON吸料/OFF排氣)
  10087. elif dict['command'] == 'tank_threewayvalve_input_status':
  10088. time.sleep(1)
  10089. if D['tank_threewayvalve_input_status'] == 'on':
  10090. return 'on'
  10091. elif D['tank_threewayvalve_input_status'] == 'off':
  10092. return 'off'
  10093. else:
  10094. return "tank_threewayvalve_input_status signal was not received"
  10095. # 測豆三通閥(ON吸料/OFF排氣)
  10096. elif dict['command'] == 'tank_threewayvalve_bean_status':
  10097. time.sleep(1)
  10098. if D['tank_threewayvalve_bean_status'] == 'on':
  10099. return 'on'
  10100. elif D['tank_threewayvalve_bean_status'] == 'off':
  10101. return 'off'
  10102. else:
  10103. return "tank_threewayvalve_bean_status signal was not received"
  10104. # 消毒電磁閥(ON噴灑消毒/OFF關)
  10105. elif dict['command'] == 'tank_solenoid_disinfect_status':
  10106. time.sleep(1)
  10107. if D['tank_solenoid_disinfect_status'] == 'on':
  10108. return 'on'
  10109. elif D['tank_solenoid_disinfect_status'] == 'off':
  10110. return 'off'
  10111. else:
  10112. return "tank_solenoid_disinfect_status signal was not received"
  10113. # 混合槽幫浦(ON抽水消毒/OFF關)
  10114. elif dict['command'] == 'tank_pump_disinfect_status':
  10115. time.sleep(1)
  10116. if D['tank_pump_disinfect_status'] == 'on':
  10117. return 'on'
  10118. elif D['tank_pump_disinfect_status'] == 'off':
  10119. return 'off'
  10120. else:
  10121. return "tank_pump_disinfect_status signal was not received"
  10122. # 外桶浮選三通閥(ON開浮選出口/OFF關)
  10123. elif dict['command'] == 'outer_threewayvalve_float_status':
  10124. time.sleep(1)
  10125. if D['outer_threewayvalve_float_status'] == 'on':
  10126. return 'on'
  10127. elif D['outer_threewayvalve_float_status'] == 'off':
  10128. return 'off'
  10129. else:
  10130. return "outer_threewayvalve_float_status signal was not received"
  10131. # 馬達(單位RPM)
  10132. elif dict['command'] == 'tank_motor_status':
  10133. print("D['tank_motor_status']", D['tank_motor_status'])
  10134. time.sleep(1)
  10135. if D['tank_motor_status'] == '0':
  10136. return 'off'
  10137. elif type(D['tank_motor_status']) == int:
  10138. return 'on'
  10139. else:
  10140. return "tank_motor_status signal was not received"
  10141. # 幫浦(清水入水)(ON開/OFF關)
  10142. elif dict['command'] == 'tank_pump_water_in_status':
  10143. time.sleep(1)
  10144. if D['tank_pump_water_in_status'] == 'on':
  10145. return 'on'
  10146. elif D['tank_pump_water_in_status'] == 'off':
  10147. return 'off'
  10148. else:
  10149. return "tank_pump_water_in_status signal was not received"
  10150. # 幫浦(清洗槽入水)(ON開/OFF關)
  10151. elif dict['command'] == 'tank_pump_cleanwater_in_status':
  10152. time.sleep(1)
  10153. if D['tank_pump_cleanwater_in_status'] == 'on':
  10154. return 'on'
  10155. elif D['tank_pump_cleanwater_in_status'] == 'off':
  10156. return 'off'
  10157. else:
  10158. return "tank_pump_cleanwater_in_status signal was not received"
  10159. # 桶外進水電磁閥(ON開/OFF關)
  10160. elif dict['command'] == 'outer_solenoid_water_status':
  10161. time.sleep(1)
  10162. if D['outer_solenoid_water_status'] == 'on':
  10163. return 'on'
  10164. elif D['outer_solenoid_water_status'] == 'off':
  10165. return 'off'
  10166. else:
  10167. return "outer_solenoid_water_status signal was not received"
  10168. # 中水入水電磁閥(ON開/OFF關)
  10169. elif dict['command'] == 'tank_solenoid_reclaimed_in_status':
  10170. time.sleep(1)
  10171. if D['tank_solenoid_reclaimed_in_status'] == 'on':
  10172. return 'on'
  10173. elif D['tank_solenoid_reclaimed_in_status'] == 'off':
  10174. return 'off'
  10175. else:
  10176. return "tank_solenoid_reclaimed_in_status signal was not received"
  10177. # 清水入水電磁閥(ON開/OFF關)
  10178. elif dict['command'] == 'tank_solenoid_water_in_status':
  10179. time.sleep(1)
  10180. if D['tank_solenoid_water_in_status'] == 'on':
  10181. return 'on'
  10182. elif D['tank_solenoid_water_in_status'] == 'off':
  10183. return 'off'
  10184. else:
  10185. return "tank_solenoid_water_in_status signal was not received"
  10186. # 排水廢水電磁閥(ON開/OFF關)
  10187. elif dict['command'] == 'tank_solenoid_water_out_status':
  10188. time.sleep(1)
  10189. if D['tank_solenoid_water_out_status'] == 'on':
  10190. return 'on'
  10191. elif D['tank_solenoid_water_out_status'] == 'off':
  10192. return 'off'
  10193. else:
  10194. return "tank_solenoid_water_out_status signal was not received"
  10195. # 排水中水電磁閥(ON開/OFF關)
  10196. elif dict['command'] == 'tank_solenoid_reclaimed_out_status':
  10197. time.sleep(1)
  10198. if D['tank_solenoid_reclaimed_out_status'] == 'on':
  10199. return 'on'
  10200. elif D['tank_solenoid_reclaimed_out_status'] == 'off':
  10201. return 'off'
  10202. else:
  10203. return "tank_solenoid_reclaimed_out_status signal was not received"
  10204. # 雙核隔膜泵(ON開/OFF關)
  10205. elif dict['command'] == 'tank_pump_sensor_status':
  10206. time.sleep(1)
  10207. if D['tank_pump_sensor_status'] == 'on':
  10208. return 'on'
  10209. elif D['tank_pump_sensor_status'] == 'off':
  10210. return 'off'
  10211. else:
  10212. return "tank_pump_sensor_status signal was not received"
  10213. # 逆洗 pump 電磁閥(ON開/OFF關)
  10214. elif dict['command'] == 'solenoid_tank_pump_status':
  10215. time.sleep(1)
  10216. if D['solenoid_tank_pump_status'] == 'on':
  10217. return 'on'
  10218. elif D['solenoid_tank_pump_status'] == 'off':
  10219. return 'off'
  10220. else:
  10221. return "solenoid_tank_pump_status signal was not received"
  10222. # 噴嘴(ON開/OFF關)
  10223. elif dict['command'] == 'tank_nozzle_status':
  10224. time.sleep(1)
  10225. if D['tank_nozzle_status'] == 'on':
  10226. return 'on'
  10227. elif D['tank_nozzle_status'] == 'off':
  10228. return 'off'
  10229. else:
  10230. return "tank_nozzle_status signal was not received"
  10231. # 鼓風機(ON開/OFF關)
  10232. elif dict['command'] == 'tank_blower_status':
  10233. time.sleep(1)
  10234. if D['tank_blower_status'] == 'on':
  10235. return 'on'
  10236. elif D['tank_blower_status'] == 'off':
  10237. return 'off'
  10238. else:
  10239. return "tank_blower_status signal was not received"
  10240. # 加熱棒 1(ON開/OFF關)
  10241. elif dict['command'] == 'tank_heater1_status':
  10242. time.sleep(1)
  10243. if D['tank_heater1_status'] == 'on':
  10244. return 'on'
  10245. elif D['tank_heater1_status'] == 'off':
  10246. return 'off'
  10247. else:
  10248. return "tank_heater1_status signal was not received"
  10249. # 加熱棒 2(ON開/OFF關)
  10250. elif dict['command'] == 'tank_heater2_status':
  10251. time.sleep(1)
  10252. if D['tank_heater2_status'] == 'on':
  10253. return 'on'
  10254. elif D['tank_heater2_status'] == 'off':
  10255. return 'off'
  10256. else:
  10257. return "tank_heater2_status signal was not received"
  10258. # 溫度控制(ON開/OFF關)
  10259. elif dict['command'] == 'temp1_enable':
  10260. time.sleep(1)
  10261. if D['temp1_enable'] == 'on':
  10262. return 'on'
  10263. elif D['temp1_enable'] == 'off':
  10264. return 'off'
  10265. else:
  10266. return "temp1_enable_status signal was not received"
  10267. # 設定溫度
  10268. elif dict['command'] == 'temp1':
  10269. time.sleep(1)
  10270. if D['temp1'] == '0':
  10271. return 'off'
  10272. elif type(D['temp1']) == float:
  10273. return 'on'
  10274. else:
  10275. return "temp1 signal was not received"
  10276. # 發酵槽 溫控開關
  10277. elif dict['command'] == 'tank_temp_enable':
  10278. time.sleep(1)
  10279. if D['tank_temp_enable'] == 'on':
  10280. return 'on'
  10281. elif D['tank_temp_enable'] == 'off':
  10282. return 'off'
  10283. else:
  10284. return "tank_temp_enable signal was not received"
  10285. # 發酵槽 設定溫度
  10286. elif dict['command'] == 'tank_temp':
  10287. time.sleep(1)
  10288. if D['tank_temp'] == '0':
  10289. return 'off'
  10290. elif type(D['tank_temp']) == float:
  10291. return 'on'
  10292. else:
  10293. return "tank_temp signal was not received"
  10294. # 蝴蝶閥(ON開/OFF關)
  10295. elif dict['command'] == 'tank_diskvalve_status':
  10296. time.sleep(1)
  10297. if D['tank_diskvalve_status'] == 'on':
  10298. return 'on'
  10299. elif D['tank_diskvalve_status'] == 'off':
  10300. return 'off'
  10301. else:
  10302. return "tank_diskvalve_status signal was not received"
  10303. # 出料儲豆槽真空吸料機(ON吸料/OFF排氣)
  10304. elif dict['command'] == 'output_vacuum_status':
  10305. time.sleep(1)
  10306. if D['output_vacuum_status'] == 'on':
  10307. return 'on'
  10308. elif D['output_vacuum_status'] == 'off':
  10309. return 'off'
  10310. else:
  10311. return "output_vacuum_status signal was not received"
  10312. else:
  10313. return "MQTT command NOT FOUND"
  10314. # return "publish done" # 1201 test
  10315. # --- 12/10 ------------------------------------------ start
  10316. @main.route('/mqtt_data/<tid>_<command>_<value>', methods=['POST'])
  10317. def mqtt_data(tank_num, command, value):
  10318. import json
  10319. data = { "tank_num": str(tank_num), "command": str(command), "value": str(value) }
  10320. json = json.dumps(data)
  10321. # print('json:', json) # json: {"tank-number": "1", tank_vacuum_status", "value": "on"}
  10322. print('json:', json)
  10323. topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
  10324. mqtt.publish(topic, json)
  10325. # --- 12/10 ------------------------------------------ finish
  10326. # --- 10/19 ------------------------------------------ start
  10327. # mqtt發布
  10328. # @main.route('/mqtt/<tid>', methods=['POST'])
  10329. @main.route('/mqtt_f/<tid>', methods=['POST'])
  10330. def mqtt_f(data):
  10331. import json
  10332. dict = request.form.to_dict()
  10333. json = json.dumps(data)
  10334. # print('dict:', dict) # dict: {'tank-number': '1', 'command': 'tank_vacuum_status', 'value': 'on'}
  10335. # print('json:', json) # json: {"tank-number": "1", tank_vacuum_status", "value": "on"}
  10336. print('json:', json)
  10337. topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
  10338. # res = mqttObj.mqttPublish(pub_topic, json)
  10339. # print(res)
  10340. # sl(2)
  10341. # print(mqttObj.res)
  10342. #
  10343. # print('test')
  10344. mqtt.publish(topic, json)
  10345. # 入料儲豆槽真空吸料機(ON吸料/OFF排氣)
  10346. if dict['command'] == 'input_vacuum_status':
  10347. time.sleep(1)
  10348. # D[input_vacuum_status]: "0"
  10349. print('D[input_vacuum_status]:', D['input_vacuum_status'])
  10350. if D['input_vacuum_status'] == 'on':
  10351. return 'on'
  10352. elif D['input_vacuum_status'] == 'off':
  10353. return 'off'
  10354. else:
  10355. return "input_vacuum_status signal was not received"
  10356. # 真空吸料機
  10357. elif dict['command'] == 'tank_vacuum_status':
  10358. time.sleep(1)
  10359. if D['tank_vacuum_status'] == 'on':
  10360. return 'on'
  10361. elif D['tank_vacuum_status'] == 'off':
  10362. return 'off'
  10363. else:
  10364. return "tank_vacuum_status signal was not received"
  10365. # 入料三通閥(ON吸料/OFF排氣)
  10366. elif dict['command'] == 'tank_threewayvalve_input_status':
  10367. time.sleep(1)
  10368. if D['tank_threewayvalve_input_status'] == 'on':
  10369. return 'on'
  10370. elif D['tank_threewayvalve_input_status'] == 'off':
  10371. return 'off'
  10372. else:
  10373. return "tank_threewayvalve_input_status signal was not received"
  10374. # 測豆三通閥(ON吸料/OFF排氣)
  10375. elif dict['command'] == 'tank_threewayvalve_bean_status':
  10376. time.sleep(1)
  10377. if D['tank_threewayvalve_bean_status'] == 'on':
  10378. return 'on'
  10379. elif D['tank_threewayvalve_bean_status'] == 'off':
  10380. return 'off'
  10381. else:
  10382. return "tank_threewayvalve_bean_status signal was not received"
  10383. # 消毒電磁閥(ON噴灑消毒/OFF關)
  10384. elif dict['command'] == 'tank_solenoid_disinfect_status':
  10385. time.sleep(1)
  10386. if D['tank_solenoid_disinfect_status'] == 'on':
  10387. return 'on'
  10388. elif D['tank_solenoid_disinfect_status'] == 'off':
  10389. return 'off'
  10390. else:
  10391. return "tank_solenoid_disinfect_status signal was not received"
  10392. # 混合槽幫浦(ON抽水消毒/OFF關)
  10393. elif dict['command'] == 'tank_pump_disinfect_status':
  10394. time.sleep(1)
  10395. if D['tank_pump_disinfect_status'] == 'on':
  10396. return 'on'
  10397. elif D['tank_pump_disinfect_status'] == 'off':
  10398. return 'off'
  10399. else:
  10400. return "tank_pump_disinfect_status signal was not received"
  10401. # 外桶浮選三通閥(ON開浮選出口/OFF關)
  10402. elif dict['command'] == 'outer_threewayvalve_float_status':
  10403. time.sleep(1)
  10404. if D['outer_threewayvalve_float_status'] == 'on':
  10405. return 'on'
  10406. elif D['outer_threewayvalve_float_status'] == 'off':
  10407. return 'off'
  10408. else:
  10409. return "outer_threewayvalve_float_status signal was not received"
  10410. # 馬達(單位RPM)
  10411. elif dict['command'] == 'tank_motor_status':
  10412. print("D['tank_motor_status']", D['tank_motor_status'])
  10413. time.sleep(1)
  10414. if D['tank_motor_status'] == '0':
  10415. return 'off'
  10416. elif type(D['tank_motor_status']) == int:
  10417. return 'on'
  10418. else:
  10419. return "tank_motor_status signal was not received"
  10420. # 幫浦(清水入水)(ON開/OFF關)
  10421. elif dict['command'] == 'tank_pump_water_in_status':
  10422. time.sleep(1)
  10423. if D['tank_pump_water_in_status'] == 'on':
  10424. return 'on'
  10425. elif D['tank_pump_water_in_status'] == 'off':
  10426. return 'off'
  10427. else:
  10428. return "tank_pump_water_in_status signal was not received"
  10429. # 幫浦(清洗槽入水)(ON開/OFF關)
  10430. elif dict['command'] == 'tank_pump_cleanwater_in_status':
  10431. time.sleep(1)
  10432. if D['tank_pump_cleanwater_in_status'] == 'on':
  10433. return 'on'
  10434. elif D['tank_pump_cleanwater_in_status'] == 'off':
  10435. return 'off'
  10436. else:
  10437. return "tank_pump_cleanwater_in_status signal was not received"
  10438. # 桶外進水電磁閥(ON開/OFF關)
  10439. elif dict['command'] == 'outer_solenoid_water_status':
  10440. time.sleep(1)
  10441. if D['outer_solenoid_water_status'] == 'on':
  10442. return 'on'
  10443. elif D['outer_solenoid_water_status'] == 'off':
  10444. return 'off'
  10445. else:
  10446. return "outer_solenoid_water_status signal was not received"
  10447. # 中水入水電磁閥(ON開/OFF關)
  10448. elif dict['command'] == 'tank_solenoid_reclaimed_in_status':
  10449. time.sleep(1)
  10450. if D['tank_solenoid_reclaimed_in_status'] == 'on':
  10451. return 'on'
  10452. elif D['tank_solenoid_reclaimed_in_status'] == 'off':
  10453. return 'off'
  10454. else:
  10455. return "tank_solenoid_reclaimed_in_status signal was not received"
  10456. # 清水入水電磁閥(ON開/OFF關)
  10457. elif dict['command'] == 'tank_solenoid_water_in_status':
  10458. time.sleep(1)
  10459. if D['tank_solenoid_water_in_status'] == 'on':
  10460. return 'on'
  10461. elif D['tank_solenoid_water_in_status'] == 'off':
  10462. return 'off'
  10463. else:
  10464. return "tank_solenoid_water_in_status signal was not received"
  10465. # 排水廢水電磁閥(ON開/OFF關)
  10466. elif dict['command'] == 'tank_solenoid_water_out_status':
  10467. time.sleep(1)
  10468. if D['tank_solenoid_water_out_status'] == 'on':
  10469. return 'on'
  10470. elif D['tank_solenoid_water_out_status'] == 'off':
  10471. return 'off'
  10472. else:
  10473. return "tank_solenoid_water_out_status signal was not received"
  10474. # 排水中水電磁閥(ON開/OFF關)
  10475. elif dict['command'] == 'tank_solenoid_reclaimed_out_status':
  10476. time.sleep(1)
  10477. if D['tank_solenoid_reclaimed_out_status'] == 'on':
  10478. return 'on'
  10479. elif D['tank_solenoid_reclaimed_out_status'] == 'off':
  10480. return 'off'
  10481. else:
  10482. return "tank_solenoid_reclaimed_out_status signal was not received"
  10483. # 雙核隔膜泵(ON開/OFF關)
  10484. elif dict['command'] == 'tank_pump_sensor_status':
  10485. time.sleep(1)
  10486. if D['tank_pump_sensor_status'] == 'on':
  10487. return 'on'
  10488. elif D['tank_pump_sensor_status'] == 'off':
  10489. return 'off'
  10490. else:
  10491. return "tank_pump_sensor_status signal was not received"
  10492. # 逆洗 pump 電磁閥(ON開/OFF關)
  10493. elif dict['command'] == 'solenoid_tank_pump_status':
  10494. time.sleep(1)
  10495. if D['solenoid_tank_pump_status'] == 'on':
  10496. return 'on'
  10497. elif D['solenoid_tank_pump_status'] == 'off':
  10498. return 'off'
  10499. else:
  10500. return "solenoid_tank_pump_status signal was not received"
  10501. # 噴嘴(ON開/OFF關)
  10502. elif dict['command'] == 'tank_nozzle_status':
  10503. time.sleep(1)
  10504. if D['tank_nozzle_status'] == 'on':
  10505. return 'on'
  10506. elif D['tank_nozzle_status'] == 'off':
  10507. return 'off'
  10508. else:
  10509. return "tank_nozzle_status signal was not received"
  10510. # 鼓風機(ON開/OFF關)
  10511. elif dict['command'] == 'tank_blower_status':
  10512. time.sleep(1)
  10513. if D['tank_blower_status'] == 'on':
  10514. return 'on'
  10515. elif D['tank_blower_status'] == 'off':
  10516. return 'off'
  10517. else:
  10518. return "tank_blower_status signal was not received"
  10519. # 加熱棒 1(ON開/OFF關)
  10520. elif dict['command'] == 'tank_heater1_status':
  10521. time.sleep(1)
  10522. if D['tank_heater1_status'] == 'on':
  10523. return 'on'
  10524. elif D['tank_heater1_status'] == 'off':
  10525. return 'off'
  10526. else:
  10527. return "tank_heater1_status signal was not received"
  10528. # 加熱棒 2(ON開/OFF關)
  10529. elif dict['command'] == 'tank_heater2_status':
  10530. time.sleep(1)
  10531. if D['tank_heater2_status'] == 'on':
  10532. return 'on'
  10533. elif D['tank_heater2_status'] == 'off':
  10534. return 'off'
  10535. else:
  10536. return "tank_heater2_status signal was not received"
  10537. # 溫度控制(ON開/OFF關)
  10538. elif dict['command'] == 'temp1_enable':
  10539. time.sleep(1)
  10540. if D['temp1_enable'] == 'on':
  10541. return 'on'
  10542. elif D['temp1_enable'] == 'off':
  10543. return 'off'
  10544. else:
  10545. return "temp1_enable_status signal was not received"
  10546. # 設定溫度
  10547. elif dict['command'] == 'temp1':
  10548. time.sleep(1)
  10549. if D['temp1'] == '0':
  10550. return 'off'
  10551. elif type(D['temp1']) == float:
  10552. return 'on'
  10553. else:
  10554. return "temp1 signal was not received"
  10555. # 發酵槽 溫控開關
  10556. elif dict['command'] == 'tank_temp_enable':
  10557. time.sleep(1)
  10558. if D['tank_temp_enable'] == 'on':
  10559. return 'on'
  10560. elif D['tank_temp_enable'] == 'off':
  10561. return 'off'
  10562. else:
  10563. return "tank_temp_enable signal was not received"
  10564. # 發酵槽 設定溫度
  10565. elif dict['command'] == 'tank_temp':
  10566. time.sleep(1)
  10567. if D['tank_temp'] == '0':
  10568. return 'off'
  10569. elif type(D['tank_temp']) == float:
  10570. return 'on'
  10571. else:
  10572. return "tank_temp signal was not received"
  10573. # 蝴蝶閥(ON開/OFF關)
  10574. elif dict['command'] == 'tank_diskvalve_status':
  10575. time.sleep(1)
  10576. if D['tank_diskvalve_status'] == 'on':
  10577. return 'on'
  10578. elif D['tank_diskvalve_status'] == 'off':
  10579. return 'off'
  10580. else:
  10581. return "tank_diskvalve_status signal was not received"
  10582. # 出料儲豆槽真空吸料機(ON吸料/OFF排氣)
  10583. elif dict['command'] == 'output_vacuum_status':
  10584. time.sleep(1)
  10585. if D['output_vacuum_status'] == 'on':
  10586. return 'on'
  10587. elif D['output_vacuum_status'] == 'off':
  10588. return 'off'
  10589. else:
  10590. return "output_vacuum_status signal was not received"
  10591. else:
  10592. return "MQTT command NOT FOUND"
  10593. # ---10/19 ------------------------------------------- end
  10594. board_prog = {
  10595. "D1": "0",
  10596. "D2": "0",
  10597. "D3": "0",
  10598. "D4": "0",
  10599. "D5": "0",
  10600. "D6": "0",
  10601. "D7": "0",
  10602. "D8": "0",
  10603. "D9": "0",
  10604. "D10": "0",
  10605. "D11": "0",
  10606. "D12": "0",
  10607. }
  10608. # 處理mqtt訂閱的信息
  10609. # 收到訊息後我們可以用 on_message(),來讀取收到的內容:
  10610. @mqtt.on_message()
  10611. def handle_mqtt_message(client, userdata, message):
  10612. # topic = message.topic # 收到的主題 Rita 原本就沒有此行, 增加說明用
  10613. payload = message.payload.decode() # 收到的內容
  10614. payload = json.loads(payload)
  10615. # print("-------msg-------")
  10616. # print('name :', p['name'])
  10617. # print('email :', p['email'])
  10618. print('payload:', payload)
  10619. # success / upload error / no reply
  10620. # {'command': 'Code_upload', 'device_id': 'b8:27:eb:7e:24:78', 'localtime': '2022-06-13 11:59:07', 'response': 'no reply', 'tank_n 'response': 'no reply', 'tank_number': 'D1'}
  10621. if payload['command'] == 'Code_upload':
  10622. board_prog[payload['tank_number']] = payload['response']
  10623. # res = "on_message" + payload['response']
  10624. # return res
  10625. # 入料儲豆槽真空吸料機(ON吸料/OFF排氣)
  10626. if payload['command'] == 'input_vacuum_status':
  10627. if payload['response'] == 'on':
  10628. D['input_vacuum_status'] = 'on'
  10629. else:
  10630. D['input_vacuum_status'] = 'off'
  10631. # 真空吸料機(ON吸料/OFF排氣)
  10632. elif payload['command'] == 'tank_vacuum_status':
  10633. if payload['response'] == 'on':
  10634. D['tank_vacuum_status'] = 'on'
  10635. else:
  10636. D['tank_vacuum_status'] = 'off'
  10637. # 入料三通閥(ON吸料/OFF排氣)
  10638. elif payload['command'] == 'tank_threewayvalve_input_status':
  10639. if payload['response'] == 'on':
  10640. D['tank_threewayvalve_input_status'] = 'on'
  10641. else:
  10642. D['tank_threewayvalve_input_status'] = 'off'
  10643. # 測豆三通閥(ON測豆/OFF排氣)
  10644. elif payload['command'] == 'tank_threewayvalve_bean_status':
  10645. if payload['response'] == 'on':
  10646. D['tank_threewayvalve_bean_status'] = 'on'
  10647. else:
  10648. D['tank_threewayvalve_bean_status'] = 'off'
  10649. # 消毒電磁閥(ON噴灑消毒/OFF關)
  10650. elif payload['command'] == 'tank_solenoid_disinfect_status':
  10651. if payload['response'] == 'on':
  10652. D['tank_solenoid_disinfect_status'] = 'on'
  10653. else:
  10654. D['tank_solenoid_disinfect_status'] = 'off'
  10655. # 混合槽幫浦(ON消毒槽抽水/OFF關)
  10656. elif payload['command'] == 'tank_pump_disinfect_status':
  10657. if payload['response'] == 'on':
  10658. D['tank_pump_disinfect_status'] = 'on'
  10659. else:
  10660. D['tank_pump_disinfect_status'] = 'off'
  10661. # 外桶浮選三通閥(ON浮選落豆/OFF桶內真空)
  10662. elif payload['command'] == 'outer_threewayvalve_float_status':
  10663. if payload['response'] == 'on':
  10664. D['outer_threewayvalve_float_status'] = 'on'
  10665. else:
  10666. D['outer_threewayvalve_float_status'] = 'off'
  10667. # 馬達(單位RPM)
  10668. elif payload['command'] == 'tank_motor_status':
  10669. if payload['response'] == 'off' or payload['response'] == '0':
  10670. D['tank_motor_status'] = '0'
  10671. else:
  10672. D['tank_motor_status'] = payload['response']
  10673. # 幫浦(清水入水)(ON開/OFF關)
  10674. elif payload['command'] == 'tank_pump_water_in_status':
  10675. if payload['response'] == 'on':
  10676. D['tank_pump_water_in_status'] = 'on'
  10677. else:
  10678. D['tank_pump_water_in_status'] = 'off'
  10679. # 幫浦(清洗槽入水)(ON開/OFF關)
  10680. elif payload['command'] == 'tank_pump_cleanwater_in_status':
  10681. if payload['response'] == 'on':
  10682. D['tank_pump_cleanwater_in_status'] = 'on'
  10683. else:
  10684. D['tank_pump_cleanwater_in_status'] = 'off'
  10685. # 桶外進水電磁閥(ON開/OFF關)
  10686. elif payload['command'] == 'outer_solenoid_water_status':
  10687. if payload['response'] == 'on':
  10688. D['outer_solenoid_water_status'] = 'on'
  10689. else:
  10690. D['outer_solenoid_water_status'] = 'off'
  10691. # 中水入水電磁閥(ON開/OFF關)
  10692. elif payload['command'] == 'tank_solenoid_reclaimed_in_status':
  10693. if payload['response'] == 'on':
  10694. D['tank_solenoid_reclaimed_in_status'] = 'on'
  10695. else:
  10696. D['tank_solenoid_reclaimed_in_status'] = 'off'
  10697. # 清水入水電磁閥(ON開/OFF關)
  10698. elif payload['command'] == 'tank_solenoid_water_in_status':
  10699. if payload['response'] == 'on':
  10700. D['tank_solenoid_water_in_status'] = 'on'
  10701. else:
  10702. D['tank_solenoid_water_in_status'] = 'off'
  10703. # 排水廢水電磁閥(ON開/OFF關)
  10704. elif payload['command'] == 'tank_solenoid_water_out_status':
  10705. if payload['response'] == 'on':
  10706. D['tank_solenoid_water_out_status'] = 'on'
  10707. else:
  10708. D['tank_solenoid_water_out_status'] = 'off'
  10709. # 排水中水電磁閥(ON開/OFF關)
  10710. elif payload['command'] == 'tank_solenoid_reclaimed_out_status':
  10711. if payload['response'] == 'on':
  10712. D['tank_solenoid_reclaimed_out_status'] = 'on'
  10713. else:
  10714. D['tank_solenoid_reclaimed_out_status'] = 'off'
  10715. # 雙核隔膜泵(ON開/OFF關)
  10716. elif payload['command'] == 'tank_pump_sensor_status':
  10717. if payload['response'] == 'on':
  10718. D['tank_pump_sensor_status'] = 'on'
  10719. else:
  10720. D['tank_pump_sensor_status'] = 'off'
  10721. # 逆洗 pump 電磁閥(ON開/OFF關)
  10722. elif payload['command'] == 'solenoid_tank_pump_status':
  10723. if payload['response'] == 'on':
  10724. D['solenoid_tank_pump_status'] = 'on'
  10725. else:
  10726. D['solenoid_tank_pump_status'] = 'off'
  10727. # 噴嘴(ON開/OFF關)
  10728. elif payload['command'] == 'tank_nozzle_status':
  10729. if payload['response'] == 'on':
  10730. D['tank_nozzle_status'] = 'on'
  10731. else:
  10732. D['tank_nozzle_status'] = 'off'
  10733. # 鼓風機(ON開/OFF關)
  10734. elif payload['command'] == 'tank_blower_status':
  10735. if payload['response'] == 'on':
  10736. D['tank_blower_status'] = 'on'
  10737. else:
  10738. D['tank_blower_status'] = 'off'
  10739. # 加熱棒 1(ON開/OFF關)
  10740. elif payload['command'] == 'tank_heater1_status':
  10741. if payload['response'] == 'on':
  10742. D['tank_heater1_status'] = 'on'
  10743. else:
  10744. D['tank_heater1_status'] = 'off'
  10745. # 加熱棒 2(ON開/OFF關)
  10746. elif payload['command'] == 'tank_heater2_status':
  10747. if payload['response'] == 'on':
  10748. D['tank_heater2_status'] = 'on'
  10749. else:
  10750. D['tank_heater2_status'] = 'off'
  10751. # 發酵槽 溫控開關
  10752. elif payload['command'] == 'tank_temp_enable':
  10753. if payload['response'] == 'on':
  10754. D['tank_temp_enable'] = 'on'
  10755. else:
  10756. D['tank_temp_enable'] = 'off'
  10757. # 發酵槽 設定溫度
  10758. elif payload['command'] == 'tank_temp':
  10759. if payload['response'] == 'off':
  10760. D['tank_temp'] = '0'
  10761. else:
  10762. D['tank_temp'] = payload['response']
  10763. # 蝴蝶閥(ON開/OFF關)
  10764. elif payload['command'] == 'tank_diskvalve_status':
  10765. if payload['response'] == 'on':
  10766. D['tank_diskvalve_status'] = 'on'
  10767. else:
  10768. D['tank_diskvalve_status'] = 'off'
  10769. # 出料儲豆槽真空吸料機(ON吸料/OFF排氣)
  10770. elif payload['command'] == 'output_vacuum_status':
  10771. if payload['response'] == 'on':
  10772. D['output_vacuum_status'] = 'on'
  10773. else:
  10774. D['output_vacuum_status'] = 'off'
  10775. else:
  10776. return "MQTT command NOT FOUND"