views.py 540 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546
  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_manage20221221 import mqtt
  12. # 導入db,用於操作數據庫
  13. from coffee_manage20221221 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. #
  61. # # Rita 參數 params 是用來取得參數的 locals=() 所有參數
  62. return render_template('index_new.html', title="Smart Coffee", **locals())
  63. else:
  64. return render_template('sign_in.html')
  65. #return render_template("index.html", title='ERP WEB')
  66. # Rita 測試
  67. # sql_get
  68. @main.route('/sql_get', methods=['GET', 'POST'])
  69. def sql_get():
  70. # 取得網頁傳回來的 SQL 指令
  71. # sql = "SELECT * FROM 零件表 WHERE 會計科目 = 04"
  72. info = request.args.to_dict('sql')
  73. datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  74. sql = info['sql'].replace('current_timestamp()', '"' + datetime + '"')
  75. # ip = request.remote_addr
  76. # sql = info['sql'].replace('IPDATA', '"' + ip + '"')
  77. print("[sql_get]sql: ", sql)
  78. # 存入 HOME
  79. mydb = pymysql.connect(host='60.250.156.230', port=3306, user='user', password='Gold@53743001', database='CoffeeManage', charset='utf8')
  80. #mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffee', password='skyeye',database='Coffee', charset='utf8')
  81. mycursor = mydb.cursor()
  82. try:
  83. mycursor.execute(sql)
  84. sql_data = mycursor.fetchall()
  85. except pymysql.err.IntegrityError:
  86. sql_data = "Home Mysql 存值錯誤"
  87. mydb.commit()
  88. mydb.close()
  89. return jsonify({"response":sql_data})
  90. @main.route('/test', methods=['GET', 'POST'])
  91. def test():
  92. info = request.args.to_dict()
  93. print(info)
  94. print("info[command]: ", info['command'])
  95. return json.dumps(info)
  96. @main.route('/save_code')
  97. def save_code():
  98. user = request.args['user']
  99. tank_num = request.args['tank_num']
  100. code = request.args['code']
  101. datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  102. CURRENT_PATH = os.path.dirname(__file__)
  103. fileTitle_c = "["+ user + "] " + tank_num + "_main.c"
  104. f = open(CURRENT_PATH + "//CTO20220623//"+fileTitle_c, mode='w')
  105. f.write(code)
  106. f.close()
  107. try:
  108. con = pymysql.connect(host='60.250.156.230', port=3306, user='user', password='Gold@53743001', database='CoffeeManage', charset='utf8')
  109. insert = con.cursor()
  110. insert_status = "INSERT INTO `code_loader`(`datetime`,`tank_num`,`code`) VALUES ('%s', '%s', '%s')" % (datetime,tank_num, code)
  111. insert.execute(insert_status)
  112. result = {"pass": "pass"}
  113. con.commit()
  114. con.close()
  115. except:
  116. result = {"pass": "error"}
  117. con.commit()
  118. con.close()
  119. return json.dumps(result)
  120. @main.route('/save_xml')
  121. def save_xml():
  122. xml = request.args['xml']
  123. tank_num = request.args['tank_num']
  124. datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  125. #CURRENT_PATH = os.path.dirname(__file__)
  126. #fileTitle_c = "[" + "user" + "] " + "D1" + "_main.xml"
  127. #f = open(CURRENT_PATH + "//CTO20220623//"+fileTitle_c, mode='w')
  128. #f.write(xml)
  129. #f.close()
  130. try:
  131. con = pymysql.connect(host='60.250.156.230', port=3306, user='user', password='Gold@53743001', database='CoffeeManage', charset='utf8')
  132. insert = con.cursor()
  133. insert_status = "INSERT INTO `xml_loader`(`datetime`,`tank_num`,`xml`) VALUES ('%s', '%s', '%s')" % (datetime,tank_num, xml)
  134. insert.execute(insert_status)
  135. result = {"pass": "pass"}
  136. con.commit()
  137. con.close()
  138. except:
  139. result = {"pass": "error"}
  140. con.commit()
  141. con.close()
  142. return json.dumps(result)
  143. @main.route('/load_xml_<tid>')
  144. def load_xml(tid):
  145. if request.method == 'GET':
  146. try:
  147. xml = xml_loader.query.filter_by(tank_num=tid).order_by(text('datetime desc')).first()
  148. db.session.close()
  149. xml = xml.xml
  150. dict = {"xml":xml}
  151. print(dict)
  152. return json.dumps(dict)
  153. except Exception as e:
  154. return json.dumps({"xml":"null"})
  155. else:
  156. pass
  157. # Rita 測試
  158. # 板子燒錄請求
  159. @main.route('/programmer')
  160. def programmer():
  161. prog_data = request.args.to_dict() # {'tank': 'D1'}
  162. CURRENT_PATH = os.path.dirname(__file__) # c:\Users\USER\Rita\Coffee\CoffeeProject\app\main
  163. # # 取得 hex 檔案內容
  164. file = os.path.join(CURRENT_PATH, 'CTO20220622', 'build', 'SDIO.hex') # c:\Users\USER\Rita\Coffee\CoffeeProject\app\main\CTO20220622\SDIO.hex
  165. f = open(file, 'r')
  166. ota_hex = f.read()
  167. import json
  168. # # MQTT 傳送燒錄
  169. MQTT_dict = {
  170. 'command':'Code_upload',
  171. 'tank_num':prog_data['tank'],
  172. 'url':ota_hex
  173. }
  174. json = json.dumps(MQTT_dict)
  175. # print("MQTT_dict: ", MQTT_dict) # MQTT_dict: {'command': 'Code_upload', 'tank_num': 'F1', 'url': ':020000040801F1\n:1000
  176. # print("json: ", json) # json: {"command": "Code_upload", "tank_num": "F1", "url": ":020000040801F1\n:1000
  177. # topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
  178. try:
  179. topic = 'AISKY/Coffee/MK-G/' + prog_data['burner_mac']
  180. mqtt.publish(topic, json)
  181. return 'start burn'
  182. except Exception as e:
  183. return 'error'
  184. @main.route('/result')
  185. def result():
  186. result = request.args['result']
  187. tank_num = request.args['tank_num']
  188. datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  189. try:
  190. con = pymysql.connect(host='60.250.156.230', port=3306, user='user', password='Gold@53743001', database='CoffeeManage', charset='utf8')
  191. insert = con.cursor()
  192. insert_status = "INSERT INTO `code_result`(`datetime`,`tank_num`,`result`) VALUES ('%s', '%s', '%s')" % (datetime,tank_num, result)
  193. insert.execute(insert_status)
  194. result = {"pass": "pass"}
  195. con.commit()
  196. con.close()
  197. except:
  198. result = {"pass": "error"}
  199. con.commit()
  200. con.close()
  201. return json.dumps(result)
  202. @main.route('/pin_history')
  203. def pin_history():
  204. if request.method == 'GET':
  205. tid = request.args['nr']
  206. print(tid)
  207. i=0
  208. result=[0]
  209. try:
  210. con = pymysql.connect(host='60.250.156.230', port=3306, user='user', password='Gold@53743001', database='CoffeeManage', charset='utf8')
  211. insert = con.cursor()
  212. insert_status = "SELECT * FROM `coffee1_0_pin` WHERE tid= '%s'" % (tid)
  213. insert.execute(insert_status)
  214. results = insert.fetchall()
  215. for row in results:
  216. i=i+1
  217. fnam = row[1]
  218. result.append(str(fnam))
  219. con.commit()
  220. con.close()
  221. return jsonify(result)
  222. except Exception as e:
  223. return "error"
  224. else:
  225. pass
  226. @main.route('/pin_set')
  227. def pin_set():
  228. if request.method == 'GET':
  229. tid = request.args['nr']
  230. datetime = request.args['datetime']
  231. try:
  232. con = pymysql.connect(host='60.250.156.230', port=3306, user='user', password='Gold@53743001', database='CoffeeManage', charset='utf8')
  233. insert = con.cursor()
  234. insert_status = "SELECT * FROM `coffee1_0_pin` WHERE tid= '%s' and datetime = '%s'" % (tid,datetime)
  235. insert.execute(insert_status)
  236. results = insert.fetchall()
  237. con.commit()
  238. con.close()
  239. return jsonify(results)
  240. except Exception as e:
  241. return "error"
  242. else:
  243. pass
  244. @main.route('/code_history')
  245. def code_history():
  246. if request.method == 'GET':
  247. tid = request.args['nr']
  248. print(tid)
  249. i=0
  250. result=[0]
  251. try:
  252. con = pymysql.connect(host='60.250.156.230', port=3306, user='user', password='Gold@53743001', database='CoffeeManage', charset='utf8')
  253. insert = con.cursor()
  254. insert_status = "SELECT * FROM `xml_loader` WHERE tank_num= '%s'" % (tid)
  255. insert.execute(insert_status)
  256. results = insert.fetchall()
  257. for row in results:
  258. i=i+1
  259. fnam = row[0]
  260. result.append(str(fnam))
  261. con.commit()
  262. con.close()
  263. return jsonify(result)
  264. except Exception as e:
  265. return "error"
  266. else:
  267. pass
  268. @main.route('/code_set')
  269. def code_set():
  270. if request.method == 'GET':
  271. tid = request.args['nr']
  272. datetime = request.args['datetime']
  273. try:
  274. con = pymysql.connect(host='60.250.156.230', port=3306, user='user', password='Gold@53743001', database='CoffeeManage', charset='utf8')
  275. insert = con.cursor()
  276. insert_status = "SELECT * FROM `xml_loader` WHERE tank_num= '%s' and datetime = '%s'" % (tid,datetime)
  277. insert.execute(insert_status)
  278. results = insert.fetchall()
  279. con.commit()
  280. con.close()
  281. return jsonify(results)
  282. except Exception as e:
  283. return "error"
  284. else:
  285. pass
  286. # Rita 測試
  287. # 板子燒錄請求
  288. @main.route('/board_programmer')
  289. def board_programmer():
  290. prog_data = request.args.to_dict() # {'tank': 'D1'}
  291. CURRENT_PATH = os.path.dirname(__file__) # c:\Users\USER\Rita\Coffee\CoffeeProject\app\main
  292. # # 取得 hex 檔案內容
  293. file = os.path.join(CURRENT_PATH, 'CTO20220622', 'build', 'SDIO.hex') # c:\Users\USER\Rita\Coffee\CoffeeProject\app\main\CTO20220622\SDIO.hex
  294. f = open(file, 'r')
  295. ota_hex = f.read()
  296. # # MQTT 傳送燒錄
  297. MQTT_dict = {
  298. 'command':'Code_upload',
  299. 'tank_num':prog_data['tank'],
  300. 'url':ota_hex
  301. }
  302. import json
  303. json = json.dumps(MQTT_dict)
  304. # print("MQTT_dict: ", MQTT_dict) # MQTT_dict: {'command': 'Code_upload', 'tank_num': 'F1', 'url': ':020000040801F1\n:1000
  305. # print("json: ", json) # json: {"command": "Code_upload", "tank_num": "F1", "url": ":020000040801F1\n:1000
  306. # topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
  307. topic = 'AISKY/Coffee/MK-G/' + str(prog_data['burner_mac'])
  308. mqtt.publish(topic, json)
  309. time.sleep(3)
  310. if board_prog[prog_data['tank']] == 'no reply':
  311. board_prog[prog_data['tank']] = '0'
  312. return 'no reply'
  313. print("===== 下載 Git CoffeeProject_SourceCode ==========================================================")
  314. # # 先下載 Git CoffeeProject_SourceCode
  315. os.system('git clone --single-branch http://60.250.156.230:3000/rita/CoffeeProject_SourceCode.git ' + CURRENT_PATH + '/source_code')
  316. time.sleep(3)
  317. print("===== 將 hex 先複製更名 ==========================================================")
  318. # # 將 hex 先複製更名
  319. copy_old_path = os.path.join(CURRENT_PATH, "CTO20220622", "build", "SDIO.hex")
  320. currentTime = dt.now().strftime("%Y%m%d_%H%M%S")
  321. fileTitle_hex = "[" + currentTime + "_" + prog_data['USERNAME'] + "] " + prog_data['tank'] + "_SDIO.hex"
  322. copy_new_path = os.path.join(CURRENT_PATH, "CTO20220622", "build", fileTitle_hex)
  323. print("copy_new_path: ", copy_new_path)
  324. shutil.copyfile(copy_old_path, copy_new_path)
  325. time.sleep(3)
  326. print("===== 再將 hex 移動到 source_code 資料夾中 ==========================================================")
  327. # # 再將 hex 移動到 source_code 資料夾中
  328. move_new_path = os.path.join(CURRENT_PATH, "source_code", fileTitle_hex)
  329. print("copy_new_path: ", copy_new_path)
  330. print("move_new_path: ", move_new_path)
  331. shutil.move(copy_new_path, move_new_path)
  332. time.sleep(3)
  333. print("===== 將 main.c 先複製更名 ==========================================================")
  334. # # 將 main.c 先複製更名
  335. copy_old_path = os.path.join(CURRENT_PATH, "CTO20220622", "Src", "main.c")
  336. # currentTime = dt.now().strftime("%Y%m%d_%H%M%S") # 同 hex 即可
  337. fileTitle_c = "[" + currentTime + "_" + prog_data['USERNAME'] + "] " + prog_data['tank'] + "_main.c"
  338. copy_new_path = os.path.join(CURRENT_PATH, "CTO20220622", "Src", fileTitle_c)
  339. print("copy_new_path: ", copy_new_path)
  340. shutil.copyfile(copy_old_path, copy_new_path)
  341. time.sleep(3)
  342. print("===== 再將 main.c 移動到 source_code 資料夾中 ==========================================================")
  343. # # 再將 main.c 移動到 source_code 資料夾中
  344. move_new_path = os.path.join(CURRENT_PATH, "source_code", fileTitle_c)
  345. print("copy_new_path: ", copy_new_path)
  346. print("move_new_path: ", move_new_path)
  347. shutil.move(copy_new_path, move_new_path)
  348. time.sleep(3)
  349. print("===== 將 source_code 資料內容 push 到 Git CoffeeProject_SourceCode ==========================================================")
  350. # # 將 source_code 資料內容 push 到 Git CoffeeProject_SourceCode
  351. cwdDATA = os.path.join(CURRENT_PATH, "source_code")
  352. subprocess.call(["git", "add", fileTitle_hex],cwd=cwdDATA)
  353. subprocess.call(["git", "commit","-m", fileTitle_hex],cwd=cwdDATA)
  354. subprocess.call(["git", "add", fileTitle_c],cwd=cwdDATA)
  355. subprocess.call(["git", "commit","-m", fileTitle_c],cwd=cwdDATA)
  356. subprocess.call(["git", "push"],cwd=cwdDATA)
  357. time.sleep(3)
  358. print("===== 刪除 source_code 資料夾 ==========================================================")
  359. # # 刪除 source_code 資料夾
  360. # shutil.rmtree(CURRENT_PATH + "\\source_code", onerror=remove_readonly)
  361. shutil.rmtree(cwdDATA, onerror=remove_readonly)
  362. time.sleep(3)
  363. # # 取得燒錄回傳
  364. print("===== SDIO.hex 燒錄等待中 =====================================================")
  365. res = board_prog[prog_data['tank']]
  366. print("res: ", res)
  367. return "燒錄中..."
  368. # time.sleep(60)
  369. # res = board_prog[prog_data['tank']]
  370. # print("res: ", res)
  371. # if board_prog[prog_data['tank']] == 'no reply':
  372. # board_prog[prog_data['tank']] = '0'
  373. # return 'no reply'
  374. # elif board_prog[prog_data['tank']] == 'success':
  375. # board_prog[prog_data['tank']] = '0'
  376. # return 'success'
  377. # elif board_prog[prog_data['tank']] == 'upload error':
  378. # board_prog[prog_data['tank']] = '0'
  379. # return 'upload error'
  380. # else:
  381. # res = "Code_upload " + prog_data['tank'] + " signal was not received"
  382. # return res
  383. @main.route('/board_programmer_result_<tid>')
  384. def board_programmer_result(tid):
  385. if board_prog[tid] == 'no reply':
  386. board_prog[tid] = '0'
  387. # return board_prog[tid] # 錯誤
  388. return 'no reply'
  389. elif board_prog[tid] == 'success':
  390. board_prog[tid] = '0'
  391. return 'success'
  392. elif board_prog[tid] == 'upload error':
  393. board_prog[tid] = '0'
  394. return 'upload error'
  395. elif board_prog[tid] == '0':
  396. return board_prog[tid]
  397. else:
  398. # res = "Code_upload " + tid + " signal was not received"
  399. return board_prog[tid]
  400. def remove_readonly(func, path, _):
  401. os.chmod(path, stat.S_IWRITE) # 更改權限 stat.S_IWRITE = windows 下取消只读
  402. func(path)
  403. # Rita 測試
  404. # 板子介面測試
  405. @main.route('/board_loadertt')
  406. def board_loadertt():
  407. pin_data = coffee1_0_pin.query.order_by(text('datetime desc')).first()
  408. # DCD1 = block_cond_d1_t.query.order_by(text('datetime desc')).first()
  409. BCD = block_cond_dry_t.query.order_by(text('datetime desc')).first()
  410. return render_template('board_loadertt.html', title="[測試]", **locals())
  411. # 檢視各使用者條件
  412. @main.route('/block_view', methods=['GET', 'POST'])
  413. def block_view():
  414. if request.method == 'GET':
  415. username = session['uname']
  416. status = session['status']
  417. sql = 'SELECT DISTINCT `UserName` FROM `block_cond_dry_t`'
  418. mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffeemanage', password='skyeye', database='CoffeeManage', charset='utf8')
  419. mycursor = mydb.cursor()
  420. try:
  421. mycursor.execute(sql)
  422. username_data = mycursor.fetchall()
  423. except pymysql.err.IntegrityError:
  424. username_data = "UserName is empty"
  425. mydb.commit()
  426. mydb.close()
  427. return render_template('block_view.html', title="檢視積木條件", **locals())
  428. # else:
  429. # prog_username = request.values['prog_username']
  430. # prog_tank = request.values['prog_tank']
  431. # print("prog_username: ", prog_username)
  432. # print("prog_tank: ", prog_tank)
  433. # return redirect('/block_view')
  434. # 桶槽間溝通
  435. @main.route('/tanks_comm')
  436. def tanks_comm():
  437. if 'id' in session and 'uname' in session and 'status' in session:
  438. username = session['uname']
  439. status = session['status']
  440. return render_template('tanks_comm.html', title="設備單元整合運作", **locals())
  441. else:
  442. print("NO session['uname']")
  443. return redirect('/login')
  444. @main.route('/select_cond', methods=['GET', 'POST'])
  445. def select_cond():
  446. info = request.args.to_dict()
  447. username = info['username']
  448. print("username: ", username)
  449. tank = info['tank']
  450. print("tank: ", tank)
  451. cond_data = (block_cond_dry_t.query.filter_by(UserName=str(username),tank_num=str(tank)).order_by(text('datetime desc')).first()).cond
  452. # print("cond_data.cond: ", cond_data.cond, "_type(cond_data.cond): ", type(cond_data.cond))
  453. print("cond_data: ", cond_data, type(cond_data))
  454. return cond_data
  455. @main.route('/board')
  456. def board():
  457. if 'id' in session and 'uname' in session and 'status' in session:
  458. username = session['uname']
  459. status = session['status']
  460. db.session.close()
  461. return render_template('board.html', title="板子燒錄介面", **locals())
  462. else:
  463. print("NO session['uname']")
  464. return redirect('/login')
  465. @main.route('/board_loader_<tankid>')
  466. def board_loader(tankid):
  467. if 'id' in session and 'uname' in session and 'status' in session:
  468. username = session['uname']
  469. status = session['status']
  470. # 取得桶槽編號
  471. TankID = tankid
  472. # 找到目前桶槽的入料儲豆槽
  473. #dry_tank_io = dry_tank_relation.query.filter_by(tank_id=tankid).first()
  474. # 若在 dry_tank_relation 桶槽關聯內無此桶槽, 則回到 /board_loader_D1
  475. #if dry_tank_io == None:
  476. # return redirect("/tank_relation")
  477. #print(dry_tank_io.tank_import) # DI1
  478. #tank_import = dry_tank_io.tank_import
  479. # 找到目前桶槽的入料儲豆槽
  480. #print(dry_tank_io.tank_export)
  481. #tank_export = dry_tank_io.tank_export
  482. # 腳位配置
  483. pin_data = coffee1_0_pin.query.filter_by(tid=tankid).order_by(text('datetime desc')).first()
  484. db.session.close()
  485. # 積木條件
  486. return render_template('index_zh-Hant.html', title="板子燒錄介面", **locals())
  487. else:
  488. print("NO session['uname']")
  489. return redirect('/login')
  490. # if 'id' in session and 'uname' in session:
  491. # print("session['uname']: ", session['uname'])
  492. # username = session['uname']
  493. # print("session['status']: ", session['status'])
  494. # status = session['status']
  495. # pin_data = coffee1_0_pin.query.order_by(text('datetime desc')).first()
  496. # # print("pin_data.R1:", pin_data.R1)
  497. # block_data = dry_block_waiting.query.order_by(text('datetime desc')).first()
  498. # # print("block_data.cond_a1_1:", block_data.cond_a1_1)
  499. # DBW = dry_block_waiting.query.order_by(text('datetime desc')).first()
  500. # return render_template('board_loader-1.html', title="板子燒錄介面", **locals())
  501. # else:
  502. # print("NO session['uname']")
  503. # return redirect('/login')
  504. # 桶槽前後關係設定
  505. @main.route('/tank_relation')
  506. def tank_relation():
  507. dtr = dry_tank_relation.query.all()
  508. # for i in dtr:
  509. # print("dtr", i, ": ", i.tank_id)
  510. return render_template('tank_relation.html', title="桶槽關係建立", **locals())
  511. #致動器功能程式定義
  512. def GPIO(relay,status):
  513. if relay=="R1":
  514. if status=="on":
  515. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_13, GPIO_PIN_RESET);\n"
  516. elif status=="off":
  517. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_13, GPIO_PIN_SET);\n"
  518. else:
  519. act=""
  520. elif relay=="R2":
  521. if status=="on":
  522. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_12, GPIO_PIN_RESET);\n"
  523. elif status=="off":
  524. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_12, GPIO_PIN_SET);\n"
  525. else:
  526. act=""
  527. elif relay=="R3":
  528. if status=="on":
  529. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_11, GPIO_PIN_RESET);\n"
  530. elif status=="off":
  531. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_11, GPIO_PIN_SET);\n"
  532. else:
  533. act=""
  534. elif relay=="R4":
  535. if status=="on":
  536. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_10, GPIO_PIN_RESET);\n"
  537. elif status=="off":
  538. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_10, GPIO_PIN_SET);\n"
  539. else:
  540. act=""
  541. elif relay=="R5":
  542. if status=="on":
  543. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_9, GPIO_PIN_RESET);\n"
  544. elif status=="off":
  545. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_9, GPIO_PIN_SET);\n"
  546. else:
  547. act=""
  548. elif relay=="R6":
  549. if status=="on":
  550. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_8, GPIO_PIN_RESET);\n"
  551. elif status=="off":
  552. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_8, GPIO_PIN_SET);\n"
  553. else:
  554. act=""
  555. elif relay=="R7":
  556. if status=="on":
  557. act=" HAL_GPIO_WritePin(GPIOC,GPIO_PIN_9, GPIO_PIN_RESET);\n"
  558. elif status=="off":
  559. act=" HAL_GPIO_WritePin(GPIOC,GPIO_PIN_9, GPIO_PIN_SET);\n"
  560. else:
  561. act=""
  562. elif relay=="R8":
  563. if status=="on":
  564. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_15, GPIO_PIN_RESET);\n"
  565. elif status=="off":
  566. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_15, GPIO_PIN_SET);\n"
  567. else:
  568. act=""
  569. elif relay=="R9":
  570. if status=="on":
  571. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_14, GPIO_PIN_RESET);\n"
  572. elif status=="off":
  573. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_14, GPIO_PIN_SET);\n"
  574. else:
  575. act=""
  576. elif relay=="R10":
  577. if status=="on":
  578. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_13, GPIO_PIN_RESET);\n"
  579. elif status=="off":
  580. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_13, GPIO_PIN_SET);\n"
  581. else:
  582. act=""
  583. elif relay=="R11":
  584. if status=="on":
  585. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_12, GPIO_PIN_RESET);\n"
  586. elif status=="off":
  587. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_12, GPIO_PIN_SET);\n"
  588. else:
  589. act=""
  590. elif relay=="R12":
  591. if status=="on":
  592. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_11, GPIO_PIN_RESET);\n"
  593. elif status=="off":
  594. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_11, GPIO_PIN_SET);\n"
  595. else:
  596. act=""
  597. elif relay=="R13":
  598. if status=="on":
  599. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_10, GPIO_PIN_RESET);\n"
  600. elif status=="off":
  601. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_10, GPIO_PIN_SET);\n"
  602. else:
  603. act=""
  604. elif relay=="R14":
  605. if status=="on":
  606. act=" HAL_GPIO_WritePin(GPIOB,GPIO_PIN_15, GPIO_PIN_RESET);\n"
  607. elif status=="off":
  608. act=" HAL_GPIO_WritePin(GPIOB,GPIO_PIN_15, GPIO_PIN_SET);\n"
  609. else:
  610. act=""
  611. elif relay=="R15":
  612. if status=="on":
  613. act=" HAL_GPIO_WritePin(GPIOB,GPIO_PIN_14, GPIO_PIN_RESET);\n"
  614. elif status=="off":
  615. act=" HAL_GPIO_WritePin(GPIOB,GPIO_PIN_14, GPIO_PIN_SET);\n"
  616. else:
  617. act=""
  618. elif relay=="R16":
  619. if status=="on":
  620. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_15, GPIO_PIN_RESET);\n"
  621. elif status=="off":
  622. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_15, GPIO_PIN_SET);\n"
  623. else:
  624. act=""
  625. elif relay=="R17":
  626. if status=="on":
  627. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_14, GPIO_PIN_RESET);\n"
  628. elif status=="off":
  629. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_14, GPIO_PIN_SET);\n"
  630. else:
  631. act=""
  632. elif relay=="R18":
  633. if status=="on":
  634. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_13, GPIO_PIN_RESET);\n"
  635. elif status=="off":
  636. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_13, GPIO_PIN_SET);\n"
  637. else:
  638. act=""
  639. elif relay=="R19":
  640. if status=="on":
  641. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_12, GPIO_PIN_RESET);\n"
  642. elif status=="off":
  643. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_12, GPIO_PIN_SET);\n"
  644. else:
  645. act=""
  646. elif relay=="R20":
  647. if status=="on":
  648. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_11, GPIO_PIN_RESET);\n"
  649. elif status=="off":
  650. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_11, GPIO_PIN_SET);\n"
  651. else:
  652. act=""
  653. elif relay=="sleep":
  654. act=" HAL_Delay("+status+"000);\n"
  655. elif relay=="M10":
  656. if int(status)>0:
  657. act=(" user_pwm_setvalue2(0);\n"
  658. +" user_pwm_setvalue("+status+");\n")
  659. elif int(status)<0:
  660. status=-1*int(status)
  661. act=(" user_pwm_setvalue(0);\n"
  662. +" user_pwm_setvalue2("+str(status)+");\n")
  663. else:
  664. act=""
  665. elif relay=="M2":
  666. if status=="on":
  667. act=" user_pwm_setvalue3(50);\n"
  668. elif status=="off":
  669. act=" user_pwm_setvalue3(180);\n"
  670. else:
  671. act=""
  672. elif relay=="M3":
  673. if status=="on":
  674. act=" user_pwm_setvalue4(50);\n"
  675. elif status=="off":
  676. act=" user_pwm_setvalue4(180);\n"
  677. else:
  678. act=""
  679. else:
  680. act=""
  681. return act
  682. #感測器功能程式定義
  683. def PH(pin_position,pin_type):
  684. global pin_variables,pin_code
  685. if pin_position=="M4":
  686. pin="ADC_CHANNEL_0"
  687. elif pin_position=="M5":
  688. pin="ADC_CHANNEL_3"
  689. elif pin_position=="M7":
  690. pin="ADC_CHANNEL_4"
  691. if pin_type =="PH":
  692. print("PH ok")
  693. pin_variables=("uint16_t "+pin_position+"_AD_Value = 0;\n"
  694. +"float "+pin_position+"_voltage_V =0;\n"
  695. +"float "+pin_position+"_pH_mid = 1.500;\n"
  696. +"float "+pin_position+"_pH_low = 2.030;\n"
  697. +"float "+pin_position+"_pH_high =0.975;\n"
  698. +"float "+pin_position+"_"+pin_type+"=0;\n")
  699. pin_code=(" MX_ADC1_Init1("+pin+");\n"
  700. +" HAL_ADC_Start(&hadc1);\n"
  701. +" HAL_ADC_PollForConversion(&hadc1, 50);\n"
  702. +" if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
  703. +" {\n"
  704. +" "+pin_position+"_AD_Value = HAL_ADC_GetValue(&hadc1);\n"
  705. +" "+pin_position+"_voltage_V = "+pin_position+"_AD_Value*3.3f/4096;\n"
  706. +" if ("+pin_position+"_voltage_V > "+pin_position+"_pH_mid)\n"
  707. +" {\n"
  708. +" "+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"
  709. +" }\n"
  710. +" else\n"
  711. +" {\n"
  712. +" "+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"
  713. +" }\n"
  714. +" }\n"
  715. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",4,10);\n")
  716. else:
  717. pin_variables=""
  718. pin_code=""
  719. def DO(pin_position,pin_type):
  720. global pin_variables,pin_code
  721. if pin_position=="M4":
  722. pin="ADC_CHANNEL_0"
  723. elif pin_position=="M5":
  724. pin="ADC_CHANNEL_3"
  725. elif pin_position=="M7":
  726. pin="ADC_CHANNEL_4"
  727. if pin_type =="DO":
  728. print("DO ok")
  729. pin_variables=("uint16_t "+pin_position+"_AD_Value = 0;\n"
  730. +"float "+pin_position+"_voltage_V =0;\n"
  731. +"float "+pin_position+"_DO_offset =0.44;\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*3.3f/4096;\n"
  740. +" "+pin_position+"_"+pin_type+"= ((("+pin_position+"_AD_Value*3.3f/4096)*100)/"+pin_position+"_DO_offset);\n"
  741. +" }\n"
  742. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",4,10);\n")
  743. else:
  744. pin_variables=""
  745. pin_code=""
  746. def WATERLEVEL(pin_position,pin_type):
  747. global pin_variables,pin_code
  748. if pin_position=="M9":
  749. pin="GPIO_PIN_9"
  750. elif pin_position=="M11":
  751. pin="GPIO_PIN_7"
  752. elif pin_position=="M12":
  753. pin="GPIO_PIN_8"
  754. elif pin_position=="M19":
  755. pin="GPIO_PIN_10"
  756. if pin_type =="WATERLEVEL":
  757. print("WATERLEVEL ok")
  758. pin_variables=("int "+pin_position+"_"+pin_type+" =0;\n")
  759. pin_code=(" MX_GPIO_Input1("+pin+");\n"
  760. +" if (HAL_GPIO_ReadPin(GPIOE, "+pin+") == GPIO_PIN_SET)\n"
  761. +" {\n"
  762. +" "+pin_position+"_"+pin_type+" =1;\n"
  763. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
  764. +" }\n"
  765. +" else\n"
  766. +" {\n"
  767. +" "+pin_position+"_"+pin_type+" =0;\n"
  768. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
  769. +" }\n")
  770. else:
  771. pin_variables=""
  772. pin_code=""
  773. def motorfeedback(pin_position,pin_type):
  774. global pin_variables,pin_code
  775. if pin_position=="M9":
  776. pin="GPIO_PIN_9"
  777. elif pin_position=="M11":
  778. pin="GPIO_PIN_7"
  779. elif pin_position=="M12":
  780. pin="GPIO_PIN_8"
  781. elif pin_position=="M19":
  782. pin="GPIO_PIN_10"
  783. if pin_type =="motorfeedback":
  784. print("feedback ok")
  785. pin_variables=("int "+pin_position+"_"+pin_type+" =0;\n")
  786. pin_code=(" MX_GPIO_Input1("+pin+");\n"
  787. +" if (HAL_GPIO_ReadPin(GPIOE, "+pin+") == GPIO_PIN_SET)\n"
  788. +" {\n"
  789. +" "+pin_position+"_"+pin_type+" =1;\n"
  790. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
  791. +" }\n"
  792. +" else\n"
  793. +" {\n"
  794. +" "+pin_position+"_"+pin_type+" =0;\n"
  795. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
  796. +" }\n")
  797. else:
  798. pin_variables=""
  799. pin_code=""
  800. def butterflyvalvefeedback(pin_position,pin_type):
  801. global pin_variables,pin_code
  802. if pin_position=="M9":
  803. pin="GPIO_PIN_9"
  804. elif pin_position=="M11":
  805. pin="GPIO_PIN_7"
  806. elif pin_position=="M12":
  807. pin="GPIO_PIN_8"
  808. elif pin_position=="M19":
  809. pin="GPIO_PIN_10"
  810. if pin_type =="butterflyvalvefeedback":
  811. print("butterflyvalvefeedback ok")
  812. pin_variables=("int "+pin_position+"_"+pin_type+" =0;\n")
  813. pin_code=(" MX_GPIO_Input1("+pin+");\n"
  814. +" if (HAL_GPIO_ReadPin(GPIOE, "+pin+") == GPIO_PIN_SET)\n"
  815. +" {\n"
  816. +" "+pin_position+"_"+pin_type+" =1;\n"
  817. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
  818. +" }\n"
  819. +" else\n"
  820. +" {\n"
  821. +" "+pin_position+"_"+pin_type+" =0;\n"
  822. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
  823. +" }\n")
  824. else:
  825. pin_variables=""
  826. pin_code=""
  827. def ORP(pin_position,pin_type):
  828. global pin_variables,pin_code
  829. if pin_position=="M4":
  830. pin="ADC_CHANNEL_0"
  831. elif pin_position=="M5":
  832. pin="ADC_CHANNEL_3"
  833. elif pin_position=="M7":
  834. pin="ADC_CHANNEL_4"
  835. if pin_type =="ORP":
  836. print("ORP ok")
  837. pin_variables=("uint16_t "+pin_position+"_AD_Value = 0;\n"
  838. +"float "+pin_position+"_voltage_V =0;\n"
  839. +"float "+pin_position+"_ORP_offset =0;\n"
  840. +"float "+pin_position+"_"+pin_type+" =0;\n")
  841. pin_code=(" MX_ADC1_Init1("+pin+");\n"
  842. +" HAL_ADC_Start(&hadc1);\n"
  843. +" HAL_ADC_PollForConversion(&hadc1, 50);\n"
  844. +" if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
  845. +" {\n"
  846. +" "+pin_position+"_AD_Value = HAL_ADC_GetValue(&hadc1);\n"
  847. +" "+pin_position+"_voltage_V = "+pin_position+"_AD_Value*3.3f/4096;\n"
  848. +" "+pin_position+"_"+pin_type+"= ((("+pin_position+"_AD_Value*3.3f/4096)-(1.5+"+pin_position+"_ORP_offset)));\n"
  849. +" }\n"
  850. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",4,10);\n")
  851. else:
  852. pin_variables=""
  853. pin_code=""
  854. def SonicESMUS07(pin_position,pin_type):
  855. global pin_variables,pin_code,pin_add_code
  856. if pin_position=="M1":
  857. pin="ADC_CHANNEL_6"
  858. if pin_type =="SonicESMUS07":
  859. print("ESMUS07 ok")
  860. pin_variables=("uint16_t "+pin_position+"_AD_Value = 0;\n"
  861. +"float "+pin_position+"_voltage_V =0;\n"
  862. +"float "+pin_position+"_"+pin_type+" =0;\n")
  863. pin_code=(" MX_ADC1_Init1("+pin+");\n"
  864. +" HAL_ADC_Start(&hadc1);\n"
  865. +" HAL_ADC_PollForConversion(&hadc1, 50);\n"
  866. +" if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
  867. +" {\n"
  868. +" "+pin_position+"_AD_Value = HAL_ADC_GetValue(&hadc1);\n"
  869. +" "+pin_position+"_voltage_V = "+pin_position+"_AD_Value*5.3f/4096;\n"
  870. +" if ("+pin_position+"_voltage_V==0)\n"
  871. +" {\n"
  872. +" "+pin_position+"_"+pin_type+ " = 100;\n"
  873. +" }\n"
  874. +" else\n"
  875. +" {\n"
  876. +" "+pin_position+"_"+pin_type+ " = ("+pin_position+"_voltage_V*180)+100;\n"
  877. +" }\n"
  878. +" }\n"
  879. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",4,10);\n")
  880. else:
  881. pin_variables=""
  882. pin_code=""
  883. pin_add_code=""
  884. def SEN0189(pin_position,pin_type):
  885. global pin_variables,pin_code,pin_add_code
  886. if pin_position=="M6":
  887. pin="ADC_CHANNEL_13"
  888. elif pin_position=="M13":
  889. pin="ADC_CHANNEL_5"
  890. if pin_type =="SEN0189":
  891. print("SEN0189 ok")
  892. pin_variables=("uint16_t "+pin_position+"_AD_Value = 0;\n"
  893. +"float "+pin_position+"_voltage_V =0;\n"
  894. +"float "+pin_position+"_"+pin_type+" =0;\n")
  895. pin_code=(" MX_ADC1_Init1("+pin+");\n"
  896. +" HAL_ADC_Start(&hadc1);\n"
  897. +" HAL_ADC_PollForConversion(&hadc1, 50);\n"
  898. +" if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
  899. +" {\n"
  900. +" "+pin_position+"_AD_Value = HAL_ADC_GetValue(&hadc1);\n"
  901. +" "+pin_position+"_voltage_V = "+pin_position+"_AD_Value*5.0f/4096;\n"
  902. +" if ("+pin_position+"_voltage_V>4.2)\n"
  903. +" {\n"
  904. +" "+pin_position+"_"+pin_type+ " = 0;\n"
  905. +" }\n"
  906. +" else if ("+pin_position+"_voltage_V<2.5)\n"
  907. +" {\n"
  908. +" "+pin_position+"_"+pin_type+ " = 3000;\n"
  909. +" }\n"
  910. +" else\n"
  911. +" {\n"
  912. +" "+pin_position+"_"+pin_type+"=(-1120.4*"+pin_position+"_voltage_V*"+pin_position+"_voltage_V)+(5742.3*"+pin_position+"_voltage_V)-4352.9;\n"
  913. +" }\n"
  914. +" }\n"
  915. +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",4,10);\n")
  916. print(pin_variables)
  917. print(pin_code)
  918. else:
  919. pin_variables=""
  920. pin_code=""
  921. pin_add_code=""
  922. def SERVO(pin_position, pin_type):
  923. global pin_variables, pin_code
  924. if pin_type == "Servo":
  925. print("Servo ok")
  926. pin_code = (
  927. " HAL_UART_Receive_IT(&huart1, (uint8_t *)checkfeedback,sizeof(checkfeedback));\n")
  928. pin_add_code = (" void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)\n"
  929. + "{\n"
  930. + " if(checkfeedback[0]==0xff && checkfeedback[6]==0x0D)\n"
  931. + " {\n"
  932. + " direction=checkfeedback[1];\n"
  933. + " if(direction==0)\n"
  934. + " {\n"
  935. + " HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_RESET);\n"
  936. + " HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, GPIO_PIN_SET);\n"
  937. + " user_pwm_setvalue(50);\n"
  938. + " }\n"
  939. + " else if(direction==1)\n"
  940. + " {\n"
  941. + " HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_RESET);\n"
  942. + " HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, GPIO_PIN_RESET);\n"
  943. + " user_pwm_setvalue(50);\n"
  944. + " }\n"
  945. + " else\n"
  946. + " {\n"
  947. + " HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_SET);\n"
  948. + " HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, GPIO_PIN_RESET);\n"
  949. + " user_pwm_setvalue(0);\n"
  950. + " }\n"
  951. + " }\n"
  952. + "}\n")
  953. print(pin_code)
  954. print(pin_add_code)
  955. else:
  956. pin_variables = ""
  957. pin_code = ""
  958. def MOTOR(pin_position, pin_type):
  959. global pin_variables, pin_code
  960. if pin_type == "Servo":
  961. print("Servo ok")
  962. pin_code = (" HAL_UART_Receive_IT(&huart1, (uint8_t *)checkfeedback,sizeof(checkfeedback));\n"
  963. + " HAL_Delay(100);\n"
  964. + " if(direction==0)\n"
  965. + " {\n"
  966. + " user_pwm_setvalue2(0);\n"
  967. + " user_pwm_setvalue(pwm_value);\n"
  968. + " }\n"
  969. + " else\n"
  970. + " {\n"
  971. + " user_pwm_setvalue2(pwm_value);\n"
  972. + " user_pwm_setvalue(0);\n"
  973. + " }\n")
  974. pin_add_code = (" void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)\n"
  975. + "{\n"
  976. + " if(checkfeedback[0]==0xff && checkfeedback[6]==0x0D)\n"
  977. + " {\n"
  978. + " pwm_value=checkfeedback[1];\n"
  979. + " direction=checkfeedback[2];\n"
  980. + ' printf("%d",pwm_value);\n'
  981. + " }\n"
  982. + "}\n")
  983. print(pin_code)
  984. print(pin_add_code)
  985. else:
  986. pin_variables = ""
  987. pin_code = ""
  988. def SOIL(pin_position,pin_type):
  989. global pin_variables,pin_code,pin_add_code
  990. if pin_type =="Soil":
  991. print("SOIL ok")
  992. pin_variables=("uint8_t soil[8] ={0x01,0x03,0x00,0x00,0x00,0x03,0x05,0xCB};\n"
  993. +"uint8_t data[11] ={0,0,0,0,0,0,0,0,0,0,0};\n"
  994. +"float "+pin_position+"_"+pin_type+" =0;\n"
  995. +"int rh=0;\n"
  996. +"int temp=0;\n"
  997. +"int ec=0;\n")
  998. pin_code=(" HAL_UART_Transmit(&huart2, (uint8_t *)soil,sizeof(soil),50);\n"
  999. +" HAL_UART_Receive_IT(&huart2, (uint8_t *)data,sizeof(data));\n")
  1000. pin_add_code=("void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)\n"
  1001. +"{\n"
  1002. +" if (huart->Instance == USART2)\n"
  1003. +" {\n"
  1004. +" if (data[0]==0x01 && data[1]==0x03)\n"
  1005. +" {\n"
  1006. +" rh = (data[3] << 8) + data[4];\n"
  1007. +" temp = (data[5] << 8) + data[6];\n"
  1008. +" ec = (data[7] << 8) + data[8];\n"
  1009. +" }\n"
  1010. +" }\n"
  1011. +"}\n")
  1012. print(pin_code)
  1013. print(pin_add_code)
  1014. else:
  1015. pin_variables=""
  1016. pin_code=""
  1017. pin_add_code=""
  1018. def EC(pin_position,pin_type):
  1019. global pin_variables,pin_code,pin_add_code
  1020. if pin_type =="EC":
  1021. print("EC ok")
  1022. pin_variables=("uint8_t data[4] ={0,0,0,0};\n"
  1023. +"float "+pin_position+"_"+pin_type+" =0;\n")
  1024. pin_code=(" HAL_UART_Receive_IT(&huart2, (uint8_t *)data,sizeof(data));\n")
  1025. pin_add_code=("void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)\n"
  1026. +"{\n"
  1027. +" if (huart->Instance == USART2)\n"
  1028. +" {\n"
  1029. +" if (data[0]==0x30 && data[1]==0x2E)\n"
  1030. +" {\n"
  1031. +" HAL_UART_Transmit(&huart4, (uint8_t *)data,sizeof(data),50);\n"
  1032. +" }\n"
  1033. +" }\n"
  1034. +"}\n")
  1035. print(pin_variables)
  1036. print(pin_code)
  1037. print(pin_add_code)
  1038. else:
  1039. pin_variables=""
  1040. pin_code=""
  1041. pin_add_code=""
  1042. def SHT11(pin_position,pin_type):
  1043. global pin_variables,pin_code,pin_add_code
  1044. global sensor_code
  1045. if pin_position=="M14":
  1046. pin_group="GPIOB"
  1047. pin1="GPIO_PIN_0"
  1048. pin2="GPIO_PIN_1"
  1049. if pin_position=="M17":
  1050. pin_group="GPIOC"
  1051. pin1="GPIO_PIN_6"
  1052. pin2="GPIO_PIN_7"
  1053. if pin_type =="SHT11":
  1054. print("SHT11 ok")
  1055. pin_variables=("uint8_t cmd[7]={0xFF,0x00,0x00,0x00,0x00,0x00,0x0D};\n"
  1056. +"uint16_t i,val,value_H,value_L,Cvalue,Hvalue;\n"
  1057. +"int error;\n"
  1058. +"float C1=-2.0468;\n"
  1059. +"float C2=0.0367;\n"
  1060. +"float C3=-0.0000015955;\n"
  1061. +"float RH_Lin;\n"
  1062. +"float RH_Ture;\n"
  1063. +"float d1=-39.6;\n"
  1064. +"float d2=0.01;\n"
  1065. +"float T1=0.01;\n"
  1066. +"float T2=0.00008;\n"
  1067. +"float temp_C=0;\n"
  1068. +"int temp;\n"
  1069. +"int RH;\n"
  1070. +"float "+pin_position+"_"+pin_type+" =0;\n")
  1071. sensor_code=("void SHT10_TransStart(void);\n"
  1072. +"void SHT10_WriteByte(void);\n"
  1073. +"void SHT10_WriteByte2(void);\n"
  1074. +"void SHT10_ReadByte(void);\n"
  1075. +"void SHT10_Calculate(void);\n"
  1076. +"void MX_GPIO_Input1(unsigned long pin);\n")
  1077. pin_code=(" Cvalue=0;\n"
  1078. +" Hvalue=0;\n"
  1079. +" value_H=0;\n"
  1080. +" value_L=0;\n"
  1081. +" SHT10_TransStart();\n"
  1082. +" SHT10_WriteByte();\n"
  1083. +" MX_GPIO_Input1("+pin1+");\n"
  1084. +" HAL_Delay(250);\n"
  1085. +" if (HAL_GPIO_ReadPin("+pin_group+","+pin1+")==0)\n"
  1086. +" {\n"
  1087. +" SHT10_ReadByte();\n"
  1088. +" value_H=val;\n"
  1089. +" SHT10_ReadByte();\n"
  1090. +" value_L=val;\n"
  1091. +" Cvalue = (value_H<< 8 | value_L);\n"
  1092. +" }\n"
  1093. +" SHT10_TransStart();\n"
  1094. +" SHT10_WriteByte2();\n"
  1095. +" MX_GPIO_Input1("+pin1+");\n"
  1096. +" HAL_Delay(250);\n"
  1097. +" if (HAL_GPIO_ReadPin("+pin_group+","+pin1+")==0)\n"
  1098. +" {\n"
  1099. +" SHT10_ReadByte();\n"
  1100. +" value_H=val;\n"
  1101. +" SHT10_ReadByte();\n"
  1102. +" value_L=val;\n"
  1103. +" Hvalue = (value_H<< 8 | value_L);\n"
  1104. +" }\n"
  1105. +" SHT10_Calculate();\n")
  1106. pin_add_code=(" void SHT10_TransStart(void)\n"
  1107. +"{\n"
  1108. +" MX_GPIO_Init();\n"
  1109. +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_SET);\n"
  1110. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
  1111. +" HAL_Delay(10);\n"
  1112. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
  1113. +" HAL_Delay(10);\n"
  1114. +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_RESET);\n"
  1115. +" HAL_Delay(10);\n"
  1116. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
  1117. +" HAL_Delay(10);\n"
  1118. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
  1119. +" HAL_Delay(10);\n"
  1120. +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_SET);\n"
  1121. +" HAL_Delay(10);\n"
  1122. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
  1123. +" HAL_Delay(10);\n"
  1124. +"}\n"
  1125. +" void SHT10_WriteByte(void)\n"
  1126. +"{\n"
  1127. +" MX_GPIO_Init();\n"
  1128. +" for (i=0x80;i>0;i/=2)\n"
  1129. +" {\n"
  1130. +" if (i & 0x03)\n"
  1131. +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_SET);\n"
  1132. +" else\n"
  1133. +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_RESET);\n"
  1134. +" HAL_Delay(10);\n"
  1135. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
  1136. +" HAL_Delay(10);\n"
  1137. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
  1138. +" HAL_Delay(10);\n"
  1139. +" }\n"
  1140. +" MX_GPIO_Input1("+pin1+");\n"
  1141. +" HAL_Delay(10);\n"
  1142. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
  1143. +" HAL_Delay(10);\n"
  1144. +" error=HAL_GPIO_ReadPin("+pin_group+","+pin1+");\n"
  1145. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
  1146. +" HAL_Delay(10);\n"
  1147. +"}\n"
  1148. +" void SHT10_WriteByte2(void)\n"
  1149. +"{\n"
  1150. +" MX_GPIO_Init();\n"
  1151. +" for (i=0x80;i>0;i/=2)\n"
  1152. +" {\n"
  1153. +" if (i & 0x05)\n"
  1154. +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_SET);\n"
  1155. +" else\n"
  1156. +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_RESET);\n"
  1157. +" HAL_Delay(10);\n"
  1158. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
  1159. +" HAL_Delay(10);\n"
  1160. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
  1161. +" HAL_Delay(10);\n"
  1162. +" }\n"
  1163. +" MX_GPIO_Input1("+pin1+");\n"
  1164. +" HAL_Delay(10);\n"
  1165. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
  1166. +" HAL_Delay(10);\n"
  1167. +" error=HAL_GPIO_ReadPin("+pin_group+", "+pin1+");\n"
  1168. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
  1169. +" HAL_Delay(10);\n"
  1170. +"}\n"
  1171. +" void SHT10_ReadByte(void)\n"
  1172. +"{\n"
  1173. +" val=0;\n"
  1174. +" MX_GPIO_Input1("+pin1+");\n"
  1175. +" for (i=0x80;i>0;i/=2)\n"
  1176. +" {\n"
  1177. +" HAL_Delay(10);\n"
  1178. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
  1179. +" HAL_Delay(10);\n"
  1180. +" if(HAL_GPIO_ReadPin("+pin_group+","+pin1+"))\n"
  1181. +" val=( val | i );\n"
  1182. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
  1183. +" }\n"
  1184. +" MX_GPIO_Init();\n"
  1185. +" if (1)\n"
  1186. +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_RESET);\n"
  1187. +" else\n"
  1188. +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_SET);\n"
  1189. +" HAL_Delay(10);\n"
  1190. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
  1191. +" HAL_Delay(10);\n"
  1192. +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
  1193. +" HAL_Delay(10);\n"
  1194. +"}\n"
  1195. +" void SHT10_Calculate(void)\n"
  1196. +"{\n"
  1197. +" temp_C=d1+d2*Cvalue;\n"
  1198. +" RH_Lin = C1+C2*Hvalue+C3*Hvalue*Hvalue;\n"
  1199. +" RH_Ture= (temp_C-25)*(T1+T2*Hvalue)+RH_Lin;\n"
  1200. +" if (RH_Ture>100)\n"
  1201. +" RH_Ture= 100;\n"
  1202. +" if (RH_Ture<0.1)\n"
  1203. +" RH_Ture=0.1;\n"
  1204. +" if (temp_C<0)\n"
  1205. +" {\n"
  1206. +" cmd[1]=1;\n"
  1207. +" cmd[2]=-1*temp_C;\n"
  1208. +" temp=(-10*temp_C);\n"
  1209. +" cmd[3]=temp%10;\n"
  1210. +" cmd[4]=RH_Ture;\n"
  1211. +" RH=RH_Ture*10;\n"
  1212. +" cmd[5]=RH%10;\n"
  1213. +" }\n"
  1214. +" else\n"
  1215. +" {\n"
  1216. +" cmd[1]=0;\n"
  1217. +" cmd[2]=temp_C;\n"
  1218. +" temp=(10*temp_C);\n"
  1219. +" cmd[3]=temp%10;\n"
  1220. +" cmd[4]=RH_Ture;\n"
  1221. +" RH=RH_Ture*10;\n"
  1222. +" cmd[5]=RH%10;\n"
  1223. +" }\n"
  1224. +"}\n")
  1225. else:
  1226. pin_variables=""
  1227. pin_code=""
  1228. pin_add_code=""
  1229. sensor_code=""
  1230. def DS18B20(pin_position,pin_type):
  1231. global pin_variables,pin_code,pin_add_code
  1232. global sensor_code
  1233. if pin_position=="M14":
  1234. pin1="GPIO_PIN_0"
  1235. if pin_position=="M16":
  1236. pin1="GPIO_PIN_7"
  1237. if pin_type =="DS18B20":
  1238. print("DS18B20 ok")
  1239. pin_variables=("#define CLR_DS18B20() HAL_GPIO_WritePin (GPIOB, "+pin1+",GPIO_PIN_RESET )\n"
  1240. +"#define SET_DS18B20() HAL_GPIO_WritePin (GPIOB, "+pin1+",GPIO_PIN_SET )\n"
  1241. +"#define DS18B20_DQ_IN HAL_GPIO_ReadPin(GPIOB, "+pin1+")\n"
  1242. +"int16_t temp;\n"
  1243. +"int error;\n"
  1244. +"float "+pin_position+"_"+pin_type+" =0;\n")
  1245. sensor_code=("uint8_t DS18B20_Init(void);\n"
  1246. +"short DS18B20_Get_Temp(void);\n"
  1247. +"void DS18B20_Start(void);\n"
  1248. +"void DS18B20_Write_Byte(uint8_t dat);\n"
  1249. +"uint8_t DS18B20_Read_Byte(void);\n"
  1250. +"uint8_t DS18B20_Read_Bit(void);\n"
  1251. +"uint8_t DS18B20_Check(void);\n"
  1252. +"void DS18B20_Rst(void);\n")
  1253. pin_code=(" temp=DS18B20_Get_Temp();\n")
  1254. pin_add_code=(" void delay_us(uint32_t value)\n"
  1255. +"{\n"
  1256. +" uint32_t i;\n"
  1257. +" i = value * 3;\n"
  1258. +" while(i--);\n"
  1259. +"}\n"
  1260. +" void DS18B20_Rst(void)\n"
  1261. +"{\n"
  1262. +" CLR_DS18B20();\n"
  1263. +" delay_us(750);\n"
  1264. +" SET_DS18B20();\n"
  1265. +" delay_us(15);\n"
  1266. +"}\n"
  1267. +" uint8_t DS18B20_Check(void)\n"
  1268. +"{\n"
  1269. +" uint8_t retry=0;\n"
  1270. +" while (DS18B20_DQ_IN&&retry<200)\n"
  1271. +" {\n"
  1272. +" retry++;\n"
  1273. +" delay_us(1);\n"
  1274. +" }\n"
  1275. +" if(retry>=200)return 1;\n"
  1276. +" else retry=0;\n"
  1277. +" while (!DS18B20_DQ_IN&&retry<240)\n"
  1278. +" {\n"
  1279. +" retry++;\n"
  1280. +" delay_us(1);\n"
  1281. +" }\n"
  1282. +" if(retry>=240)return 1;\n"
  1283. +" return 0;\n"
  1284. +"}\n"
  1285. +" uint8_t DS18B20_Read_Bit(void)\n"
  1286. +"{\n"
  1287. +" uint8_t data;\n"
  1288. +" CLR_DS18B20();\n"
  1289. +" delay_us(2);\n"
  1290. +" SET_DS18B20();\n"
  1291. +" delay_us(12);\n"
  1292. +" if(DS18B20_DQ_IN)data=1;\n"
  1293. +" else data=0;\n"
  1294. +" delay_us(50);\n"
  1295. +" return data;\n"
  1296. +"}\n"
  1297. +" uint8_t DS18B20_Read_Byte(void)\n"
  1298. +"{\n"
  1299. +" uint8_t i,j,dat;\n"
  1300. +" dat=0;\n"
  1301. +" for (i=1;i<=8;i++)\n"
  1302. +" {\n"
  1303. +" j=DS18B20_Read_Bit();\n"
  1304. +" dat=(j<<7)|(dat>>1);\n"
  1305. +" }\n"
  1306. +" return dat;\n"
  1307. +"}\n"
  1308. +" void DS18B20_Write_Byte(uint8_t dat)\n"
  1309. +"{\n"
  1310. +" uint8_t j;\n"
  1311. +" uint8_t testb;\n"
  1312. +" for (j=1;j<=8;j++)\n"
  1313. +" {\n"
  1314. +" testb=dat&0x01;\n"
  1315. +" dat=dat>>1;\n"
  1316. +" if (testb)\n"
  1317. +" {\n"
  1318. +" CLR_DS18B20();\n"
  1319. +" delay_us(2);\n"
  1320. +" SET_DS18B20();\n"
  1321. +" delay_us(60);\n"
  1322. +" }\n"
  1323. +" else\n"
  1324. +" {\n"
  1325. +" CLR_DS18B20();\n"
  1326. +" delay_us(60);\n"
  1327. +" SET_DS18B20();\n"
  1328. +" delay_us(2);\n"
  1329. +" }\n"
  1330. +" }\n"
  1331. +"}\n"
  1332. +" uint8_t DS18B20_Init(void)\n"
  1333. +"{\n"
  1334. +" SET_DS18B20();\n"
  1335. +" DS18B20_Rst();\n"
  1336. +" return DS18B20_Check();\n"
  1337. +"}\n"
  1338. +" void DS18B20_Start(void)\n"
  1339. +"{\n"
  1340. +" DS18B20_Rst();\n"
  1341. +" DS18B20_Check();\n"
  1342. +" DS18B20_Write_Byte(0xcc);\n"
  1343. +" DS18B20_Write_Byte(0x44);\n"
  1344. +"}\n"
  1345. +" short DS18B20_Get_Temp(void)\n"
  1346. +"{\n"
  1347. +" uint8_t temp;\n"
  1348. +" uint8_t TL,TH;\n"
  1349. +" short tem;\n"
  1350. +" DS18B20_Start();\n"
  1351. +" DS18B20_Rst();\n"
  1352. +" DS18B20_Check();\n"
  1353. +" DS18B20_Write_Byte(0xcc);\n"
  1354. +" DS18B20_Write_Byte(0xbe);\n"
  1355. +" TL=DS18B20_Read_Byte();\n"
  1356. +" TH=DS18B20_Read_Byte();\n"
  1357. +" if(TH>7)\n"
  1358. +" {\n"
  1359. +" TH=~TH;\n"
  1360. +" TL=~TL;\n"
  1361. +" temp=0;\n"
  1362. +" }\n"
  1363. +" else temp=1;\n"
  1364. +" tem=TH;\n"
  1365. +" tem<<=8;\n"
  1366. +" tem+=TL;\n"
  1367. +" tem=(float)tem*0.625f;\n"
  1368. +" if(temp)return tem;\n"
  1369. +" else return -tem;\n"
  1370. +"}\n")
  1371. else:
  1372. pin_variables=""
  1373. pin_code=""
  1374. pin_add_code=""
  1375. sensor_code=""
  1376. def BMP280(pin_position,pin_type):
  1377. global pin_variables,pin_code,pin_add_code,init_code
  1378. global sensor_code
  1379. if pin_type =="BMP280":
  1380. print("BMP280 ok")
  1381. pin_variables=("uint8_t cmd[7]={0xFF,0x00,0x00,0x00,0x00,0x00,0x0D};\n"
  1382. +"HAL_StatusTypeDef Status;\n"
  1383. +"#define ADDR_AT24C04_WRITE_FIRST_16_PAGES 0xEC\n"
  1384. +"#define ADDR_AT24C04_WRITE_FIRST_16_PAGES 0xEC\n"
  1385. +"#define ADDR_AT24C04_READ 0xED\n"
  1386. +"#define AT24C04_TIMEOUT 0xED\n"
  1387. +"#define AT24C04_PAGE_SIZE 16\n"
  1388. +"#define BUFFER_SIZE 1\n"
  1389. +"uint16_t dig_T1;\n"
  1390. +"uint16_t dig_T2;\n"
  1391. +"uint16_t dig_T3;\n"
  1392. +"uint16_t dig_P1;\n"
  1393. +"uint16_t dig_P2;\n"
  1394. +"uint16_t dig_P3;\n"
  1395. +"uint16_t dig_P4;\n"
  1396. +"uint16_t dig_P5;\n"
  1397. +"uint16_t dig_P6;\n"
  1398. +"uint16_t dig_P7;\n"
  1399. +"uint16_t dig_P8;\n"
  1400. +"uint16_t dig_P9;\n"
  1401. +"uint32_t adc_P=0;\n"
  1402. +"uint32_t adc_T=0;\n"
  1403. +"uint8_t WriteBuffer[BUFFER_SIZE]={0xb6};\n"
  1404. +"uint8_t WriteBuffer1[BUFFER_SIZE]={0xff};\n"
  1405. +"uint8_t WriteBuffer2[BUFFER_SIZE]={0x00};\n"
  1406. +"uint8_t ReadBuffer[BUFFER_SIZE];\n"
  1407. +"int RH;\n"
  1408. +"float "+pin_position+"_"+pin_type+" =0;\n")
  1409. sensor_code=("HAL_StatusTypeDef AT24C04_Write(I2C_HandleTypeDef *hi2c,uint16_t MemAddress,uint8_t *pData);\n"
  1410. +"HAL_StatusTypeDef AT24C04_Read(I2C_HandleTypeDef *hi2c,uint16_t MemAddress,uint8_t *pData);\n"
  1411. +"long bmp280_T_MultipleReadThree(void);\n"
  1412. +"long bmp280_P_MultipleReadThree(void);\n"
  1413. +"short bmp280_MultipleReadTwo(uint16_t addr);\n")
  1414. init_code=(" AT24C04_Write(&hi2c1,0xe0,WriteBuffer);\n"
  1415. +" AT24C04_Write(&hi2c1,0xf4,WriteBuffer1);\n"
  1416. +" AT24C04_Write(&hi2c1,0xf5,WriteBuffer2);\n"
  1417. +" dig_T1 = bmp280_MultipleReadTwo(0x88);\n"
  1418. +" dig_T2 = bmp280_MultipleReadTwo(0x8A);\n"
  1419. +" dig_T3 = bmp280_MultipleReadTwo(0x8C);\n"
  1420. +" dig_P1 = bmp280_MultipleReadTwo(0x8E);\n"
  1421. +" dig_P2 = bmp280_MultipleReadTwo(0x90);\n"
  1422. +" dig_P3 = bmp280_MultipleReadTwo(0x92);\n"
  1423. +" dig_P4 = bmp280_MultipleReadTwo(0x94);\n"
  1424. +" dig_P5 = bmp280_MultipleReadTwo(0x96);\n"
  1425. +" dig_P6 = bmp280_MultipleReadTwo(0x98);\n"
  1426. +" dig_P7 = bmp280_MultipleReadTwo(0x9A);\n"
  1427. +" dig_P8 = bmp280_MultipleReadTwo(0x9C);\n"
  1428. +" dig_P9 = bmp280_MultipleReadTwo(0x9E);\n")
  1429. pin_code=(" adc_T=bmp280_T_MultipleReadThree();\n"
  1430. +" adc_P=bmp280_P_MultipleReadThree();\n"
  1431. +" double var1, var2,t_fine;\n"
  1432. +" var1 = (((double) adc_T) / 16384.0 - ((double) dig_T1) / 1024.0)* ((double) dig_T2);\n"
  1433. +" 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"
  1434. +" t_fine = (int32_t) (var1 + var2);\n"
  1435. +" double temperature = (var1 + var2) / 5120.0;\n"
  1436. +" double pressure;\n"
  1437. +" var1 = (t_fine / 2.0) - 64000.0;\n"
  1438. +" var2 = var1 * var1 * ((double) dig_P6) / 32768.0;\n"
  1439. +" var2 = var2 + var1 * ((double) dig_P5) * 2.0;\n"
  1440. +" var2 = (var2 / 4.0) + (((double) dig_P4) * 65536.0);\n"
  1441. +" var1 = (((double) dig_P3) * var1 * var1 / 524288.0+ ((double) dig_P2) * var1) / 524288.0;\n"
  1442. +" var1 = (1.0 + var1 / 32768.0) * ((double) dig_P1);\n"
  1443. +" if (var1 == 0.0)\n"
  1444. +" {\n"
  1445. +" var1 = 0;\n"
  1446. +" }\n"
  1447. +" pressure = 1048576.0 - (double) adc_P;\n"
  1448. +" pressure = (pressure - (var2 / 4096.0)) * 6250.0 / var1;\n"
  1449. +" var1 = ((double) dig_P9) * pressure * pressure / 2147483648.0;"
  1450. +" var2 = pressure * ((double) dig_P8) / 32768.0;\n"
  1451. +" pressure = pressure + (var1 + var2 + ((double) dig_P7)) / 16.0;\n"
  1452. +" cmd[1]=pressure/10000; \n"
  1453. +" int pa =pressure;\n"
  1454. +" cmd[2]=(pa%10000)/100;\n"
  1455. +" cmd[3]=(pa%10000)%100;\n"
  1456. +" HAL_UART_Transmit(&huart4, (uint8_t *)cmd, sizeof(cmd),1);\n")
  1457. pin_add_code=("HAL_StatusTypeDef AT24C04_Write(I2C_HandleTypeDef *hi2c,uint16_t MemAddress,uint8_t *pData)\n"
  1458. +"{\n"
  1459. +" Status = HAL_I2C_Mem_Write(&hi2c1, ADDR_AT24C04_WRITE_FIRST_16_PAGES, MemAddress, I2C_MEMADD_SIZE_8BIT, pData, AT24C04_PAGE_SIZE, AT24C04_TIMEOUT);\n"
  1460. +" return Status;\n"
  1461. +"}\n"
  1462. +"HAL_StatusTypeDef AT24C04_Read(I2C_HandleTypeDef *hi2c,uint16_t MemAddress,uint8_t *pData)\n"
  1463. +"{\n"
  1464. +" Status = HAL_I2C_Mem_Read(&hi2c1, ADDR_AT24C04_READ, MemAddress, I2C_MEMADD_SIZE_8BIT, pData, BUFFER_SIZE, AT24C04_TIMEOUT);\n"
  1465. +" return Status;\n"
  1466. +"}\n"
  1467. +" long bmp280_T_MultipleReadThree()\n"
  1468. +"{\n"
  1469. +" uint8_t msb, lsb, xlsb;\n"
  1470. +" int32_t temp = 0;\n"
  1471. +" AT24C04_Read(&hi2c1,0xfa,ReadBuffer);\n"
  1472. +" msb=ReadBuffer[0];\n"
  1473. +" AT24C04_Read(&hi2c1,0xfb,ReadBuffer);\n"
  1474. +" lsb=ReadBuffer[0];\n"
  1475. +" AT24C04_Read(&hi2c1,0xfc,ReadBuffer);\n"
  1476. +" xlsb=ReadBuffer[0];\n"
  1477. +" temp = ((msb << 12)|(lsb << 4)|(xlsb >> 4));\n"
  1478. +" return temp;\n"
  1479. +"}\n"
  1480. +"long bmp280_P_MultipleReadThree()\n"
  1481. +"{\n"
  1482. +" uint8_t msb, lsb, xlsb;\n"
  1483. +" int32_t pressure = 0;\n"
  1484. +" AT24C04_Read(&hi2c1,0xf7,ReadBuffer);\n"
  1485. +" msb=ReadBuffer[0];\n"
  1486. +" AT24C04_Read(&hi2c1,0xf8,ReadBuffer);\n"
  1487. +" lsb=ReadBuffer[0];\n"
  1488. +" AT24C04_Read(&hi2c1,0xf9,ReadBuffer);\n"
  1489. +" xlsb=ReadBuffer[0];\n"
  1490. +" pressure = ((msb << 12)|(lsb << 4)|(xlsb >> 4));\n"
  1491. +" return pressure;\n"
  1492. +"}\n"
  1493. +" short bmp280_MultipleReadTwo(uint16_t addr )\n"
  1494. +"{\n"
  1495. +" uint8_t msb, lsb;\n"
  1496. +" uint16_t temp = 0;\n"
  1497. +" AT24C04_Read(&hi2c1,addr,ReadBuffer);\n"
  1498. +" lsb = ReadBuffer[0];\n"
  1499. +" AT24C04_Read(&hi2c1,addr+1,ReadBuffer);\n"
  1500. +" msb = ReadBuffer[0];\n"
  1501. +" temp = msb << 8|lsb;\n"
  1502. +" return temp;\n"
  1503. +"}\n")
  1504. else:
  1505. pin_variables=""
  1506. pin_code=""
  1507. pin_add_code=""
  1508. init_code=""
  1509. sensor_code=""
  1510. def motor(pin_position,pin_type):
  1511. global act_code,init_code
  1512. global sensor_code
  1513. if pin_type =="Motor":
  1514. print("motor ok")
  1515. sensor_code=("void user_pwm_setvalue(uint16_t value);\n"
  1516. +"void user_pwm_setvalue2(uint16_t value);\n")
  1517. act_code=("void user_pwm_setvalue(uint16_t value)\n"
  1518. +"{\n"
  1519. +" TIM_OC_InitTypeDef sConfigOC;\n"
  1520. +" sConfigOC.OCMode = TIM_OCMODE_PWM1;\n"
  1521. +" sConfigOC.Pulse = value;\n"
  1522. +" sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;\n"
  1523. +" sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;\n"
  1524. +" HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1);\n"
  1525. +" HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);\n"
  1526. +"}\n")
  1527. init_code=(" MX_TIM2_Init();\n")
  1528. else:
  1529. act_code=""
  1530. init_code=""
  1531. sensor_code=""
  1532. def zigbee(pin_type):
  1533. global pin_variables,pin_code,init_code
  1534. if pin_type =="ON":
  1535. print("zigbee ok")
  1536. pin_variables=("uint8_t zigbeecmd1[5]={0xFE,0x00,0x01,0x00,0x01};\n"
  1537. +"uint8_t zigbeecmd2[5]={0xFE,0x00,0x02,0x00,0x02};\n"
  1538. +"uint8_t zigbeestatu[20];\n"
  1539. +"uint8_t zigbeestatu1[5];\n"
  1540. +'uint8_t zigbeecon[7]="connect";\n'
  1541. +'uint8_t zigbeenotcon[11]="not connect";\n'
  1542. +'uint8_t zigbeechang[14]="change is down";\n')
  1543. init_code=(" HAL_UART_Transmit(&huart2, (uint8_t *)zigbeecmd2, sizeof(zigbeecmd2), 10);\n"
  1544. +" HAL_UART_Receive(&huart2, (uint8_t *)zigbeestatu,sizeof(zigbeestatu),2000);\n"
  1545. +" HAL_UART_Transmit(&huart4, (uint8_t *)zigbeestatu, sizeof(zigbeestatu),10);\n"
  1546. +" HAL_UART_Transmit(&huart2, (uint8_t *)zigbeecmd1, sizeof(zigbeecmd1), 10);\n"
  1547. +" HAL_UART_Receive(&huart2, (uint8_t *)zigbeestatu,sizeof(zigbeestatu),2000);\n"
  1548. +" HAL_UART_Transmit(&huart4, (uint8_t *)zigbeestatu, sizeof(zigbeestatu),10);\n"
  1549. +" if (zigbeestatu[18]== 0x01)\n"
  1550. +" {\n"
  1551. +" HAL_UART_Transmit(&huart4, (uint8_t *)zigbeecon, sizeof(zigbeecon),10);\n"
  1552. +" }\n"
  1553. +" else if(zigbeestatu[18]== 0x05 || zigbeestatu[18]== 0x00)\n"
  1554. +" {\n"
  1555. +" HAL_UART_Transmit(&huart4, (uint8_t *)zigbeenotcon, sizeof(zigbeenotcon),10);\n"
  1556. +" }\n")
  1557. else:
  1558. pin_variables=""
  1559. pin_code=""
  1560. init_code=""
  1561. # 控制板燒錄:生成 main.c
  1562. @main.route('/creat_hex')
  1563. def creat_hex():
  1564. info = request.args.to_dict()
  1565. print("info: ", info)
  1566. # 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'}
  1567. # 'mainLength': '1', 'addLength': '0', 'comLength': '22', '
  1568. z_range = int(info['mainLength']) + 1
  1569. x_range = int(info['addLength']) + 1
  1570. y_range = int(info['comLength']) + 1
  1571. tank_num_data = info['tank_num']
  1572. # print("tank_num_data: ", tank_num_data)
  1573. cond_main_all_list = []
  1574. for z in range(1, z_range):
  1575. # 初始
  1576. cond_main_all_dict = {}
  1577. cond_add_list = [] # 附加條件 List
  1578. cond_com_list = [] # 物件動作 List
  1579. # cond_main_dict_all = {}
  1580. # cond_add_dict_all = {}
  1581. # cond_com_dict_all = {}
  1582. # print(z)
  1583. # 總條件
  1584. try:
  1585. cond_main_all_dict['cond_main'] = info['cond_main' + str(z)]
  1586. except(KeyError):
  1587. pass
  1588. # print("cond_main_dict: ", cond_main_dict)
  1589. # 附加條件
  1590. for x in range(1, x_range):
  1591. try:
  1592. cond_add_list.append(info['cond_add' + str(z) + '_' + str(x)])
  1593. except(KeyError):
  1594. pass
  1595. # print("cond_add_list: ", cond_add_list)
  1596. cond_main_all_dict['cond_add'] = cond_add_list
  1597. # print("cond_main_dict: ", cond_main_dict)
  1598. # 物件動作
  1599. for y in range(1, y_range):
  1600. try:
  1601. cond_com_list.append(info['cond_com' + str(z) + '_' + str(y)])
  1602. except(KeyError):
  1603. pass
  1604. # print("cond_com_list: ", cond_com_list)
  1605. cond_main_all_dict['cond_com'] = cond_com_list
  1606. # print("cond_main_dict: ", cond_main_dict)
  1607. if cond_com_list != []:
  1608. cond_main_all_list.append(cond_main_all_dict)
  1609. # cond_main_all_list.append(cond_add_dict_all)
  1610. # cond_main_all_list.append(cond_com_dict_all)
  1611. print("cond_main_all_list: ", cond_main_all_list)
  1612. # 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']}]
  1613. dry_block_sehedule = {'command':'Dry_OTA', 'tank_num':tank_num_data, 'cond':cond_main_all_list}
  1614. msg = dry_block_sehedule
  1615. # ===== 阿超 CTO.py 程式碼 start ========================================================================================
  1616. # msg = request.args.to_dict()
  1617. print("/creat_hex/<msg> msg: ", msg)
  1618. CURRENT_PATH = os.path.dirname(__file__)
  1619. print("CURRENT_PATH: ", CURRENT_PATH)
  1620. f = open(CURRENT_PATH + "//CTO20220622//Src//main.c", mode='w')
  1621. f.write("/* USER CODE BEGIN Header */\n"
  1622. +"/**\n"
  1623. +" ******************************************************************************\n"
  1624. +" * @file : main.c\n"
  1625. +" * @brief : Main program body\n"
  1626. +" * @attention\n"
  1627. +" *\n"
  1628. +" * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics.\n"
  1629. +" * All rights reserved.</center></h2>\n"
  1630. +" *\n"
  1631. +" * This software component is licensed by ST under BSD 3-Clause license,\n"
  1632. +" * the License; You may not use this file except in compliance with the\n"
  1633. +" * License. You may obtain a copy of the License at:\n"
  1634. +" * www.st.com/SLA0044\n"
  1635. +" *\n"
  1636. +" ******************************************************************************\n"
  1637. +" */\n"
  1638. +"/* USER CODE END Header */\n"
  1639. +"\n"
  1640. +"/* Includes ------------------------------------------------------------------*/\n")
  1641. # 添加標題檔
  1642. header = ('#include"main.h"\n'
  1643. +'#include "adc.h"\n'
  1644. +'#include "usart.h"\n'
  1645. +'#include "i2c.h"\n'
  1646. +'#include "tim.h"\n'
  1647. +'#include "stm32f4xx_hal.h"\n'
  1648. +'#include "gpio.h"\n')
  1649. f.write(header)
  1650. # 變數宣告說明
  1651. f.write("\n"
  1652. + "/* Private variables ---------------------------------------------------------*/\n")
  1653. f.write("\n"
  1654. + "/* Private variables ---------------------------------------------------------*/\n"
  1655. + "#define VECT_TAB_OFFSET 0x10000\n"
  1656. + "int tankstatus = 0;\n")
  1657. # 連接資料庫
  1658. #conn = sqlite3.connect('/home/pi/coffee.db')
  1659. # conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffeemanage', passwd='skyeye', database='CoffeeManage', charset='utf8')
  1660. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='Gold@53743001', database='CoffeeManage', charset='utf8')
  1661. c = conn.cursor()
  1662. print("connect success")
  1663. # 搜尋最新腳位配置時間
  1664. c.execute("SELECT *from coffee1_0_pin ORDER BY datetime ASC")
  1665. results = c.fetchall()
  1666. for row in results:
  1667. time = row[1]
  1668. c.execute("SELECT *from coffee1_0_pin where datetime='%s'"\
  1669. %(time))
  1670. results=c.fetchall()
  1671. for row in results:
  1672. for i in range (19):
  1673. row[i+26]
  1674. if(row[5]=="ON"):
  1675. print("zigbee on")
  1676. zigbee(row[5])
  1677. f.write(pin_variables)
  1678. for i in range (19):
  1679. if(i==3 or i==4 or i==6):
  1680. PH("M"+str(i+1),row[i+26])
  1681. f.write(pin_variables)
  1682. DO("M"+str(i+1),row[i+26])
  1683. f.write(pin_variables)
  1684. ORP("M"+str(i+1),row[i+26])
  1685. f.write(pin_variables)
  1686. if(i==13 or i== 16):
  1687. SHT11("M"+str(i+1),row[i+26])
  1688. f.write(pin_variables)
  1689. if(i==13 or i== 15):
  1690. DS18B20("M"+str(i+1),row[i+26])
  1691. f.write(pin_variables)
  1692. if(i==14):
  1693. BMP280("M"+str(i+1),row[i+26])
  1694. f.write(pin_variables)
  1695. if(i==5 or i==12):
  1696. SEN0189("M"+str(i+1),row[i+26])
  1697. f.write(pin_variables)
  1698. if(i==0):
  1699. SonicESMUS07("M"+str(i+1),row[i+26])
  1700. f.write(pin_variables)
  1701. if(i==7):
  1702. SOIL("M"+str(i+1),row[i+26])
  1703. f.write(pin_variables)
  1704. if(i==8 or i==11 or i==18 or i==10):
  1705. WATERLEVEL("M"+str(i+1),row[i+26])
  1706. f.write(pin_variables)
  1707. motorfeedback("M"+str(i+1),row[i+26])
  1708. f.write(pin_variables)
  1709. butterflyvalvefeedback("M"+str(i+1),row[i+26])
  1710. f.write(pin_variables)
  1711. if(i==15):
  1712. EC("M"+str(i+1),row[i+26])
  1713. f.write(pin_variables)
  1714. #感測器和致動器副函式宣告----------------------------------------------------------------
  1715. f.write("/* USER CODE BEGIN PV */\n"
  1716. +"typedef void (*pFunction)(void);\n"
  1717. +"/* USER CODE END PV */\n"
  1718. +"/* Private function prototypes -----------------------------------------------*/\n"
  1719. +"void SystemClock_Config(void);\n"
  1720. +"void MX_ADC1_Init1(char pin);\n"
  1721. +"void sensor(void);\n")
  1722. #感測器和致動器副函式宣告----------------------------------------------------------------
  1723. #連接資料庫
  1724. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='Gold@53743001', database='CoffeeManage', charset='utf8')
  1725. c = conn.cursor()
  1726. print ("connect success")
  1727. #搜尋最新腳位配置時間
  1728. c.execute("SELECT *from coffee1_0_pin ORDER BY datetime ASC")
  1729. results=c.fetchall()
  1730. for row in results:
  1731. time = row[1]
  1732. #腳位配置加入
  1733. c.execute("SELECT *from coffee1_0_pin where datetime='%s'"\
  1734. %(time))
  1735. results=c.fetchall()
  1736. for row in results:
  1737. for i in range (19):
  1738. row[i+26]
  1739. for i in range (19):
  1740. if(i==13 or i== 16):
  1741. SHT11("M"+str(i+1),row[i+26])
  1742. f.write(sensor_code)
  1743. if(i==13 or i== 15):
  1744. DS18B20("M"+str(i+1),row[i+26])
  1745. f.write(sensor_code)
  1746. if(i==14):
  1747. BMP280("M"+str(i+1),row[i+26])
  1748. f.write(sensor_code)
  1749. if(i==9):
  1750. motor("M"+str(i+1),row[i+26])
  1751. f.write(sensor_code)
  1752. f.write("/* USER CODE BEGIN PFP */\n"
  1753. +"/* USER CODE END PFP */\n"
  1754. +"/* Private user code ---------------------------------------------------------*/\n"
  1755. +"/* USER CODE BEGIN 0 */\n"
  1756. +"/* USER CODE END 0 */\n"
  1757. +"/**\n"
  1758. +"* @brief The application entry point.\n"
  1759. +"* @retval int\n"
  1760. +"*/\n")
  1761. #主程式撰寫--------------------------------------------------------------------------------
  1762. #main宣告
  1763. f.write("int main(void)\n"
  1764. +"{\n"
  1765. +" SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET;\n")
  1766. #致能週邊---------------------------------------------------------------------------------------
  1767. enable=(" HAL_Init();\n"
  1768. +" SystemClock_Config();\n"
  1769. +" MX_GPIO_Init();\n"
  1770. +" MX_USART2_UART_Init();\n"
  1771. +" MX_UART4_Init();\n"
  1772. +" MX_USART1_UART_Init();\n")
  1773. f.write(enable)
  1774. #連接資料庫
  1775. # conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffeemanage', passwd='skyeye', database='CoffeeManage', charset='utf8')
  1776. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='Gold@53743001', database='CoffeeManage', charset='utf8')
  1777. #conn = sqlite3.connect('/home/pi/coffee.db')
  1778. c = conn.cursor()
  1779. print("connect success")
  1780. #搜尋最新腳位配置時間
  1781. c.execute("SELECT *from coffee1_0_pin ORDER BY datetime ASC")
  1782. results = c.fetchall()
  1783. for row in results:
  1784. time = row[1]
  1785. # 腳位配置加入
  1786. c.execute("SELECT *from coffee1_0_pin where datetime='%s'"
  1787. % (time))
  1788. results = c.fetchall()
  1789. for row in results:
  1790. for i in range(19):
  1791. row[i+26]
  1792. if(row[5]=="ON"):
  1793. print("zigbee on")
  1794. zigbee(row[5])
  1795. f.write(init_code)
  1796. for i in range (19):
  1797. if(i==14):
  1798. BMP280("M"+str(i+1),row[i+26])
  1799. f.write(init_code)
  1800. if(i==9):
  1801. motor("M"+str(i+1),row[i+26])
  1802. f.write(init_code)
  1803. #---------------------------------------------------------------------------------------------
  1804. code=(" while (1)\n"
  1805. +" {\n"
  1806. +" sensor();\n")
  1807. f.write(code)
  1808. #MQTT條件分析寫入--------------------------------------------------------------------------------
  1809. for i in range (len(msg['cond'])):
  1810. m=msg['cond'][i]['cond_main'].split(" ")
  1811. if(m[0]=="else" and m[1]=="if"):
  1812. m[0]=m[0]+" "+m[1]
  1813. m[1]=m[1]
  1814. m[2]=m[2]
  1815. m[3]=m[3]
  1816. m[4]=m[4]
  1817. m=""+m[0]+"("+m[1]+m[2]+m[3]
  1818. f.write(" "+m)
  1819. if(m[0] == " "):
  1820. m = ""
  1821. else:
  1822. print(len(msg['cond'][i]['cond_add']))
  1823. if(len(msg['cond'][i]['cond_add'])==0):
  1824. add=")\n"
  1825. f.write(add)
  1826. else:
  1827. for j in range (len(msg['cond'][i]['cond_add'])):
  1828. if(j==len(msg['cond'][i]['cond_add'])-1):
  1829. if(msg['cond'][i]['cond_add'][j]==" "):
  1830. add=")\n"
  1831. else:
  1832. add=" "+str(msg['cond'][i]['cond_add'][j])+")\n"
  1833. f.write(add)
  1834. else:
  1835. if(msg['cond'][i]['cond_add'][j]==" "):
  1836. add=""
  1837. else:
  1838. add=" "+str(msg['cond'][i]['cond_add'][j])
  1839. f.write(add)
  1840. f.write(" {\n")
  1841. for j in range(len(msg['cond'][i]['cond_com'])):
  1842. if(j == len(msg['cond'][i]['cond_com'])-1):
  1843. if(msg['cond'][i]['cond_com'][j] == " "):
  1844. com = "\n}\n"
  1845. else:
  1846. com = msg['cond'][i]['cond_com'][j].split("_")
  1847. comm = msg['cond'][i]['cond_com'][j].split(" ")
  1848. if(comm[0] == "sleep"):
  1849. com[0] = comm[0]
  1850. com = " "+GPIO(com[0], comm[1])+"\n }\n"
  1851. f.write(com)
  1852. else:
  1853. if(msg['cond'][i]['cond_com'][j] == " "):
  1854. com = ""
  1855. else:
  1856. com = msg['cond'][i]['cond_com'][j].split("_")
  1857. comm = msg['cond'][i]['cond_com'][j].split(" ")
  1858. if(comm[0] == "sleep"):
  1859. com[0] = comm[0]
  1860. com = " "+GPIO(com[0], comm[1])+"\n"
  1861. f.write(com)
  1862. f.write(" }\n")
  1863. f.write("}\n")
  1864. # 系統時鐘宣告
  1865. time = ("void SystemClock_Config(void)\n"
  1866. + "{\n"
  1867. + " RCC_OscInitTypeDef RCC_OscInitStruct = {0};\n"
  1868. + " RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};\n"
  1869. + " __HAL_RCC_PWR_CLK_ENABLE();\n"
  1870. + " __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);\n"
  1871. + " RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;\n"
  1872. + " RCC_OscInitStruct.HSIState = RCC_HSI_ON;\n"
  1873. + " RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;\n"
  1874. + " RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;\n"
  1875. + " RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;\n"
  1876. + " RCC_OscInitStruct.PLL.PLLM = 8;\n"
  1877. + " RCC_OscInitStruct.PLL.PLLN = 72;\n"
  1878. + " RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;\n"
  1879. + " RCC_OscInitStruct.PLL.PLLQ = 3;\n"
  1880. + " RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;\n"
  1881. + " if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)\n"
  1882. + " {\n"
  1883. + " Error_Handler();\n"
  1884. + " }\n"
  1885. + " RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK\n"
  1886. + " |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;\n"
  1887. + " RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;\n"
  1888. + " RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;\n"
  1889. + " RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;\n"
  1890. + " RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;\n"
  1891. + " if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)\n"
  1892. + " {\n"
  1893. + " Error_Handler();\n"
  1894. + " }\n"
  1895. + "}\n")
  1896. f.write(time)
  1897. #馬達和伺服馬達副函式------------------------------------------------------------------------------
  1898. add_code2=("void user_pwm_setvalue(uint16_t value)\n"
  1899. +"{\n"
  1900. +" TIM_OC_InitTypeDef sConfigOC;\n"
  1901. +" sConfigOC.OCMode = TIM_OCMODE_PWM1;\n"
  1902. +" sConfigOC.Pulse = value;\n"
  1903. +" sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;\n"
  1904. +" sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;\n"
  1905. +" HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1);\n"
  1906. +" HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);\n"
  1907. +"}\n"
  1908. +"void user_pwm_setvalue2(uint16_t value)\n"
  1909. +"{\n"
  1910. +" TIM_OC_InitTypeDef sConfigOC;\n"
  1911. +" sConfigOC.OCMode = TIM_OCMODE_PWM1;\n"
  1912. +" sConfigOC.Pulse = value;\n"
  1913. +" sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;\n"
  1914. +" sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;\n"
  1915. +" HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_2);\n"
  1916. +" HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_2);\n"
  1917. +"}\n")
  1918. f.write(add_code2)
  1919. #感測器程式-----------------------------------------------------------------------------------------------------
  1920. sensor=("void sensor(void)\n"
  1921. +"{\n")
  1922. f.write(sensor)
  1923. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='Gold@53743001', database='CoffeeManage', charset='utf8')
  1924. #conn = sqlite3.connect('/home/pi/coffee.db')
  1925. c = conn.cursor()
  1926. print ("connect success")
  1927. #搜尋最新腳位配置時間
  1928. c.execute("SELECT *from coffee1_0_pin ORDER BY datetime ASC")
  1929. results = c.fetchall()
  1930. for row in results:
  1931. time = row[1]
  1932. #腳位配置加入
  1933. c.execute("SELECT *from coffee1_0_pin where datetime='%s'"\
  1934. %(time))
  1935. results = c.fetchall()
  1936. for row in results:
  1937. for i in range (19):
  1938. row[i+26]
  1939. if(row[5]=="ON"):
  1940. print("zigbee on")
  1941. zigbee(row[5])
  1942. f.write(pin_code)
  1943. for i in range (19):
  1944. if(i==3 or i==4 or i==6):
  1945. PH("M"+str(i+1),row[i+26])
  1946. f.write(pin_code)
  1947. DO("M"+str(i+1),row[i+26])
  1948. f.write(pin_code)
  1949. ORP("M"+str(i+1),row[i+26])
  1950. f.write(pin_code)
  1951. if(i==13 or i== 16):
  1952. SHT11("M"+str(i+1),row[i+26])
  1953. f.write(pin_code)
  1954. if(i==13 or i== 15):
  1955. DS18B20("M"+str(i+1),row[i+26])
  1956. f.write(pin_code)
  1957. if(i==14):
  1958. BMP280("M"+str(i+1),row[i+26])
  1959. f.write(pin_code)
  1960. if(i==5 or i==12):
  1961. SEN0189("M"+str(i+1),row[i+26])
  1962. f.write(pin_code)
  1963. if(i==0):
  1964. SonicESMUS07("M"+str(i+1),row[i+26])
  1965. f.write(pin_code)
  1966. if(i==7):
  1967. SOIL("M"+str(i+1),row[i+26])
  1968. f.write(pin_code)
  1969. if(i==8 or i==11 or i==18 or i==10):
  1970. WATERLEVEL("M"+str(i+1),row[i+26])
  1971. f.write(pin_code)
  1972. motorfeedback("M"+str(i+1),row[i+26])
  1973. f.write(pin_code)
  1974. butterflyvalvefeedback("M"+str(i+1),row[i+26])
  1975. f.write(pin_code)
  1976. if(i==15):
  1977. EC("M"+str(i+1),row[i+26])
  1978. f.write(pin_code)
  1979. sensor=(" HAL_Delay(10000);\n"
  1980. +"}\n")
  1981. f.write(sensor)
  1982. #加入感測器副函式程式碼-------------------------------------------------------------------------------
  1983. conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='Gold@53743001', database='CoffeeManage', charset='utf8')
  1984. c = conn.cursor()
  1985. print ("connect success")
  1986. #搜尋最新腳位配置時間
  1987. c.execute("SELECT *from coffee1_0_pin ORDER BY datetime ASC")
  1988. results = c.fetchall()
  1989. for row in results:
  1990. time = row[1]
  1991. #腳位配置加入
  1992. c.execute("SELECT *from coffee1_0_pin where datetime='%s'"\
  1993. %(time))
  1994. results = c.fetchall()
  1995. for row in results:
  1996. for i in range (19):
  1997. row[i+26]
  1998. for i in range (19):
  1999. if(i==13 or i== 16):
  2000. SHT11("M"+str(i+1),row[i+26])
  2001. f.write(pin_add_code)
  2002. if(i==13 or i== 15):
  2003. DS18B20("M"+str(i+1),row[i+26])
  2004. f.write(pin_add_code)
  2005. if(i==14):
  2006. BMP280("M"+str(i+1),row[i+26])
  2007. f.write(pin_add_code)
  2008. if(i==0):
  2009. SonicESMUS07("M"+str(i+1),row[i+26])
  2010. f.write(pin_add_code)
  2011. if(i==7):
  2012. SOIL("M"+str(i+1),row[i+26])
  2013. f.write(pin_add_code)
  2014. if(i==15):
  2015. EC("M"+str(i+1),row[i+26])
  2016. f.write(pin_add_code)
  2017. #ADC程式宣告----------------------------------------------------------------------------------
  2018. gpio=("void MX_ADC1_Init1(char pin)\n"
  2019. +"{\n"
  2020. +" ADC_ChannelConfTypeDef sConfig = {0};\n"
  2021. +" hadc1.Instance = ADC1;\n"
  2022. +" hadc1.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;\n"
  2023. +" hadc1.Init.Resolution = ADC_RESOLUTION_12B;\n"
  2024. +" hadc1.Init.ScanConvMode = DISABLE;\n"
  2025. +" hadc1.Init.ContinuousConvMode = DISABLE;\n"
  2026. +" hadc1.Init.DiscontinuousConvMode = DISABLE;\n"
  2027. +" hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;\n"
  2028. +" hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;\n"
  2029. +" hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;\n"
  2030. +" hadc1.Init.NbrOfConversion = 1;\n"
  2031. +" hadc1.Init.DMAContinuousRequests = DISABLE;\n"
  2032. +" hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;\n"
  2033. +" if (HAL_ADC_Init(&hadc1) != HAL_OK)\n"
  2034. +" {\n"
  2035. +" Error_Handler();\n"
  2036. +" }\n"
  2037. +" sConfig.Channel = pin;\n"
  2038. +" sConfig.Rank = 1;\n"
  2039. +" sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;\n"
  2040. +" if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)\n"
  2041. +" {\n"
  2042. +" Error_Handler();\n"
  2043. +" }\n"
  2044. +"}\n")
  2045. f.write(gpio)
  2046. #GPIO input程式宣告----------------------------------------------------------------------------------
  2047. gpio2=("void MX_GPIO_Input1(unsigned long pin)\n"
  2048. +"{\n"
  2049. +" GPIO_InitTypeDef GPIO_InitStruct = {0};\n"
  2050. +" __HAL_RCC_GPIOE_CLK_ENABLE();\n"
  2051. +" GPIO_InitStruct.Pin = pin;\n"
  2052. +" GPIO_InitStruct.Mode = GPIO_MODE_INPUT;\n"
  2053. +" GPIO_InitStruct.Pull = GPIO_PULLDOWN;\n"
  2054. +" HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);\n"
  2055. +"}\n")
  2056. f.write(gpio2)
  2057. #錯誤程式-------------------------------------------------------------------------------------
  2058. f.write("void Error_Handler(void)\n{\n}\n")
  2059. f.close()
  2060. f = open(CURRENT_PATH + "//CTO20220622//Src//main.c", mode='r')
  2061. words = f.read()
  2062. # print(words)
  2063. f.close()
  2064. # server_log(msg['command'], "D1", "ok") # 06/15 Rita 原為阿超丟 MQTT 給網頁, 先註解
  2065. # ===== 阿超 CTO.py 程式碼 end ========================================================================================
  2066. # ===== 編譯 CTO20220622整個資料夾並在build資料夾生成所需的hex檔 start ========================
  2067. cwdDATA = os.path.join(CURRENT_PATH, "CTO20220622")
  2068. print("cwdDATA: ", cwdDATA)
  2069. # 以下指令要在 Linux 上測試, Windows 未安裝會報錯
  2070. # make_result = 0
  2071. make_result = subprocess.call(["sudo", "make"],cwd = cwdDATA)
  2072. # ===== 編譯 CTO20220622整個資料夾並在build資料夾生成所需的hex檔 end ========================
  2073. if make_result == 0:
  2074. return "OK"
  2075. else:
  2076. return "NG"
  2077. # 2023 控制板燒錄:生成hex檔
  2078. @main.route('/make_hex')
  2079. def make_hex():
  2080. # ===== 編譯 CTO20220622整個資料夾並在build資料夾生成所需的hex檔 start ========================
  2081. CURRENT_PATH = os.path.dirname(__file__)
  2082. print("CURRENT_PATH: ", CURRENT_PATH)
  2083. cwdDATA = os.path.join(CURRENT_PATH, "CTO20220622")
  2084. print("cwdDATA: ", cwdDATA)
  2085. # 以下指令要在 Linux 上測試, Windows 未安裝會報錯
  2086. # make_result = 0
  2087. make_result = subprocess.call(["sudo", "make"],cwd = cwdDATA)
  2088. # ===== 編譯 CTO20220622整個資料夾並在build資料夾生成所需的hex檔 end ========================
  2089. if make_result == 0:
  2090. result = {"pass": "pass"}
  2091. else:
  2092. result = {"pass": "NG"}
  2093. return json.dumps(result)
  2094. #
  2095. @main.route('/loader', methods=['GET', 'POST'])
  2096. def loader():
  2097. info = request.args.to_dict()
  2098. # print("info: ", info)
  2099. ethernet_list = info['ethernet_list']
  2100. print("ethernet_list: ", ethernet_list, type(ethernet_list))
  2101. wifi_list = info['wifi_list']
  2102. print("wifi_list: ", wifi_list, type(wifi_list))
  2103. zigbee_list = info['zigbee_list']
  2104. print("zigbee_list: ", zigbee_list, type(zigbee_list))
  2105. # 將 string 以 , 分割成 list
  2106. relay_list = info['relay_list'].split(',')
  2107. print("relay_list: ", relay_list, type(relay_list))
  2108. pwm_list = info['pwm_list'].split(',')
  2109. print("pwm_list: ", pwm_list, type(pwm_list))
  2110. digital_list = info['digital_list'].split(',')
  2111. print("digital_list: ", digital_list, type(digital_list))
  2112. uart_list = info['uart_list'].split(',')
  2113. print("uart_list: ", uart_list, type(uart_list))
  2114. i2c_list = info['i2c_list'].split(',')
  2115. print("i2c_list: ", i2c_list, type(i2c_list))
  2116. s485_list = info['s485_list'].split(',')
  2117. print("s485_list: ", s485_list, type(s485_list))
  2118. ppa_list = info['ppa_list'].split(',')
  2119. print("ppa_list: ", ppa_list, type(ppa_list))
  2120. return jsonify({"response":"OK" })
  2121. # # Rita 測試
  2122. @main.route('/drop_down_list')
  2123. def drop_down_list():
  2124. # 獲取登入信息
  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. # TODO
  2133. mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffee',
  2134. password='skyeye', database='Coffee', charset='utf8')
  2135. mycursor = mydb.cursor()
  2136. conn = pymysql.connect(
  2137. host='52.69.200.169',
  2138. port=3306,
  2139. user='coffee',
  2140. password='skyeye',
  2141. database='Coffee',
  2142. charset='utf8'
  2143. )
  2144. cur = conn.cursor()
  2145. #獲取欄位資料
  2146. sql = "select * from product_info"
  2147. cur.execute(sql)
  2148. content = cur.fetchall()
  2149. #獲取欄位名稱
  2150. sql = "SHOW FIELDS FROM product_info"
  2151. cur.execute(sql)
  2152. labels = cur.fetchall()
  2153. # print("labels: ", labels) # labels: (('產品', 'varchar(4)', 'YES', '', None, ''), ('系統', 'varchar(5)', 'YES', '', None, ''),
  2154. labels = [g[0] for g in labels]
  2155. # print("labels: ", labels) # labels: ['產品', '系統', '系統圖號', '狀態', '進貨狀態', '序號', '組序號',
  2156. return render_template('drop_down_list.html', labels=labels, content=content)
  2157. else:
  2158. return render_template('sign_in.html')
  2159. # !!! AttributeError: 'NoneType' object has no attribute 'vacuum'
  2160. @main.route('/loading/container', methods=['GET', 'POST'])
  2161. def container_loading():
  2162. if request.method == 'GET':
  2163. # 清洗浮選狀態
  2164. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  2165. Clean_container_status_list = [clean_status.Clean_Tank_1,
  2166. clean_status.Clean_Tank_2,
  2167. clean_status.Clean_Tank_3,
  2168. clean_status.Clean_Tank_4]
  2169. CLEAN_Waiting_number = int(Clean_container_status_list.count('C_Waiting'))
  2170. CLEAN_Warning_number = int(Clean_container_status_list.count('C_Warning'))
  2171. if CLEAN_Waiting_number == len(Clean_container_status_list): Clean_container = 'Waiting'
  2172. elif CLEAN_Warning_number >= 1: Clean_container = 'Warning'
  2173. else: Clean_container = 'Working'
  2174. # 清洗浮選狀態
  2175. ColorSelect_container_status_list = [clean_status.ColorSelect_Tank_1,
  2176. clean_status.ColorSelect_Tank_2]
  2177. COLORSELECT_Waiting_number = int(ColorSelect_container_status_list.count('S_Waiting'))
  2178. COLORSELECT_Warning_number = int(ColorSelect_container_status_list.count('S_Warning'))
  2179. if COLORSELECT_Waiting_number == len(ColorSelect_container_status_list): ColorSelect_container = 'Waiting'
  2180. elif COLORSELECT_Warning_number >= 1: ColorSelect_container = 'Warning'
  2181. else: ColorSelect_container = 'Working'
  2182. # 脫皮機
  2183. Peel_container_status_list = [clean_status.Peel_Tank_1,
  2184. clean_status.Peel_Tank_2]
  2185. PEEL_Waiting_number = int(Peel_container_status_list.count('P_Waiting'))
  2186. PEEL_Warning_number = int(Peel_container_status_list.count('P_Warning'))
  2187. if PEEL_Waiting_number == len(Peel_container_status_list): Peel_container = 'Waiting'
  2188. elif PEEL_Warning_number >= 1: Peel_container = 'Warning'
  2189. else: Peel_container = 'Working'
  2190. # 發酵槽
  2191. ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  2192. Ferment_container_status_list = [ferment_status.Ferment_Tank_1,
  2193. ferment_status.Ferment_Tank_2,
  2194. ferment_status.Ferment_Tank_3,
  2195. ferment_status.Ferment_Tank_4,
  2196. ferment_status.Ferment_Tank_5,
  2197. ferment_status.Ferment_Tank_6,
  2198. ferment_status.Ferment_Tank_7,
  2199. ferment_status.Ferment_Tank_8,
  2200. ferment_status.Ferment_Tank_9,
  2201. ferment_status.Ferment_Tank_10,
  2202. ferment_status.Ferment_Tank_11,
  2203. ferment_status.Ferment_Tank_12]
  2204. FERMENT_Waiting_number = int(Ferment_container_status_list.count('F_Waiting'))
  2205. FERMENT_Warning_number = int(Ferment_container_status_list.count('F_Warning'))
  2206. if FERMENT_Waiting_number == len(Ferment_container_status_list): Ferment_container = 'Waiting'
  2207. elif FERMENT_Warning_number >= 1: Ferment_container = 'Warning'
  2208. else: Ferment_container = 'Working'
  2209. # 乾燥槽
  2210. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  2211. Dry_container_status_list = [dry_status.Dry_Tank_1,
  2212. dry_status.Dry_Tank_2,
  2213. dry_status.Dry_Tank_3,
  2214. dry_status.Dry_Tank_4,
  2215. dry_status.Dry_Tank_5,
  2216. dry_status.Dry_Tank_6,
  2217. dry_status.Dry_Tank_7,
  2218. dry_status.Dry_Tank_8,
  2219. dry_status.Dry_Tank_9,
  2220. dry_status.Dry_Tank_10,
  2221. dry_status.Dry_Tank_11,
  2222. dry_status.Dry_Tank_12]
  2223. DRY_Waiting_number= int(Dry_container_status_list.count('D_Waiting'))
  2224. DRY_Warning_number= int(Dry_container_status_list.count('D_Warning'))
  2225. if DRY_Waiting_number == len(Dry_container_status_list): Dry_container = 'Waiting'
  2226. elif DRY_Warning_number >= 1: Dry_container = 'Warning'
  2227. else: Dry_container = 'Working'
  2228. return jsonify({"Clean_container":Clean_container,
  2229. "ColorSelect_container":ColorSelect_container,
  2230. "Peel_container":Peel_container,
  2231. "Ferment_container":Ferment_container,
  2232. "Dry_container":Dry_container
  2233. })
  2234. @main.route('/loading_sensors', methods=['GET', 'POST'])
  2235. def loading_sensors():
  2236. C1_UltraSonic = (clean_tank_UltraSonic.query.filter_by(tank_num='C1').order_by(text('datetime desc')).first()).UltraSonic
  2237. C2_UltraSonic = (clean_tank_UltraSonic.query.filter_by(tank_num='C2').order_by(text('datetime desc')).first()).UltraSonic
  2238. PO1_UltraSonic = (peel_output_UltraSonic.query.filter_by(tank_num='PO1').order_by(text('datetime desc')).first()).UltraSonic
  2239. PO2_UltraSonic = (peel_output_UltraSonic.query.filter_by(tank_num='PO2').order_by(text('datetime desc')).first()).UltraSonic
  2240. F1_UltraSonic = (ferment_tank_UltraSonic.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()).UltraSonic
  2241. F1_SHT11Temp = (ferment_tank_SHT11.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()).SHT11_Temp
  2242. F1_SHT11Humidity = (ferment_tank_SHT11.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()).SHT11_Humidity
  2243. F2_UltraSonic = (ferment_tank_UltraSonic.query.filter_by(tank_num='F2').order_by(text('datetime desc')).first()).UltraSonic
  2244. D1_UltraSonic = (dry_tank_UltraSonic.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()).UltraSonic
  2245. D1_SHT11Temp = (dry_tank_SHT11.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()).SHT11_Temp
  2246. D1_SHT11Humidity = (dry_tank_SHT11.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()).SHT11_Humidity
  2247. D2_UltraSonic = (dry_tank_UltraSonic.query.filter_by(tank_num='D2').order_by(text('datetime desc')).first()).UltraSonic
  2248. DO1_UltraSonic = (dry_output_sensor.query.filter_by(tank_num='DO1').order_by(text('datetime desc')).first()).UltraSonic
  2249. DO2_UltraSonic = (dry_output_sensor.query.filter_by(tank_num='DO2').order_by(text('datetime desc')).first()).UltraSonic
  2250. return jsonify({"C1_UltraSonic":C1_UltraSonic,
  2251. "C2_UltraSonic":C2_UltraSonic,
  2252. "PO1_UltraSonic":PO1_UltraSonic,
  2253. "PO2_UltraSonic":PO2_UltraSonic,
  2254. "F1_UltraSonic":F1_UltraSonic,
  2255. "F1_SHT11Temp":F1_SHT11Temp,
  2256. "F1_SHT11Humidity":F1_SHT11Humidity,
  2257. "F2_UltraSonic":F2_UltraSonic,
  2258. "D1_UltraSonic":D1_UltraSonic,
  2259. "D1_SHT11Temp":D1_SHT11Temp,
  2260. "D1_SHT11Humidity":D1_SHT11Humidity,
  2261. "D2_UltraSonic":D2_UltraSonic,
  2262. "DO1_UltraSonic":DO1_UltraSonic,
  2263. "DO2_UltraSonic":DO2_UltraSonic
  2264. })
  2265. @main.route('/demo', methods=['GET', 'POST'])
  2266. def demo():
  2267. if 'id' in session and 'uname' in session and 'status' in session:
  2268. username = session['uname']
  2269. status = session['status']
  2270. if status == 9:
  2271. return render_template('signin_disable.html')
  2272. elif status == 8:
  2273. return render_template('signin_new.html')
  2274. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  2275. db.session.close()
  2276. CI1 = clean_status.Clean_Input_1
  2277. CI2 = clean_status.Clean_Input_2
  2278. C1 = clean_status.Clean_Tank_1
  2279. C2 = clean_status.Clean_Tank_2
  2280. R1 = clean_status.Reclaimed_Tank_1
  2281. S1 = clean_status.ColorSelect_Tank_1
  2282. S2 = clean_status.ColorSelect_Tank_2
  2283. P1 = clean_status.Peel_Tank_1
  2284. P2 = clean_status.Peel_Tank_2
  2285. PO1 = clean_status.Peel_Output_1
  2286. POb1 = clean_status.Peel_Output_b1
  2287. ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  2288. db.session.close()
  2289. F1 = ferment_status.Ferment_Tank_1
  2290. F2 = ferment_status.Ferment_Tank_2
  2291. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  2292. db.session.close()
  2293. D1 = dry_status.Dry_Tank_1
  2294. return render_template('demo.html', title="DEMO 貨櫃", **locals())
  2295. else:
  2296. return render_template('sign_in.html')
  2297. @main.route('/demo_auto_data', methods=['GET', 'POST'])
  2298. def demo_auto_data():
  2299. if request.method == 'GET':
  2300. try:
  2301. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  2302. db.session.close()
  2303. CI1 = clean_status.Clean_Input_1
  2304. CI2 = clean_status.Clean_Input_2
  2305. C1 = clean_status.Clean_Tank_1
  2306. C2 = clean_status.Clean_Tank_2
  2307. R1 = clean_status.Reclaimed_Tank_1
  2308. S1 = clean_status.ColorSelect_Tank_1
  2309. S2 = clean_status.ColorSelect_Tank_2
  2310. P1 = clean_status.Peel_Tank_1
  2311. P2 = clean_status.Peel_Tank_2
  2312. PO1 = clean_status.Peel_Output_1
  2313. POb1 = clean_status.Peel_Output_b1
  2314. ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  2315. db.session.close()
  2316. F1 = ferment_status.Ferment_Tank_1
  2317. F2 = ferment_status.Ferment_Tank_2
  2318. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  2319. db.session.close()
  2320. D1 = dry_status.Dry_Tank_1
  2321. dict = {"CI1":CI1, "CI2":CI2, "C1":C1, "C2":C2,"R1":R1, "S1":S1, "S2":S2, "P1":P1, "P2":P2, "PO1":PO1,"POb1":POb1,"F1":F1,"F2":F2,"D1":D1}
  2322. return json.dumps(dict)
  2323. except Exception as e:
  2324. return json.dumps({"status":None})
  2325. else:
  2326. pass
  2327. # 脫皮機自動化測試頁
  2328. @main.route('/peel_auto_status', methods=['GET', 'POST'])
  2329. def peel_auto_test():
  2330. info = request.args.to_dict()
  2331. # 寫定出料的空桶標準, 若 <= 2 則為空桶
  2332. Peel_Output_bean_empty = 2
  2333. # 從介面取得 指定生豆高度
  2334. Peel_Tank_bean_height = float(info['Peel_Tank_bean_height'])
  2335. Peel_Tank_motor_rpm = float(info['Peel_Tank_motor_rpm'])
  2336. Peel_Tank_vacuumON_time = float(info['Peel_Tank_vacuumON_time'])
  2337. Peel_Tank_vacuumOFF_time = float(info['Peel_Tank_vacuumOFF_time'])
  2338. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  2339. P1 = clean_status.Peel_Tank_1
  2340. P2 = clean_status.Peel_Tank_2
  2341. PO1 = clean_status.Peel_Output_1
  2342. PO2 = clean_status.Peel_Output_2
  2343. SO1 = 'SO_OutputtingBean' # SO_OutputtingBean SO_Waiting
  2344. SO2 = 'SO_Waiting'
  2345. # -- 取得脫皮機 P1~P2 桶內高度 UltraSonic -------------
  2346. PO_UP_tank_UltraSonic = []
  2347. for i in range(1, 3, 1):
  2348. output_UltraSonic = peel_output_UltraSonic.query.filter_by(tank_num='PO' + str(i)).order_by(text('datetime desc')).first()
  2349. UltraSonic = float(output_UltraSonic.UltraSonic)
  2350. PO_UP_tank_UltraSonic.append(UltraSonic)
  2351. print('PO_UP_tank_UltraSonic: ', PO_UP_tank_UltraSonic)
  2352. # -- 取得脫皮機 P1~P2 桶內高度 UltraSonic -------------
  2353. if P1 == 'P_Waiting' and PO1 != 'PO_OutputtingBean' and SO1 == 'SO_OutputtingBean':
  2354. P1 = 'P_Peeling'
  2355. PO1 = 'PO_InputtingBean'
  2356. print('------- P1 狀態更新:脫皮中 -------')
  2357. print('------- PO1 狀態更新:入豆中 -------')
  2358. # [致動器] 馬達 指定轉速
  2359. data = { "tank_num": "P1", "command": "tank_motor_status", "value": Peel_Tank_motor_rpm}
  2360. print('data: ', data)
  2361. # mqtt_f(data)
  2362. if P1 == 'P_Peeling':
  2363. if PO_UP_tank_UltraSonic[0] >= Peel_Tank_bean_height:
  2364. # [致動器] 真空吸料機 OFF
  2365. data = { "tank_num": "P1", "command": "tank_vacuum_status", "value": "off" }
  2366. print('data: ', data)
  2367. # mqtt_f(data)
  2368. # [致動器] 馬達 0
  2369. data = { "tank_num": "P1", "command": "tank_motor_status", "value": "0" }
  2370. print('data: ', data)
  2371. # mqtt_f(data)
  2372. P1 = 'P_Waiting'
  2373. PO1 = 'PO_OutputtingBean'
  2374. print('------- P1 狀態更新:等待中 -------')
  2375. print('------- PO1 狀態更新:可出豆 -------')
  2376. elif PO_UP_tank_UltraSonic[0] < Peel_Tank_bean_height:
  2377. # [致動器] 真空吸料機 ON
  2378. data = { "tank_num": "P1", "command": "tank_vacuum_status", "value": "on" }
  2379. print('data: ', data)
  2380. # mqtt_f(data)
  2381. timer = time.time()
  2382. while True:
  2383. if (time.time() - timer) > Peel_Tank_vacuumON_time:
  2384. # [致動器] 真空吸料機 OFF
  2385. data = { "tank_num": "P1", "command": "tank_vacuum_status", "value": "off" }
  2386. print('data: ', data)
  2387. # mqtt_f(data)
  2388. timer = time.time()
  2389. break
  2390. while True:
  2391. if (time.time() - timer) > Peel_Tank_vacuumOFF_time:
  2392. break
  2393. if PO1 == 'PO_OutputtingBean' and PO_UP_tank_UltraSonic[0] <= Peel_Output_bean_empty:
  2394. PO1 = 'PO_Waiting'
  2395. print('------- PO1 狀態更新:空桶等待 -------')
  2396. CI1 = 'CI_Warning'
  2397. CI2 = 'CI_Waiting'
  2398. C1 = 'C_Warning'
  2399. C2 = 'C_Waiting'
  2400. C3 = 'C_Waiting'
  2401. C4 = 'C_Waiting'
  2402. SI1 = 'SI_Warning'
  2403. SI2 = 'SI_Waiting'
  2404. S1 = 'S_Warning'
  2405. S2 = 'S_Waiting'
  2406. SOg1 = 'SO_Warning'
  2407. SOb1 = 'SO_Warning'
  2408. SOg2 = 'SO_Waiting'
  2409. SOb2 = 'SO_Waiting'
  2410. POb1 = 'PO_Waiting'
  2411. # ----- 將狀態寫入資料庫 ------------------------------
  2412. # 獲取文本框的值並賦值給user實體對象
  2413. C_status = clean_container_status()
  2414. C_status.Clean_Input_1 = CI1
  2415. C_status.Clean_Input_2 = CI2
  2416. C_status.Clean_Tank_1 = C1
  2417. C_status.Clean_Tank_2 = C2
  2418. C_status.Clean_Tank_3 = C3
  2419. C_status.Clean_Tank_4 = C4
  2420. C_status.ColorSelect_Input_1 = SI1
  2421. C_status.ColorSelect_Input_2 = SI2
  2422. C_status.ColorSelect_Tank_1 = S1
  2423. C_status.ColorSelect_Tank_2 = S2
  2424. C_status.ColorSelect_Output_g1 = SOg1
  2425. C_status.ColorSelect_Output_b1 = SOb1
  2426. C_status.ColorSelect_Output_g2 = SOg2
  2427. C_status.ColorSelect_Output_b2 = SOb2
  2428. C_status.Peel_Tank_1 = P1
  2429. C_status.Peel_Tank_2 = P2
  2430. C_status.Peel_Output_1 = PO1
  2431. C_status.Peel_Output_2 = PO2
  2432. C_status.Peel_Output_b1 = POb1
  2433. #將數據保存進資料庫
  2434. db.session.add(C_status)
  2435. # 手動提交
  2436. db.session.commit()
  2437. # ----- 將狀態寫入資料庫 ------------------------------
  2438. return jsonify({"Peel_Tank_1":P1,
  2439. "Peel_Tank_2":P2,
  2440. "Peel_Output_1":PO1,
  2441. "Peel_Output_2":PO2
  2442. })
  2443. # 乾燥槽狀態更新
  2444. @main.route('/dry_status_update', methods=['GET', 'POST'])
  2445. def dry_status_update():
  2446. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  2447. DI1 = dry_status.Dry_Input_1
  2448. DI2 = dry_status.Dry_Input_2
  2449. D1 = dry_status.Dry_Tank_1
  2450. D2 = dry_status.Dry_Tank_2
  2451. D3 = dry_status.Dry_Tank_3
  2452. D4 = dry_status.Dry_Tank_4
  2453. D5 = dry_status.Dry_Tank_5
  2454. D6 = dry_status.Dry_Tank_6
  2455. D7 = dry_status.Dry_Tank_7
  2456. D8 = dry_status.Dry_Tank_8
  2457. D9 = dry_status.Dry_Tank_9
  2458. D10 = dry_status.Dry_Tank_10
  2459. D11 = dry_status.Dry_Tank_11
  2460. D12 = dry_status.Dry_Tank_12
  2461. DO1 = dry_status.Dry_Output_1
  2462. DO2 = dry_status.Dry_Output_2
  2463. return jsonify({"DI1":DI1,
  2464. "DI2":DI2,
  2465. "D1":D1,
  2466. "D2":D2,
  2467. "D3":D3,
  2468. "D4":D4,
  2469. "D5":D5,
  2470. "D6":D6,
  2471. "D7":D7,
  2472. "D8":D8,
  2473. "D9":D9,
  2474. "D10":D10,
  2475. "D11":D11,
  2476. "D12":D12,
  2477. "DO1":DO1,
  2478. "DO2":DO2
  2479. })
  2480. @main.route('/camera_clean', methods=['GET', 'POST'])
  2481. def camera_clean():
  2482. # 獲取登入信息
  2483. if 'id' in session and 'uname' in session and 'status' in session:
  2484. username = session['uname']
  2485. status = session['status']
  2486. db.session.close()
  2487. return render_template('camera_clean.html', title="清洗貨櫃攝影機", **locals())
  2488. else:
  2489. return render_template('sign_in.html')
  2490. @main.route('/camera_ferment', methods=['GET', 'POST'])
  2491. def camera_ferment():
  2492. # 獲取登入信息
  2493. if 'id' in session and 'uname' in session and 'status' in session:
  2494. username = session['uname']
  2495. status = session['status']
  2496. db.session.close()
  2497. return render_template('camera_ferment.html', title="發酵貨櫃攝影機", **locals())
  2498. else:
  2499. return render_template('sign_in.html')
  2500. @main.route('/camera_dry', methods=['GET', 'POST'])
  2501. def camera_dry():
  2502. # 獲取登入信息
  2503. if 'id' in session and 'uname' in session and 'status' in session:
  2504. username = session['uname']
  2505. status = session['status']
  2506. db.session.close()
  2507. return render_template('camera_dry.html', title="乾燥貨櫃攝影機", **locals())
  2508. else:
  2509. return render_template('sign_in.html')
  2510. # 乾燥槽入料自動化測試頁
  2511. @main.route('/auto_DI/<ditid>', methods=['GET', 'POST'])
  2512. def auto_DI(ditid):
  2513. # 獲取登入信息
  2514. if 'id' in session and 'uname' in session and 'status' in session:
  2515. username = session['uname']
  2516. status = session['status']
  2517. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  2518. db.session.close()
  2519. DI1 = dry_status.Dry_Input_1
  2520. DI2 = dry_status.Dry_Input_2
  2521. D1 = dry_status.Dry_Tank_1
  2522. D2 = dry_status.Dry_Tank_2
  2523. D3 = dry_status.Dry_Tank_3
  2524. D4 = dry_status.Dry_Tank_4
  2525. D5 = dry_status.Dry_Tank_5
  2526. D6 = dry_status.Dry_Tank_6
  2527. D7 = dry_status.Dry_Tank_7
  2528. D8 = dry_status.Dry_Tank_8
  2529. D9 = dry_status.Dry_Tank_9
  2530. D10 = dry_status.Dry_Tank_10
  2531. D11 = dry_status.Dry_Tank_11
  2532. D12 = dry_status.Dry_Tank_12
  2533. DO1 = dry_status.Dry_Output_1
  2534. DO2 = dry_status.Dry_Output_2
  2535. input_seneor = dry_input_sensor.query.filter_by(tank_num='DI' + '1').order_by(text('datetime desc')).first()
  2536. db.session.close()
  2537. UltraSonic_input = float(input_seneor.UltraSonic)
  2538. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D' + '1').order_by(text('datetime desc')).first()
  2539. db.session.close()
  2540. SHT11_Temp = float(tank_SHT11.SHT11_Temp)
  2541. SHT11_Humidity = float(tank_SHT11.SHT11_Humidity)
  2542. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D' + '1').order_by(text('datetime desc')).first()
  2543. db.session.close()
  2544. Soil_Temp = float(tank_Soil.soil_Temp)
  2545. Soil_Humidity = float(tank_Soil.soil_Humidity)
  2546. Soil_EC = float(tank_Soil.soil_EC)
  2547. tank_PA = dry_tank_PA.query.filter_by(tank_num='D' + '1').order_by(text('datetime desc')).first()
  2548. db.session.close()
  2549. PA = float(tank_PA.PA)
  2550. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D' + '1').order_by(text('datetime desc')).first()
  2551. db.session.close()
  2552. UltraSonic_tank = float(tank_UltraSonic.UltraSonic)
  2553. output_sensor = dry_output_sensor.query.filter_by(tank_num='DO' + '1').order_by(text('datetime desc')).first()
  2554. db.session.close()
  2555. UltraSonic_output = float(output_sensor.UltraSonic)
  2556. return render_template('auto_DI.html', title="乾燥入料 DI"+ditid+"自動化設定", **locals())
  2557. else:
  2558. return render_template('sign_in.html')
  2559. # 乾燥槽出料自動化測試頁
  2560. @main.route('/auto_DO/<dotid>', methods=['GET', 'POST'])
  2561. def auto_DO(dotid):
  2562. # 獲取登入信息
  2563. if 'id' in session and 'uname' in session and 'status' in session:
  2564. username = session['uname']
  2565. status = session['status']
  2566. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  2567. db.session.close()
  2568. DI1 = dry_status.Dry_Input_1
  2569. DI2 = dry_status.Dry_Input_2
  2570. D1 = dry_status.Dry_Tank_1
  2571. D2 = dry_status.Dry_Tank_2
  2572. D3 = dry_status.Dry_Tank_3
  2573. D4 = dry_status.Dry_Tank_4
  2574. D5 = dry_status.Dry_Tank_5
  2575. D6 = dry_status.Dry_Tank_6
  2576. D7 = dry_status.Dry_Tank_7
  2577. D8 = dry_status.Dry_Tank_8
  2578. D9 = dry_status.Dry_Tank_9
  2579. D10 = dry_status.Dry_Tank_10
  2580. D11 = dry_status.Dry_Tank_11
  2581. D12 = dry_status.Dry_Tank_12
  2582. DO1 = dry_status.Dry_Output_1
  2583. DO2 = dry_status.Dry_Output_2
  2584. input_seneor = dry_input_sensor.query.filter_by(tank_num='DI' + '1').order_by(text('datetime desc')).first()
  2585. db.session.close()
  2586. UltraSonic_input = float(input_seneor.UltraSonic)
  2587. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D' + '1').order_by(text('datetime desc')).first()
  2588. db.session.close()
  2589. SHT11_Temp = float(tank_SHT11.SHT11_Temp)
  2590. SHT11_Humidity = float(tank_SHT11.SHT11_Humidity)
  2591. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D' + '1').order_by(text('datetime desc')).first()
  2592. db.session.close()
  2593. Soil_Temp = float(tank_Soil.soil_Temp)
  2594. Soil_Humidity = float(tank_Soil.soil_Humidity)
  2595. Soil_EC = float(tank_Soil.soil_EC)
  2596. tank_PA = dry_tank_PA.query.filter_by(tank_num='D' + '1').order_by(text('datetime desc')).first()
  2597. db.session.close()
  2598. PA = float(tank_PA.PA)
  2599. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D' + '1').order_by(text('datetime desc')).first()
  2600. db.session.close()
  2601. UltraSonic_tank = float(tank_UltraSonic.UltraSonic)
  2602. output_sensor = dry_output_sensor.query.filter_by(tank_num='DO' + '1').order_by(text('datetime desc')).first()
  2603. db.session.close()
  2604. UltraSonic_output = float(output_sensor.UltraSonic)
  2605. return render_template('auto_DO.html', title="乾燥出料 DO"+dotid+"自動化設定", **locals())
  2606. else:
  2607. return render_template('sign_in.html')
  2608. # 乾燥槽自動化測試頁
  2609. @main.route('/auto_D/<dtid>', methods=['GET', 'POST'])
  2610. def auto_D(dtid):
  2611. # 獲取登入信息
  2612. if 'id' in session and 'uname' in session and 'status' in session:
  2613. username = session['uname']
  2614. status = session['status']
  2615. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  2616. db.session.close()
  2617. DI1 = dry_status.Dry_Input_1
  2618. DI2 = dry_status.Dry_Input_2
  2619. D1 = dry_status.Dry_Tank_1
  2620. D2 = dry_status.Dry_Tank_2
  2621. D3 = dry_status.Dry_Tank_3
  2622. D4 = dry_status.Dry_Tank_4
  2623. D5 = dry_status.Dry_Tank_5
  2624. D6 = dry_status.Dry_Tank_6
  2625. D7 = dry_status.Dry_Tank_7
  2626. D8 = dry_status.Dry_Tank_8
  2627. D9 = dry_status.Dry_Tank_9
  2628. D10 = dry_status.Dry_Tank_10
  2629. D11 = dry_status.Dry_Tank_11
  2630. D12 = dry_status.Dry_Tank_12
  2631. DO1 = dry_status.Dry_Output_1
  2632. DO2 = dry_status.Dry_Output_2
  2633. input_seneor = dry_input_sensor.query.filter_by(tank_num='DI' + '1').order_by(text('datetime desc')).first()
  2634. db.session.close()
  2635. UltraSonic_input = float(input_seneor.UltraSonic)
  2636. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D' + '1').order_by(text('datetime desc')).first()
  2637. db.session.close()
  2638. SHT11_Temp = float(tank_SHT11.SHT11_Temp)
  2639. SHT11_Humidity = float(tank_SHT11.SHT11_Humidity)
  2640. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D' + '1').order_by(text('datetime desc')).first()
  2641. db.session.close()
  2642. Soil_Temp = float(tank_Soil.soil_Temp)
  2643. Soil_Humidity = float(tank_Soil.soil_Humidity)
  2644. Soil_EC = float(tank_Soil.soil_EC)
  2645. tank_PA = dry_tank_PA.query.filter_by(tank_num='D' + '1').order_by(text('datetime desc')).first()
  2646. db.session.close()
  2647. PA = float(tank_PA.PA)
  2648. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D' + '1').order_by(text('datetime desc')).first()
  2649. db.session.close()
  2650. UltraSonic_tank = float(tank_UltraSonic.UltraSonic)
  2651. output_sensor = dry_output_sensor.query.filter_by(tank_num='DO' + '1').order_by(text('datetime desc')).first()
  2652. db.session.close()
  2653. UltraSonic_output = float(output_sensor.UltraSonic)
  2654. return render_template('auto_D.html', title="乾燥 D"+dtid+"自動化設定", **locals())
  2655. else:
  2656. return render_template('sign_in.html')
  2657. # 色選機自動化測試頁
  2658. @main.route('/auto_S/<stid>', methods=['GET', 'POST'])
  2659. def auto_S(stid):
  2660. if 'id' in session and 'uname' in session and 'status' in session:
  2661. username = session['uname']
  2662. status = session['status']
  2663. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  2664. db.session.close()
  2665. CI1 = clean_status.Clean_Input_1
  2666. CI2 = clean_status.Clean_Input_2
  2667. C1 = clean_status.Clean_Tank_1
  2668. C2 = clean_status.Clean_Tank_2
  2669. C3 = clean_status.Clean_Tank_3
  2670. C4 = clean_status.Clean_Tank_4
  2671. R1 = clean_status.Reclaimed_Tank_1
  2672. S1 = clean_status.ColorSelect_Tank_1
  2673. S2 = clean_status.ColorSelect_Tank_2
  2674. SO1 = clean_status.ColorSelect_Output_g1
  2675. SO2 = clean_status.ColorSelect_Output_g2
  2676. P1 = clean_status.Peel_Tank_1
  2677. P2 = clean_status.Peel_Tank_2
  2678. PO1 = clean_status.Peel_Output_1
  2679. PO2 = clean_status.Peel_Output_2
  2680. return render_template('auto_S.html', title="色選機 S"+stid+"自動化設定", **locals())
  2681. else:
  2682. return render_template('sign_in.html')
  2683. # 色選機出料槽自動化測試頁
  2684. @main.route('/auto_SO/<sotid>', methods=['GET', 'POST'])
  2685. def auto_SO(sotid):
  2686. if 'id' in session and 'uname' in session and 'status' in session:
  2687. username = session['uname']
  2688. status = session['status']
  2689. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  2690. db.session.close()
  2691. CI1 = clean_status.Clean_Input_1
  2692. CI2 = clean_status.Clean_Input_2
  2693. C1 = clean_status.Clean_Tank_1
  2694. C2 = clean_status.Clean_Tank_2
  2695. C3 = clean_status.Clean_Tank_3
  2696. C4 = clean_status.Clean_Tank_4
  2697. R1 = clean_status.Reclaimed_Tank_1
  2698. S1 = clean_status.ColorSelect_Tank_1
  2699. S2 = clean_status.ColorSelect_Tank_2
  2700. SO1 = clean_status.ColorSelect_Output_g1
  2701. SO2 = clean_status.ColorSelect_Output_g2
  2702. P1 = clean_status.Peel_Tank_1
  2703. P2 = clean_status.Peel_Tank_2
  2704. PO1 = clean_status.Peel_Output_1
  2705. PO2 = clean_status.Peel_Output_2
  2706. return render_template('auto_SO.html', title="色選機出料 SO"+sotid+"自動化設定", **locals())
  2707. else:
  2708. return render_template('sign_in.html')
  2709. # 脫皮機自動化測試頁
  2710. @main.route('/auto_P/<ptid>', methods=['GET', 'POST'])
  2711. def auto_P(ptid):
  2712. if 'id' in session and 'uname' in session and 'status' in session:
  2713. username = session['uname']
  2714. status = session['status']
  2715. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  2716. db.session.close()
  2717. CI1 = clean_status.Clean_Input_1
  2718. CI2 = clean_status.Clean_Input_2
  2719. C1 = clean_status.Clean_Tank_1
  2720. C2 = clean_status.Clean_Tank_2
  2721. C3 = clean_status.Clean_Tank_3
  2722. C4 = clean_status.Clean_Tank_4
  2723. R1 = clean_status.Reclaimed_Tank_1
  2724. S1 = clean_status.ColorSelect_Tank_1
  2725. S2 = clean_status.ColorSelect_Tank_2
  2726. SO1 = clean_status.ColorSelect_Output_g1
  2727. SO2 = clean_status.ColorSelect_Output_g2
  2728. P1 = clean_status.Peel_Tank_1
  2729. P2 = clean_status.Peel_Tank_2
  2730. PO1 = clean_status.Peel_Output_1
  2731. PO2 = clean_status.Peel_Output_2
  2732. return render_template('auto_P.html', title="脫皮機 P"+ptid+"自動化設定", **locals())
  2733. else:
  2734. return render_template('sign_in.html')
  2735. # 脫皮機出料槽自動化測試頁
  2736. @main.route('/auto_PO/<potid>', methods=['GET', 'POST'])
  2737. def auto_PO(potid):
  2738. if 'id' in session and 'uname' in session and 'status' in session:
  2739. username = session['uname']
  2740. status = session['status']
  2741. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  2742. db.session.close()
  2743. CI1 = clean_status.Clean_Input_1
  2744. CI2 = clean_status.Clean_Input_2
  2745. C1 = clean_status.Clean_Tank_1
  2746. C2 = clean_status.Clean_Tank_2
  2747. C3 = clean_status.Clean_Tank_3
  2748. C4 = clean_status.Clean_Tank_4
  2749. R1 = clean_status.Reclaimed_Tank_1
  2750. S1 = clean_status.ColorSelect_Tank_1
  2751. S2 = clean_status.ColorSelect_Tank_2
  2752. SO1 = clean_status.ColorSelect_Output_g1
  2753. SO2 = clean_status.ColorSelect_Output_g2
  2754. P1 = clean_status.Peel_Tank_1
  2755. P2 = clean_status.Peel_Tank_2
  2756. PO1 = clean_status.Peel_Output_1
  2757. PO2 = clean_status.Peel_Output_2
  2758. return render_template('auto_PO.html', title="脫皮機出料 PO"+potid+"自動化設定", **locals())
  2759. else:
  2760. return render_template('sign_in.html')
  2761. # 中水槽自動化測試頁
  2762. @main.route('/auto_R/<rtid>', methods=['GET', 'POST'])
  2763. def auto_R(rtid):
  2764. if 'id' in session and 'uname' in session and 'status' in session:
  2765. username = session['uname']
  2766. status = session['status']
  2767. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  2768. db.session.close()
  2769. CI1 = clean_status.Clean_Input_1
  2770. CI2 = clean_status.Clean_Input_2
  2771. C1 = clean_status.Clean_Tank_1
  2772. C2 = clean_status.Clean_Tank_2
  2773. C3 = clean_status.Clean_Tank_3
  2774. C4 = clean_status.Clean_Tank_4
  2775. R1 = clean_status.Reclaimed_Tank_1
  2776. S1 = clean_status.ColorSelect_Tank_1
  2777. S2 = clean_status.ColorSelect_Tank_2
  2778. SO1 = clean_status.ColorSelect_Output_g1
  2779. SO2 = clean_status.ColorSelect_Output_g2
  2780. P1 = clean_status.Peel_Tank_1
  2781. P2 = clean_status.Peel_Tank_2
  2782. PO1 = clean_status.Peel_Output_1
  2783. PO2 = clean_status.Peel_Output_2
  2784. return render_template('auto_R.html', title="中水槽 R"+rtid+"自動化設定", **locals())
  2785. else:
  2786. return render_template('sign_in.html')
  2787. #清洗槽入料自動化測試頁
  2788. @main.route('/auto_CI/<citid>', methods=['GET', 'POST'])
  2789. def auto_CI(citid):
  2790. if 'id' in session and 'uname' in session and 'status' in session:
  2791. username = session['uname']
  2792. status = session['status']
  2793. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  2794. db.session.close()
  2795. CI1 = clean_status.Clean_Input_1
  2796. CI2 = clean_status.Clean_Input_2
  2797. C1 = clean_status.Clean_Tank_1
  2798. C2 = clean_status.Clean_Tank_2
  2799. C3 = clean_status.Clean_Tank_3
  2800. C4 = clean_status.Clean_Tank_4
  2801. R1 = clean_status.Reclaimed_Tank_1
  2802. S1 = clean_status.ColorSelect_Tank_1
  2803. S2 = clean_status.ColorSelect_Tank_2
  2804. SO1 = clean_status.ColorSelect_Output_g1
  2805. SO2 = clean_status.ColorSelect_Output_g2
  2806. P1 = clean_status.Peel_Tank_1
  2807. P2 = clean_status.Peel_Tank_2
  2808. PO1 = clean_status.Peel_Output_1
  2809. PO2 = clean_status.Peel_Output_2
  2810. return render_template('auto_CI.html', title="清洗入料 CI"+citid+"自動化設定", **locals())
  2811. else:
  2812. return render_template('sign_in.html')
  2813. #清洗槽自動化測試頁
  2814. @main.route('/auto_C/<ctid>', methods=['GET', 'POST'])
  2815. def auto_C(ctid):
  2816. if 'id' in session and 'uname' in session and 'status' in session:
  2817. username = session['uname']
  2818. status = session['status']
  2819. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  2820. db.session.close()
  2821. CI1 = clean_status.Clean_Input_1
  2822. CI2 = clean_status.Clean_Input_2
  2823. C1 = clean_status.Clean_Tank_1
  2824. C2 = clean_status.Clean_Tank_2
  2825. C3 = clean_status.Clean_Tank_3
  2826. C4 = clean_status.Clean_Tank_4
  2827. R1 = clean_status.Reclaimed_Tank_1
  2828. S1 = clean_status.ColorSelect_Tank_1
  2829. S2 = clean_status.ColorSelect_Tank_2
  2830. SO1 = clean_status.ColorSelect_Output_g1
  2831. SO2 = clean_status.ColorSelect_Output_g2
  2832. P1 = clean_status.Peel_Tank_1
  2833. P2 = clean_status.Peel_Tank_2
  2834. PO1 = clean_status.Peel_Output_1
  2835. PO2 = clean_status.Peel_Output_2
  2836. return render_template('auto_C.html', title="清洗 C"+ctid+"自動化設定", **locals())
  2837. else:
  2838. return render_template('sign_in.html')
  2839. # 清洗槽自動化數據
  2840. @main.route('/clean_auto_data', methods=['GET', 'POST'])
  2841. def clean_auto_data():
  2842. if request.method == 'GET':
  2843. try:
  2844. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  2845. db.session.close()
  2846. CI1 = clean_status.Clean_Input_1
  2847. CI2 = clean_status.Clean_Input_2
  2848. C1 = clean_status.Clean_Tank_1
  2849. C2 = clean_status.Clean_Tank_2
  2850. C3 = clean_status.Clean_Tank_3
  2851. C4 = clean_status.Clean_Tank_4
  2852. R1 = clean_status.Reclaimed_Tank_1
  2853. S1 = clean_status.ColorSelect_Tank_1
  2854. S2 = clean_status.ColorSelect_Tank_2
  2855. SO1 = clean_status.ColorSelect_Output_g1
  2856. SO2 = clean_status.ColorSelect_Output_g2
  2857. P1 = clean_status.Peel_Tank_1
  2858. P2 = clean_status.Peel_Tank_2
  2859. PO1 = clean_status.Peel_Output_1
  2860. PO2 = clean_status.Peel_Output_2
  2861. dict = {"CI1":CI1, "CI2":CI2, "C1":C1, "C2":C2, "C3":C3, "C4":C4, "R1":R1, "S1":S1, "S2":S2, "SO1":SO1, "SO2":SO2, "P1":P1, "P2":P2, "PO1":PO1, "PO2":PO2}
  2862. return json.dumps(dict)
  2863. except Exception as e:
  2864. return json.dumps({"status":None})
  2865. else:
  2866. pass
  2867. # 乾燥槽自動化數據
  2868. @main.route('/dry_auto_data', methods=['GET', 'POST'])
  2869. def dry_auto_data():
  2870. if request.method == 'GET':
  2871. try:
  2872. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  2873. db.session.close()
  2874. DI1 = dry_status.Dry_Input_1
  2875. DI2 = dry_status.Dry_Input_2
  2876. D1 = dry_status.Dry_Tank_1
  2877. D2 = dry_status.Dry_Tank_2
  2878. D3 = dry_status.Dry_Tank_3
  2879. D4 = dry_status.Dry_Tank_4
  2880. D5 = dry_status.Dry_Tank_5
  2881. D6 = dry_status.Dry_Tank_6
  2882. D7 = dry_status.Dry_Tank_7
  2883. D8 = dry_status.Dry_Tank_8
  2884. D9 = dry_status.Dry_Tank_9
  2885. D10 = dry_status.Dry_Tank_10
  2886. D11 = dry_status.Dry_Tank_11
  2887. D12 = dry_status.Dry_Tank_12
  2888. DO1 = dry_status.Dry_Output_1
  2889. DO2 = dry_status.Dry_Output_2
  2890. #感測器數據
  2891. input_seneor = dry_input_sensor.query.filter_by(tank_num='DI' + '1').order_by(text('datetime desc')).first()
  2892. db.session.close()
  2893. UltraSonic_input = float(input_seneor.UltraSonic)
  2894. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D' + '1').order_by(text('datetime desc')).first()
  2895. db.session.close()
  2896. SHT11_Temp = float(tank_SHT11.SHT11_Temp)
  2897. SHT11_Humidity = float(tank_SHT11.SHT11_Humidity)
  2898. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D' + '1').order_by(text('datetime desc')).first()
  2899. db.session.close()
  2900. Soil_Temp = float(tank_Soil.soil_Temp)
  2901. Soil_Humidity = float(tank_Soil.soil_Humidity)
  2902. Soil_EC = float(tank_Soil.soil_EC)
  2903. tank_PA = dry_tank_PA.query.filter_by(tank_num='D' + '1').order_by(text('datetime desc')).first()
  2904. db.session.close()
  2905. PA = float(tank_PA.PA)
  2906. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D' + '1').order_by(text('datetime desc')).first()
  2907. db.session.close()
  2908. UltraSonic_tank = float(tank_UltraSonic.UltraSonic)
  2909. tank_motorEncoder = dry_tank_motorEncoder.query.filter_by(tank_num='D' + '1').order_by(text('datetime desc')).first()
  2910. db.session.close()
  2911. motorEncoder = tank_motorEncoder.motorEncoder
  2912. output_sensor = dry_output_sensor.query.filter_by(tank_num='DO' + '1').order_by(text('datetime desc')).first()
  2913. db.session.close()
  2914. UltraSonic_output = float(output_sensor.UltraSonic)
  2915. #致動器數據
  2916. input_brake = dry_input_brake.query.filter_by(tank_num='DI' + '1').order_by(
  2917. text('datetime desc')).first()
  2918. db.session.close()
  2919. vacuum_input= input_brake.vacuum
  2920. tank_brake = dry_tank_brake.query.filter_by(tank_num='D' + '1').order_by(
  2921. text('datetime desc')).first()
  2922. db.session.close()
  2923. vacuum = tank_brake.vacuum
  2924. threewayvalve_input = tank_brake.threewayvalve_input
  2925. diskvalve = tank_brake.diskvalve
  2926. solenoid_disinfect = tank_brake.solenoid_disinfect
  2927. solenoid_outer_water = tank_brake.solenoid_outer_water
  2928. vacuum_pump = tank_brake.vacuum_pump
  2929. heater1 = tank_brake.heater1
  2930. heater2 = tank_brake.heater2
  2931. tank_brake = dry_tank_brake.query.filter_by(tank_num='D' + '1').order_by(
  2932. text('datetime desc')).first()
  2933. db.session.close()
  2934. motor = tank_brake.motor
  2935. output_brake = dry_output_brake.query.filter_by(tank_num='DO' + '1').order_by(
  2936. text('datetime desc')).first()
  2937. db.session.close()
  2938. vacuum_output = output_brake.vacuum
  2939. dict = {"DI1":DI1, "DI2":DI2, "D1":D1, "D2":D2, "D3":D3, "D4":D4, "D5":D5, "D6":D6, "D7":D7, "D8":D8, "D9":D9, "D10":D10, "D11":D11, "D12":D12, "DO1":DO1, "DO2":DO2,"UltraSonic_input":UltraSonic_input,"SHT11_Temp":SHT11_Temp,"SHT11_Humidity":SHT11_Humidity,"Soil_Temp":Soil_Temp,"Soil_Humidity":Soil_Humidity,"Soil_EC":Soil_EC,"PA":PA,"UltraSonic_tank":UltraSonic_tank,"UltraSonic_output":UltraSonic_output,"vacuum_input":vacuum_input,"vacuum":vacuum,"threewayvalve_input":threewayvalve_input,"diskvalve":diskvalve,"solenoid_disinfect":solenoid_disinfect,"solenoid_outer_water":solenoid_outer_water,"vacuum_pump":vacuum_pump,"heater1":heater1,"heater2":heater2,"motorEncoder":motorEncoder,"vacuum_output":vacuum_output,"motor":motor}
  2940. return json.dumps(dict)
  2941. except Exception as e:
  2942. return json.dumps({"status":None})
  2943. else:
  2944. pass
  2945. # 乾燥槽 乾燥暫停 出料
  2946. @main.route('/dryDEMO_outputtingBean', methods=['GET', 'POST'])
  2947. def dryDEMO_outputtingBean():
  2948. info = request.args.to_dict()
  2949. Dry_Output_bean_height = float(info['Dry_Output_bean_height'])
  2950. Dry_Output_vacuumON_time = float(info['Dry_Output_vacuumON_time'])
  2951. Dry_Output_vacuumOFF_time = float(info['Dry_Output_vacuumOFF_time'])
  2952. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  2953. DI1 = dry_status.Dry_Input_1 # DI1 == 'DI_OutputtingBean'
  2954. DI2 = dry_status.Dry_Input_2
  2955. D1 = dry_status.Dry_Tank_1
  2956. D2 = dry_status.Dry_Tank_2
  2957. D3 = dry_status.Dry_Tank_3
  2958. D4 = dry_status.Dry_Tank_4
  2959. D5 = dry_status.Dry_Tank_5
  2960. D6 = dry_status.Dry_Tank_6
  2961. D7 = dry_status.Dry_Tank_7
  2962. D8 = dry_status.Dry_Tank_8
  2963. D9 = dry_status.Dry_Tank_9
  2964. D10 = dry_status.Dry_Tank_10
  2965. D11 = dry_status.Dry_Tank_11
  2966. D12 = dry_status.Dry_Tank_12
  2967. DO1 = dry_status.Dry_Output_1
  2968. DO2 = dry_status.Dry_Output_2
  2969. # # -- 取得乾燥出料儲豆槽 DO1~DO2 桶內高度 UltraSonic -------------
  2970. # DO_UP_UltraSoniclist = []
  2971. # for i in range(1, 3, 1):
  2972. # output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO' + str(i)).order_by(text('datetime desc')).first()
  2973. # UltraSonic = float(output_UltraSonic.UltraSonic)
  2974. # DO_UP_UltraSoniclist.append(UltraSonic)
  2975. # print('DO_UP_UltraSoniclist: ', DO_UP_UltraSoniclist)
  2976. # # -- 取得乾燥出料儲豆槽 DO1~DO2 桶內高度 UltraSonic -------------
  2977. # 將桶槽 D1 狀態轉換成可出豆, DO1 狀態轉換成可入豆
  2978. D1 = 'D_OutputtingBean'
  2979. # [致動器] 設定溫度 0.0
  2980. data = { "tank_num": "D1", "command": "tank_temp", "value": "0.0" }
  2981. print('data: ', data)
  2982. # mqtt_f(data)
  2983. # [致動器] 溫控開關 OFF
  2984. data = { "tank_num": "D1", "command": "tank_temp_enable", "value": "off" }
  2985. print('data: ', data)
  2986. # mqtt_f(data)
  2987. # [致動器] 馬達 0
  2988. data = { "tank_num": "D1", "command": "tank_motor_status", "value": "0" }
  2989. print('data: ', data)
  2990. # mqtt_f(data)
  2991. # [致動器] 排水電磁閥 OFF
  2992. data = { "tank_num": "D1", "command": "tank_solenoid_water_out_status", "value": "off" }
  2993. print('data: ', data)
  2994. # mqtt_f(data)
  2995. # [致動器] D1 蝴蝶閥 ON
  2996. data = { "tank_num": "D1", "command": "tank_diskvalve_status", "value": "on" }
  2997. print('data: ', data)
  2998. # mqtt_f(data)
  2999. # ----- 將狀態寫入資料庫 ------------------------------
  3000. # 獲取文本框的值並賦值給user實體對象
  3001. D_status = dry_container_status()
  3002. D_status.Dry_Input_1 = DI1
  3003. D_status.Dry_Input_2 = DI2
  3004. D_status.Dry_Tank_1 = D1
  3005. D_status.Dry_Tank_2 = D2
  3006. D_status.Dry_Tank_3 = D3
  3007. D_status.Dry_Tank_4 = D4
  3008. D_status.Dry_Tank_5 = D5
  3009. D_status.Dry_Tank_6 = D6
  3010. D_status.Dry_Tank_7 = D7
  3011. D_status.Dry_Tank_8 = D8
  3012. D_status.Dry_Tank_9 = D9
  3013. D_status.Dry_Tank_10 = D10
  3014. D_status.Dry_Tank_11 = D11
  3015. D_status.Dry_Tank_12 = D12
  3016. D_status.Dry_Output_1 = DO1
  3017. D_status.Dry_Output_2 = DO2
  3018. #將數據保存進資料庫
  3019. db.session.add(D_status)
  3020. # 手動提交
  3021. db.session.commit()
  3022. # ----- 將狀態寫入資料庫 ------------------------------
  3023. return jsonify({"Dry_Tank_1":D1,
  3024. "Dry_Tank_2":D2,
  3025. "Dry_Output_1":DO1,
  3026. "Dry_Output_2":DO2
  3027. })
  3028. @main.route('/dryDEMO_auto_status', methods=['GET', 'POST'])
  3029. def dryDEMO_auto_status():
  3030. info = request.args.to_dict()
  3031. # 寫定入料、桶槽、出料的空桶標準, 若 <= 2 則為空桶
  3032. Dry_Tank_bean_empty = 2
  3033. Dry_Output_bean_empty = 2
  3034. # 從介面取得 指定生豆高度/發酵桶槽排程:發酵、清洗、校正 EC、校正攪拌棒
  3035. Dry_Tank_bean_height = float(info['Dry_Tank_bean_height'])
  3036. Dry_Tank_vacuumON_time = float(info['Dry_Tank_vacuumON_time'])
  3037. Dry_Tank_vacuumOFF_time = float(info['Dry_Tank_vacuumOFF_time'])
  3038. Dry_Tank_drying_temp = float(info['Dry_Tank_drying_temp'])
  3039. Dry_Tank_drying_time = float(info['Dry_Tank_drying_time'])
  3040. Dry_Tank_motor_rpm = float(info['Dry_Tank_motor_rpm'])
  3041. Dry_Tank_drying_Humidity = float(info['Dry_Tank_drying_Humidity'])
  3042. Dry_Output_bean_height = float(info['Dry_Output_bean_height'])
  3043. Dry_Output_vacuumON_time = float(info['Dry_Output_vacuumON_time'])
  3044. Dry_Output_vacuumOFF_time = float(info['Dry_Output_vacuumOFF_time'])
  3045. Dry_Tank_Disinfect_time = float(info['Dry_Tank_Disinfect_timef'])
  3046. # [介面] 讓使用者可以選擇排程內有乾燥/清洗/校正, 此處預設為 True
  3047. Dry_btn = True
  3048. # 從資料庫資料表中取得最新狀態
  3049. # ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  3050. # FO1 = 'FO_OutputtingBean'
  3051. # FO2 = 'FO_Waiting'
  3052. # FO1 = 'FO_OutputtingBean' # 'FO_OutputtingBean' FO_Waiting
  3053. # FO2 = 'FO_Waiting'
  3054. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  3055. DI1 = dry_status.Dry_Input_1 # DI1 == 'DI_OutputtingBean'
  3056. DI2 = dry_status.Dry_Input_2
  3057. D1 = dry_status.Dry_Tank_1
  3058. D2 = dry_status.Dry_Tank_2
  3059. D3 = dry_status.Dry_Tank_3
  3060. D4 = dry_status.Dry_Tank_4
  3061. D5 = dry_status.Dry_Tank_5
  3062. D6 = dry_status.Dry_Tank_6
  3063. D7 = dry_status.Dry_Tank_7
  3064. D8 = dry_status.Dry_Tank_8
  3065. D9 = dry_status.Dry_Tank_9
  3066. D10 = dry_status.Dry_Tank_10
  3067. D11 = dry_status.Dry_Tank_11
  3068. D12 = dry_status.Dry_Tank_12
  3069. DO1 = dry_status.Dry_Output_1
  3070. DO2 = dry_status.Dry_Output_2
  3071. D_UP_tanklist = [D1, D2, D3, D4, D5, D6]
  3072. D_DOWN_tanklist = [D7, D8, D9, D10, D11, D12]
  3073. DOutputtingBean_Tank = '' # 出料桶槽號
  3074. DryAuto_cleaning = 0 # 清洗次數
  3075. # 目前乾燥槽 D1~D6 正在入豆的桶槽數量 (應小於一桶)
  3076. DryUp_Waiting_number = int(D_UP_tanklist.count('D_Waiting'))
  3077. DryUp_InputtingBean_number = int(D_UP_tanklist.count('D_InputtingBean'))
  3078. DryUp_InputtingBeanPause_number = int(D_UP_tanklist.count('D_InputtingBean_Pause'))
  3079. # -- 取得乾燥入料儲豆槽 FI1~FI2 桶內高度 UltraSonic -------------
  3080. DI_UP_UltraSoniclist = []
  3081. for i in range(1, 3, 1):
  3082. input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI' + str(i)).order_by(text('datetime desc')).first()
  3083. UltraSonic = float(input_UltraSonic.UltraSonic)
  3084. DI_UP_UltraSoniclist.append(UltraSonic)
  3085. print('DI_UP_UltraSoniclist: ', DI_UP_UltraSoniclist)
  3086. # -- 取得乾燥入料儲豆槽 FI1~FI2 桶內高度 UltraSonic -------------
  3087. # -- 取得乾燥桶槽 D1~D6 超音波生豆高度 UltraSonic -------------
  3088. D_UP_tank_UltraSonic = []
  3089. for i in range(1, 7, 1):
  3090. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
  3091. UltraSonic = float(tank_UltraSonic.UltraSonic)
  3092. D_UP_tank_UltraSonic.append(UltraSonic)
  3093. print('D_UP_tank_UltraSonic: ', D_UP_tank_UltraSonic)
  3094. # -- 取得乾燥桶槽 D1~D6 超音波生豆高度 UltraSonic -------------
  3095. # -- 取得乾燥出料儲豆槽 DO1~DO2 桶內高度 UltraSonic -------------
  3096. DO_UP_UltraSoniclist = []
  3097. for i in range(1, 3, 1):
  3098. output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO' + str(i)).order_by(text('datetime desc')).first()
  3099. UltraSonic = float(output_UltraSonic.UltraSonic)
  3100. DO_UP_UltraSoniclist.append(UltraSonic)
  3101. print('DO_UP_UltraSoniclist: ', DO_UP_UltraSoniclist)
  3102. # -- 取得乾燥出料儲豆槽 DO1~DO2 桶內高度 UltraSonic -------------
  3103. # -- 取得乾燥桶槽 D1~D6 桶內溫濕度計 SHT11 -------------
  3104. D_UP_tank_SHT11Temp = []
  3105. D_UP_tank_SHT11Humidity = []
  3106. for i in range(1, 7, 1):
  3107. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
  3108. SHT11_Temp = float(tank_SHT11.SHT11_Temp)
  3109. D_UP_tank_SHT11Temp.append(SHT11_Temp)
  3110. SHT11_Humidity = float(tank_SHT11.SHT11_Humidity)
  3111. D_UP_tank_SHT11Humidity.append(SHT11_Humidity)
  3112. print('D_UP_tank_SHT11Temp: ', D_UP_tank_SHT11Temp)
  3113. print('D_UP_tank_SHT11Humidity: ', D_UP_tank_SHT11Humidity)
  3114. # -- 取得乾燥桶槽 D1~D6 桶內溫濕度計 SHT11 -------------
  3115. # -- 取得乾燥桶槽 D1~D6 三合一土壤感測器 Soil -------------
  3116. D_UP_tank_SoilTemp = []
  3117. D_UP_tank_SoilHumidity = []
  3118. D_UP_tank_SoilEC = []
  3119. for i in range(1, 7, 1):
  3120. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
  3121. soil_Temp = float(tank_Soil.soil_Temp)
  3122. D_UP_tank_SoilTemp.append(soil_Temp)
  3123. soil_Humidity = float(tank_Soil.soil_Humidity)
  3124. D_UP_tank_SoilHumidity.append(soil_Humidity)
  3125. soil_EC = float(tank_Soil.soil_EC)
  3126. D_UP_tank_SoilEC.append(soil_EC)
  3127. # print('D_UP_tank_SoilTemp: ', D_UP_tank_SoilTemp)
  3128. # print('D_UP_tank_SoilHumidity: ', D_UP_tank_SoilHumidity)
  3129. # print('D_UP_tank_SoilEC: ', D_UP_tank_SoilEC)
  3130. # -- 取得乾燥桶槽 D1~D6 三合一土壤感測器 SHT11 -------------
  3131. # ----- 發酵排程動作 start ------------------------------------------------------------------
  3132. # if D1 == 'D_InputtingBean': D_UP_tank_UltraSonic[0] >= Dry_Tank_bean_height:
  3133. def DInputtingBean_TO_DInputtingBeanFinish(tid):
  3134. # [致動器] 真空吸料機 OFF
  3135. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  3136. print('data: ', data)
  3137. # mqtt_f(data)
  3138. # [致動器] 蝴蝶閥 OFF
  3139. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
  3140. print('data: ', data)
  3141. # mqtt_f(data)
  3142. # # [致動器] F1 蝴蝶閥 OFF [ 1109 測試用 ]
  3143. # data = { "tank_num": "F1", "command": "tank_diskvalve_status", "value": "off" }
  3144. # print('data: ', data)
  3145. # # mqtt_f(data)
  3146. # [致動器] 馬達 0
  3147. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  3148. print('data: ', data)
  3149. # mqtt_f(data)
  3150. # [致動器] 入料三通閥 ON排氣
  3151. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "on" }
  3152. print('data: ', data)
  3153. # mqtt_f(data)
  3154. print('------- ', tid,' 狀態更新:入豆完成 -------')
  3155. # if D1 == 'D_InputtingBean': elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
  3156. def DInputtingBean_AND_notfilled(tid):
  3157. # [致動器] 蝴蝶閥 OFF
  3158. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
  3159. print('data: ', data)
  3160. # mqtt_f(data)
  3161. # [致動器] 入料三通閥 OFF入豆
  3162. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  3163. print('data: ', data)
  3164. # mqtt_f(data)
  3165. # [致動器] 真空吸料機 ON
  3166. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "on" }
  3167. print('data: ', data)
  3168. # mqtt_f(data)
  3169. timer = time.time()
  3170. while True:
  3171. if (time.time() - timer) > Dry_Tank_vacuumON_time:
  3172. # [致動器] 真空吸料機 OFF
  3173. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  3174. print('data: ', data)
  3175. # mqtt_f(data)
  3176. timer = time.time()
  3177. break
  3178. while True:
  3179. if (time.time() - timer) > Dry_Tank_vacuumOFF_time:
  3180. break
  3181. # if D1 == 'D_InputtingBean': elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
  3182. def DInputtingBean_TO_DInputtingBeanPause(tid):
  3183. # [致動器] 蝴蝶閥 OFF
  3184. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
  3185. print('data: ', data)
  3186. # mqtt_f(data)
  3187. # [致動器] 真空吸料機 OFF
  3188. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  3189. print('data: ', data)
  3190. # mqtt_f(data)
  3191. # [致動器] 馬達 0
  3192. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  3193. print('data: ', data)
  3194. # mqtt_f(data)
  3195. print('------- ', tid,' 狀態更新:入豆暫停 -------')
  3196. # elif DryUp_InputtingBeanPause_number == 1 and DI1 == 'DI_OutputtingBean': if D1 == 'D_InputtingBean_Pause':
  3197. def DInputtingBeanPause_TO_DInputtingBean(tid):
  3198. # [致動器] 入料三通閥 OFF入豆
  3199. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  3200. print('data: ', data)
  3201. # mqtt_f(data)
  3202. # [致動器] 馬達 5
  3203. data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
  3204. print('data: ', data)
  3205. # mqtt_f(data)
  3206. print('------- ', tid, ' 狀態更新:入豆中 -------')
  3207. # elif DryUp_InputtingBean_number == 0 and DryUp_InputtingBeanPause_number == 0 and DI1 == 'DI_OutputtingBean' and DryUp_Waiting_number >= 1:
  3208. def DWaiting_TO_DInputtingBean(tid):
  3209. # [致動器] F1 蝴蝶閥 ON
  3210. data = { "tank_num": "F1", "command": "tank_diskvalve_status", "value": "on" }
  3211. print('data: ', data)
  3212. # mqtt_f(data)
  3213. # [致動器] 蝴蝶閥 OFF
  3214. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
  3215. print('data: ', data)
  3216. # mqtt_f(data)
  3217. # [致動器] 入料三通閥 OFF入豆
  3218. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  3219. print('data: ', data)
  3220. # mqtt_f(data)
  3221. # [致動器] 馬達 5
  3222. data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
  3223. print('data: ', data)
  3224. # mqtt_f(data)
  3225. print('------- ', tid, ' 狀態更新:入豆中 -------')
  3226. # else: if D1 == 'D_InputtingBean_Finish':
  3227. def DInputtingBeanFinish_TO_DDrying(tid):
  3228. # [致動器] 馬達 指定轉速
  3229. data = { "tank_num": tid, "command": "tank_motor_status", "value": Dry_Tank_motor_rpm }
  3230. print('data: ', data)
  3231. # mqtt_f(data)
  3232. # [致動器] 排水電磁閥 ON
  3233. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "on" }
  3234. print('data: ', data)
  3235. # mqtt_f(data)
  3236. # # [致動器] 鼓風機 ON
  3237. # data = { "tank_num": tid, "command": "tank_blower_status", "value": "on" }
  3238. # print('data: ', data)
  3239. # # mqtt_f(data)
  3240. # # [致動器] 加熱器 1 ON
  3241. # data = { "tank_num": tid, "command": "tank_heater1_status", "value": "on" }
  3242. # print('data: ', data)
  3243. # # mqtt_f(data)
  3244. # # [致動器] 加熱器 2 ON
  3245. # data = { "tank_num": tid, "command": "tank_heater2_status", "value": "on" }
  3246. # print('data: ', data)
  3247. # # mqtt_f(data)
  3248. # [致動器] 溫控開關 ON
  3249. data = { "tank_num": tid, "command": "tank_temp_enable", "value": "on" }
  3250. print('data: ', data)
  3251. # mqtt_f(data)
  3252. # [致動器] 設定溫度 (指定溫度)
  3253. data = { "tank_num": tid, "command": "tank_temp", "value": Dry_Tank_drying_temp }
  3254. print('data: ', data)
  3255. # mqtt_f(data)
  3256. print('------- ', tid, ' 狀態更新:乾燥中 -------')
  3257. # 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:
  3258. def DDrying_TO_DOutputtingBean(tid):
  3259. # # [致動器] 鼓風機 OFF
  3260. # data = { "tank_num": tid, "command": "tank_blower_status", "value": "off" }
  3261. # print('data: ', data)
  3262. # # mqtt_f(data)
  3263. # # [致動器] 加熱器 1 OFF
  3264. # data = { "tank_num": tid, "command": "tank_heater1_status", "value": "off" }
  3265. # print('data: ', data)
  3266. # # mqtt_f(data)
  3267. # # [致動器] 加熱器 2 OFF
  3268. # data = { "tank_num": tid, "command": "tank_heater2_status", "value": "off" }
  3269. # print('data: ', data)
  3270. # # mqtt_f(data)
  3271. # [致動器] 設定溫度 0
  3272. data = { "tank_num": tid, "command": "tank_temp", "value": "0" }
  3273. print('data: ', data)
  3274. # mqtt_f(data)
  3275. # [致動器] 溫控開關 OFF
  3276. data = { "tank_num": tid, "command": "tank_temp_enable", "value": "off" }
  3277. print('data: ', data)
  3278. # mqtt_f(data)
  3279. # [致動器] 馬達 0
  3280. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  3281. print('data: ', data)
  3282. # mqtt_f(data)
  3283. print("乾燥結束, 返潮暫停 ", Dry_Tank_drying_time, " 秒")
  3284. timer = time.time()
  3285. while True:
  3286. if (time.time() - timer) > Dry_Tank_drying_time:
  3287. # [致動器] 排水電磁閥 OFF
  3288. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  3289. print('data: ', data)
  3290. # mqtt_f(data)
  3291. break
  3292. print('------- ', tid, ' 狀態更新:可出豆 -------')
  3293. # else: if D1 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[0] <= Dry_Tank_bean_empty):
  3294. def DOutputtingBean_TO_DWaiting(tid):
  3295. # [致動器] D1 蝴蝶閥 OFF
  3296. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
  3297. print('data: ', data)
  3298. # mqtt_f(data)
  3299. # D_Cleaning
  3300. def DCleaning(tid):
  3301. # [致動器] 馬達 10
  3302. data = { "tank_num": tid, "command": "tank_motor_status", "value": "10" }
  3303. print('data: ', data)
  3304. # mqtt_f(data)
  3305. # [致動器] 消毒電磁閥 ON
  3306. data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "on" }
  3307. print('data: ', data)
  3308. # mqtt_f(data)
  3309. # [致動器] 排水電磁閥 OFF
  3310. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  3311. print('data: ', data)
  3312. # mqtt_f(data)
  3313. # [致動器] TODO 消毒抽水 pump ON
  3314. print("消毒 ", Dry_Tank_Disinfect_time, " 秒")
  3315. timer = time.time()
  3316. while True:
  3317. if (time.time() - timer) > Dry_Tank_Disinfect_time:
  3318. # [致動器] TODO 消毒抽水 pump OFF
  3319. break
  3320. # [致動器] 消毒電磁閥 OFF
  3321. data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "off" }
  3322. print('data: ', data)
  3323. # mqtt_f(data)
  3324. # [致動器] 馬達 0
  3325. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  3326. print('data: ', data)
  3327. # mqtt_f(data)
  3328. # [致動器] 排水電磁閥 ON
  3329. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "on" }
  3330. print('data: ', data)
  3331. # mqtt_f(data)
  3332. print("桶內排水 ", Dry_Tank_Disinfect_time, " 秒")
  3333. timer = time.time()
  3334. while True:
  3335. if (time.time() - timer) > Dry_Tank_Disinfect_time:
  3336. break
  3337. # [致動器] 排水電磁閥 OFF
  3338. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  3339. print('data: ', data)
  3340. # mqtt_f(data)
  3341. print('------- ', tid, ' 狀態更新:空桶等待 -------')
  3342. # ----- 發酵排程動作 end ------------------------------------------------------------------
  3343. # [介面] 若啟用 乾燥 狀態
  3344. if Dry_btn:
  3345. # ----- 乾燥桶槽 D1~D6 入料桶槽優先入料判斷 ------------------------------
  3346. # 若 D1~D6 桶槽中有一個桶槽入豆中
  3347. if DryUp_InputtingBean_number == 1:
  3348. # 若 D1 桶槽為入豆中
  3349. if D1 == 'D_InputtingBean':
  3350. # 若桶槽生豆高度大於指定生豆高度, 則狀態轉換成 入料完成
  3351. if D_UP_tank_UltraSonic[0] >= Dry_Tank_bean_height:
  3352. DInputtingBean_TO_DInputtingBeanFinish("D1")
  3353. D1 = 'D_InputtingBean_Finish'
  3354. # 若桶槽生豆高度未達指定生豆高度, 且 入料儲豆槽可出豆
  3355. elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
  3356. DInputtingBean_AND_notfilled("D1")
  3357. # 若桶槽生豆高度未達指定生豆高度, 且 入料儲豆槽 非可出豆
  3358. elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
  3359. DInputtingBean_TO_DInputtingBeanPause("D1")
  3360. D1 = 'D_InputtingBean_Pause'
  3361. # 若 D1~D6 桶槽中有一個桶槽入豆暫停
  3362. elif DryUp_InputtingBeanPause_number == 1 and DI1 == 'DI_OutputtingBean':
  3363. if D1 == 'D_InputtingBean_Pause':
  3364. DInputtingBeanPause_TO_DInputtingBean("D1")
  3365. D1 = 'D_InputtingBean'
  3366. # 若 D1~D6 桶槽中皆無 入豆中 和 入豆暫停, 且入料儲豆槽可出豆
  3367. elif DryUp_InputtingBean_number == 0 and DryUp_InputtingBeanPause_number == 0 and DI1 == 'DI_OutputtingBean' and DryUp_Waiting_number >= 1:
  3368. if D1 == 'D_Waiting':
  3369. DWaiting_TO_DInputtingBean("D1")
  3370. D1 = 'D_InputtingBean'
  3371. # 其他
  3372. # else:
  3373. # 以下內容原在此 else 內, 測試無誤後維持
  3374. # 如果桶槽為 入豆完成, 將狀態轉換成 乾燥中
  3375. if D1 == 'D_InputtingBean_Finish':
  3376. DInputtingBeanFinish_TO_DDrying("D1")
  3377. D1 = 'D_Drying'
  3378. # 如果桶槽為 乾燥中, 達乾燥條件後, 將狀態轉換成 可出豆
  3379. if D1 == 'D_Drying' and D_UP_tank_SHT11Temp[0] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[0] <= Dry_Tank_drying_Humidity:
  3380. DDrying_TO_DOutputtingBean("D1")
  3381. D1 = 'D_OutputtingBean'
  3382. if DOutputtingBean_Tank == '': DOutputtingBean_Tank = 'D1'
  3383. # 如果桶槽 D1~D6 可出豆 且 桶槽內為空桶 且 有指定清洗排程, 進行清洗桶槽
  3384. # TODO 發酵次數計算、消毒次數、校正
  3385. if D1 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[0] <= Dry_Tank_bean_empty):
  3386. if DOutputtingBean_Tank == 'D1':
  3387. DOutputtingBean_TO_DWaiting('D1')
  3388. DOutputtingBean_Tank = ''
  3389. if (DryAuto_cleaning == 0): D1 = 'D_Waiting'
  3390. elif (DryAuto_cleaning != 0): D1 = 'D_Cleaning'
  3391. # 避免桶槽可出豆時未賦值
  3392. if DOutputtingBean_Tank == '':
  3393. if D1 == 'D_OutputtingBean': DOutputtingBean_Tank = 'D1'
  3394. # 乾燥槽消毒
  3395. if D1 == 'D_Cleaning':
  3396. DCleaning("D1")
  3397. D1 = 'D_Waiting'
  3398. else:
  3399. print('未啟用乾燥流程')
  3400. # ----- 乾燥出料儲豆槽 DO1~DO2 入豆→可出豆判斷 ------------------------------
  3401. # 若出料儲豆槽狀態為 空桶等待 且 桶槽狀態為 D_OutputtingBean 可出豆, 與 FO1 配合開始出豆
  3402. # # 1109 註解實驗用
  3403. # if DO1 == 'DO_Waiting' and DOutputtingBean_Tank != '':
  3404. # # 判斷要對應出料的桶槽為何, 設定成 DOutputtingBean_Tank = 'D1', 待出完料再把 DOutputtingBean_Tank = ''
  3405. # DO1 = 'DO_InputtingBean'
  3406. # print('------- ' + DOutputtingBean_Tank + ' 狀態更新:出豆中 -------')
  3407. # print('------- DO1 狀態更新:入豆中 -------')
  3408. # # [致動器] D1 蝴蝶閥 ON
  3409. # data = { "tank_num": DOutputtingBean_Tank, "command": "tank_diskvalve_status", "value": "on" }
  3410. # print('data: ', data)
  3411. # # mqtt_f(data)
  3412. # elif DO1 == 'DO_InputtingBean' and DOutputtingBean_Tank != '':
  3413. # if DO_UP_UltraSoniclist[0] >= Dry_Output_bean_height:
  3414. # # [致動器] 出料真空吸料機 OFF
  3415. # data = { "tank_num": DOutputtingBean_Tank, "command": "output_vacuum_status", "value": "off" }
  3416. # print('data: ', data)
  3417. # # mqtt_f(data)
  3418. # # [致動器] D1 蝴蝶閥 OFF
  3419. # data = { "tank_num": DOutputtingBean_Tank, "command": "tank_diskvalve_status", "value": "off" }
  3420. # print('data: ', data)
  3421. # # mqtt_f(data)
  3422. # DO1 = 'DO_OutputtingBean'
  3423. # print('------- DO1 狀態更新:可出豆 -------')
  3424. # elif DO_UP_UltraSoniclist[0] < Dry_Output_bean_height:
  3425. # # [致動器] 出料真空吸料機 ON
  3426. # data = { "tank_num": DOutputtingBean_Tank, "command": "output_vacuum_status", "value": "on" }
  3427. # print('data: ', data)
  3428. # # mqtt_f(data)
  3429. # timer = time.time()
  3430. # while True:
  3431. # if (time.time() - timer) > Dry_Output_vacuumON_time:
  3432. # # [致動器] 出料真空吸料機 OFF
  3433. # data = { "tank_num": DOutputtingBean_Tank, "command": "output_vacuum_status", "value": "off" }
  3434. # print('data: ', data)
  3435. # # mqtt_f(data)
  3436. # timer = time.time()
  3437. # break
  3438. # while True:
  3439. # if (time.time() - timer) > Dry_Output_vacuumOFF_time:
  3440. # break
  3441. # # 若是無桶槽可入豆, 出料儲豆槽判斷是否可出豆或空桶等待入豆
  3442. # elif DO1 == 'DO_InputtingBean' and DOutputtingBean_Tank == '':
  3443. # if DO_UP_UltraSoniclist[0] > Dry_Output_bean_empty:
  3444. # DO1 = 'DO_OutputtingBean'
  3445. # print('------- DO1 狀態更新:可出豆 -------')
  3446. # elif DO_UP_UltraSoniclist[0] <= Dry_Output_bean_empty:
  3447. # DO1 = 'DO_Waiting'
  3448. # print('------- DO1 狀態更新:空桶等待 -------')
  3449. # elif DO1 == 'DO_OutputtingBean' and DO_UP_UltraSoniclist[0] <= Dry_Output_bean_empty:
  3450. # DO1 = 'DO_Waiting'
  3451. # # [致動器] D1 蝴蝶閥 OFF
  3452. # data = { "tank_num": "D1", "command": "tank_diskvalve_status", "value": "off" }
  3453. # print('data: ', data)
  3454. # # mqtt_f(data)
  3455. # print('------- DO1 狀態更新:空桶等待 -------')
  3456. # # 1109 註解實驗用
  3457. # # ----- [測試用] !!!!! D1~D6 入料完成→可出豆 判斷 ------------------------------
  3458. # if D1 == 'D_InputtingBean_Finish': D1 = 'D_OutputtingBean'
  3459. # if D2 == 'D_InputtingBean_Finish': D2 = 'D_OutputtingBean'
  3460. # if D3 == 'D_InputtingBean_Finish': D3 = 'D_OutputtingBean'
  3461. # if D4 == 'D_InputtingBean_Finish': D4 = 'D_OutputtingBean'
  3462. # if D5 == 'D_InputtingBean_Finish': D5 = 'D_OutputtingBean'
  3463. # if D6 == 'D_InputtingBean_Finish': D6 = 'D_OutputtingBean'
  3464. # # ----- [測試用] !!!!! D1~D6 入料完成→可出豆 判斷 ------------------------------
  3465. # ----- 將狀態寫入資料庫 ------------------------------
  3466. # 獲取文本框的值並賦值給user實體對象
  3467. D_status = dry_container_status()
  3468. D_status.Dry_Input_1 = DI1
  3469. D_status.Dry_Input_2 = DI2
  3470. D_status.Dry_Tank_1 = D1
  3471. D_status.Dry_Tank_2 = D2
  3472. D_status.Dry_Tank_3 = D3
  3473. D_status.Dry_Tank_4 = D4
  3474. D_status.Dry_Tank_5 = D5
  3475. D_status.Dry_Tank_6 = D6
  3476. D_status.Dry_Tank_7 = D7
  3477. D_status.Dry_Tank_8 = D8
  3478. D_status.Dry_Tank_9 = D9
  3479. D_status.Dry_Tank_10 = D10
  3480. D_status.Dry_Tank_11 = D11
  3481. D_status.Dry_Tank_12 = D12
  3482. D_status.Dry_Output_1 = DO1
  3483. D_status.Dry_Output_2 = DO2
  3484. #將數據保存進資料庫
  3485. db.session.add(D_status)
  3486. # 手動提交
  3487. db.session.commit()
  3488. # ----- 將狀態寫入資料庫 ------------------------------
  3489. return jsonify({"Dry_Tank_1":D1,
  3490. "Dry_Tank_2":D2,
  3491. "Dry_Output_1":DO1,
  3492. "Dry_Output_2":DO2
  3493. })
  3494. @main.route('/dry_auto_status', methods=['GET', 'POST'])
  3495. def dry_auto_status():
  3496. info = request.args.to_dict()
  3497. # 寫定入料、桶槽、出料的空桶標準, 若 <= 2 則為空桶
  3498. Dry_Input_bean_empty = 2
  3499. Dry_Tank_bean_empty = 2
  3500. Dry_Output_bean_empty = 2
  3501. # 從介面取得 指定生豆高度/發酵桶槽排程:發酵、清洗、校正 EC、校正攪拌棒
  3502. Dry_Input_bean_height = float(info['Dry_Input_bean_height'])
  3503. Dry_Input_vacuumON_time = float(info['Dry_Input_vacuumON_time'])
  3504. Dry_Input_vacuumOFF_time = float(info['Dry_Input_vacuumOFF_time'])
  3505. Dry_Tank_bean_height = float(info['Dry_Tank_bean_height'])
  3506. Dry_Tank_vacuumON_time = float(info['Dry_Tank_vacuumON_time'])
  3507. Dry_Tank_vacuumOFF_time = float(info['Dry_Tank_vacuumOFF_time'])
  3508. Dry_Tank_drying_temp = float(info['Dry_Tank_drying_temp'])
  3509. Dry_Tank_drying_time = float(info['Dry_Tank_drying_time'])
  3510. Dry_Tank_drying_EC = float(info['Dry_Tank_drying_EC'])
  3511. Dry_Tank_motor_rpm = float(info['Dry_Tank_motor_rpm'])
  3512. Dry_Tank_TempWeight_SHT11 = float(info['Dry_Tank_TempWeight_SHT11'])
  3513. Dry_Tank_TempWeight_soil = float(info['Dry_Tank_TempWeight_soil'])
  3514. Dry_Tank_drying_Humidity = float(info['Dry_Tank_drying_Humidity'])
  3515. Dry_Output_bean_height = float(info['Dry_Output_bean_height'])
  3516. Dry_Output_vacuumON_time = float(info['Dry_Output_vacuumON_time'])
  3517. Dry_Output_vacuumOFF_time = float(info['Dry_Output_vacuumOFF_time'])
  3518. Dry_Tank_Disinfect_time = float(info['Dry_Tank_Disinfect_time'])
  3519. # [介面] 讓使用者可以選擇排程內有乾燥/清洗/校正, 此處預設為 True
  3520. Dry_btn = True
  3521. # 從資料庫資料表中取得最新狀態
  3522. ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  3523. FO1 = ferment_status.Ferment_Output_1
  3524. FO2 = ferment_status.Ferment_Output_2
  3525. # FO1 = 'FO_OutputtingBean' # 'FO_OutputtingBean' FO_Waiting
  3526. # FO2 = 'FO_Waiting'
  3527. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  3528. DI1 = dry_status.Dry_Input_1
  3529. DI2 = dry_status.Dry_Input_2
  3530. D1 = dry_status.Dry_Tank_1
  3531. D2 = dry_status.Dry_Tank_2
  3532. D3 = dry_status.Dry_Tank_3
  3533. D4 = dry_status.Dry_Tank_4
  3534. D5 = dry_status.Dry_Tank_5
  3535. D6 = dry_status.Dry_Tank_6
  3536. D7 = dry_status.Dry_Tank_7
  3537. D8 = dry_status.Dry_Tank_8
  3538. D9 = dry_status.Dry_Tank_9
  3539. D10 = dry_status.Dry_Tank_10
  3540. D11 = dry_status.Dry_Tank_11
  3541. D12 = dry_status.Dry_Tank_12
  3542. DO1 = dry_status.Dry_Output_1
  3543. DO2 = dry_status.Dry_Output_2
  3544. D_UP_tanklist = [D1, D2, D3, D4, D5, D6]
  3545. D_DOWN_tanklist = [D7, D8, D9, D10, D11, D12]
  3546. DOutputtingBean_Tank = '' # 出料桶槽號
  3547. DryAuto_cleaning = 0 # 清洗次數
  3548. # 目前乾燥槽 D1~D6 正在入豆的桶槽數量 (應小於一桶)
  3549. DryUp_Waiting_number = int(D_UP_tanklist.count('D_Waiting'))
  3550. DryUp_InputtingBean_number = int(D_UP_tanklist.count('D_InputtingBean'))
  3551. DryUp_InputtingBeanPause_number = int(D_UP_tanklist.count('D_InputtingBean_Pause'))
  3552. # -- 取得乾燥入料儲豆槽 FI1~FI2 桶內高度 UltraSonic -------------
  3553. DI_UP_UltraSoniclist = []
  3554. for i in range(1, 3, 1):
  3555. input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI' + str(i)).order_by(text('datetime desc')).first()
  3556. UltraSonic = float(input_UltraSonic.UltraSonic)
  3557. DI_UP_UltraSoniclist.append(UltraSonic)
  3558. print('DI_UP_UltraSoniclist: ', DI_UP_UltraSoniclist)
  3559. # -- 取得乾燥入料儲豆槽 FI1~FI2 桶內高度 UltraSonic -------------
  3560. # -- 取得乾燥桶槽 D1~D6 超音波生豆高度 UltraSonic -------------
  3561. D_UP_tank_UltraSonic = []
  3562. for i in range(1, 7, 1):
  3563. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
  3564. UltraSonic = float(tank_UltraSonic.UltraSonic)
  3565. D_UP_tank_UltraSonic.append(UltraSonic)
  3566. print('D_UP_tank_UltraSonic: ', D_UP_tank_UltraSonic)
  3567. # -- 取得乾燥桶槽 D1~D6 超音波生豆高度 UltraSonic -------------
  3568. # -- 取得乾燥出料儲豆槽 DO1~DO2 桶內高度 UltraSonic -------------
  3569. DO_UP_UltraSoniclist = []
  3570. for i in range(1, 3, 1):
  3571. output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO' + str(i)).order_by(text('datetime desc')).first()
  3572. UltraSonic = float(output_UltraSonic.UltraSonic)
  3573. DO_UP_UltraSoniclist.append(UltraSonic)
  3574. print('DO_UP_UltraSoniclist: ', DO_UP_UltraSoniclist)
  3575. # -- 取得乾燥出料儲豆槽 DO1~DO2 桶內高度 UltraSonic -------------
  3576. # -- 取得乾燥桶槽 D1~D6 桶內溫濕度計 SHT11 -------------
  3577. D_UP_tank_SHT11Temp = []
  3578. D_UP_tank_SHT11Humidity = []
  3579. for i in range(1, 7, 1):
  3580. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
  3581. SHT11_Temp = float(tank_SHT11.SHT11_Temp)
  3582. D_UP_tank_SHT11Temp.append(SHT11_Temp)
  3583. SHT11_Humidity = float(tank_SHT11.SHT11_Humidity)
  3584. D_UP_tank_SHT11Humidity.append(SHT11_Humidity)
  3585. # print('D_UP_tank_SHT11Temp: ', D_UP_tank_SHT11Temp)
  3586. # print('D_UP_tank_SHT11Humidity: ', D_UP_tank_SHT11Humidity)
  3587. # -- 取得乾燥桶槽 D1~D6 桶內溫濕度計 SHT11 -------------
  3588. # -- 取得乾燥桶槽 D1~D6 三合一土壤感測器 Soil -------------
  3589. D_UP_tank_SoilTemp = []
  3590. D_UP_tank_SoilHumidity = []
  3591. D_UP_tank_SoilEC = []
  3592. for i in range(1, 7, 1):
  3593. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
  3594. soil_Temp = float(tank_Soil.soil_Temp)
  3595. D_UP_tank_SoilTemp.append(soil_Temp)
  3596. soil_Humidity = float(tank_Soil.soil_Humidity)
  3597. D_UP_tank_SoilHumidity.append(soil_Humidity)
  3598. soil_EC = float(tank_Soil.soil_EC)
  3599. D_UP_tank_SoilEC.append(soil_EC)
  3600. # print('D_UP_tank_SoilTemp: ', D_UP_tank_SoilTemp)
  3601. # print('D_UP_tank_SoilHumidity: ', D_UP_tank_SoilHumidity)
  3602. # print('D_UP_tank_SoilEC: ', D_UP_tank_SoilEC)
  3603. # -- 取得乾燥桶槽 D1~D6 三合一土壤感測器 SHT11 -------------
  3604. # -- 取得乾燥桶槽 D1~D6 權重後溫度值 -------------
  3605. D_UP_tank_weightTemp = []
  3606. for i in range(1, 7, 1):
  3607. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
  3608. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
  3609. 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)
  3610. D_UP_tank_weightTemp.append(Temp)
  3611. print('D_UP_tank_weightTemp: ', D_UP_tank_weightTemp)
  3612. # -- 取得乾燥桶槽 D1~D6 權重後溫度值 -------------
  3613. # ----- 發酵排程動作 start ------------------------------------------------------------------
  3614. # if D1 == 'D_InputtingBean': D_UP_tank_UltraSonic[0] >= Dry_Tank_bean_height:
  3615. def DInputtingBean_TO_DInputtingBeanFinish(tid):
  3616. # [致動器] 真空吸料機 OFF
  3617. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  3618. print('data: ', data)
  3619. # mqtt_f(data)
  3620. # [致動器] 馬達 0
  3621. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  3622. print('data: ', data)
  3623. # mqtt_f(data)
  3624. # [致動器] 入料三通閥 ON排氣
  3625. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "on" }
  3626. print('data: ', data)
  3627. # mqtt_f(data)
  3628. print('------- ', tid,' 狀態更新:入豆完成 -------')
  3629. # if D1 == 'D_InputtingBean': elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
  3630. def DInputtingBean_AND_notfilled(tid):
  3631. # [致動器] 入料三通閥 OFF入豆
  3632. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  3633. print('data: ', data)
  3634. # mqtt_f(data)
  3635. # [致動器] 真空吸料機 ON
  3636. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "on" }
  3637. print('data: ', data)
  3638. # mqtt_f(data)
  3639. timer = time.time()
  3640. while True:
  3641. if (time.time() - timer) > Dry_Tank_vacuumON_time:
  3642. # [致動器] 真空吸料機 OFF
  3643. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  3644. print('data: ', data)
  3645. # mqtt_f(data)
  3646. timer = time.time()
  3647. break
  3648. while True:
  3649. if (time.time() - timer) > Dry_Tank_vacuumOFF_time:
  3650. break
  3651. # if D1 == 'D_InputtingBean': elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
  3652. def DInputtingBean_TO_DInputtingBeanPause(tid):
  3653. # [致動器] 真空吸料機 OFF
  3654. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  3655. print('data: ', data)
  3656. # mqtt_f(data)
  3657. # [致動器] 馬達 0
  3658. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  3659. print('data: ', data)
  3660. # mqtt_f(data)
  3661. print('------- ', tid,' 狀態更新:入豆暫停 -------')
  3662. # elif DryUp_InputtingBeanPause_number == 1 and DI1 == 'DI_OutputtingBean': if D1 == 'D_InputtingBean_Pause':
  3663. def DInputtingBeanPause_TO_DInputtingBean(tid):
  3664. # [致動器] 入料三通閥 OFF入豆
  3665. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  3666. print('data: ', data)
  3667. # mqtt_f(data)
  3668. # [致動器] 馬達 5
  3669. data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
  3670. print('data: ', data)
  3671. # mqtt_f(data)
  3672. print('------- ', tid, ' 狀態更新:入豆中 -------')
  3673. # elif DryUp_InputtingBean_number == 0 and DryUp_InputtingBeanPause_number == 0 and DI1 == 'DI_OutputtingBean' and DryUp_Waiting_number >= 1:
  3674. def DWaiting_TO_DInputtingBean(tid):
  3675. # [致動器] 入料三通閥 OFF入豆
  3676. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  3677. print('data: ', data)
  3678. # mqtt_f(data)
  3679. # [致動器] 馬達 5
  3680. data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
  3681. print('data: ', data)
  3682. # mqtt_f(data)
  3683. print('------- ', tid, ' 狀態更新:入豆中 -------')
  3684. # else: if D1 == 'D_InputtingBean_Finish':
  3685. def DInputtingBeanFinish_TO_DDrying(tid):
  3686. # [致動器] 馬達 指定轉速
  3687. data = { "tank_num": tid, "command": "tank_motor_status", "value": Dry_Tank_motor_rpm }
  3688. print('data: ', data)
  3689. # mqtt_f(data)
  3690. # [致動器] 排水電磁閥 ON
  3691. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "on" }
  3692. print('data: ', data)
  3693. # mqtt_f(data)
  3694. # [致動器] 鼓風機 ON
  3695. data = { "tank_num": tid, "command": "tank_blower_status", "value": "on" }
  3696. print('data: ', data)
  3697. # mqtt_f(data)
  3698. # [致動器] 加熱器 1 ON
  3699. data = { "tank_num": tid, "command": "tank_heater1_status", "value": "on" }
  3700. print('data: ', data)
  3701. # mqtt_f(data)
  3702. # [致動器] 加熱器 2 ON
  3703. data = { "tank_num": tid, "command": "tank_heater2_status", "value": "on" }
  3704. print('data: ', data)
  3705. # mqtt_f(data)
  3706. print('------- ', tid, ' 狀態更新:乾燥中 -------')
  3707. # 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:
  3708. def DDrying_TO_DOutputtingBean(tid):
  3709. # [致動器] 鼓風機 OFF
  3710. data = { "tank_num": tid, "command": "tank_blower_status", "value": "off" }
  3711. print('data: ', data)
  3712. # mqtt_f(data)
  3713. # [致動器] 加熱器 1 OFF
  3714. data = { "tank_num": tid, "command": "tank_heater1_status", "value": "off" }
  3715. print('data: ', data)
  3716. # mqtt_f(data)
  3717. # [致動器] 加熱器 2 OFF
  3718. data = { "tank_num": tid, "command": "tank_heater2_status", "value": "off" }
  3719. print('data: ', data)
  3720. # mqtt_f(data)
  3721. # [致動器] 馬達 0
  3722. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  3723. print('data: ', data)
  3724. # mqtt_f(data)
  3725. print("乾燥結束, 返潮暫停 ", Dry_Tank_drying_time, " 秒")
  3726. timer = time.time()
  3727. while True:
  3728. if (time.time() - timer) > Dry_Tank_drying_time:
  3729. # [致動器] 排水電磁閥 OFF
  3730. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  3731. print('data: ', data)
  3732. # mqtt_f(data)
  3733. break
  3734. print('------- ', tid, ' 狀態更新:可出豆 -------')
  3735. # else: if D1 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[0] <= Dry_Tank_bean_empty):
  3736. def DOutputtingBean_TO_DWaiting(tid):
  3737. # [致動器] D1 蝴蝶閥 OFF
  3738. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
  3739. print('data: ', data)
  3740. # mqtt_f(data)
  3741. # D_Cleaning
  3742. def DCleaning(tid):
  3743. # [致動器] 馬達 10
  3744. data = { "tank_num": tid, "command": "tank_motor_status", "value": "10" }
  3745. print('data: ', data)
  3746. # mqtt_f(data)
  3747. # [致動器] 消毒電磁閥 ON
  3748. data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "on" }
  3749. print('data: ', data)
  3750. # mqtt_f(data)
  3751. # [致動器] 排水電磁閥 OFF
  3752. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  3753. print('data: ', data)
  3754. # mqtt_f(data)
  3755. # [致動器] TODO 消毒抽水 pump ON
  3756. print("消毒 ", Dry_Tank_Disinfect_time, " 秒")
  3757. timer = time.time()
  3758. while True:
  3759. if (time.time() - timer) > Dry_Tank_Disinfect_time:
  3760. # [致動器] TODO 消毒抽水 pump OFF
  3761. break
  3762. # [致動器] 消毒電磁閥 OFF
  3763. data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "off" }
  3764. print('data: ', data)
  3765. # mqtt_f(data)
  3766. # [致動器] 馬達 0
  3767. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  3768. print('data: ', data)
  3769. # mqtt_f(data)
  3770. # [致動器] 排水電磁閥 ON
  3771. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "on" }
  3772. print('data: ', data)
  3773. # mqtt_f(data)
  3774. print("桶內排水 ", Dry_Tank_Disinfect_time, " 秒")
  3775. timer = time.time()
  3776. while True:
  3777. if (time.time() - timer) > Dry_Tank_Disinfect_time:
  3778. break
  3779. # [致動器] 排水電磁閥 OFF
  3780. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  3781. print('data: ', data)
  3782. # mqtt_f(data)
  3783. print('------- ', tid, ' 狀態更新:空桶等待 -------')
  3784. # ----- 發酵排程動作 end ------------------------------------------------------------------
  3785. # ----- 乾燥入料儲豆槽 DI1~DI2 入豆→可出豆判斷 ------------------------------
  3786. # 如果入料儲豆槽 空桶等待, 且發酵出料儲豆槽 FO1 為可出豆, 則開始入豆
  3787. if DI1 == 'DI_Waiting' and FO1 == 'FO_OutputtingBean':
  3788. DI1 = 'DI_InputtingBean'
  3789. print('------- DI1 狀態更新:入料中 -------')
  3790. # 如果入料儲豆槽 入豆中
  3791. elif DI1 == 'DI_InputtingBean':
  3792. # 如果入豆儲豆槽達指定高度時
  3793. if DI_UP_UltraSoniclist[0] >= Dry_Input_bean_height:
  3794. # [致動器] 入料真空吸料機 OFF
  3795. data = { "tank_num": "D1", "command": "input_vacuum_status", "value": "off" }
  3796. print('data: ', data)
  3797. # mqtt_f(data)
  3798. DI1 = 'DI_OutputtingBean'
  3799. print('------- DI1 狀態更新:可出豆 -------')
  3800. # 如果入豆儲豆槽未達指定高度, 且 發酵出料儲豆槽 可出豆
  3801. elif DI_UP_UltraSoniclist[0] < Dry_Input_bean_height and FO1 == 'FO_OutputtingBean':
  3802. # [致動器] 入料真空吸料機 ON
  3803. data = { "tank_num": "D1", "command": "input_vacuum_status", "value": "on" }
  3804. print('data: ', data)
  3805. # mqtt_f(data)
  3806. timer = time.time()
  3807. while True:
  3808. if (time.time() - timer) > Dry_Input_vacuumON_time:
  3809. # [致動器] 入料真空吸料機 OFF
  3810. data = { "tank_num": "D1", "command": "input_vacuum_status", "value": "off" }
  3811. print('data: ', data)
  3812. # mqtt_f(data)
  3813. timer = time.time()
  3814. break
  3815. while True:
  3816. if (time.time() - timer) > Dry_Input_vacuumOFF_time:
  3817. break
  3818. # 如果入料儲豆槽生豆大於空桶高度, 且 前方 FO1 非可出豆, 將狀態轉為可出豆
  3819. elif (DI_UP_UltraSoniclist[0] > Dry_Input_bean_empty) and FO1 != 'FO_OutputtingBean':
  3820. DI1 = 'DI_OutputtingBean'
  3821. print('------- DI1 狀態更新:可出豆 -------')
  3822. # 桶槽內小於空桶高度, 且 前方 FO1 非可出豆, 將狀態轉為空桶等待
  3823. elif (DI_UP_UltraSoniclist[0] <= Dry_Input_bean_empty) and FO1 != 'PO_OutputtingBean':
  3824. DI1 = 'DI_Waiting'
  3825. print('------- FI1 狀態更新:空桶等待 -------')
  3826. # 入料儲豆槽出豆時, 桶槽高度為 空桶高度時, 狀態轉為 空桶等待
  3827. elif DI1 == 'DI_OutputtingBean' and (DI_UP_UltraSoniclist[0] <= Dry_Input_bean_empty):
  3828. DI1 = 'DI_Waiting'
  3829. print('------- DI1 狀態更新:空桶等待 -------')
  3830. # [介面] 若啟用 乾燥 狀態
  3831. if Dry_btn:
  3832. # ----- 乾燥桶槽 D1~D6 入料桶槽優先入料判斷 ------------------------------
  3833. # 若 D1~D6 桶槽中有一個桶槽入豆中
  3834. if DryUp_InputtingBean_number == 1:
  3835. # 若 D1 桶槽為入豆中
  3836. if D1 == 'D_InputtingBean':
  3837. # 若桶槽生豆高度大於指定生豆高度, 則狀態轉換成 入料完成
  3838. if D_UP_tank_UltraSonic[0] >= Dry_Tank_bean_height:
  3839. DInputtingBean_TO_DInputtingBeanFinish("D1")
  3840. D1 = 'D_InputtingBean_Finish'
  3841. # 若桶槽生豆高度未達指定生豆高度, 且 入料儲豆槽可出豆
  3842. elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
  3843. DInputtingBean_AND_notfilled("D1")
  3844. # 若桶槽生豆高度未達指定生豆高度, 且 入料儲豆槽 非可出豆
  3845. elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
  3846. DInputtingBean_TO_DInputtingBeanPause("D1")
  3847. D1 = 'D_InputtingBean_Pause'
  3848. elif D2 == 'D_InputtingBean':
  3849. if D_UP_tank_UltraSonic[1] >= Dry_Tank_bean_height:
  3850. DInputtingBean_TO_DInputtingBeanFinish("D2")
  3851. D2 = 'D_InputtingBean_Finish'
  3852. elif D_UP_tank_UltraSonic[1] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
  3853. DInputtingBean_AND_notfilled("D2")
  3854. elif D_UP_tank_UltraSonic[1] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
  3855. DInputtingBean_TO_DInputtingBeanPause("D2")
  3856. D2 = 'D_InputtingBean_Pause'
  3857. elif D3 == 'D_InputtingBean':
  3858. if D_UP_tank_UltraSonic[2] >= Dry_Tank_bean_height:
  3859. DInputtingBean_TO_DInputtingBeanFinish("D3")
  3860. D3 = 'D_InputtingBean_Finish'
  3861. elif D_UP_tank_UltraSonic[2] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
  3862. DInputtingBean_AND_notfilled("D2")
  3863. elif D_UP_tank_UltraSonic[2] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
  3864. DInputtingBean_TO_DInputtingBeanPause("D2")
  3865. D3 = 'D_InputtingBean_Pause'
  3866. elif D4 == 'D_InputtingBean':
  3867. if D_UP_tank_UltraSonic[3] >= Dry_Tank_bean_height:
  3868. DInputtingBean_TO_DInputtingBeanFinish("D4")
  3869. D4 = 'D_InputtingBean_Finish'
  3870. elif D_UP_tank_UltraSonic[3] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
  3871. DInputtingBean_AND_notfilled("D4")
  3872. elif D_UP_tank_UltraSonic[3] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
  3873. DInputtingBean_TO_DInputtingBeanPause("D4")
  3874. D4 = 'D_InputtingBean_Pause'
  3875. elif D5 == 'D_InputtingBean':
  3876. if D_UP_tank_UltraSonic[4] >= Dry_Tank_bean_height:
  3877. DInputtingBean_TO_DInputtingBeanFinish("D5")
  3878. D5 = 'D_InputtingBean_Finish'
  3879. elif D_UP_tank_UltraSonic[4] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
  3880. DInputtingBean_AND_notfilled("D5")
  3881. elif D_UP_tank_UltraSonic[4] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
  3882. DInputtingBean_TO_DInputtingBeanPause("D5")
  3883. D5 = 'D_InputtingBean_Pause'
  3884. elif D6 == 'D_InputtingBean':
  3885. if D_UP_tank_UltraSonic[5] >= Dry_Tank_bean_height:
  3886. DInputtingBean_TO_DInputtingBeanFinish("D6")
  3887. D6 = 'D_InputtingBean_Finish'
  3888. elif D_UP_tank_UltraSonic[5] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
  3889. DInputtingBean_AND_notfilled("D6")
  3890. elif D_UP_tank_UltraSonic[5] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
  3891. DInputtingBean_TO_DInputtingBeanPause("D6")
  3892. D6 = 'D_InputtingBean_Pause'
  3893. # 若 D1~D6 桶槽中有一個桶槽入豆暫停
  3894. elif DryUp_InputtingBeanPause_number == 1 and DI1 == 'DI_OutputtingBean':
  3895. if D1 == 'D_InputtingBean_Pause':
  3896. DInputtingBeanPause_TO_DInputtingBean("D1")
  3897. D1 = 'D_InputtingBean'
  3898. elif D2 == 'D_InputtingBean_Pause':
  3899. DInputtingBeanPause_TO_DInputtingBean("D2")
  3900. D2 = 'D_InputtingBean'
  3901. elif D3 == 'D_InputtingBean_Pause':
  3902. DInputtingBeanPause_TO_DInputtingBean("D3")
  3903. D3 = 'D_InputtingBean'
  3904. elif D4 == 'D_InputtingBean_Pause':
  3905. DInputtingBeanPause_TO_DInputtingBean("D4")
  3906. D4 = 'D_InputtingBean'
  3907. elif D5 == 'D_InputtingBean_Pause':
  3908. DInputtingBeanPause_TO_DInputtingBean("D5")
  3909. D5 = 'D_InputtingBean'
  3910. elif D6 == 'D_InputtingBean_Pause':
  3911. DInputtingBeanPause_TO_DInputtingBean("D6")
  3912. D6 = 'D_InputtingBean'
  3913. # 若 D1~D6 桶槽中皆無 入豆中 和 入豆暫停, 且入料儲豆槽可出豆
  3914. elif DryUp_InputtingBean_number == 0 and DryUp_InputtingBeanPause_number == 0 and DI1 == 'DI_OutputtingBean' and DryUp_Waiting_number >= 1:
  3915. if D1 == 'D_Waiting':
  3916. DWaiting_TO_DInputtingBean("D1")
  3917. D1 = 'D_InputtingBean'
  3918. elif D2 == 'D_Waiting':
  3919. DWaiting_TO_DInputtingBean("D2")
  3920. D2 = 'D_InputtingBean'
  3921. elif D3 == 'D_Waiting':
  3922. DWaiting_TO_DInputtingBean("D3")
  3923. D3 = 'D_InputtingBean'
  3924. elif D4 == 'D_Waiting':
  3925. DWaiting_TO_DInputtingBean("D4")
  3926. D4 = 'D_InputtingBean'
  3927. elif D5 == 'D_Waiting':
  3928. DWaiting_TO_DInputtingBean("D5")
  3929. D5 = 'D_InputtingBean'
  3930. elif D6 == 'D_Waiting':
  3931. DWaiting_TO_DInputtingBean("D6")
  3932. D6 = 'D_InputtingBean'
  3933. # 其他
  3934. else:
  3935. # 如果桶槽為 入豆完成, 將狀態轉換成 乾燥中
  3936. if D1 == 'D_InputtingBean_Finish':
  3937. DInputtingBeanFinish_TO_DDrying("D1")
  3938. D1 = 'D_Drying'
  3939. if D2 == 'D_InputtingBean_Finish':
  3940. DInputtingBeanFinish_TO_DDrying("D2")
  3941. D2 = 'D_Drying'
  3942. if D3 == 'D_InputtingBean_Finish':
  3943. DInputtingBeanFinish_TO_DDrying("D3")
  3944. D3 = 'D_Drying'
  3945. if D4 == 'D_InputtingBean_Finish':
  3946. DInputtingBeanFinish_TO_DDrying("D4")
  3947. D4 = 'D_Drying'
  3948. if D5 == 'D_InputtingBean_Finish':
  3949. DInputtingBeanFinish_TO_DDrying("D5")
  3950. D5 = 'D_Drying'
  3951. if D6 == 'D_InputtingBean_Finish':
  3952. DInputtingBeanFinish_TO_DDrying("D6")
  3953. D6 = 'D_Drying'
  3954. # 如果桶槽為 乾燥中, 達乾燥條件後, 將狀態轉換成 可出豆
  3955. if D1 == 'D_Drying' and D_UP_tank_weightTemp[0] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[0] <= Dry_Tank_drying_Humidity:
  3956. DDrying_TO_DOutputtingBean("D1")
  3957. D1 = 'D_OutputtingBean'
  3958. if DOutputtingBean_Tank == '': DOutputtingBean_Tank = 'D1'
  3959. if D2 == 'D_Drying' and D_UP_tank_weightTemp[1] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[1] <= Dry_Tank_drying_Humidity:
  3960. DDrying_TO_DOutputtingBean("D2")
  3961. D2 = 'D_OutputtingBean'
  3962. if DOutputtingBean_Tank == '': DOutputtingBean_Tank = 'D2'
  3963. if D3 == 'D_Drying' and D_UP_tank_weightTemp[2] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[2] <= Dry_Tank_drying_Humidity:
  3964. DDrying_TO_DOutputtingBean("D3")
  3965. D3 = 'D_OutputtingBean'
  3966. if DOutputtingBean_Tank == '': DOutputtingBean_Tank = 'D3'
  3967. if D4 == 'D_Drying' and D_UP_tank_weightTemp[3] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[3] <= Dry_Tank_drying_Humidity:
  3968. DDrying_TO_DOutputtingBean("D4")
  3969. D4 = 'D_OutputtingBean'
  3970. if DOutputtingBean_Tank == '': DOutputtingBean_Tank = 'D4'
  3971. if D5 == 'D_Drying' and D_UP_tank_weightTemp[4] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[4] <= Dry_Tank_drying_Humidity:
  3972. DDrying_TO_DOutputtingBean("D5")
  3973. D5 = 'D_OutputtingBean'
  3974. if DOutputtingBean_Tank == '': DOutputtingBean_Tank = 'D5'
  3975. if D6 == 'D_Drying' and D_UP_tank_weightTemp[5] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[5] <= Dry_Tank_drying_Humidity:
  3976. DDrying_TO_DOutputtingBean("D6")
  3977. D6 = 'D_OutputtingBean'
  3978. if DOutputtingBean_Tank == '': DOutputtingBean_Tank = 'D6'
  3979. # 如果桶槽 D1~D6 可出豆 且 桶槽內為空桶 且 有指定清洗排程, 進行清洗桶槽
  3980. # TODO 發酵次數計算、消毒次數、校正
  3981. if D1 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[0] <= Dry_Tank_bean_empty):
  3982. if DOutputtingBean_Tank == 'D1':
  3983. DOutputtingBean_TO_DWaiting('D1')
  3984. DOutputtingBean_Tank = ''
  3985. if (DryAuto_cleaning == 0): D1 = 'D_Waiting'
  3986. elif (DryAuto_cleaning != 0): D1 = 'D_Cleaning'
  3987. if D2 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[1] <= Dry_Tank_bean_empty):
  3988. if DOutputtingBean_Tank == 'D2':
  3989. DOutputtingBean_TO_DWaiting('D2')
  3990. DOutputtingBean_Tank = ''
  3991. if (DryAuto_cleaning == 0): D2 = 'D_Waiting'
  3992. elif (DryAuto_cleaning != 0): D2 = 'D_Cleaning'
  3993. if D3 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[2] <= Dry_Tank_bean_empty):
  3994. if DOutputtingBean_Tank == 'D2':
  3995. DOutputtingBean_TO_DWaiting('D2')
  3996. DOutputtingBean_Tank = ''
  3997. if (DryAuto_cleaning == 0): D3 = 'D_Waiting'
  3998. elif (DryAuto_cleaning != 0): D3 = 'D_Cleaning'
  3999. if D4 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[3] <= Dry_Tank_bean_empty):
  4000. if DOutputtingBean_Tank == 'D4':
  4001. DOutputtingBean_TO_DWaiting('D4')
  4002. DOutputtingBean_Tank = ''
  4003. if (DryAuto_cleaning == 0): D4 = 'D_Waiting'
  4004. elif (DryAuto_cleaning != 0): D4 = 'D_Cleaning'
  4005. if D5 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[4] <= Dry_Tank_bean_empty):
  4006. if DOutputtingBean_Tank == 'D5':
  4007. DOutputtingBean_TO_DWaiting('D5')
  4008. DOutputtingBean_Tank = ''
  4009. if (DryAuto_cleaning == 0): D5 = 'D_Waiting'
  4010. elif (DryAuto_cleaning != 0): D5 = 'D_Cleaning'
  4011. if D6 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[5] <= Dry_Tank_bean_empty):
  4012. if DOutputtingBean_Tank == 'D6':
  4013. DOutputtingBean_TO_DWaiting('D6')
  4014. DOutputtingBean_Tank = ''
  4015. if (DryAuto_cleaning == 0): D6 = 'D_Waiting'
  4016. elif (DryAuto_cleaning != 0): D6 = 'D_Cleaning'
  4017. # 避免桶槽可出豆時未賦值
  4018. if DOutputtingBean_Tank == '':
  4019. if D1 == 'D_OutputtingBean': DOutputtingBean_Tank = 'D1'
  4020. elif D2 == 'D_OutputtingBean': DOutputtingBean_Tank = 'D2'
  4021. elif D3 == 'D_OutputtingBean': DOutputtingBean_Tank = 'D3'
  4022. elif D4 == 'D_OutputtingBean': DOutputtingBean_Tank = 'D4'
  4023. elif D5 == 'D_OutputtingBean': DOutputtingBean_Tank = 'D5'
  4024. elif D6 == 'D_OutputtingBean': DOutputtingBean_Tank = 'D6'
  4025. # 乾燥槽消毒
  4026. if D1 == 'D_Cleaning':
  4027. DCleaning("D1")
  4028. D1 = 'D_Waiting'
  4029. if D2 == 'D_Cleaning':
  4030. DCleaning("D2")
  4031. D2 = 'D_Waiting'
  4032. if D3 == 'D_Cleaning':
  4033. DCleaning("D3")
  4034. D3 = 'D_Waiting'
  4035. if D4 == 'D_Cleaning':
  4036. DCleaning("D4")
  4037. D4 = 'D_Waiting'
  4038. if D5 == 'D_Cleaning':
  4039. DCleaning("D5")
  4040. D5 = 'D_Waiting'
  4041. if D6 == 'D_Cleaning':
  4042. DCleaning("D6")
  4043. D6 = 'D_Waiting'
  4044. else:
  4045. print('未啟用乾燥流程')
  4046. # ----- 乾燥出料儲豆槽 DO1~DO2 入豆→可出豆判斷 ------------------------------
  4047. # 若出料儲豆槽狀態為 空桶等待 且 桶槽狀態為 D_OutputtingBean 可出豆, 與 FO1 配合開始出豆
  4048. if DO1 == 'DO_Waiting' and DOutputtingBean_Tank != '':
  4049. # 判斷要對應出料的桶槽為何, 設定成 DOutputtingBean_Tank = 'D1', 待出完料再把 DOutputtingBean_Tank = ''
  4050. DO1 = 'DO_InputtingBean'
  4051. print('------- ' + DOutputtingBean_Tank + ' 狀態更新:出豆中 -------')
  4052. print('------- DO1 狀態更新:入豆中 -------')
  4053. # [致動器] D1 蝴蝶閥 ON
  4054. data = { "tank_num": DOutputtingBean_Tank, "command": "tank_diskvalve_status", "value": "on" }
  4055. print('data: ', data)
  4056. # mqtt_f(data)
  4057. elif DO1 == 'DO_InputtingBean' and DOutputtingBean_Tank != '':
  4058. if DO_UP_UltraSoniclist[0] >= Dry_Output_bean_height:
  4059. # [致動器] 出料真空吸料機 OFF
  4060. data = { "tank_num": DOutputtingBean_Tank, "command": "output_vacuum_status", "value": "off" }
  4061. print('data: ', data)
  4062. # mqtt_f(data)
  4063. # [致動器] D1 蝴蝶閥 OFF
  4064. data = { "tank_num": DOutputtingBean_Tank, "command": "tank_diskvalve_status", "value": "off" }
  4065. print('data: ', data)
  4066. # mqtt_f(data)
  4067. DO1 = 'DO_OutputtingBean'
  4068. print('------- DO1 狀態更新:可出豆 -------')
  4069. elif DO_UP_UltraSoniclist[0] < Dry_Output_bean_height:
  4070. # [致動器] 出料真空吸料機 ON
  4071. data = { "tank_num": DOutputtingBean_Tank, "command": "output_vacuum_status", "value": "on" }
  4072. print('data: ', data)
  4073. # mqtt_f(data)
  4074. timer = time.time()
  4075. while True:
  4076. if (time.time() - timer) > Dry_Output_vacuumON_time:
  4077. # [致動器] 出料真空吸料機 OFF
  4078. data = { "tank_num": DOutputtingBean_Tank, "command": "output_vacuum_status", "value": "off" }
  4079. print('data: ', data)
  4080. # mqtt_f(data)
  4081. timer = time.time()
  4082. break
  4083. while True:
  4084. if (time.time() - timer) > Dry_Output_vacuumOFF_time:
  4085. break
  4086. # 若是無桶槽可入豆, 出料儲豆槽判斷是否可出豆或空桶等待入豆
  4087. elif DOutputtingBean_Tank == '':
  4088. if DO_UP_UltraSoniclist[0] > Dry_Output_bean_empty:
  4089. DO1 = 'DO_OutputtingBean'
  4090. print('------- DO1 狀態更新:可出豆 -------')
  4091. elif DO_UP_UltraSoniclist[0] <= Dry_Output_bean_empty:
  4092. DO1 = 'DO_Waiting'
  4093. print('------- DO1 狀態更新:空桶等待 -------')
  4094. elif DO1 == 'DO_OutputtingBean' and DO_UP_UltraSoniclist[0] <= Dry_Output_bean_empty:
  4095. DO1 = 'DO_Waiting'
  4096. print('------- DO1 狀態更新:空桶等待 -------')
  4097. # # ----- [測試用] !!!!! D1~D6 入料完成→可出豆 判斷 ------------------------------
  4098. # if D1 == 'D_InputtingBean_Finish': D1 = 'D_OutputtingBean'
  4099. # if D2 == 'D_InputtingBean_Finish': D2 = 'D_OutputtingBean'
  4100. # if D3 == 'D_InputtingBean_Finish': D3 = 'D_OutputtingBean'
  4101. # if D4 == 'D_InputtingBean_Finish': D4 = 'D_OutputtingBean'
  4102. # if D5 == 'D_InputtingBean_Finish': D5 = 'D_OutputtingBean'
  4103. # if D6 == 'D_InputtingBean_Finish': D6 = 'D_OutputtingBean'
  4104. # # ----- [測試用] !!!!! D1~D6 入料完成→可出豆 判斷 ------------------------------
  4105. # ----- 將狀態寫入資料庫 ------------------------------
  4106. # 獲取文本框的值並賦值給user實體對象
  4107. D_status = dry_container_status()
  4108. D_status.Dry_Input_1 = DI1
  4109. D_status.Dry_Input_2 = DI2
  4110. D_status.Dry_Tank_1 = D1
  4111. D_status.Dry_Tank_2 = D2
  4112. D_status.Dry_Tank_3 = D3
  4113. D_status.Dry_Tank_4 = D4
  4114. D_status.Dry_Tank_5 = D5
  4115. D_status.Dry_Tank_6 = D6
  4116. D_status.Dry_Tank_7 = D7
  4117. D_status.Dry_Tank_8 = D8
  4118. D_status.Dry_Tank_9 = D9
  4119. D_status.Dry_Tank_10 = D10
  4120. D_status.Dry_Tank_11 = D11
  4121. D_status.Dry_Tank_12 = D12
  4122. D_status.Dry_Output_1 = DO1
  4123. D_status.Dry_Output_2 = DO2
  4124. #將數據保存進資料庫
  4125. db.session.add(D_status)
  4126. # 手動提交
  4127. db.session.commit()
  4128. # ----- 將狀態寫入資料庫 ------------------------------
  4129. return jsonify({"Dry_Input_1":DI1,
  4130. "Dry_Tank_1":D1,
  4131. "Dry_Tank_2":D2,
  4132. "Dry_Tank_3":D3,
  4133. "Dry_Tank_4":D4,
  4134. "Dry_Tank_5":D5,
  4135. "Dry_Tank_6":D6,
  4136. "Dry_Output_1":DO1
  4137. })
  4138. #測試新發酵流程功能
  4139. @main.route('/test_ferment', methods=['GET', 'POST'])
  4140. def test_ferment():
  4141. # 獲取登入信息
  4142. if 'id' in session and 'uname' in session and 'status' in session:
  4143. username = session['uname']
  4144. status = session['status']
  4145. #ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  4146. mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffee', password='skyeye', database='Coffee', charset='utf8')
  4147. mycursor = mydb.cursor()
  4148. sql = '''SELECT * FROM `ferment_container_status` ORDER BY `sn` DESC LIMIT 1 '''
  4149. mycursor.execute(sql)
  4150. content = mycursor.fetchall()
  4151. return render_template('test_ferment.html', title="[測試] 發酵流程自動化", **locals())
  4152. else:
  4153. return render_template('sign_in.html')
  4154. # 發酵槽自動化測試頁
  4155. @main.route('/auto_F/<ftid>', methods=['GET', 'POST'])
  4156. def ferment_auto(ftid):
  4157. # 獲取登入信息
  4158. if 'id' in session and 'uname' in session and 'status' in session:
  4159. username = session['uname']
  4160. status = session['status']
  4161. ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  4162. db.session.close()
  4163. FI1 = ferment_status.Ferment_Input_1
  4164. FI2 = ferment_status.Ferment_Input_2
  4165. F1 = ferment_status.Ferment_Tank_1
  4166. F2 = ferment_status.Ferment_Tank_2
  4167. F3 = ferment_status.Ferment_Tank_3
  4168. F4 = ferment_status.Ferment_Tank_4
  4169. F5 = ferment_status.Ferment_Tank_5
  4170. F6 = ferment_status.Ferment_Tank_6
  4171. F7 = ferment_status.Ferment_Tank_7
  4172. F8 = ferment_status.Ferment_Tank_8
  4173. F9 = ferment_status.Ferment_Tank_9
  4174. F10 = ferment_status.Ferment_Tank_10
  4175. F11 = ferment_status.Ferment_Tank_11
  4176. F12 = ferment_status.Ferment_Tank_12
  4177. FO1 = ferment_status.Ferment_Output_1
  4178. FO2 = ferment_status.Ferment_Output_2
  4179. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  4180. db.session.close()
  4181. PO1 = clean_status.Peel_Output_1 # PO_Waiting # PO_OutputtingBean
  4182. PO2 = clean_status.Peel_Output_2
  4183. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  4184. db.session.close()
  4185. DI1 = dry_status.Dry_Input_1
  4186. DI2 = dry_status.Dry_Input_2
  4187. return render_template('auto_F.html', title="發酵 F"+ftid+"自動化設定", **locals())
  4188. else:
  4189. return render_template('sign_in.html')
  4190. # 發酵槽自動化測試頁
  4191. @main.route('/auto_FI/<fitid>', methods=['GET', 'POST'])
  4192. def auto_FI(fitid):
  4193. # 獲取登入信息
  4194. if 'id' in session and 'uname' in session and 'status' in session:
  4195. username = session['uname']
  4196. status = session['status']
  4197. ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  4198. db.session.close()
  4199. FI1 = ferment_status.Ferment_Input_1
  4200. FI2 = ferment_status.Ferment_Input_2
  4201. F1 = ferment_status.Ferment_Tank_1
  4202. F2 = ferment_status.Ferment_Tank_2
  4203. F3 = ferment_status.Ferment_Tank_3
  4204. F4 = ferment_status.Ferment_Tank_4
  4205. F5 = ferment_status.Ferment_Tank_5
  4206. F6 = ferment_status.Ferment_Tank_6
  4207. F7 = ferment_status.Ferment_Tank_7
  4208. F8 = ferment_status.Ferment_Tank_8
  4209. F9 = ferment_status.Ferment_Tank_9
  4210. F10 = ferment_status.Ferment_Tank_10
  4211. F11 = ferment_status.Ferment_Tank_11
  4212. F12 = ferment_status.Ferment_Tank_12
  4213. FO1 = ferment_status.Ferment_Output_1
  4214. FO2 = ferment_status.Ferment_Output_2
  4215. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  4216. db.session.close()
  4217. PO1 = clean_status.Peel_Output_1 # PO_Waiting # PO_OutputtingBean
  4218. PO2 = clean_status.Peel_Output_2
  4219. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  4220. db.session.close()
  4221. DI1 = dry_status.Dry_Input_1
  4222. DI2 = dry_status.Dry_Input_2
  4223. return render_template('auto_FI.html', title="發酵入料 FI"+fitid+"自動化設定", **locals())
  4224. else:
  4225. return render_template('sign_in.html')
  4226. # 發酵槽自動化測試頁
  4227. @main.route('/auto_FO/<fotid>', methods=['GET', 'POST'])
  4228. def auto_FO(fotid):
  4229. # 獲取登入信息
  4230. if 'id' in session and 'uname' in session and 'status' in session:
  4231. username = session['uname']
  4232. status = session['status']
  4233. ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  4234. db.session.close()
  4235. FI1 = ferment_status.Ferment_Input_1
  4236. FI2 = ferment_status.Ferment_Input_2
  4237. F1 = ferment_status.Ferment_Tank_1
  4238. F2 = ferment_status.Ferment_Tank_2
  4239. F3 = ferment_status.Ferment_Tank_3
  4240. F4 = ferment_status.Ferment_Tank_4
  4241. F5 = ferment_status.Ferment_Tank_5
  4242. F6 = ferment_status.Ferment_Tank_6
  4243. F7 = ferment_status.Ferment_Tank_7
  4244. F8 = ferment_status.Ferment_Tank_8
  4245. F9 = ferment_status.Ferment_Tank_9
  4246. F10 = ferment_status.Ferment_Tank_10
  4247. F11 = ferment_status.Ferment_Tank_11
  4248. F12 = ferment_status.Ferment_Tank_12
  4249. FO1 = ferment_status.Ferment_Output_1
  4250. FO2 = ferment_status.Ferment_Output_2
  4251. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  4252. db.session.close()
  4253. PO1 = clean_status.Peel_Output_1 # PO_Waiting # PO_OutputtingBean
  4254. PO2 = clean_status.Peel_Output_2
  4255. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  4256. db.session.close()
  4257. DI1 = dry_status.Dry_Input_1
  4258. DI2 = dry_status.Dry_Input_2
  4259. return render_template('auto_FO.html', title="發酵出料 FO"+fotid+"自動化設定", **locals())
  4260. else:
  4261. return render_template('sign_in.html')
  4262. # 發酵槽自動化測試頁
  4263. @main.route('/ferment_auto_data', methods=['GET', 'POST'])
  4264. def ferment_auto_data():
  4265. if request.method == 'GET':
  4266. try:
  4267. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  4268. db.session.close()
  4269. DI1 = dry_status.Dry_Input_1
  4270. DI2 = dry_status.Dry_Input_2
  4271. ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  4272. db.session.close()
  4273. FI1 = ferment_status.Ferment_Input_1
  4274. FI2 = ferment_status.Ferment_Input_2
  4275. F1 = ferment_status.Ferment_Tank_1
  4276. F2 = ferment_status.Ferment_Tank_2
  4277. F3 = ferment_status.Ferment_Tank_3
  4278. F4 = ferment_status.Ferment_Tank_4
  4279. F5 = ferment_status.Ferment_Tank_5
  4280. F6 = ferment_status.Ferment_Tank_6
  4281. F7 = ferment_status.Ferment_Tank_7
  4282. F8 = ferment_status.Ferment_Tank_8
  4283. F9 = ferment_status.Ferment_Tank_9
  4284. F10 = ferment_status.Ferment_Tank_10
  4285. F11 = ferment_status.Ferment_Tank_11
  4286. F12 = ferment_status.Ferment_Tank_12
  4287. FO1 = ferment_status.Ferment_Output_1
  4288. FO2 = ferment_status.Ferment_Output_2
  4289. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  4290. db.session.close()
  4291. PO1 = clean_status.Peel_Output_1 # PO_Waiting # PO_OutputtingBean
  4292. PO2 = clean_status.Peel_Output_2
  4293. dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
  4294. db.session.close()
  4295. DI1 = dry_status.Dry_Input_1
  4296. DI2 = dry_status.Dry_Input_2
  4297. dict = {"PO1":PO1, "PO2":PO2,"FI1":FI1, "FI2":FI2, "F1":F1, "F2":F2, "F3":F3, "F4":F4, "F5":F5, "F6":F6, "F7":F7, "F8":F8, "F9":F9, "F10":F10, "F11":F11, "F12":F12, "FO1":FO1, "FO2":FO2,"DI1":DI1, "DI2":DI2, "DI2":DI2}
  4298. return json.dumps(dict)
  4299. except Exception as e:
  4300. return json.dumps({"status":None})
  4301. else:
  4302. pass
  4303. @main.route('/fermentDEMO_auto_status', methods=['GET', 'POST'])
  4304. def fermentDEMO_auto_status():
  4305. info = request.args.to_dict()
  4306. Ferment_Tank_bean_height = float(info['Ferment_Tank_bean_height'])
  4307. Ferment_Tank_vacuumON_time = float(info['Ferment_Tank_vacuumON_time'])
  4308. Ferment_Tank_vacuumOFF_time = float(info['Ferment_Tank_vacuumOFF_time'])
  4309. Ferment_Tank_water_height = float(info['Ferment_Tank_water_height'])
  4310. Ferment_Tank_fermenting_temp = float(info['Ferment_Tank_fermenting_temp'])
  4311. Ferment_Tank_fermenting_time = float(info['Ferment_Tank_fermenting_time'])
  4312. Ferment_Tank_motor_rpm = float(info['Ferment_Tank_motor_rpm'])
  4313. Ferment_Tank_WaterOut_time = float(info['Ferment_Tank_WaterOut_time'])
  4314. Ferment_btn = True
  4315. # 從資料庫資料表中取得最新狀態
  4316. ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  4317. FI1 = ferment_status.Ferment_Input_1 # FI1 = 'FI_OutputtingBean'
  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. F_UP_tanklist = [F1, F2, F3, F4, F5, F6]
  4334. FOutputtingBean_Tank = '' # 這是給出料儲豆槽判斷目前出豆的桶槽
  4335. # 寫定入料、桶槽、出料的空桶標準, 若 <= 2 則為空桶
  4336. Ferment_Input_bean_empty = 2
  4337. Ferment_Tank_bean_empty = 2
  4338. Ferment_Output_bean_empty = 2
  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. # F1 == 'F_InputtingBean' AND (F_UP_UltraSoniclist[0] >= Ferment_Tank_bean_height):
  4392. def FInputtingBean_TO_FInputtingBeanFinish(tid): # 1108 [測試] 入豆後直接出豆
  4393. # [致動器] 蝴蝶閥 OFF
  4394. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
  4395. print('data: ', data)
  4396. # mqtt_f(data)
  4397. # [致動器] 真空吸料機 OFF
  4398. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  4399. print('data: ', data)
  4400. # mqtt_f(data)
  4401. # [致動器] 馬達 0
  4402. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  4403. print('data: ', data)
  4404. # mqtt_f(data)
  4405. # [致動器] 入料三通閥 ON排氣
  4406. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "on" }
  4407. print('data: ', data)
  4408. # mqtt_f(data)
  4409. # print('------- ', tid,' 狀態更新:入料完成 -------')
  4410. print('------- ', tid,' 狀態更新:可出豆 -------')
  4411. # (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height) AND FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height):
  4412. def FInputtingBean_AND_notfilled(tid):
  4413. # [致動器] 蝴蝶閥 OFF
  4414. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
  4415. print('data: ', data)
  4416. # mqtt_f(data)
  4417. # [致動器] 入料三通閥 OFF入豆
  4418. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  4419. print('data: ', data)
  4420. # mqtt_f(data)
  4421. # [致動器] 真空吸料機 ON
  4422. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "on" }
  4423. print('data: ', data)
  4424. # mqtt_f(data)
  4425. timer = time.time()
  4426. while True:
  4427. if (time.time() - timer) > Ferment_Tank_vacuumON_time:
  4428. # [致動器] 入料真空吸料機 OFF
  4429. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  4430. print('data: ', data)
  4431. # mqtt_f(data)
  4432. timer = time.time()
  4433. break
  4434. while True:
  4435. if (time.time() - timer) > Ferment_Tank_vacuumOFF_time:
  4436. break
  4437. # (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height) AND FI1 != 'FI_OutputtingBean'
  4438. def FInputtingBean_TO_FInputtingBeanPause(tid):
  4439. # [致動器] 蝴蝶閥 OFF
  4440. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
  4441. print('data: ', data)
  4442. # mqtt_f(data)
  4443. # [致動器] 真空吸料機 OFF
  4444. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  4445. print('data: ', data)
  4446. # mqtt_f(data)
  4447. # [致動器] 入料三通閥 OFF入豆
  4448. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  4449. print('data: ', data)
  4450. # mqtt_f(data)
  4451. # [致動器] 馬達 0
  4452. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  4453. print('data: ', data)
  4454. # mqtt_f(data)
  4455. print('------- ', tid,' 狀態更新:入豆暫停 -------')
  4456. # FermentUp_InputtingBeanPause_number == 1 and FI1 == 'FI_OutputtingBean'
  4457. # if F1 == 'F_InputtingBean_Pause' AND FI1 == 'FI_OutputtingBean'
  4458. def FInputtingBeanPause_AND_FIOutputtingBean(tid):
  4459. # [致動器] 入料三通閥 OFF入豆
  4460. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  4461. print('data: ', data)
  4462. # mqtt_f(data)
  4463. # [致動器] 馬達 5
  4464. data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
  4465. print('data: ', data)
  4466. # mqtt_f(data)
  4467. print('------- ', tid, ' 狀態更新:入料中 -------')
  4468. # elif FermentUp_InputtingBean_number == 0 and FermentUp_InputtingBeanPause_number == 0 and FI1 == 'FI_OutputtingBean' and FermentUp_Waiting_number >= 1
  4469. def FWaiting_TO_FInputtingBean(tid):
  4470. # [致動器] 蝴蝶閥 OFF
  4471. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
  4472. print('data: ', data)
  4473. # mqtt_f(data)
  4474. # [致動器] 入料三通閥 OFF入豆
  4475. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  4476. print('data: ', data)
  4477. # mqtt_f(data)
  4478. # [致動器] 馬達 5
  4479. data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
  4480. print('data: ', data)
  4481. # mqtt_f(data)
  4482. print('------- ', tid, ' 狀態更新:入料中 -------')
  4483. # elif FermentUp_InputtingWater_number == 0 and FermentUp_InputtingBeanFinish_number >= 1:
  4484. def FInputtingBeanFinish_TO_FInputtingWater_UP(tid, sn):
  4485. print('------- ', tid,' 狀態更新:入水中 -------')
  4486. # # [致動器] 浮選三通閥 ON
  4487. # data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "on" }
  4488. # print('data: ', data)
  4489. # # # mqtt_f(data)
  4490. # if (F_UP_tank_WaterLevel[sn] == 0):
  4491. # # [致動器] 桶外進水電磁閥 ON
  4492. # data = { "tank_num": tid, "command": "outer_solenoid_water_status", "value": "on" }
  4493. # print('data: ', data)
  4494. # # mqtt_f(data)
  4495. if (F_UP_UltraSoniclist[sn] < Ferment_Tank_water_height):
  4496. # 桶內高度若低於水位指定高度, [致動器] 桶內進水電磁閥 ON
  4497. data = { "tank_num": tid, "command": "tank_solenoid_water_in_status", "value": "on" }
  4498. print('data: ', data)
  4499. # mqtt_f(data)
  4500. # elif FermentUp_InputtingWater_number == 1:
  4501. # 'F_InputtingWater' if (F_UP_tank_WaterLevel[0] == 1) and (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height):
  4502. def FInputtingWater_TO_FFermenting(tid):
  4503. # 若夾層入水達水位計高度 且 桶內入水達指定水位高度, 狀態轉換為發酵中
  4504. # 桶外水位高度高於水位計高度, [致動器] 桶外進水電磁閥 OFF
  4505. # data = { "tank_num": tid, "command": "outer_solenoid_water_status", "value": "off" }
  4506. # print('data: ', data)
  4507. # # mqtt_f(data)
  4508. # 桶內高度若高於水位指定高度, [致動器] 桶內進水電磁閥 OFF
  4509. data = { "tank_num": tid, "command": "tank_solenoid_water_in_status", "value": "off" }
  4510. print('data: ', data)
  4511. # mqtt_f(data)
  4512. print('------- ', tid, ' 狀態更新:發酵中 -------')
  4513. # [致動器] 馬達 (指定轉速)
  4514. data = { "tank_num": tid, "command": "tank_motor_status", "value": Ferment_Tank_motor_rpm }
  4515. print('data: ', data)
  4516. # mqtt_f(data)
  4517. # [致動器] 溫控開關 ON
  4518. # data = { "tank_num": tid, "command": "tank_temp_enable", "value": "on", "duration": Ferment_Tank_fermenting_time}
  4519. # print('data: ', data)
  4520. # # mqtt_f(data)
  4521. # [致動器] 設定溫度、持溫時間
  4522. # [致動器] 加熱器 1 ON
  4523. # data = { "tank_num": tid, "command": "tank_heater1_status", "value": "on" }
  4524. # print('data: ', data)
  4525. # mqtt_f(data)
  4526. # [致動器] 加熱器 2 ON
  4527. # data = { "tank_num": tid, "command": "tank_heater2_status", "value": "on" }
  4528. # print('data: ', data)
  4529. # mqtt_f(data)
  4530. # # [致動器] 雙核薄膜泵 水質檢測 ON
  4531. # data = { "tank_num": tid, "command": "tank_pump_sensor_status", "value": "on"}
  4532. # print('data: ', data)
  4533. # # mqtt_f(data)
  4534. # TODO 增加發酵條件等
  4535. # 'F_InputtingWater' AND (F_UP_tank_WaterLevel[0] == 1)
  4536. def FInputtingWater_AND_WaterLevel1(tid):
  4537. # # [致動器] 桶外進水電磁閥 OFF
  4538. # data = { "tank_num": tid, "command": "outer_solenoid_water_status", "value": "off" }
  4539. # print('data: ', data)
  4540. # # mqtt_f(data)
  4541. pass
  4542. # 'F_InputtingWater' AND (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height)
  4543. def FInputtingWater_AND_tankwaterfilled(tid):
  4544. # 桶內高度若高於水位指定高度, [致動器] 桶內進水電磁閥 OFF
  4545. data = { "tank_num": tid, "command": "tank_solenoid_water_in_status", "value": "off" }
  4546. print('data: ', data)
  4547. # mqtt_f(data)
  4548. # else
  4549. # F1 == 'F_Fermenting' and F_UP_tank_SHT11_Temp[0] >= Ferment_Tank_fermenting_temp and F_UP_tank_PH[0] <= Ferment_Tank_fermenting_pH:
  4550. def FFermenting_TO_FOutputtingBean(tid):
  4551. print(tid, ' 發酵等待 ', Ferment_Tank_fermenting_time, ' 秒')
  4552. timer = time.time()
  4553. while True:
  4554. if (time.time() - timer) > Ferment_Tank_fermenting_time :
  4555. # [致動器] 外桶浮選三通閥 OFF
  4556. data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "off" }
  4557. print('data: ', data)
  4558. # mqtt_f(data)
  4559. # [致動器] 馬達 0
  4560. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  4561. print('data: ', data)
  4562. # mqtt_f(data)
  4563. # [致動器] 設定溫度 0
  4564. # data = { "tank_num": tid, "command": "tank_temp", "value": "0" }
  4565. # print('data: ', data)
  4566. # # mqtt_f(data)
  4567. # [致動器] 溫控開關 OFF
  4568. # data = { "tank_num": tid, "command": "tank_temp_enable", "value": "off" }
  4569. # print('data: ', data)
  4570. # # mqtt_f(data)
  4571. # [致動器] 加熱器 1 OFF
  4572. data = { "tank_num": tid, "command": "tank_heater1_status", "value": "off" }
  4573. print('data: ', data)
  4574. # mqtt_f(data)
  4575. # [致動器] 加熱器 2 OFF
  4576. data = { "tank_num": tid, "command": "tank_heater2_status", "value": "off" }
  4577. print('data: ', data)
  4578. # mqtt_f(data)
  4579. # # [致動器] 雙核薄膜泵 水質檢測 OFF
  4580. # data = { "tank_num": tid, "command": "tank_pump_sensor_status", "value": "off"}
  4581. # print('data: ', data)
  4582. # # mqtt_f(data)
  4583. # TODO 增加發酵條件等
  4584. break
  4585. # [致動器] 廢水排水閥 (桶內) ON
  4586. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "on" }
  4587. print('data: ', data)
  4588. # mqtt_f(data)
  4589. print(tid, '桶內廢水排水 ', Ferment_Tank_WaterOut_time, ' 秒')
  4590. timer = time.time()
  4591. while True:
  4592. if (time.time() - timer) > Ferment_Tank_WaterOut_time:
  4593. # [致動器] 廢水排水閥 (桶內) OFF
  4594. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  4595. print('data: ', data)
  4596. # mqtt_f(data)
  4597. break
  4598. print('------- ', tid, ' 狀態更新:可出豆 -------')
  4599. # else: if F1 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[0] <= Ferment_Tank_bean_empty):
  4600. def FOutputtingBean_TO_FWaiting(tid):
  4601. # [致動器] F1 蝴蝶閥 ON
  4602. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "on" }
  4603. print('data: ', data)
  4604. # mqtt_f(data)
  4605. # ----- 發酵排程動作 end ------------------------------------------------------------------
  4606. # [介面] 若啟用 發酵 狀態
  4607. if Ferment_btn:
  4608. # ----- 發酵桶槽 F1~F6 入料桶槽優先入料判斷 ------------------------------
  4609. # 若 F1~F6 桶槽中有一個桶槽入豆中
  4610. if FermentUp_InputtingBean_number == 1:
  4611. # 若 F1 桶槽為入豆中
  4612. if F1 == 'F_InputtingBean':
  4613. if (F_UP_UltraSoniclist[0] >= Ferment_Tank_bean_height):
  4614. FInputtingBean_TO_FInputtingBeanFinish("F1")
  4615. # F1 = 'F_InputtingBean_Finish'
  4616. F1 = 'F_OutputtingBean'
  4617. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height):
  4618. FInputtingBean_AND_notfilled("F1")
  4619. elif FI1 != 'FI_OutputtingBean':
  4620. FInputtingBean_TO_FInputtingBeanPause("F1")
  4621. F1 = 'F_InputtingBean_Pause'
  4622. # 若 F1~F6 桶槽中有一個桶槽入豆暫停中, 且 FI1 可出豆
  4623. elif FermentUp_InputtingBeanPause_number == 1 and FI1 == 'FI_OutputtingBean':
  4624. # 若 F1 桶槽為入豆暫停 且 FI1 可出料
  4625. if F1 == 'F_InputtingBean_Pause':
  4626. FInputtingBeanPause_AND_FIOutputtingBean("F1")
  4627. F1 = 'F_InputtingBean'
  4628. # 若 F1~F6 桶槽中 無桶槽正在入料或入料等待, 且 FI1 可出豆時
  4629. elif FermentUp_InputtingBean_number == 0 and FermentUp_InputtingBeanPause_number == 0 and FI1 == 'FI_OutputtingBean' and FermentUp_Waiting_number >= 1:
  4630. if F1 == 'F_Waiting':
  4631. FWaiting_TO_FInputtingBean("F1")
  4632. F1 = 'F_InputtingBean'
  4633. # 若 F1~F6 桶槽中 無桶槽正在入水, 則入豆完成者轉換狀態 開始入水
  4634. elif FermentUp_InputtingWater_number == 0 and FermentUp_InputtingBeanFinish_number >= 1:
  4635. if F1 == 'F_InputtingBean_Finish':
  4636. F1 = 'F_InputtingWater'
  4637. FInputtingBeanFinish_TO_FInputtingWater_UP("F1", 0)
  4638. elif FermentUp_InputtingWater_number == 1:
  4639. if F1 == 'F_InputtingWater':
  4640. if (F_UP_tank_WaterLevel[0] == 1) and (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height):
  4641. F1 = 'F_Fermenting'
  4642. FInputtingWater_TO_FFermenting("F1")
  4643. elif (F_UP_tank_WaterLevel[0] == 1):
  4644. FInputtingWater_AND_WaterLevel1("F1")
  4645. elif (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height):
  4646. FInputtingWater_AND_tankwaterfilled("F1")
  4647. else:
  4648. if F1 == 'F_Fermenting' and F_UP_tank_SHT11_Temp[0] >= Ferment_Tank_fermenting_temp:
  4649. FFermenting_TO_FOutputtingBean("F1")
  4650. F1 = 'F_OutputtingBean'
  4651. # 將可出豆桶槽賦值
  4652. if FOutputtingBean_Tank == '': FOutputtingBean_Tank = 'F1'
  4653. # 若桶槽 F1~F6 可出豆 且 桶槽內為空桶 且 有指定清洗排程, 進行清洗桶槽
  4654. # TODO 發酵次數計算、消毒次數、校正
  4655. if F1 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[0] <= Ferment_Tank_bean_empty):
  4656. if FOutputtingBean_Tank == 'F1':
  4657. FOutputtingBean_TO_FWaiting('F1')
  4658. FOutputtingBean_Tank = ''
  4659. F1 = 'F_Waiting'
  4660. print('------- F1 狀態更新:空桶等待 -------')
  4661. # 避免桶槽可出豆時未賦值
  4662. if FOutputtingBean_Tank == '':
  4663. if F1 == 'F_OutputtingBean': FOutputtingBean_Tank = 'F1'
  4664. # 若桶槽 F1~F6 為清洗中
  4665. if F1 == 'F_Cleaning':
  4666. # FCleaning("F1")
  4667. F1 = 'F_Waiting'
  4668. print('------- F1 狀態更新:空桶等待 -------')
  4669. # # ----- [測試用] !!!!! F1~F6 入料完成→可出豆 判斷 ------------------------------
  4670. # if F1 == 'F_InputtingBean_Finish': F1 = 'F_OutputtingBean'
  4671. # if F2 == 'F_InputtingBean_Finish': F2 = 'F_OutputtingBean'
  4672. # if F3 == 'F_InputtingBean_Finish': F3 = 'F_OutputtingBean'
  4673. # if F4 == 'F_InputtingBean_Finish': F4 = 'F_OutputtingBean'
  4674. # if F5 == 'F_InputtingBean_Finish': F5 = 'F_OutputtingBean'
  4675. # if F6 == 'F_InputtingBean_Finish': F6 = 'F_OutputtingBean'
  4676. # # ----- [測試用] !!!!! F1~F6 入料完成→可出豆 判斷 ------------------------------
  4677. else:
  4678. # [介面] 若未啟用 發酵 狀態
  4679. print('未啟用發酵流程')
  4680. # ----- 將狀態寫入資料庫 ------------------------------
  4681. # 獲取文本框的值並賦值給user實體對象
  4682. F_status = ferment_container_status()
  4683. F_status.Ferment_Input_1 = FI1
  4684. F_status.Ferment_Input_2 = FI2
  4685. F_status.Ferment_Tank_1 = F1
  4686. F_status.Ferment_Tank_2 = F2
  4687. F_status.Ferment_Tank_3 = F3
  4688. F_status.Ferment_Tank_4 = F4
  4689. F_status.Ferment_Tank_5 = F5
  4690. F_status.Ferment_Tank_6 = F6
  4691. F_status.Ferment_Tank_7 = F7
  4692. F_status.Ferment_Tank_8 = F8
  4693. F_status.Ferment_Tank_9 = F9
  4694. F_status.Ferment_Tank_10 = F10
  4695. F_status.Ferment_Tank_11 = F11
  4696. F_status.Ferment_Tank_12 = F12
  4697. F_status.Ferment_Output_1 = FO1
  4698. F_status.Ferment_Output_2 = FO2
  4699. #將數據保存進資料庫
  4700. db.session.add(F_status)
  4701. # 手動提交
  4702. db.session.commit()
  4703. # ----- 將狀態寫入資料庫 ------------------------------
  4704. return jsonify({"Ferment_Tank_1":F1,
  4705. "Ferment_Tank_2":F2
  4706. })
  4707. @main.route('/ferment_auto_status', methods=['GET', 'POST'])
  4708. def ferment_auto_test():
  4709. info = request.args.to_dict()
  4710. # 寫定入料、桶槽、出料的空桶標準, 若 <= 2 則為空桶
  4711. Ferment_Input_bean_empty = 2
  4712. Ferment_Tank_bean_empty = 2
  4713. Ferment_Output_bean_empty = 2
  4714. # 從介面取得 指定生豆高度/發酵桶槽排程:發酵、清洗、校正 EC、校正攪拌棒
  4715. FermentAuto_fermenting = int(info['FermentAuto_fermenting'])
  4716. FermentAuto_cleaning = int(info['FermentAuto_cleaning'])
  4717. FermentAuto_calibratingEC = int(info['FermentAuto_calibratingEC'])
  4718. FermentAuto_calibratingSTIR = int(info['FermentAuto_calibratingSTIR'])
  4719. Ferment_Input_bean_height = float(info['Ferment_Input_bean_height'])
  4720. Ferment_Input_vacuumON_time = float(info['Ferment_Input_vacuumON_time'])
  4721. Ferment_Input_vacuumOFF_time = float(info['Ferment_Input_vacuumOFF_time'])
  4722. Ferment_Tank_bean_height = float(info['Ferment_Tank_bean_height'])
  4723. Ferment_Tank_vacuumON_time = float(info['Ferment_Tank_vacuumON_time'])
  4724. Ferment_Tank_vacuumOFF_time = float(info['Ferment_Tank_vacuumOFF_time'])
  4725. Ferment_Tank_water_height = float(info['Ferment_Tank_water_height'])
  4726. Ferment_Tank_fermenting_temp = float(info['Ferment_Tank_fermenting_temp'])
  4727. Ferment_Tank_fermenting_time = float(info['Ferment_Tank_fermenting_time'])
  4728. Ferment_Tank_motor_rpm = float(info['Ferment_Tank_motor_rpm'])
  4729. Ferment_Tank_motor_time = float(info['Ferment_Tank_motor_time'])
  4730. Ferment_Tank_fermenting_pH = float(info['Ferment_Tank_fermenting_pH'])
  4731. Ferment_Output_bean_height = float(info['Ferment_Output_bean_height'])
  4732. Ferment_Output_vacuumON_time = float(info['Ferment_Output_vacuumON_time'])
  4733. Ferment_Output_vacuumOFF_time = float(info['Ferment_Output_vacuumOFF_time'])
  4734. Ferment_Tank_WaterOut_time = float(info['Ferment_Tank_WaterOut_time'])
  4735. Ferment_Tank_Disinfect_time = float(info['Ferment_Tank_Disinfect_time'])
  4736. Ferment_cb_vacuum = info['Ferment_cb_vacuum'] # 'true' 'false'
  4737. Ferment_cb_vacuum_time = float(info['Ferment_cb_vacuum_time'])
  4738. # [介面] 讓使用者可以選擇排程內有發酵/清洗/校正, 此處預設為 True
  4739. Ferment_btn = FermentAuto_fermenting # Ferment_btn = True
  4740. # 從資料庫資料表中取得最新狀態
  4741. ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
  4742. FI1 = ferment_status.Ferment_Input_1
  4743. FI2 = ferment_status.Ferment_Input_2
  4744. F1 = ferment_status.Ferment_Tank_1
  4745. F2 = ferment_status.Ferment_Tank_2
  4746. F3 = ferment_status.Ferment_Tank_3
  4747. F4 = ferment_status.Ferment_Tank_4
  4748. F5 = ferment_status.Ferment_Tank_5
  4749. F6 = ferment_status.Ferment_Tank_6
  4750. F7 = ferment_status.Ferment_Tank_7
  4751. F8 = ferment_status.Ferment_Tank_8
  4752. F9 = ferment_status.Ferment_Tank_9
  4753. F10 = ferment_status.Ferment_Tank_10
  4754. F11 = ferment_status.Ferment_Tank_11
  4755. F12 = ferment_status.Ferment_Tank_12
  4756. FO1 = ferment_status.Ferment_Output_1
  4757. FO2 = ferment_status.Ferment_Output_2
  4758. clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
  4759. PO1 = clean_status.Peel_Output_1 # PO_Waiting # PO_OutputtingBean
  4760. PO2 = clean_status.Peel_Output_2
  4761. F_UP_tanklist = [F1, F2, F3, F4, F5, F6]
  4762. F_DOWN_tanklist = [F7, F8, F9, F10, F11, F12]
  4763. FOutputtingBean_Tank = '' # 這是給出料儲豆槽判斷目前出豆的桶槽
  4764. # 目前發酵槽 F1~F6 正在入豆、入水的桶槽數量 (應小於一桶)
  4765. FermentUp_Waiting_number = int(F_UP_tanklist.count('F_Waiting'))
  4766. FermentUp_InputtingBean_number = int(F_UP_tanklist.count('F_InputtingBean'))
  4767. FermentUp_InputtingBeanPause_number = int(F_UP_tanklist.count('F_InputtingBean_Pause'))
  4768. FermentUp_InputtingBeanFinish_number = int(F_UP_tanklist.count('F_InputtingBean_Finish'))
  4769. FermentUp_InputtingWater_number = int(F_UP_tanklist.count('F_InputtingWater'))
  4770. # -- 取得發酵 入料儲豆槽 FI1~FI2 / 桶槽 F1~F6 / 出料 FO1~FO2 桶內高度 UltraSonic start -------------
  4771. FI_UP_UltraSoniclist = []
  4772. for i in range(1, 3, 1):
  4773. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  4774. # UltraSonic = float("{:.2f}".format(34.6 - float(input_UltraSonic.UltraSonic)))
  4775. UltraSonic = float(input_UltraSonic.UltraSonic)
  4776. FI_UP_UltraSoniclist.append(UltraSonic)
  4777. print('FI_UP_UltraSoniclist: ', FI_UP_UltraSoniclist)
  4778. F_UP_UltraSoniclist = []
  4779. for i in range(1, 7, 1):
  4780. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  4781. UltraSonic = (float(tank_UltraSonic.UltraSonic))
  4782. F_UP_UltraSoniclist.append(UltraSonic)
  4783. print('F_UP_UltraSoniclist: ', F_UP_UltraSoniclist)
  4784. FO_UP_UltraSoniclist = []
  4785. for i in range(1, 3, 1):
  4786. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO' + str(i)).order_by(text('datetime desc')).first()
  4787. UltraSonic = float(output_UltraSonic.UltraSonic)
  4788. FO_UP_UltraSoniclist.append(UltraSonic)
  4789. print('FO_UP_UltraSoniclist: ', FO_UP_UltraSoniclist)
  4790. # -- 取得發酵 入料儲豆槽 FI1~FI2 / 桶槽 F1~F6 / 出料 FO1~FO2 桶內高度 UltraSonic end -------------
  4791. # -- 取得發酵桶槽 F1~F6 夾層水位高度 WaterLevel start -------------
  4792. F_UP_tank_WaterLevel = []
  4793. for i in range(1, 7, 1):
  4794. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  4795. WaterLevel = float(tank_WaterLevel.WaterLevel)
  4796. F_UP_tank_WaterLevel.append(WaterLevel)
  4797. print('F_UP_tank_WaterLevel: ', F_UP_tank_WaterLevel)
  4798. # -- 取得發酵桶槽 F1~F6 夾層水位高度 WaterLevel end -------------
  4799. # -- 取得發酵桶槽 F1~F6 pH -------------
  4800. F_UP_tank_PH = []
  4801. for i in range(1, 7, 1):
  4802. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  4803. PH = float(tank_PH.PH)
  4804. F_UP_tank_PH.append(PH)
  4805. print('F_UP_tank_PH: ', F_UP_tank_PH)
  4806. # -- 取得發酵桶槽 F1~F6 pH -------------
  4807. # -- 取得發酵桶槽 F1~F6 SHT11_TEMP -------------
  4808. F_UP_tank_SHT11_Temp = []
  4809. for i in range(1, 7, 1):
  4810. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
  4811. SHT11_Temp = float(tank_SHT11.SHT11_Temp)
  4812. F_UP_tank_SHT11_Temp.append(SHT11_Temp)
  4813. print('F_UP_tank_SHT11_Temp: ', F_UP_tank_SHT11_Temp)
  4814. # -- 取得發酵桶槽 F1~F6 SHT11_TEMP -------------
  4815. # ----- 發酵排程動作 start ------------------------------------------------------------------
  4816. # FI1 == 'FI_InputtingBean' AND if (FI_UP_UltraSoniclist[0] >= Ferment_Input_bean_height):
  4817. def FIInputtingBean_filled(tid):
  4818. # [致動器] 入料真空吸料機 OFF
  4819. data = { "tank_num": tid, "command": "input_vacuum_status", "value": "off" }
  4820. print('data: ', data)
  4821. # mqtt_f(data)
  4822. print('------- ', tid, ' 狀態更新:可出豆 -------')
  4823. # FI1 == 'FI_InputtingBean' AND elif (FI_UP_UltraSoniclist[0] < Ferment_Input_bean_height) and PO1 == 'PO_OutputtingBean':
  4824. def FIInputtingBean_AND_notfilled(tid):
  4825. # [致動器] 入料真空吸料機 ON
  4826. data = { "tank_num": tid, "command": "input_vacuum_status", "value": "on" }
  4827. print('data: ', data)
  4828. # mqtt_f(data)
  4829. # 暫停 (指定吸料時間) 秒
  4830. time.sleep(Ferment_Input_vacuumON_time)
  4831. # [致動器] 入料真空吸料機 OFF
  4832. data = { "tank_num": tid, "command": "input_vacuum_status", "value": "off" }
  4833. print('data: ', data)
  4834. # mqtt_f(data)
  4835. # 暫停 (指定放料時間) 秒
  4836. time.sleep(Ferment_Input_vacuumOFF_time)
  4837. # F1 == 'F_InputtingBean' AND (F_UP_UltraSoniclist[0] >= Ferment_Tank_bean_height):
  4838. def FInputtingBean_TO_FInputtingBeanFinish(tid):
  4839. # [致動器] 真空吸料機 OFF
  4840. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  4841. print('data: ', data)
  4842. # mqtt_f(data)
  4843. # [致動器] 馬達 0
  4844. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  4845. print('data: ', data)
  4846. # mqtt_f(data)
  4847. # [致動器] 入料三通閥 ON排氣
  4848. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "on" }
  4849. print('data: ', data)
  4850. # mqtt_f(data)
  4851. print('------- ', tid,' 狀態更新:入料完成 -------')
  4852. # (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height) AND FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height):
  4853. def FInputtingBean_AND_notfilled(tid):
  4854. # [致動器] 入料三通閥 OFF入豆
  4855. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  4856. print('data: ', data)
  4857. # mqtt_f(data)
  4858. # [致動器] 真空吸料機 ON
  4859. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "on" }
  4860. print('data: ', data)
  4861. # mqtt_f(data)
  4862. # 暫停 (指定吸料時間) 秒
  4863. time.sleep(Ferment_Tank_vacuumON_time)
  4864. # [致動器] 入料真空吸料機 OFF
  4865. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  4866. print('data: ', data)
  4867. # mqtt_f(data)
  4868. # 暫停 (指定吸料時間) 秒
  4869. time.sleep(Ferment_Tank_vacuumOFF_time)
  4870. # # [致動器] 真空吸料機 ON
  4871. # data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "on" }
  4872. # print('data: ', data)
  4873. # # mqtt_f(data)
  4874. # timer = time.time()
  4875. # while True:
  4876. # if (time.time() - timer) > Ferment_Tank_vacuumON_time:
  4877. # # [致動器] 入料真空吸料機 OFF
  4878. # data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  4879. # print('data: ', data)
  4880. # # mqtt_f(data)
  4881. # timer = time.time()
  4882. # break
  4883. # while True:
  4884. # if (time.time() - timer) > Ferment_Tank_vacuumOFF_time:
  4885. # break
  4886. # (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height) AND FI1 != 'FI_OutputtingBean'
  4887. def FInputtingBean_TO_FInputtingBeanPause(tid):
  4888. # [致動器] 真空吸料機 OFF
  4889. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  4890. print('data: ', data)
  4891. # mqtt_f(data)
  4892. # [致動器] 入料三通閥 OFF入豆
  4893. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  4894. print('data: ', data)
  4895. # mqtt_f(data)
  4896. # [致動器] 馬達 0
  4897. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  4898. print('data: ', data)
  4899. # mqtt_f(data)
  4900. print('------- ', tid,' 狀態更新:入豆暫停 -------')
  4901. # FermentUp_InputtingBeanPause_number == 1 and FI1 == 'FI_OutputtingBean'
  4902. # if F1 == 'F_InputtingBean_Pause' AND FI1 == 'FI_OutputtingBean'
  4903. def FInputtingBeanPause_AND_FIOutputtingBean(tid):
  4904. # [致動器] 入料三通閥 OFF入豆
  4905. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  4906. print('data: ', data)
  4907. # mqtt_f(data)
  4908. # [致動器] 馬達 5
  4909. data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
  4910. print('data: ', data)
  4911. # mqtt_f(data)
  4912. print('------- ', tid, ' 狀態更新:入料中 -------')
  4913. # elif FermentUp_InputtingBean_number == 0 and FermentUp_InputtingBeanPause_number == 0 and FI1 == 'FI_OutputtingBean' and FermentUp_Waiting_number >= 1
  4914. def FWaiting_TO_FInputtingBean(tid):
  4915. # [致動器] 入料三通閥 OFF入豆
  4916. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
  4917. print('data: ', data)
  4918. # mqtt_f(data)
  4919. # [致動器] 馬達 5
  4920. data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
  4921. print('data: ', data)
  4922. # mqtt_f(data)
  4923. print('------- ', tid, ' 狀態更新:入料中 -------')
  4924. # elif FermentUp_InputtingWater_number == 0 and FermentUp_InputtingBeanFinish_number >= 1:
  4925. def FInputtingBeanFinish_TO_FInputtingWater_UP(tid, sn):
  4926. print('------- ', tid,' 狀態更新:入水中 -------')
  4927. # [致動器] 浮選三通閥 ON
  4928. data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "on" }
  4929. print('data: ', data)
  4930. # mqtt_f(data)
  4931. if (F_UP_tank_WaterLevel[sn] == 0):
  4932. # [致動器] 桶外進水電磁閥 ON
  4933. data = { "tank_num": tid, "command": "outer_solenoid_water_status", "value": "on" }
  4934. print('data: ', data)
  4935. # mqtt_f(data)
  4936. if (F_UP_UltraSoniclist[sn] < Ferment_Tank_water_height):
  4937. # 桶內高度若低於水位指定高度, [致動器] 桶內進水電磁閥 ON
  4938. data = { "tank_num": tid, "command": "tank_solenoid_water_in_status", "value": "on" }
  4939. print('data: ', data)
  4940. # mqtt_f(data)
  4941. # elif FermentUp_InputtingWater_number == 1:
  4942. # 'F_InputtingWater' if (F_UP_tank_WaterLevel[0] == 1) and (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height):
  4943. def FInputtingWater_TO_FFermenting(tid):
  4944. # 若夾層入水達水位計高度 且 桶內入水達指定水位高度, 狀態轉換為發酵中
  4945. # 桶外水位高度高於水位計高度, [致動器] 桶外進水電磁閥 OFF
  4946. data = { "tank_num": tid, "command": "outer_solenoid_water_status", "value": "off" }
  4947. print('data: ', data)
  4948. # mqtt_f(data)
  4949. # 桶內高度若高於水位指定高度, [致動器] 桶內進水電磁閥 OFF
  4950. data = { "tank_num": tid, "command": "tank_solenoid_water_in_status", "value": "off" }
  4951. print('data: ', data)
  4952. # mqtt_f(data)
  4953. print('------- ', tid, ' 狀態更新:發酵中 -------')
  4954. # 若勾選 發酵時桶內抽真空?
  4955. if Ferment_cb_vacuum == 'true':
  4956. # [致動器] 入料三通閥 ON排氣
  4957. data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "on" }
  4958. print('data: ', data)
  4959. # mqtt_f(data)
  4960. # [致動器] 外桶浮選三通閥 OFF
  4961. data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "off" }
  4962. print('data: ', data)
  4963. # mqtt_f(data)
  4964. # [致動器] 真空吸料機 ON
  4965. data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "on" }
  4966. print('data: ', data)
  4967. # mqtt_f(data)
  4968. # 暫停 (桶內抽氣時間) 秒
  4969. print(tid, '真空發酵, 桶槽抽氣 ' , Ferment_cb_vacuum_time, ' 秒')
  4970. time.sleep(Ferment_cb_vacuum_time)
  4971. # timer = time.time()
  4972. # while True:
  4973. # if (time.time() - timer) > Ferment_cb_vacuum_time:
  4974. # # [致動器] 入料真空吸料機 OFF
  4975. # data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
  4976. # print('data: ', data)
  4977. # # mqtt_f(data)
  4978. # break
  4979. # [致動器] 馬達 (指定轉速)
  4980. data = { "tank_num": tid, "command": "tank_motor_status", "value": Ferment_Tank_motor_rpm }
  4981. print('data: ', data)
  4982. # mqtt_f(data)
  4983. # [致動器] 溫控開關 ON
  4984. # data = { "tank_num": tid, "command": "tank_temp_enable", "value": "on", "duration": Ferment_Tank_fermenting_time}
  4985. # print('data: ', data)
  4986. # # mqtt_f(data)
  4987. # [致動器] 設定溫度、持溫時間
  4988. # [致動器] 加熱器 1 ON
  4989. data = { "tank_num": tid, "command": "tank_heater1_status", "value": "on" }
  4990. print('data: ', data)
  4991. # mqtt_f(data)
  4992. # [致動器] 加熱器 2 ON
  4993. data = { "tank_num": tid, "command": "tank_heater2_status", "value": "on" }
  4994. print('data: ', data)
  4995. # mqtt_f(data)
  4996. # [致動器] 雙核薄膜泵 水質檢測 ON
  4997. data = { "tank_num": tid, "command": "tank_pump_sensor_status", "value": "on"}
  4998. print('data: ', data)
  4999. # mqtt_f(data)
  5000. # TODO 增加發酵條件等
  5001. # 'F_InputtingWater' AND (F_UP_tank_WaterLevel[0] == 1)
  5002. def FInputtingWater_AND_WaterLevel1(tid):
  5003. # [致動器] 桶外進水電磁閥 OFF
  5004. data = { "tank_num": tid, "command": "outer_solenoid_water_status", "value": "off" }
  5005. print('data: ', data)
  5006. # mqtt_f(data)
  5007. # 'F_InputtingWater' AND (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height)
  5008. def FInputtingWater_AND_tankwaterfilled(tid):
  5009. # 桶內高度若高於水位指定高度, [致動器] 桶內進水電磁閥 OFF
  5010. data = { "tank_num": tid, "command": "tank_solenoid_water_in_status", "value": "off" }
  5011. print('data: ', data)
  5012. # mqtt_f(data)
  5013. # else
  5014. # F1 == 'F_Fermenting' and F_UP_tank_SHT11_Temp[0] >= Ferment_Tank_fermenting_temp and F_UP_tank_PH[0] <= Ferment_Tank_fermenting_pH:
  5015. def FFermenting_TO_FOutputtingBean(tid):
  5016. # 暫停 (桶內抽氣時間) 秒
  5017. print(tid, ' 發酵等待 ', Ferment_Tank_fermenting_time, ' 秒')
  5018. time.sleep(Ferment_Tank_fermenting_time)
  5019. # [致動器] 外桶浮選三通閥 OFF
  5020. data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "off" }
  5021. print('data: ', data)
  5022. # mqtt_f(data)
  5023. # [致動器] 馬達 0
  5024. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  5025. print('data: ', data)
  5026. # mqtt_f(data)
  5027. # [致動器] 設定溫度 0
  5028. data = { "tank_num": tid, "command": "tank_temp", "value": "0" }
  5029. print('data: ', data)
  5030. # mqtt_f(data)
  5031. # [致動器] 溫控開關 OFF
  5032. # data = { "tank_num": tid, "command": "tank_temp_enable", "value": "off" }
  5033. # print('data: ', data)
  5034. # # mqtt_f(data)
  5035. # [致動器] 加熱器 1 OFF
  5036. data = { "tank_num": tid, "command": "tank_heater1_status", "value": "off" }
  5037. print('data: ', data)
  5038. # mqtt_f(data)
  5039. # [致動器] 加熱器 2 OFF
  5040. data = { "tank_num": tid, "command": "tank_heater2_status", "value": "off" }
  5041. print('data: ', data)
  5042. # mqtt_f(data)
  5043. # [致動器] 雙核薄膜泵 水質檢測 OFF
  5044. data = { "tank_num": tid, "command": "tank_pump_sensor_status", "value": "off"}
  5045. print('data: ', data)
  5046. # mqtt_f(data)
  5047. # timer = time.time()
  5048. # while True:
  5049. # if (time.time() - timer) > Ferment_Tank_fermenting_time :
  5050. # # [致動器] 外桶浮選三通閥 OFF
  5051. # data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "off" }
  5052. # print('data: ', data)
  5053. # # mqtt_f(data)
  5054. # # [致動器] 馬達 0
  5055. # data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  5056. # print('data: ', data)
  5057. # # mqtt_f(data)
  5058. # # [致動器] 設定溫度 0
  5059. # data = { "tank_num": tid, "command": "tank_temp", "value": "0" }
  5060. # print('data: ', data)
  5061. # # mqtt_f(data)
  5062. # # [致動器] 溫控開關 OFF
  5063. # # data = { "tank_num": tid, "command": "tank_temp_enable", "value": "off" }
  5064. # # print('data: ', data)
  5065. # # # mqtt_f(data)
  5066. # # [致動器] 加熱器 1 OFF
  5067. # data = { "tank_num": tid, "command": "tank_heater1_status", "value": "off" }
  5068. # print('data: ', data)
  5069. # # mqtt_f(data)
  5070. # # [致動器] 加熱器 2 OFF
  5071. # data = { "tank_num": tid, "command": "tank_heater2_status", "value": "off" }
  5072. # print('data: ', data)
  5073. # # mqtt_f(data)
  5074. # # [致動器] 雙核薄膜泵 水質檢測 OFF
  5075. # data = { "tank_num": tid, "command": "tank_pump_sensor_status", "value": "off"}
  5076. # print('data: ', data)
  5077. # # mqtt_f(data)
  5078. # # TODO 增加發酵條件等
  5079. # break
  5080. # [致動器] 廢水排水閥 (桶內) ON
  5081. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "on" }
  5082. print('data: ', data)
  5083. # mqtt_f(data)
  5084. # 暫停 (桶內抽氣時間) 秒
  5085. print(tid, '桶內廢水排水 ', Ferment_Tank_WaterOut_time, ' 秒')
  5086. time.sleep(Ferment_Tank_WaterOut_time)
  5087. # [致動器] 廢水排水閥 (桶內) OFF
  5088. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  5089. print('data: ', data)
  5090. # mqtt_f(data)
  5091. # timer = time.time()
  5092. # while True:
  5093. # if (time.time() - timer) > Ferment_Tank_WaterOut_time:
  5094. # # [致動器] 廢水排水閥 (桶內) OFF
  5095. # data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  5096. # print('data: ', data)
  5097. # # mqtt_f(data)
  5098. # break
  5099. print('------- ', tid, ' 狀態更新:可出豆 -------')
  5100. # else: if F1 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[0] <= Ferment_Tank_bean_empty):
  5101. def FOutputtingBean_TO_FWaiting(tid):
  5102. # [致動器] F1 蝴蝶閥 ON
  5103. data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "on" }
  5104. print('data: ', data)
  5105. # mqtt_f(data)
  5106. # F_Cleaning
  5107. def FCleaning(tid):
  5108. # [致動器] 浮選三通閥 OFF
  5109. data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "off" }
  5110. print('data: ', data)
  5111. # mqtt_f(data)
  5112. # [致動器] 逆洗雙核薄膜泵電磁閥 ON
  5113. data = { "tank_num": tid, "command": "solenoid_tank_pump_status", "value": "on" }
  5114. print('data: ', data)
  5115. # mqtt_f(data)
  5116. # [致動器] 馬達 10
  5117. data = { "tank_num": tid, "command": "tank_motor_status", "value": "10" }
  5118. print('data: ', data)
  5119. # mqtt_f(data)
  5120. # [致動器] 消毒電磁閥 ON
  5121. data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "on" }
  5122. print('data: ', data)
  5123. # mqtt_f(data)
  5124. # [致動器] 消毒抽水 Pump ON TODO
  5125. # 暫停 (消毒時間) 秒
  5126. print(tid, ' 桶內消毒 ', Ferment_Tank_Disinfect_time, ' 秒')
  5127. time.sleep(Ferment_Tank_Disinfect_time)
  5128. # [致動器] 消毒電磁閥 OFF
  5129. data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "off" }
  5130. print('data: ', data)
  5131. # mqtt_f(data)
  5132. # timer = time.time()
  5133. # while True:
  5134. # if (time.time() - timer) > Ferment_Tank_Disinfect_time :
  5135. # # [致動器] 消毒電磁閥 OFF
  5136. # data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "off" }
  5137. # print('data: ', data)
  5138. # # mqtt_f(data)
  5139. # break
  5140. # [致動器] 消毒抽水 Pump OFF TODO
  5141. # [致動器] 馬達 0
  5142. data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
  5143. print('data: ', data)
  5144. # mqtt_f(data)
  5145. # [致動器] 浮選三通閥 ON
  5146. data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "on" }
  5147. print('data: ', data)
  5148. # mqtt_f(data)
  5149. # [致動器] 逆洗雙核薄膜泵電磁閥 OFF
  5150. data = { "tank_num": tid, "command": "solenoid_tank_pump_status", "value": "off" }
  5151. print('data: ', data)
  5152. # mqtt_f(data)
  5153. # [致動器] 消毒電磁閥 OFF
  5154. data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "off" }
  5155. print('data: ', data)
  5156. # mqtt_f(data)
  5157. # [致動器] 廢水排水閥 (桶內) ON
  5158. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "on" }
  5159. print('data: ', data)
  5160. # mqtt_f(data)
  5161. print(tid, ' 桶內廢水排水 ', Ferment_Tank_WaterOut_time, ' 秒')
  5162. time.sleep(Ferment_Tank_WaterOut_time)
  5163. # [致動器] 廢水排水閥 (桶內) OFF
  5164. data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  5165. print('data: ', data)
  5166. # mqtt_f(data)
  5167. # timer = time.time()
  5168. # while True:
  5169. # if (time.time() - timer) > Ferment_Tank_WaterOut_time:
  5170. # # [致動器] 廢水排水閥 (桶內) OFF
  5171. # data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
  5172. # print('data: ', data)
  5173. # # mqtt_f(data)
  5174. # break
  5175. print('------- ', tid, ' 狀態更新:空桶等待 -------')
  5176. # elif FO1 == 'FO_InputtingBean' and FOutputtingBean_Tank != '': AND elif FO_UP_UltraSoniclist[0] < Ferment_Output_bean_height:
  5177. def FOInputtingBean_filled(tid):
  5178. # [致動器] 出料真空吸料機 ON
  5179. data = { "tank_num": FOutputtingBean_Tank, "command": "input_vacuum_status", "value": "on" }
  5180. print('data: ', data)
  5181. # mqtt_f(data)
  5182. # 暫停 (指定吸料時間) 秒
  5183. time.sleep(Ferment_Output_vacuumON_time)
  5184. # [致動器] 出料真空吸料機 OFF
  5185. data = { "tank_num": FOutputtingBean_Tank, "command": "input_vacuum_status", "value": "off" }
  5186. print('data: ', data)
  5187. # mqtt_f(data)
  5188. # 暫停 (指定放料時間) 秒
  5189. time.sleep(Ferment_Output_vacuumOFF_time)
  5190. # # [致動器] 出料真空吸料機 ON
  5191. # data = { "tank_num": FOutputtingBean_Tank, "command": "input_vacuum_status", "value": "on" }
  5192. # print('data: ', data)
  5193. # # mqtt_f(data)
  5194. # timer = time.time()
  5195. # while True:
  5196. # if (time.time() - timer) > Ferment_Output_vacuumON_time:
  5197. # # [致動器] 出料真空吸料機 OFF
  5198. # data = { "tank_num": FOutputtingBean_Tank, "command": "input_vacuum_status", "value": "off" }
  5199. # print('data: ', data)
  5200. # # mqtt_f(data)
  5201. # timer = time.time()
  5202. # break
  5203. # while True:
  5204. # if (time.time() - timer) > Ferment_Output_vacuumOFF_time:
  5205. # break
  5206. # ----- 發酵排程動作 end ------------------------------------------------------------------
  5207. # ----- 發酵入料儲豆槽 FI1~FI2 入豆→可出豆判斷 ------------------------------
  5208. # 入料儲豆槽等待中、且脫皮機儲豆槽可出豆時, 入料儲豆槽入豆
  5209. if FI1 == 'FI_Waiting' and PO1 == 'PO_OutputtingBean':
  5210. FI1 = 'FI_InputtingBean'
  5211. print('------- FI1 狀態更新:入豆中 -------')
  5212. # 入料儲豆槽入豆時
  5213. elif FI1 == 'FI_InputtingBean':
  5214. # 桶槽內達指定生豆高度時, 入料儲豆槽狀態轉為 可出豆
  5215. if (FI_UP_UltraSoniclist[0] >= Ferment_Input_bean_height):
  5216. FIInputtingBean_filled("FI1")
  5217. FI1 = 'FI_OutputtingBean'
  5218. # 桶槽內未達指定生豆高度, 且 前方 PO1 可出豆, 就執行入料動作
  5219. elif (FI_UP_UltraSoniclist[0] < Ferment_Input_bean_height) and PO1 == 'PO_OutputtingBean':
  5220. FI1_thread = threading.Thread(target=FIInputtingBean_AND_notfilled, args=["FI1"])
  5221. FI1_thread.start()
  5222. # 桶槽內大於空桶高度, 且 前方 PO1 非可出豆, 將狀態轉為可出豆
  5223. elif (FI_UP_UltraSoniclist[0] > Ferment_Input_bean_empty) and PO1 != 'PO_OutputtingBean':
  5224. FI1 = 'FI_OutputtingBean'
  5225. print('------- FI1 狀態更新:可出豆 -------')
  5226. # 桶槽內小於空桶高度, 且 前方 PO1 非可出豆, 將狀態轉為空桶等待
  5227. elif (FI_UP_UltraSoniclist[0] <= Ferment_Input_bean_empty) and PO1 != 'PO_OutputtingBean':
  5228. FI1 = 'FI_Waiting'
  5229. print('------- FI1 狀態更新:空桶等待 -------')
  5230. # 入料儲豆槽出豆時, 桶槽高度為 空桶高度時, 狀態轉為 空桶等待
  5231. elif FI1 == 'FI_OutputtingBean' and (FI_UP_UltraSoniclist[0] <= Ferment_Input_bean_empty):
  5232. FI1 = 'FI_Waiting'
  5233. print('------- FI1 狀態更新:空桶等待 -------')
  5234. # [介面] 若啟用 發酵 狀態
  5235. if Ferment_btn:
  5236. # ----- 發酵桶槽 F1~F6 入料桶槽優先入料判斷 ------------------------------
  5237. # 若 F1~F6 桶槽中有一個桶槽入豆中
  5238. if FermentUp_InputtingBean_number == 1:
  5239. # 若 F1 桶槽為入豆中
  5240. if F1 == 'F_InputtingBean':
  5241. if (F_UP_UltraSoniclist[0] >= Ferment_Tank_bean_height):
  5242. FInputtingBean_TO_FInputtingBeanFinish("F1")
  5243. F1 = 'F_InputtingBean_Finish'
  5244. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height):
  5245. F1_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F1"])
  5246. F1_thread.start()
  5247. elif FI1 != 'FI_OutputtingBean':
  5248. FInputtingBean_TO_FInputtingBeanPause("F1")
  5249. F1 = 'F_InputtingBean_Pause'
  5250. elif F2 == 'F_InputtingBean':
  5251. if (F_UP_UltraSoniclist[1] >= Ferment_Tank_bean_height):
  5252. FInputtingBean_TO_FInputtingBeanFinish("F2")
  5253. F2 = 'F_InputtingBean_Finish'
  5254. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[1] < Ferment_Tank_bean_height):
  5255. F2_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F2"])
  5256. F2_thread.start()
  5257. elif FI1 != 'FI_OutputtingBean':
  5258. FInputtingBean_TO_FInputtingBeanPause("F2")
  5259. F2 = 'F_InputtingBean_Pause'
  5260. elif F3 == 'F_InputtingBean':
  5261. if (F_UP_UltraSoniclist[2] >= Ferment_Tank_bean_height):
  5262. FInputtingBean_TO_FInputtingBeanFinish("F3")
  5263. F3 = 'F_InputtingBean_Finish'
  5264. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[2] < Ferment_Tank_bean_height):
  5265. F3_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F3"])
  5266. F3_thread.start()
  5267. elif FI1 != 'FI_OutputtingBean':
  5268. FInputtingBean_TO_FInputtingBeanPause("F3")
  5269. F3 = 'F_InputtingBean_Pause'
  5270. elif F4 == 'F_InputtingBean':
  5271. if (F_UP_UltraSoniclist[3] >= Ferment_Tank_bean_height):
  5272. FInputtingBean_TO_FInputtingBeanFinish("F4")
  5273. F4 = 'F_InputtingBean_Finish'
  5274. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[3] < Ferment_Tank_bean_height):
  5275. F4_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F4"])
  5276. F4_thread.start()
  5277. elif FI1 != 'FI_OutputtingBean':
  5278. FInputtingBean_TO_FInputtingBeanPause("F4")
  5279. F4 = 'F_InputtingBean_Pause'
  5280. elif F5 == 'F_InputtingBean':
  5281. if (F_UP_UltraSoniclist[4] >= Ferment_Tank_bean_height):
  5282. FInputtingBean_TO_FInputtingBeanFinish("F5")
  5283. F5 = 'F_InputtingBean_Finish'
  5284. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[4] < Ferment_Tank_bean_height):
  5285. F5_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F5"])
  5286. F5_thread.start()
  5287. elif FI1 != 'FI_OutputtingBean':
  5288. FInputtingBean_TO_FInputtingBeanPause("F5")
  5289. F5 = 'F_InputtingBean_Pause'
  5290. elif F6 == 'F_InputtingBean':
  5291. if (F_UP_UltraSoniclist[5] >= Ferment_Tank_bean_height):
  5292. FInputtingBean_TO_FInputtingBeanFinish("F6")
  5293. F6 = 'F_InputtingBean_Finish'
  5294. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[5] < Ferment_Tank_bean_height):
  5295. F6_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F6"])
  5296. F6_thread.start()
  5297. elif FI1 != 'FI_OutputtingBean':
  5298. FInputtingBean_TO_FInputtingBeanPause("F6")
  5299. F6 = 'F_InputtingBean_Pause'
  5300. # 若 F1~F6 桶槽中有一個桶槽入豆暫停中, 且 FI1 可出豆
  5301. elif FermentUp_InputtingBeanPause_number == 1 and FI1 == 'FI_OutputtingBean':
  5302. # 若 F1 桶槽為入豆暫停 且 FI1 可出料
  5303. if F1 == 'F_InputtingBean_Pause':
  5304. FInputtingBeanPause_AND_FIOutputtingBean("F1")
  5305. F1 = 'F_InputtingBean'
  5306. elif F2 == 'F_InputtingBean_Pause':
  5307. FInputtingBeanPause_AND_FIOutputtingBean("F2")
  5308. F2 = 'F_InputtingBean'
  5309. elif F3 == 'F_InputtingBean_Pause':
  5310. FInputtingBeanPause_AND_FIOutputtingBean("F3")
  5311. F3 = 'F_InputtingBean'
  5312. elif F4 == 'F_InputtingBean_Pause':
  5313. FInputtingBeanPause_AND_FIOutputtingBean("F4")
  5314. F4 = 'F_InputtingBean'
  5315. elif F5 == 'F_InputtingBean_Pause':
  5316. FInputtingBeanPause_AND_FIOutputtingBean("F5")
  5317. F5 = 'F_InputtingBean'
  5318. elif F6 == 'F_InputtingBean_Pause':
  5319. FInputtingBeanPause_AND_FIOutputtingBean("F6")
  5320. F6 = 'F_InputtingBean'
  5321. # 若 F1~F6 桶槽中, 兩個桶槽皆為 入料中, 則桶號小者優先入料
  5322. elif FermentUp_InputtingBean_number >= 2:
  5323. if F1 == 'F_InputtingBean':
  5324. if (F_UP_UltraSoniclist[0] >= Ferment_Tank_bean_height):
  5325. FInputtingBean_TO_FInputtingBeanFinish("F1")
  5326. F1 = 'F_InputtingBean_Finish'
  5327. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height):
  5328. F1_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F1"])
  5329. F1_thread.start()
  5330. elif FI1 != 'FI_OutputtingBean':
  5331. FInputtingBean_TO_FInputtingBeanPause("F1")
  5332. F1 = 'F_InputtingBean_Pause'
  5333. elif F2 == 'F_InputtingBean':
  5334. if (F_UP_UltraSoniclist[1] >= Ferment_Tank_bean_height):
  5335. FInputtingBean_TO_FInputtingBeanFinish("F2")
  5336. F2 = 'F_InputtingBean_Finish'
  5337. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[1] < Ferment_Tank_bean_height):
  5338. F2_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F2"])
  5339. F2_thread.start()
  5340. elif FI1 != 'FI_OutputtingBean':
  5341. FInputtingBean_TO_FInputtingBeanPause("F2")
  5342. F2 = 'F_InputtingBean_Pause'
  5343. elif F3 == 'F_InputtingBean':
  5344. if (F_UP_UltraSoniclist[2] >= Ferment_Tank_bean_height):
  5345. FInputtingBean_TO_FInputtingBeanFinish("F3")
  5346. F3 = 'F_InputtingBean_Finish'
  5347. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[2] < Ferment_Tank_bean_height):
  5348. F3_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F3"])
  5349. F3_thread.start()
  5350. elif FI1 != 'FI_OutputtingBean':
  5351. FInputtingBean_TO_FInputtingBeanPause("F3")
  5352. F3 = 'F_InputtingBean_Pause'
  5353. elif F4 == 'F_InputtingBean':
  5354. if (F_UP_UltraSoniclist[3] >= Ferment_Tank_bean_height):
  5355. FInputtingBean_TO_FInputtingBeanFinish("F4")
  5356. F4 = 'F_InputtingBean_Finish'
  5357. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[3] < Ferment_Tank_bean_height):
  5358. F4_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F4"])
  5359. F4_thread.start()
  5360. elif FI1 != 'FI_OutputtingBean':
  5361. FInputtingBean_TO_FInputtingBeanPause("F4")
  5362. F4 = 'F_InputtingBean_Pause'
  5363. elif F5 == 'F_InputtingBean':
  5364. if (F_UP_UltraSoniclist[4] >= Ferment_Tank_bean_height):
  5365. FInputtingBean_TO_FInputtingBeanFinish("F5")
  5366. F5 = 'F_InputtingBean_Finish'
  5367. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[4] < Ferment_Tank_bean_height):
  5368. F5_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F5"])
  5369. F5_thread.start()
  5370. elif FI1 != 'FI_OutputtingBean':
  5371. FInputtingBean_TO_FInputtingBeanPause("F5")
  5372. F5 = 'F_InputtingBean_Pause'
  5373. elif F6 == 'F_InputtingBean':
  5374. if (F_UP_UltraSoniclist[5] >= Ferment_Tank_bean_height):
  5375. FInputtingBean_TO_FInputtingBeanFinish("F6")
  5376. F6 = 'F_InputtingBean_Finish'
  5377. elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[5] < Ferment_Tank_bean_height):
  5378. F6_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F6"])
  5379. F6_thread.start()
  5380. elif FI1 != 'FI_OutputtingBean':
  5381. FInputtingBean_TO_FInputtingBeanPause("F6")
  5382. F6 = 'F_InputtingBean_Pause'
  5383. # 若 F1~F6 桶槽中, 兩個桶槽皆為 入料暫停中, 則桶號小者優先入料
  5384. elif FermentUp_InputtingBeanPause_number >= 2 and FI1 == 'FI_OutputtingBean':
  5385. # 若 F1 桶槽為入豆暫停 且 FI1 可出料
  5386. if F1 == 'F_InputtingBean_Pause':
  5387. FInputtingBeanPause_AND_FIOutputtingBean("F1")
  5388. F1 = 'F_InputtingBean'
  5389. elif F2 == 'F_InputtingBean_Pause':
  5390. FInputtingBeanPause_AND_FIOutputtingBean("F2")
  5391. F2 = 'F_InputtingBean'
  5392. elif F3 == 'F_InputtingBean_Pause':
  5393. FInputtingBeanPause_AND_FIOutputtingBean("F3")
  5394. F3 = 'F_InputtingBean'
  5395. elif F4 == 'F_InputtingBean_Pause':
  5396. FInputtingBeanPause_AND_FIOutputtingBean("F4")
  5397. F4 = 'F_InputtingBean'
  5398. elif F5 == 'F_InputtingBean_Pause':
  5399. FInputtingBeanPause_AND_FIOutputtingBean("F5")
  5400. F5 = 'F_InputtingBean'
  5401. elif F6 == 'F_InputtingBean_Pause':
  5402. FInputtingBeanPause_AND_FIOutputtingBean("F6")
  5403. F6 = 'F_InputtingBean'
  5404. # 若 F1~F6 桶槽中 無桶槽正在入料或入料等待, 且 FI1 可出豆時
  5405. elif FermentUp_InputtingBean_number == 0 and FermentUp_InputtingBeanPause_number == 0 and FI1 == 'FI_OutputtingBean' and FermentUp_Waiting_number >= 1:
  5406. if F1 == 'F_Waiting':
  5407. FWaiting_TO_FInputtingBean("F1")
  5408. F1 = 'F_InputtingBean'
  5409. elif F2 == 'F_Waiting':
  5410. FWaiting_TO_FInputtingBean("F2")
  5411. F2 = 'F_InputtingBean'
  5412. elif F3 == 'F_Waiting':
  5413. FWaiting_TO_FInputtingBean("F3")
  5414. F3 = 'F_InputtingBean'
  5415. elif F4 == 'F_Waiting':
  5416. FWaiting_TO_FInputtingBean("F4")
  5417. F4 = 'F_InputtingBean'
  5418. elif F5 == 'F_Waiting':
  5419. FWaiting_TO_FInputtingBean("F5")
  5420. F5 = 'F_InputtingBean'
  5421. elif F6 == 'F_Waiting':
  5422. FWaiting_TO_FInputtingBean("F6")
  5423. F6 = 'F_InputtingBean'
  5424. # 若 F1~F6 桶槽中 無桶槽正在入水, 則入豆完成者轉換狀態 開始入水
  5425. if FermentUp_InputtingWater_number == 0 and FermentUp_InputtingBeanFinish_number >= 1:
  5426. if F1 == 'F_InputtingBean_Finish':
  5427. F1 = 'F_InputtingWater'
  5428. FInputtingBeanFinish_TO_FInputtingWater_UP("F1", 0)
  5429. elif F2 == 'F_InputtingBean_Finish':
  5430. F2 = 'F_InputtingWater'
  5431. FInputtingBeanFinish_TO_FInputtingWater_UP("F2", 1)
  5432. elif F3 == 'F_InputtingBean_Finish':
  5433. F3 = 'F_InputtingWater'
  5434. FInputtingBeanFinish_TO_FInputtingWater_UP("F3", 2)
  5435. elif F4 == 'F_InputtingBean_Finish':
  5436. F4 = 'F_InputtingWater'
  5437. FInputtingBeanFinish_TO_FInputtingWater_UP("F4", 3)
  5438. elif F5 == 'F_InputtingBean_Finish':
  5439. F5 = 'F_InputtingWater'
  5440. FInputtingBeanFinish_TO_FInputtingWater_UP("F5", 4)
  5441. elif F6 == 'F_InputtingBean_Finish':
  5442. F6 = 'F_InputtingWater'
  5443. FInputtingBeanFinish_TO_FInputtingWater_UP("F6", 5)
  5444. # 若 F1~F6 桶槽中 無桶槽正在入水, 則入豆完成者轉換狀態 開始入水
  5445. if FermentUp_InputtingWater_number == 1:
  5446. if F1 == 'F_InputtingWater':
  5447. if (F_UP_tank_WaterLevel[0] == 1) and (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height):
  5448. F1 = 'F_Fermenting'
  5449. F1_thread = threading.Thread(target=FInputtingWater_TO_FFermenting, args=["F1"])
  5450. F1_thread.start()
  5451. elif (F_UP_tank_WaterLevel[0] == 1):
  5452. FInputtingWater_AND_WaterLevel1("F1")
  5453. elif (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height):
  5454. FInputtingWater_AND_tankwaterfilled("F1")
  5455. elif F2 == 'F_InputtingWater':
  5456. if (F_UP_tank_WaterLevel[1] == 1) and (F_UP_UltraSoniclist[1] >= Ferment_Tank_water_height):
  5457. F2 = 'F_Fermenting'
  5458. F2_thread = threading.Thread(target=FInputtingWater_TO_FFermenting, args=["F2"])
  5459. F2_thread.start()
  5460. elif (F_UP_tank_WaterLevel[1] == 1):
  5461. FInputtingWater_AND_WaterLevel1("F2")
  5462. elif (F_UP_UltraSoniclist[1] >= Ferment_Tank_water_height):
  5463. FInputtingWater_AND_tankwaterfilled("F2")
  5464. elif F3 == 'F_InputtingWater':
  5465. if (F_UP_tank_WaterLevel[2] == 1) and (F_UP_UltraSoniclist[2] >= Ferment_Tank_water_height):
  5466. F3 = 'F_Fermenting'
  5467. F3_thread = threading.Thread(target=FInputtingWater_TO_FFermenting, args=["F3"])
  5468. F3_thread.start()
  5469. elif (F_UP_tank_WaterLevel[2] == 1):
  5470. FInputtingWater_AND_WaterLevel1("F3")
  5471. elif (F_UP_UltraSoniclist[2] >= Ferment_Tank_water_height):
  5472. FInputtingWater_AND_tankwaterfilled("F3")
  5473. elif F4 == 'F_InputtingWater':
  5474. if (F_UP_tank_WaterLevel[3] == 1) and (F_UP_UltraSoniclist[3] >= Ferment_Tank_water_height):
  5475. F4 = 'F_Fermenting'
  5476. F4_thread = threading.Thread(target=FInputtingWater_TO_FFermenting, args=["F4"])
  5477. F4_thread.start()
  5478. elif (F_UP_tank_WaterLevel[3] == 1):
  5479. FInputtingWater_AND_WaterLevel1("F4")
  5480. elif (F_UP_UltraSoniclist[3] >= Ferment_Tank_water_height):
  5481. FInputtingWater_AND_tankwaterfilled("F4")
  5482. elif F5 == 'F_InputtingWater':
  5483. if (F_UP_tank_WaterLevel[4] == 1) and (F_UP_UltraSoniclist[4] >= Ferment_Tank_water_height):
  5484. F5 = 'F_Fermenting'
  5485. F5_thread = threading.Thread(target=FInputtingWater_TO_FFermenting, args=["F5"])
  5486. F5_thread.start()
  5487. elif (F_UP_tank_WaterLevel[0] == 1):
  5488. FInputtingWater_AND_WaterLevel1("F5")
  5489. elif (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height):
  5490. FInputtingWater_AND_tankwaterfilled("F5")
  5491. elif F6 == 'F_InputtingWater':
  5492. if (F_UP_tank_WaterLevel[5] == 1) and (F_UP_UltraSoniclist[5] >= Ferment_Tank_water_height):
  5493. F6 = 'F_Fermenting'
  5494. F6_thread = threading.Thread(target=FInputtingWater_TO_FFermenting, args=["F6"])
  5495. F6_thread.start()
  5496. elif (F_UP_tank_WaterLevel[5] == 1):
  5497. FInputtingWater_AND_WaterLevel1("F6")
  5498. elif (F_UP_UltraSoniclist[5] >= Ferment_Tank_water_height):
  5499. FInputtingWater_AND_tankwaterfilled("F6")
  5500. else:
  5501. print("else ---------------------------- ")
  5502. 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:
  5503. F1_thread = threading.Thread(target=FFermenting_TO_FOutputtingBean, args=["F1"])
  5504. F1_thread.start()
  5505. F1 = 'F_OutputtingBean'
  5506. # 將可出豆桶槽賦值
  5507. if FOutputtingBean_Tank == '': FOutputtingBean_Tank = 'F1'
  5508. if F2 == 'F_Fermenting':
  5509. F2_thread = threading.Thread(target=FFermenting_TO_FOutputtingBean, args=["F2"])
  5510. F2_thread.start()
  5511. F2 = 'F_OutputtingBean'
  5512. if FOutputtingBean_Tank == '': FOutputtingBean_Tank = 'F2'
  5513. if F3 == 'F_Fermenting':
  5514. F3_thread = threading.Thread(target=FFermenting_TO_FOutputtingBean, args=["F3"])
  5515. F3_thread.start()
  5516. F3 = 'F_OutputtingBean'
  5517. if FOutputtingBean_Tank == '': FOutputtingBean_Tank = 'F3'
  5518. if F4 == 'F_Fermenting':
  5519. F4_thread = threading.Thread(target=FFermenting_TO_FOutputtingBean, args=["F4"])
  5520. F4_thread.start()
  5521. F4 = 'F_OutputtingBean'
  5522. if FOutputtingBean_Tank == '': FOutputtingBean_Tank = 'F4'
  5523. if F5 == 'F_Fermenting':
  5524. F5_thread = threading.Thread(target=FFermenting_TO_FOutputtingBean, args=["F5"])
  5525. F5_thread.start()
  5526. F5 = 'F_OutputtingBean'
  5527. if FOutputtingBean_Tank == '': FOutputtingBean_Tank = 'F5'
  5528. if F6 == 'F_Fermenting':
  5529. F6_thread = threading.Thread(target=FFermenting_TO_FOutputtingBean, args=["F6"])
  5530. F6_thread.start()
  5531. F6 = 'F_OutputtingBean'
  5532. if FOutputtingBean_Tank == '': FOutputtingBean_Tank = 'F6'
  5533. # 若桶槽 F1~F6 可出豆 且 桶槽內為空桶 且 有指定清洗排程, 進行清洗桶槽
  5534. # TODO 發酵次數計算、消毒次數、校正
  5535. if F1 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[0] <= Ferment_Tank_bean_empty):
  5536. if FOutputtingBean_Tank == 'F1':
  5537. FOutputtingBean_TO_FWaiting('F1')
  5538. FOutputtingBean_Tank = ''
  5539. if (FermentAuto_cleaning == 0): F1 = 'F_Waiting'
  5540. elif (FermentAuto_cleaning != 0): F1 = 'F_Cleaning'
  5541. if F2 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[1] <= Ferment_Tank_bean_empty):
  5542. if FOutputtingBean_Tank == 'F2':
  5543. FOutputtingBean_TO_FWaiting('F2')
  5544. FOutputtingBean_Tank = ''
  5545. if (FermentAuto_cleaning == 0): F2 = 'F_Waiting'
  5546. elif (FermentAuto_cleaning != 0): F2 = 'F_Cleaning'
  5547. if F3 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[2] <= Ferment_Tank_bean_empty):
  5548. if FOutputtingBean_Tank == 'F3':
  5549. FOutputtingBean_TO_FWaiting('F3')
  5550. FOutputtingBean_Tank = ''
  5551. if (FermentAuto_cleaning == 0): F3 = 'F_Waiting'
  5552. elif (FermentAuto_cleaning != 0): F3 = 'F_Cleaning'
  5553. if F4 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[3] <= Ferment_Tank_bean_empty):
  5554. if FOutputtingBean_Tank == 'F4':
  5555. FOutputtingBean_TO_FWaiting('F4')
  5556. FOutputtingBean_Tank = ''
  5557. if (FermentAuto_cleaning == 0): F4 = 'F_Waiting'
  5558. elif (FermentAuto_cleaning != 0): F4 = 'F_Cleaning'
  5559. if F5 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[4] <= Ferment_Tank_bean_empty):
  5560. if FOutputtingBean_Tank == 'F5':
  5561. FOutputtingBean_TO_FWaiting('F5')
  5562. FOutputtingBean_Tank = ''
  5563. if (FermentAuto_cleaning == 0): F5 = 'F_Waiting'
  5564. elif (FermentAuto_cleaning != 0): F5 = 'F_Cleaning'
  5565. if F6 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[5] <= Ferment_Tank_bean_empty):
  5566. if FOutputtingBean_Tank == 'F6':
  5567. FOutputtingBean_TO_FWaiting('F6')
  5568. FOutputtingBean_Tank = ''
  5569. if (FermentAuto_cleaning == 0): F6 = 'F_Waiting'
  5570. elif (FermentAuto_cleaning != 0): F6 = 'F_Cleaning'
  5571. # 避免桶槽可出豆時未賦值
  5572. if FOutputtingBean_Tank == '':
  5573. if F1 == 'F_OutputtingBean': FOutputtingBean_Tank = 'F1'
  5574. elif F2 == 'F_OutputtingBean': FOutputtingBean_Tank = 'F2'
  5575. elif F3 == 'F_OutputtingBean': FOutputtingBean_Tank = 'F3'
  5576. elif F4 == 'F_OutputtingBean': FOutputtingBean_Tank = 'F4'
  5577. elif F5 == 'F_OutputtingBean': FOutputtingBean_Tank = 'F5'
  5578. elif F6 == 'F_OutputtingBean': FOutputtingBean_Tank = 'F6'
  5579. # 若桶槽 F1~F6 為清洗中
  5580. if F1 == 'F_Cleaning':
  5581. F1_thread = threading.Thread(target=FCleaning, args=["F1"])
  5582. F1_thread.start()
  5583. F1 = 'F_Waiting'
  5584. if F2 == 'F_Cleaning':
  5585. F2_thread = threading.Thread(target=FCleaning, args=["F2"])
  5586. F2_thread.start()
  5587. F2 = 'F_Waiting'
  5588. if F3 == 'F_Cleaning':
  5589. F3_thread = threading.Thread(target=FCleaning, args=["F3"])
  5590. F3_thread.start()
  5591. F3 = 'F_Waiting'
  5592. if F4 == 'F_Cleaning':
  5593. F4_thread = threading.Thread(target=FCleaning, args=["F4"])
  5594. F4_thread.start()
  5595. F4 = 'F_Waiting'
  5596. if F5 == 'F_Cleaning':
  5597. F5_thread = threading.Thread(target=FCleaning, args=["F5"])
  5598. F5_thread.start()
  5599. F5 = 'F_Waiting'
  5600. if F6 == 'F_Cleaning':
  5601. F6_thread = threading.Thread(target=FCleaning, args=["F6"])
  5602. F6_thread.start()
  5603. F6 = 'F_Waiting'
  5604. # # ----- [測試用] !!!!! F1~F6 入料完成→可出豆 判斷 ------------------------------
  5605. # if F1 == 'F_InputtingBean_Finish': F1 = 'F_OutputtingBean'
  5606. # if F2 == 'F_InputtingBean_Finish': F2 = 'F_OutputtingBean'
  5607. # if F3 == 'F_InputtingBean_Finish': F3 = 'F_OutputtingBean'
  5608. # if F4 == 'F_InputtingBean_Finish': F4 = 'F_OutputtingBean'
  5609. # if F5 == 'F_InputtingBean_Finish': F5 = 'F_OutputtingBean'
  5610. # if F6 == 'F_InputtingBean_Finish': F6 = 'F_OutputtingBean'
  5611. # # ----- [測試用] !!!!! F1~F6 入料完成→可出豆 判斷 ------------------------------
  5612. else:
  5613. # [介面] 若未啟用 發酵 狀態
  5614. print('未啟用發酵流程')
  5615. # ----- 發酵出料儲豆槽 FO1~FO2 入豆→可出豆判斷 ------------------------------
  5616. # 目前發酵槽 F1~F6 正在入豆、入水的桶槽數量 (應小於一桶)
  5617. # Ferment_OutputtingBean_number = int(F_UP_tanklist.count('F_OutputtingBean'))
  5618. # 若出料儲豆槽狀態為 空桶等待 且 桶槽狀態為 F_OutputtingBean 可出豆, 與 FO1 配合開始出豆
  5619. if FO1 == 'FO_Waiting' and FOutputtingBean_Tank != '':
  5620. # 判斷要對應出料的桶槽為何, 設定成 FOutputtingBean_Tank = 'F1', 待出完料再把 FOutputtingBean_Tank = ''
  5621. FO1 = 'FO_InputtingBean'
  5622. print('------- ' + FOutputtingBean_Tank + ' 狀態更新:出豆中 -------')
  5623. print('------- FO1 狀態更新:入豆中 -------')
  5624. # [致動器] F1 蝴蝶閥 ON
  5625. data = { "tank_num": FOutputtingBean_Tank, "command": "tank_diskvalve_status", "value": "on" }
  5626. print('data: ', data)
  5627. # mqtt_f(data)
  5628. elif FO1 == 'FO_InputtingBean' and FOutputtingBean_Tank != '':
  5629. if FO_UP_UltraSoniclist[0] >= Ferment_Output_bean_height:
  5630. # [致動器] 出料真空吸料機 OFF
  5631. data = { "tank_num": FOutputtingBean_Tank, "command": "input_vacuum_status", "value": "off" }
  5632. print('data: ', data)
  5633. # mqtt_f(data)
  5634. # [致動器] F1 蝴蝶閥 OFF
  5635. data = { "tank_num": FOutputtingBean_Tank, "command": "tank_diskvalve_status", "value": "off" }
  5636. print('data: ', data)
  5637. # mqtt_f(data)
  5638. FO1 = 'FO_OutputtingBean'
  5639. print('------- FO1 狀態更新:出豆中 -------')
  5640. elif FO_UP_UltraSoniclist[0] < Ferment_Output_bean_height:
  5641. FO1_thread = threading.Thread(target=FOInputtingBean_filled, args=["FO1"])
  5642. FO1_thread.start()
  5643. # 若是無桶槽可入豆, 出料儲豆槽判斷是否可出豆或空桶等待入豆
  5644. elif FOutputtingBean_Tank == '':
  5645. if FO_UP_UltraSoniclist[0] > Ferment_Output_bean_empty:
  5646. FO1 = 'FO_OutputtingBean'
  5647. print('------- FO1 狀態更新:可出豆 -------')
  5648. elif FO_UP_UltraSoniclist[0] <= Ferment_Output_bean_empty:
  5649. FO1 = 'FO_Waiting'
  5650. print('------- FO1 狀態更新:空桶等待 -------')
  5651. elif FO1 == 'FO_OutputtingBean' and FO_UP_UltraSoniclist[0] <= Ferment_Output_bean_empty:
  5652. FO1 = 'FO_Waiting'
  5653. print('------- FO1 狀態更新:空桶等待 -------')
  5654. # ----- 等待 thread 多執行緒執行完成 --------
  5655. # 若 FI1_thread 有被定義, 則執行 FI1_thread.join() 等待執行完成 (當入料儲豆槽入料時)
  5656. # 若 FI1_thread 有被定義, 會出現 UnboundLocalError: local variable 'FO1_thread' referenced before assignment 錯誤訊息
  5657. # (非入料儲豆槽入料時) 此時就不進行任何處理
  5658. try:
  5659. FI1_thread.join()
  5660. print("-- FI1_thread complete! --")
  5661. except UnboundLocalError:
  5662. pass
  5663. try:
  5664. F1_thread.join()
  5665. print("-- F1_thread complete! --")
  5666. except UnboundLocalError:
  5667. pass
  5668. try:
  5669. F2_thread.join()
  5670. print("-- F2_thread complete! --")
  5671. except UnboundLocalError:
  5672. pass
  5673. try:
  5674. F3_thread.join()
  5675. print("-- F3_thread complete! --")
  5676. except UnboundLocalError:
  5677. pass
  5678. try:
  5679. F4_thread.join()
  5680. print("-- F4_thread complete! --")
  5681. except UnboundLocalError:
  5682. pass
  5683. try:
  5684. F5_thread.join()
  5685. print("-- F5_thread complete! --")
  5686. except UnboundLocalError:
  5687. pass
  5688. try:
  5689. F6_thread.join()
  5690. print("-- F6_thread complete! --")
  5691. except UnboundLocalError:
  5692. pass
  5693. try:
  5694. FO1_thread.join()
  5695. print("-- FO1_thread complete! --")
  5696. except UnboundLocalError:
  5697. pass
  5698. # ----- 將狀態寫入資料庫 ------------------------------
  5699. # 獲取文本框的值並賦值給user實體對象
  5700. F_status = ferment_container_status()
  5701. F_status.Ferment_Input_1 = FI1
  5702. F_status.Ferment_Input_2 = FI2
  5703. F_status.Ferment_Tank_1 = F1
  5704. F_status.Ferment_Tank_2 = F2
  5705. F_status.Ferment_Tank_3 = F3
  5706. F_status.Ferment_Tank_4 = F4
  5707. F_status.Ferment_Tank_5 = F5
  5708. F_status.Ferment_Tank_6 = F6
  5709. F_status.Ferment_Tank_7 = F7
  5710. F_status.Ferment_Tank_8 = F8
  5711. F_status.Ferment_Tank_9 = F9
  5712. F_status.Ferment_Tank_10 = F10
  5713. F_status.Ferment_Tank_11 = F11
  5714. F_status.Ferment_Tank_12 = F12
  5715. F_status.Ferment_Output_1 = FO1
  5716. F_status.Ferment_Output_2 = FO2
  5717. #將數據保存進資料庫
  5718. db.session.add(F_status)
  5719. # 手動提交
  5720. db.session.commit()
  5721. # ----- 將狀態寫入資料庫 ------------------------------
  5722. return jsonify({"Peel_Output_1":PO1,
  5723. "Ferment_Input_1":FI1,
  5724. "Ferment_Tank_1":F1,
  5725. "Ferment_Tank_2":F2,
  5726. "Ferment_Tank_3":F3,
  5727. "Ferment_Tank_4":F4,
  5728. "Ferment_Tank_5":F5,
  5729. "Ferment_Tank_6":F6,
  5730. "Ferment_Output_1":FO1
  5731. })
  5732. @main.route('/sitemap')
  5733. def sitemap():
  5734. if request.method == 'GET':
  5735. if 'id' in session and 'uname' in session and 'status' in session:
  5736. username = session['uname']
  5737. status = session['status']
  5738. print('username: ', username)
  5739. print('status: ', status)
  5740. if status == 9:
  5741. return render_template('signin_disable.html', **locals())
  5742. elif status == 8:
  5743. return render_template('signin_new.html', **locals())
  5744. return render_template('sitemap.html', **locals())
  5745. else:
  5746. return render_template('sign_in.html')
  5747. @main.route('/index_navbar', methods=['GET'])
  5748. def index_navbar():
  5749. return render_template('index_navbar.html')
  5750. @main.route('/dry_SHT11_<dtid>', methods=['GET', 'POST'])
  5751. def dry_SHT11(dtid):
  5752. if request.method == 'GET':
  5753. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D' + dtid).order_by(text('datetime desc')).first()
  5754. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D' + dtid).order_by(text('datetime desc')).first()
  5755. SHT11_Temp = tank_SHT11.SHT11_Temp
  5756. SHT11_Humidity = tank_SHT11.SHT11_Humidity
  5757. Soil_Temp = tank_Soil.soil_Temp
  5758. return jsonify({"SHT11_Temp":SHT11_Temp,
  5759. "SHT11_Humidity":SHT11_Humidity,
  5760. "Soil_Temp":Soil_Temp
  5761. })
  5762. else:
  5763. pass
  5764. @main.route('/dry_UltraSonic_<dtid>', methods=['GET', 'POST'])
  5765. def dry_UltraSonic(dtid):
  5766. if request.method == 'GET':
  5767. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D' + dtid).order_by(text('datetime desc')).first()
  5768. UltraSonic = tank_UltraSonic.UltraSonic
  5769. return jsonify({"UltraSonic":UltraSonic
  5770. })
  5771. else:
  5772. pass
  5773. @main.route('/dry_input_UltraSonic_<dtid>', methods=['GET', 'POST'])
  5774. def dry_input_UltraSonic(dtid):
  5775. if request.method == 'GET':
  5776. input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI' + dtid).order_by(text('datetime desc')).first()
  5777. UltraSonic = input_UltraSonic.UltraSonic
  5778. return jsonify({"UltraSonic":UltraSonic
  5779. })
  5780. else:
  5781. pass
  5782. @main.route('/dry_output_UltraSonic_<dtid>', methods=['GET', 'POST'])
  5783. def dry_output_UltraSonic(dtid):
  5784. if request.method == 'GET':
  5785. output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO' + dtid).order_by(text('datetime desc')).first()
  5786. UltraSonic = output_UltraSonic.UltraSonic
  5787. return jsonify({"UltraSonic":UltraSonic
  5788. })
  5789. else:
  5790. pass
  5791. @main.route('/ferment_SHT11_<ftid>', methods=['GET', 'POST'])
  5792. def ferment_SHT11(ftid):
  5793. if request.method == 'GET':
  5794. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  5795. SHT11_Temp = tank_SHT11.SHT11_Temp
  5796. return jsonify({"SHT11_Temp":SHT11_Temp
  5797. })
  5798. else:
  5799. pass
  5800. @main.route('/ferment_WaterLevel_<ftid>', methods=['GET', 'POST'])
  5801. def ferment_WaterLevel(ftid):
  5802. if request.method == 'GET':
  5803. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  5804. WaterLevel = tank_WaterLevel.WaterLevel
  5805. return jsonify({"WaterLevel":WaterLevel
  5806. })
  5807. else:
  5808. pass
  5809. @main.route('/ferment_WaterIn_<ftid>', methods=['GET', 'POST'])
  5810. def ferment_WaterIn(ftid):
  5811. if request.method == 'GET':
  5812. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  5813. UltraSonic = (float(tank_UltraSonic.UltraSonic))
  5814. # tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  5815. # PressureWaterLevel = '{:.2f}'.format((float(tank_PressureWaterLevel.PressureWaterLevel) -15 -90.278)/9.4214)
  5816. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  5817. WaterLevel = tank_WaterLevel.WaterLevel
  5818. return jsonify({"UltraSonic":UltraSonic,
  5819. "WaterLevel":WaterLevel
  5820. })
  5821. else:
  5822. pass
  5823. @main.route('/ferment_UltraSonic_<ftid>', methods=['GET', 'POST'])
  5824. def ferment_UltraSonic(ftid):
  5825. if request.method == 'GET':
  5826. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
  5827. UltraSonic = (float(tank_UltraSonic.UltraSonic))
  5828. return jsonify({"UltraSonic":UltraSonic
  5829. })
  5830. else:
  5831. pass
  5832. @main.route('/ferment_input_UltraSonic_<ftid>', methods=['GET', 'POST'])
  5833. def ferment_input_UltraSonic_(ftid):
  5834. if request.method == 'GET':
  5835. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI' + ftid).order_by(text('datetime desc')).first()
  5836. UltraSonic = input_UltraSonic.UltraSonic
  5837. return jsonify({"UltraSonic":UltraSonic
  5838. })
  5839. else:
  5840. pass
  5841. @main.route('/ferment_output_UltraSonic_<ftid>', methods=['GET', 'POST'])
  5842. def ferment_output_UltraSonic_(ftid):
  5843. if request.method == 'GET':
  5844. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO' + ftid).order_by(text('datetime desc')).first()
  5845. UltraSonic = output_UltraSonic.UltraSonic
  5846. return jsonify({"UltraSonic":UltraSonic
  5847. })
  5848. else:
  5849. pass
  5850. @main.route('/ferment_watertesting_<tid>', methods=['GET', 'POST'])
  5851. def ferment_watertesting(tid):
  5852. if request.method == 'GET':
  5853. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  5854. tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  5855. tank_DO = ferment_tank_DO.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  5856. tank_EC = ferment_tank_EC.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  5857. PH = tank_PH.PH
  5858. ORP = tank_ORP.ORP
  5859. DO = tank_DO.DO
  5860. EC = tank_EC.EC
  5861. return jsonify({"PH":PH,
  5862. "ORP":ORP,
  5863. "DO":DO,
  5864. "EC":EC,
  5865. })
  5866. @main.route('/loading/R<rtid>', methods=['GET', 'POST'])
  5867. def R_loading(rtid):
  5868. if request.method == 'GET':
  5869. # 致動器_中水桶
  5870. try:
  5871. tank_actuator = reclaimed_tank_actuator.query.filter_by(tank_num='R'+rtid).order_by(text('datetime desc')).first()
  5872. db.session.close()
  5873. tank_solenoid_water_in = tank_actuator.solenoid_water_in
  5874. tank_solenoid_reclaimed_out = tank_actuator.solenoid_reclaimed_out
  5875. tank_solenoid_water_out = tank_actuator.solenoid_water_out
  5876. tank_pump_reclaimed_out = tank_actuator.pump_reclaimed_out
  5877. except:
  5878. tank_solenoid_water_in = 2
  5879. tank_solenoid_reclaimed_out = 2
  5880. tank_solenoid_water_out = 2
  5881. tank_pump_reclaimed_out = 2
  5882. try:
  5883. tank_sensor = reclaimed_tank_sensor.query.filter_by(tank_num='R'+rtid).order_by(text('datetime desc')).first()
  5884. db.session.close()
  5885. tank_UltraSonic = float(tank_sensor.UltraSonic)
  5886. tank_Turbidity = tank_sensor.tankTurbidity
  5887. return jsonify({"tank_solenoid_water_in":tank_solenoid_water_in,
  5888. "tank_solenoid_reclaimed_out":tank_solenoid_reclaimed_out,
  5889. "tank_solenoid_water_out":tank_solenoid_water_out,
  5890. "tank_pump_reclaimed_out":tank_pump_reclaimed_out,
  5891. "tank_UltraSonic":tank_UltraSonic,
  5892. "tank_Turbidity":tank_Turbidity
  5893. })
  5894. except:
  5895. return jsonify({"tank_solenoid_water_in":tank_solenoid_water_in,
  5896. "tank_solenoid_reclaimed_out":tank_solenoid_reclaimed_out,
  5897. "tank_solenoid_water_out":tank_solenoid_water_out,
  5898. "tank_pump_reclaimed_out":tank_pump_reclaimed_out,
  5899. "tank_UltraSonic":"null",
  5900. "tank_Turbidity":"null"
  5901. })
  5902. else:
  5903. pass
  5904. @main.route('/loading/SO<sotid>', methods=['GET', 'POST'])
  5905. def SO_loading(sotid):
  5906. if request.method == 'GET':
  5907. # 致動器_脫皮機_ALL
  5908. try:
  5909. output_actuator = colorselect_output_actuator.query.filter_by(tank_num='SO'+sotid).order_by(text('datetime desc')).first()
  5910. db.session.close()
  5911. output_vacuum = output_actuator.vacuum
  5912. except:
  5913. output_vacuum = 2
  5914. try:
  5915. tank_UltraSonic = colorselect_tank_UltraSonic.query.filter_by(tank_num='SO'+sotid).order_by(text('datetime desc')).first()
  5916. db.session.close()
  5917. tank_UltraSonic = float(tank_UltraSonic.UltraSonic)
  5918. return jsonify({"output_vacuum":output_vacuum,
  5919. "tank_UltraSonic":tank_UltraSonic
  5920. })
  5921. except:
  5922. return jsonify({"output_vacuum":output_vacuum,
  5923. "tank_UltraSonic":"null"
  5924. })
  5925. else:
  5926. pass
  5927. @main.route('/loading/S<stid>', methods=['GET', 'POST'])
  5928. def S_loading(stid):
  5929. if request.method == 'GET':
  5930. # 致動器_色選機
  5931. try:
  5932. tank_actuator = colorselect_tank_actuator.query.filter_by(tank_num='S'+stid).order_by(text('datetime desc')).first()
  5933. db.session.close()
  5934. tank_vacuum = tank_actuator.vacuum
  5935. tank_motor = tank_actuator.motor
  5936. tank_nozzle = tank_actuator.nozzle
  5937. except:
  5938. tank_vacuum = 2
  5939. tank_motor = 2
  5940. tank_nozzle = 2
  5941. # 致動器_顏色感測器
  5942. try:
  5943. tank_color = colorselect_tank_color.query.filter_by(tank_num='S'+stid).order_by(text('datetime desc')).first()
  5944. db.session.close()
  5945. color = tank_color.color
  5946. return jsonify({"tank_vacuum":tank_vacuum,
  5947. "tank_motor":tank_motor,
  5948. "tank_nozzle":tank_nozzle,
  5949. "color":color
  5950. })
  5951. except:
  5952. return jsonify({"tank_vacuum":tank_vacuum,
  5953. "tank_motor":tank_motor,
  5954. "tank_nozzle":tank_nozzle,
  5955. "color":"null"
  5956. })
  5957. else:
  5958. pass
  5959. @main.route('/loading/PO<potid>', methods=['GET', 'POST'])
  5960. def PO_loading(potid):
  5961. if request.method == 'GET':
  5962. # 致動器_脫皮機_ALL
  5963. try:
  5964. output_actuator = peel_output_actuator.query.filter_by(tank_num='PO'+potid).order_by(text('datetime desc')).first()
  5965. db.session.close()
  5966. output_vacuum = output_actuator.vacuum
  5967. except:
  5968. output_vacuum = 2
  5969. try:
  5970. output_UltraSonic = peel_output_UltraSonic.query.filter_by(tank_num='PO'+potid).order_by(text('datetime desc')).first()
  5971. db.session.close()
  5972. output_UltraSonic = float(output_UltraSonic.UltraSonic)
  5973. return jsonify({"output_vacuum":output_vacuum,
  5974. "output_UltraSonic":output_UltraSonic
  5975. })
  5976. except:
  5977. return jsonify({"output_vacuum":output_vacuum,
  5978. "output_UltraSonic":"null"
  5979. })
  5980. else:
  5981. pass
  5982. @main.route('/loading/P<ptid>', methods=['GET', 'POST'])
  5983. def P_loading(ptid):
  5984. if request.method == 'GET':
  5985. # 致動器_脫皮機_ALL
  5986. try:
  5987. tank_actuator = peel_tank_actuator.query.filter_by(tank_num='P'+ptid).order_by(text('datetime desc')).first()
  5988. db.session.close()
  5989. tank_vacuum = tank_actuator.vacuum
  5990. tank_motor = tank_actuator.motor
  5991. except:
  5992. tank_vacuum = 2
  5993. tank_motor = 2
  5994. try:
  5995. output_motorEncoder = peel_output_motorEncoder.query.filter_by(tank_num='P'+ptid).order_by(text('datetime desc')).first()
  5996. db.session.close()
  5997. motorEncoder = output_motorEncoder.motorEncoder
  5998. return jsonify({"tank_vacuum":tank_vacuum,
  5999. "tank_motor":tank_motor,
  6000. "motorEncoder":motorEncoder})
  6001. except:
  6002. return jsonify({"tank_vacuum":tank_vacuum,
  6003. "tank_motor":tank_motor,
  6004. "motorEncoder":"null"})
  6005. else:
  6006. pass
  6007. @main.route('/loading/CI<citid>', methods=['GET', 'POST'])
  6008. def CI_loading(citid):
  6009. if request.method == 'GET':
  6010. try:
  6011. input_actuator = clean_input_actuator.query.filter_by(tank_num='CI'+citid).order_by(text('datetime desc')).first()
  6012. db.session.close()
  6013. input_vacuum = input_actuator.vacuum
  6014. except:
  6015. input_vacuum = 2
  6016. try:
  6017. input_sensor = clean_input_sensor.query.filter_by(tank_num='CI'+citid).order_by(text('datetime desc')).first()
  6018. db.session.close()
  6019. input_UltraSonic = input_sensor.UltraSonic
  6020. return jsonify({"input_vacuum":input_vacuum,
  6021. "input_UltraSonic":input_UltraSonic
  6022. })
  6023. except:
  6024. return jsonify({"input_vacuum":input_vacuum,
  6025. "input_UltraSonic":"null"
  6026. })
  6027. else:
  6028. pass
  6029. @main.route('/loading/C<ctid>', methods=['GET', 'POST'])
  6030. def C_loading(ctid):
  6031. if request.method == 'GET':
  6032. try:
  6033. tank_actuator = cleann_tank_actuator.query.filter_by(tank_num='C'+ctid).order_by(text('datetime desc')).first()
  6034. db.session.close()
  6035. vacuum = tank_actuator.vacuum
  6036. threewayvalve_input = tank_actuator.threewayvalve_input
  6037. motor = tank_actuator.motor
  6038. solenoid_reclaimed_in = tank_actuator.solenoid_reclaimed_in
  6039. solenoid_water_in = tank_actuator.solenoid_water_in
  6040. pump_water_in = tank_actuator.pump_water_in
  6041. solenoid_water_out = tank_actuator.solenoid_water_out
  6042. solenoid_reclaimed_out = tank_actuator.solenoid_reclaimed_out
  6043. solenoid_disinfect = tank_actuator.solenoid_disinfect
  6044. pump_disinfect = tank_actuator.pump_disinfect
  6045. diskvalve = tank_actuator.diskvalve
  6046. warning_light = tank_actuator.warning_light
  6047. except:
  6048. vacuum = 2
  6049. threewayvalve_input = 2
  6050. motor = 2
  6051. solenoid_reclaimed_in = 2
  6052. solenoid_water_in = 2
  6053. pump_water_in = 2
  6054. solenoid_water_out = 2
  6055. solenoid_reclaimed_out = 2
  6056. solenoid_disinfect = 2
  6057. pump_disinfect = 2
  6058. diskvalve = 2
  6059. warning_light=2
  6060. try:
  6061. # 感測器_浮選清洗_超音波感測器
  6062. tank_UltraSonic = clean_tank_UltraSonic.query.filter_by(tank_num='C'+ctid).order_by(text('datetime desc')).first()
  6063. db.session.close()
  6064. UltraSonic = tank_UltraSonic.UltraSonic
  6065. except:
  6066. UltraSonic = "null"
  6067. try:
  6068. tank_butterflyvalve = clean_tank_butterflyvalve.query.filter_by(tank_num='C'+ctid).order_by(text('datetime desc')).first()
  6069. db.session.close()
  6070. butterflyvalve = tank_butterflyvalve.butterflyvalve
  6071. except:
  6072. butterflyvalve = "null"
  6073. try:
  6074. tank_Encoder = clean_tank_Encoder.query.filter_by(tank_num='C'+ctid).order_by(text('datetime desc')).first()
  6075. db.session.close()
  6076. Encoder = tank_Encoder.Encoder
  6077. except:
  6078. Encoder = "null"
  6079. try:
  6080. tank_Turbidity = clean_tank_Turbidity.query.filter_by(tank_num='C'+ctid).order_by(text('datetime desc')).first()
  6081. db.session.close()
  6082. tankTurbidity = tank_Turbidity.tankTurbidity
  6083. return jsonify({"UltraSonic":UltraSonic,
  6084. "butterflyvalve":butterflyvalve,
  6085. "Encoder":Encoder,
  6086. "tankTurbidity":tankTurbidity,
  6087. "vacuum":vacuum,
  6088. "threewayvalve_input":threewayvalve_input,
  6089. "motor":motor,
  6090. "solenoid_reclaimed_in":solenoid_reclaimed_in,
  6091. "solenoid_water_in":solenoid_water_in,
  6092. "pump_water_in":pump_water_in,
  6093. "solenoid_water_out":solenoid_water_out,
  6094. "solenoid_reclaimed_out":solenoid_reclaimed_out,
  6095. "solenoid_disinfect":solenoid_disinfect,
  6096. "pump_disinfect":pump_disinfect,
  6097. "diskvalve":diskvalve,
  6098. "warning_light":warning_light
  6099. })
  6100. except:
  6101. return jsonify({"UltraSonic":UltraSonic,
  6102. "butterflyvalve":butterflyvalve,
  6103. "Encoder":Encoder,
  6104. "tankTurbidity":"null",
  6105. "vacuum":vacuum,
  6106. "threewayvalve_input":threewayvalve_input,
  6107. "motor":motor,
  6108. "solenoid_reclaimed_in":solenoid_reclaimed_in,
  6109. "solenoid_water_in":solenoid_water_in,
  6110. "pump_water_in":pump_water_in,
  6111. "solenoid_water_out":solenoid_water_out,
  6112. "solenoid_reclaimed_out":solenoid_reclaimed_out,
  6113. "solenoid_disinfect":solenoid_disinfect,
  6114. "pump_disinfect":pump_disinfect,
  6115. "diskvalve":diskvalve,
  6116. "warning_light":warning_light
  6117. })
  6118. else:
  6119. pass
  6120. @main.route('/loading/F<ftid>', methods=['GET', 'POST'])
  6121. def F_loading(ftid):
  6122. if request.method == 'GET':
  6123. # 致動器_發酵槽_ALL
  6124. try:
  6125. tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6126. db.session.close()
  6127. vacuum = tank_actuator.vacuum
  6128. threewayvalve_input = tank_actuator.threewayvalve_input
  6129. diskvalve = tank_actuator.diskvalve
  6130. solenoid_tank_pump = tank_actuator.solenoid_tank_pump
  6131. solenoid_disinfect = tank_actuator.solenoid_disinfect
  6132. solenoid_outer_water = tank_actuator.solenoid_outer_water
  6133. solenoid_water_in = tank_actuator.solenoid_water_in
  6134. solenoid_water_out = tank_actuator.solenoid_water_out
  6135. pump_sensor = tank_actuator.pump_sensor
  6136. threewayvalve_outer_float = tank_actuator.threewayvalve_outer_float
  6137. motor = tank_actuator.motor
  6138. heater1 = tank_actuator.heater1
  6139. heater2 = tank_actuator.heater2
  6140. warning_light = tank_actuator.warning_light
  6141. except:
  6142. vacuum = 2
  6143. threewayvalve_input = 2
  6144. diskvalve = 2
  6145. solenoid_tank_pump = 2
  6146. solenoid_disinfect = 2
  6147. solenoid_outer_water = 2
  6148. solenoid_water_in = 2
  6149. solenoid_water_out = 2
  6150. pump_sensor = 2
  6151. threewayvalve_outer_float = 2
  6152. motor = 2
  6153. heater1 = 2
  6154. heater2 = 2
  6155. warning_light=2
  6156. try:
  6157. # 感測器_發酵桶_SHT11
  6158. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6159. db.session.close()
  6160. SHT11_Temp = float(tank_SHT11.SHT11_Temp)
  6161. SHT11_Humidity = float(tank_SHT11.SHT11_Humidity)
  6162. except:
  6163. SHT11_Temp = "null"
  6164. SHT11_Humidity = "null"
  6165. # 感測器_發酵桶_二氧化碳
  6166. try:
  6167. tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6168. db.session.close()
  6169. CO2 = float(tank_CO2.CO2)
  6170. except:
  6171. CO2 = "null"
  6172. # 感測器_發酵桶_酸鹼值
  6173. try:
  6174. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6175. db.session.close()
  6176. PH = float(tank_PH.PH)
  6177. except:
  6178. PH = "null"
  6179. try:
  6180. tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6181. db.session.close()
  6182. ORP = float(tank_ORP.ORP)
  6183. except:
  6184. ORP = "null"
  6185. try:
  6186. tank_DO = ferment_tank_DO.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6187. db.session.close()
  6188. DO = float(tank_DO.DO)
  6189. except:
  6190. DO = "null"
  6191. try:
  6192. tank_EC = ferment_tank_EC.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6193. db.session.close()
  6194. EC = float(tank_EC.EC)
  6195. except:
  6196. EC = "null"
  6197. # 感測器_發酵桶_氣壓
  6198. try:
  6199. tank_butterflyvalve = ferment_tank_butterflyvalve.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6200. db.session.close()
  6201. butterflyvalve = tank_butterflyvalve.butterflyvalve
  6202. except:
  6203. butterflyvalve = "null"
  6204. try:
  6205. tank_PA = ferment_tank_PA.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6206. db.session.close()
  6207. PA = float(tank_PA.PA)
  6208. except:
  6209. PA = "null"
  6210. # 感測器_發酵桶_超音波感測器
  6211. try:
  6212. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6213. db.session.close()
  6214. UltraSonic= (float(tank_UltraSonic.UltraSonic))
  6215. except:
  6216. UltraSonic= "null"
  6217. # 感測器_發酵桶_保溫夾層水位計
  6218. try:
  6219. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6220. db.session.close()
  6221. WaterLevel = tank_WaterLevel.WaterLevel
  6222. except:
  6223. WaterLevel = "null"
  6224. # 感測器_發酵桶_馬達編碼器
  6225. try:
  6226. tank_motorEncoder = ferment_tank_motorEncoder.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
  6227. db.session.close()
  6228. motorEncoder = tank_motorEncoder.motorEncoder
  6229. return jsonify({"SHT11_Temp": SHT11_Temp,
  6230. "SHT11_Humidity":SHT11_Humidity,
  6231. "CO2":CO2,
  6232. "PH":PH,
  6233. "ORP":ORP,
  6234. "DO":DO,
  6235. "EC":EC,
  6236. "PA":PA,
  6237. "WaterLevel":WaterLevel,
  6238. "UltraSonic":UltraSonic,
  6239. "motorEncoder":motorEncoder,
  6240. "butterflyvalve":butterflyvalve,
  6241. "vacuum":vacuum,
  6242. "threewayvalve_input":threewayvalve_input,
  6243. "diskvalve":diskvalve,
  6244. "solenoid_tank_pump":solenoid_tank_pump,
  6245. "solenoid_disinfect":solenoid_disinfect,
  6246. "solenoid_outer_water":solenoid_outer_water,
  6247. "solenoid_water_in":solenoid_water_in,
  6248. "solenoid_water_out":solenoid_water_out,
  6249. "pump_sensor":pump_sensor,
  6250. "threewayvalve_outer_float":threewayvalve_outer_float,
  6251. "motor":motor,
  6252. "heater1":heater1,
  6253. "heater2":heater2,
  6254. "warning_light":warning_light
  6255. })
  6256. except:
  6257. return jsonify({"SHT11_Temp": SHT11_Temp,
  6258. "SHT11_Humidity":SHT11_Humidity,
  6259. "CO2":CO2,
  6260. "PH":PH,
  6261. "ORP":ORP,
  6262. "DO":DO,
  6263. "EC":EC,
  6264. "PA":PA,
  6265. "WaterLevel":WaterLevel,
  6266. "UltraSonic":UltraSonic,
  6267. "motorEncoder":"null",
  6268. "butterflyvalve":butterflyvalve,
  6269. "vacuum":vacuum,
  6270. "threewayvalve_input":threewayvalve_input,
  6271. "diskvalve":diskvalve,
  6272. "solenoid_tank_pump":solenoid_tank_pump,
  6273. "solenoid_disinfect":solenoid_disinfect,
  6274. "solenoid_outer_water":solenoid_outer_water,
  6275. "solenoid_water_in":solenoid_water_in,
  6276. "solenoid_water_out":solenoid_water_out,
  6277. "pump_sensor":pump_sensor,
  6278. "threewayvalve_outer_float":threewayvalve_outer_float,
  6279. "motor":motor,
  6280. "heater1":heater1,
  6281. "heater2":heater2,
  6282. "warning_light":warning_light
  6283. })
  6284. else:
  6285. pass
  6286. @main.route('/loading/FI<fitid>', methods=['GET', 'POST'])
  6287. def FI_loading(fitid):
  6288. if request.method == 'GET':
  6289. try:
  6290. input_actuator = ferment_input_actuator.query.filter_by(tank_num='FI'+ fitid).order_by(
  6291. text('datetime desc')).first()
  6292. db.session.close()
  6293. input_vacuum = input_actuator.vacuum
  6294. except:
  6295. input_vacuum = 2
  6296. try:
  6297. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI' + fitid).order_by(
  6298. text('datetime desc')).first()
  6299. db.session.close()
  6300. input_UltraSonic = float(input_UltraSonic.UltraSonic)
  6301. dict={"input_vacuum":input_vacuum,"input_UltraSonic":input_UltraSonic}
  6302. return json.dumps(dict)
  6303. except:
  6304. dict={"input_vacuum":input_vacuum,"input_UltraSonic":"null"}
  6305. return json.dumps(dict)
  6306. else:
  6307. pass
  6308. @main.route('/loading/FO<fotid>', methods=['GET', 'POST'])
  6309. def FO_loading(fotid):
  6310. if request.method == 'GET':
  6311. try:
  6312. output_actuator = ferment_output_actuator.query.filter_by(tank_num='FO'+fotid).order_by(text('datetime desc')).first()
  6313. db.session.close()
  6314. output_vacuum = output_actuator.vacuum
  6315. except:
  6316. output_vacuum = 2
  6317. try:
  6318. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO'+fotid).order_by(text('datetime desc')).first()
  6319. db.session.close()
  6320. output_UltraSonic = float(output_UltraSonic.UltraSonic)
  6321. dict={"output_vacuum":output_vacuum,"output_UltraSonic":output_UltraSonic}
  6322. return json.dumps(dict)
  6323. except:
  6324. dict={"output_vacuum":output_vacuum,"output_UltraSonic":"null"}
  6325. return json.dumps(dict)
  6326. else:
  6327. pass
  6328. @main.route('/loading/DI<ditid>', methods=['GET', 'POST'])
  6329. def DI_loading(ditid):
  6330. if request.method == 'GET':
  6331. try:
  6332. input_brake = dry_input_brake.query.filter_by(tank_num='DI'+ditid).order_by(text('datetime desc')).first()
  6333. db.session.close()
  6334. input_vacuum = input_brake.vacuum
  6335. except:
  6336. input_vacuum = 2
  6337. try:
  6338. input_sensor = dry_input_sensor.query.filter_by(tank_num='DI'+ditid).order_by(text('datetime desc')).first()
  6339. db.session.close()
  6340. input_UltraSonic = float(input_sensor.UltraSonic)
  6341. return jsonify({"input_UltraSonic":input_UltraSonic,
  6342. "input_vacuum":input_vacuum
  6343. })
  6344. except:
  6345. return jsonify({"input_UltraSonic":"null",
  6346. "input_vacuum":input_vacuum
  6347. })
  6348. else:
  6349. pass
  6350. @main.route('/loading/DO<dotid>', methods=['GET', 'POST'])
  6351. def DO_loading(dotid):
  6352. if request.method == 'GET':
  6353. try:
  6354. output_actuator = dry_output_brake.query.filter_by(tank_num='DO'+dotid).order_by(text('datetime desc')).first()
  6355. db.session.close()
  6356. output_vacuum = output_actuator.vacuum
  6357. except:
  6358. output_vacuum = 2
  6359. try:
  6360. output_sensor = dry_output_sensor.query.filter_by(tank_num='DO'+dotid).order_by(text('datetime desc')).first()
  6361. db.session.close()
  6362. output_UltraSonic = float(output_sensor.UltraSonic)
  6363. dict={"output_vacuum":output_vacuum,"output_UltraSonic":output_UltraSonic}
  6364. return json.dumps(dict)
  6365. except:
  6366. dict={"output_vacuum":output_vacuum,"output_UltraSonic":"null"}
  6367. return json.dumps(dict)
  6368. else:
  6369. pass
  6370. @main.route('/loading/D<dtid>', methods=['GET', 'POST'])
  6371. def D_loading(dtid):
  6372. if request.method == 'GET':
  6373. # 感測器_乾燥桶_超音波感測器
  6374. try:
  6375. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  6376. db.session.close()
  6377. UltraSonic = tank_UltraSonic.UltraSonic
  6378. except:
  6379. UltraSonic = "null"
  6380. # 感測器_馬達編碼器
  6381. try:
  6382. tank_motorEncoder = dry_tank_motorEncoder.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  6383. db.session.close()
  6384. motorEncoder = tank_motorEncoder.motorEncoder
  6385. except:
  6386. motorEncoder = "null"
  6387. try:
  6388. tank_butterflyvalve = dry_tank_butterflyvalve.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  6389. db.session.close()
  6390. butterflyvalve = tank_butterflyvalve.butterflyvalve
  6391. except:
  6392. butterflyvalve = "null"
  6393. # 感測器_乾燥桶_SHT11
  6394. try:
  6395. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  6396. db.session.close()
  6397. SHT11_Temp = tank_SHT11.SHT11_Temp
  6398. SHT11_Humidity = tank_SHT11.SHT11_Humidity
  6399. except:
  6400. SHT11_Temp = "null"
  6401. SHT11_Humidity = "null"
  6402. # 感測器_乾燥桶_土壤三合一
  6403. try:
  6404. tank_Soil = dry_tank_Soil.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  6405. db.session.close()
  6406. soil_Temp = tank_Soil.soil_Temp
  6407. soil_Humidity = tank_Soil.soil_Humidity
  6408. soil_EC = tank_Soil.soil_EC
  6409. except:
  6410. soil_Temp = "null"
  6411. soil_Humidity = "null"
  6412. soil_EC = "null"
  6413. # 感測器_乾燥桶_氣壓
  6414. try:
  6415. tank_PA = dry_tank_PA.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  6416. db.session.close()
  6417. PA = tank_PA.PA
  6418. except:
  6419. PA = "null"
  6420. try:
  6421. tank_WaterLevel = dry_tank_WaterLevel.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  6422. db.session.close()
  6423. WaterLevel = tank_WaterLevel.WaterLevel
  6424. except:
  6425. WaterLevel = "null"
  6426. try:
  6427. # 致動器_乾燥桶_ALL
  6428. tank_brake = dry_tank_brake.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
  6429. db.session.close()
  6430. vacuum = tank_brake.vacuum
  6431. threewayvalve_input = tank_brake.threewayvalve_input
  6432. diskvalve = tank_brake.diskvalve
  6433. solenoid_disinfect = tank_brake.solenoid_disinfect
  6434. solenoid_water_out = tank_brake.solenoid_water_out
  6435. solenoid_outer_water = tank_brake.solenoid_outer_water
  6436. motor = tank_brake.motor
  6437. vacuum_pump = tank_brake.vacuum_pump
  6438. heater1 = tank_brake.heater1
  6439. heater2 = tank_brake.heater2
  6440. warning_light = tank_brake.warning_light
  6441. return jsonify({"UltraSonic":UltraSonic,
  6442. "SHT11_Temp": SHT11_Temp,
  6443. "SHT11_Humidity":SHT11_Humidity,
  6444. "soil_Temp":soil_Temp,
  6445. "soil_Humidity":soil_Humidity,
  6446. "soil_EC":soil_EC,
  6447. "PA":PA,
  6448. "motorEncoder":motorEncoder,
  6449. "WaterLevel":WaterLevel,
  6450. "butterflyvalve":butterflyvalve,
  6451. "vacuum":vacuum,
  6452. "threewayvalve_input":threewayvalve_input,
  6453. "diskvalve":diskvalve,
  6454. "solenoid_disinfect":solenoid_disinfect,
  6455. "solenoid_water_out":solenoid_water_out,
  6456. "solenoid_outer_water":solenoid_outer_water,
  6457. "motor":motor,
  6458. "vacuum_pump":vacuum_pump,
  6459. "heater1":heater1,
  6460. "heater2":heater2,
  6461. "warning_light":warning_light
  6462. })
  6463. except:
  6464. return jsonify({"UltraSonic":UltraSonic,
  6465. "SHT11_Temp": SHT11_Temp,
  6466. "SHT11_Humidity":SHT11_Humidity,
  6467. "soil_Temp":soil_Temp,
  6468. "soil_Humidity":soil_Humidity,
  6469. "soil_EC":soil_EC,
  6470. "PA":PA,
  6471. "motorEncoder":motorEncoder,
  6472. "WaterLevel":WaterLevel,
  6473. "butterflyvalve":butterflyvalve,
  6474. "vacuum":2,
  6475. "threewayvalve_input":2,
  6476. "diskvalve":2,
  6477. "solenoid_disinfect":2,
  6478. "solenoid_water_out":2,
  6479. "solenoid_outer_water":2,
  6480. "motor":2,
  6481. "vacuum_pump":2,
  6482. "heater1":2,
  6483. "heater2":2,
  6484. "warning_light":2
  6485. })
  6486. else:
  6487. pass
  6488. @main.route('/index_new')
  6489. def index_new():
  6490. if 'id' in session and 'uname' in session and 'status' in session:
  6491. username = session['uname']
  6492. status = session['status']
  6493. if status == 9:
  6494. return render_template('signin_disable.html', **locals())
  6495. elif status == 8:
  6496. return render_template('signin_new.html', **locals())
  6497. else:
  6498. return render_template('sign_in.html', **locals())
  6499. return render_template('index_new.html', title='Smart Coffee', **locals())
  6500. @main.route('/user/<name>')
  6501. def user(name):
  6502. return render_template('hello.html', name=name)
  6503. @main.route('/actuator_chart_<tank>/<sensor_name>/<tid>', methods=['GET', 'POST'])
  6504. def actuator_chart(tank, sensor_name, tid):
  6505. if request.method == 'GET':
  6506. if 'id' in session and 'uname' in session and 'status' in session:
  6507. username = session['uname']
  6508. status = session['status']
  6509. if status == 9:
  6510. return render_template('signin_disable.html')
  6511. elif status == 8:
  6512. return render_template('signin_new.html')
  6513. else:
  6514. return render_template('sign_in.html')
  6515. if tank == 'DI':
  6516. return render_template('actuator_chart_DI.html', title="[致動器]乾燥入料槽", **locals())
  6517. elif tank == 'DO':
  6518. return render_template('actuator_chart_DO.html', title="[致動器]乾燥出料槽", **locals())
  6519. elif tank == 'FI':
  6520. return render_template('actuator_chart_FI.html', title="[致動器]發酵入料槽", **locals())
  6521. elif tank == 'FO':
  6522. return render_template('actuator_chart_FO.html', title="[致動器]發酵出料槽", **locals())
  6523. elif tank == 'F':
  6524. return render_template('actuator_chart_F.html', title="[致動器]發酵槽", **locals())
  6525. elif tank == 'P':
  6526. return render_template('actuator_chart_P.html', title="[致動器]脫皮機", **locals())
  6527. elif tank == 'PO':
  6528. return render_template('actuator_chart_PO.html', title="[致動器]脫皮機出料槽", **locals())
  6529. elif tank == 'S':
  6530. return render_template('actuator_chart_S.html', title="[致動器]色選機", **locals())
  6531. elif tank == 'SO':
  6532. return render_template('actuator_chart_SO.html', title="[致動器]色選機出料槽", **locals())
  6533. elif tank == 'CI':
  6534. return render_template('actuator_chart_CI.html', title="[致動器]清洗槽入料槽", **locals())
  6535. elif tank == 'C':
  6536. return render_template('actuator_chart_C.html', title="[致動器]清洗槽", **locals())
  6537. elif tank == 'R':
  6538. return render_template('actuator_chart_R.html', title="[致動器]中水槽", **locals())
  6539. else:
  6540. return render_template('actuator_chart_D.html', title="[致動器]乾燥槽", **locals())
  6541. @main.route('/sensor_chart_<tank>/<sensor_name>/<tid>', methods=['GET', 'POST'])
  6542. def sensor_chart_D(tank, sensor_name, tid):
  6543. if request.method == 'GET':
  6544. if 'id' in session and 'uname' in session and 'status' in session:
  6545. username = session['uname']
  6546. status = session['status']
  6547. if status == 9:
  6548. return render_template('signin_disable.html')
  6549. elif status == 8:
  6550. return render_template('signin_new.html')
  6551. else:
  6552. return render_template('sign_in.html')
  6553. if tank == 'DI':
  6554. return render_template('sensor_chart_DI.html', title='[感測器]' + '乾燥入料槽', **locals())
  6555. elif tank == 'DO':
  6556. return render_template('sensor_chart_DO.html', title='[感測器]' + '乾燥出料槽', **locals())
  6557. elif tank == 'FI':
  6558. return render_template('sensor_chart_FI.html', title='[感測器]' + '發酵入料槽', **locals())
  6559. elif tank == 'FO':
  6560. return render_template('sensor_chart_FO.html', title='[感測器]' + '發酵出料槽', **locals())
  6561. elif tank == 'F':
  6562. return render_template('sensor_chart_F.html', title='[感測器]' + '發酵槽', **locals())
  6563. elif tank == 'P':
  6564. return render_template('sensor_chart_P.html', title='[感測器]' + '脫皮機', **locals())
  6565. elif tank == 'PO':
  6566. return render_template('sensor_chart_PO.html', title='[感測器]' + '脫皮機出料槽', **locals())
  6567. elif tank == 'S':
  6568. return render_template('sensor_chart_S.html', title='[感測器]' + '色選機', **locals())
  6569. elif tank == 'SO':
  6570. return render_template('sensor_chart_SO.html', title='[感測器]' + '色選機出料槽', **locals())
  6571. elif tank == 'CI':
  6572. return render_template('sensor_chart_CI.html', title='[感測器]' + '清洗槽入料槽', **locals())
  6573. elif tank == 'C':
  6574. return render_template('sensor_chart_C.html', title='[感測器]' + '清洗槽', **locals())
  6575. elif tank == 'R':
  6576. return render_template('sensor_chart_R.html', title='[感測器]' + '中水槽', **locals())
  6577. else:
  6578. return render_template('sensor_chart_D.html', title='[感測器]' + '乾燥槽', **locals())
  6579. # Rita 測試
  6580. # 乾燥桶感測器/致動器測試
  6581. # Rita 須加上 <tid> 區分桶號 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  6582. @main.route('/dry_tank/1', methods=['GET'])
  6583. def dry_tank():
  6584. if request.method == 'GET':
  6585. return render_template('dry_tank.html')
  6586. @main.route('/clean', methods=['GET'])
  6587. def clean():
  6588. if 'id' in session and 'uname' in session and 'status' in session:
  6589. username = session['uname']
  6590. status = session['status']
  6591. if status == 9:
  6592. return render_template('signin_disable.html')
  6593. elif status == 8:
  6594. return render_template('signin_new.html')
  6595. else:
  6596. return render_template('sign_in.html')
  6597. return render_template('clean.html', title='清洗貨櫃', **locals())
  6598. @main.route('/ferment', methods=['GET'])
  6599. def ferment():
  6600. if 'id' in session and 'uname' in session and 'status' in session:
  6601. username = session['uname']
  6602. status = session['status']
  6603. if status == 9:
  6604. return render_template('signin_disable.html')
  6605. elif status == 8:
  6606. return render_template('signin_new.html')
  6607. else:
  6608. return render_template('sign_in.html')
  6609. return render_template('ferment.html', title='發酵貨櫃', **locals())
  6610. @main.route('/dry', methods=['GET'])
  6611. def dry():
  6612. if request.method == 'GET':
  6613. if 'id' in session and 'uname' in session and 'status' in session:
  6614. username = session['uname']
  6615. status = session['status']
  6616. if status == 9:
  6617. return render_template('signin_disable.html')
  6618. elif status == 8:
  6619. return render_template('signin_new.html')
  6620. else:
  6621. return render_template('sign_in.html')
  6622. return render_template('dry.html', title='乾燥貨櫃', **locals())
  6623. @main.route('/reclaimedwater_tank/<tid>', methods=['GET', 'POST'])
  6624. def reclaimedwater_tank(tid):
  6625. if request.method == 'GET':
  6626. if 'id' in session and 'uname' in session and 'status' in session:
  6627. username = session['uname']
  6628. status = session['status']
  6629. if status == 9:
  6630. return render_template('signin_disable.html')
  6631. elif status == 8:
  6632. return render_template('signin_new.html')
  6633. else:
  6634. return render_template('oops.html')
  6635. # 致動器_中水桶
  6636. tank_actuator = reclaimed_tank_actuator.query.filter_by(tank_num='R'+tid).order_by(text('datetime desc')).first()
  6637. tank_solenoid_water_in = tank_actuator.solenoid_water_in
  6638. tank_solenoid_reclaimed_out = tank_actuator.solenoid_reclaimed_out
  6639. tank_solenoid_water_out = tank_actuator.solenoid_water_out
  6640. tank_pump_reclaimed_out = tank_actuator.pump_reclaimed_out
  6641. return render_template('reclaimedwater_tank.html', title='[操作] 中水桶操作介面', **locals())
  6642. elif request.method == 'POST':
  6643. pass
  6644. @main.route('/colorselect_container_tank/<tid>', methods=['GET', 'POST'])
  6645. def colorselect_container_tank(tid):
  6646. if request.method == 'GET':
  6647. if 'id' in session and 'uname' in session and 'status' in session:
  6648. username = session['uname']
  6649. status = session['status']
  6650. if status == 9:
  6651. return render_template('signin_disable.html')
  6652. elif status == 8:
  6653. return render_template('signin_new.html')
  6654. else:
  6655. return render_template('oops.html')
  6656. # 致動器_色選機
  6657. tank_actuator = colorselect_tank_actuator.query.filter_by(tank_num='S'+tid).order_by(text('datetime desc')).first()
  6658. tank_vacuum = tank_actuator.vacuum
  6659. tank_motor = tank_actuator.motor
  6660. tank_nozzle = tank_actuator.nozzle
  6661. # 致動器_超音波感測器colorselect_tank_UltraSonic
  6662. tank_UltraSonic = colorselect_tank_UltraSonic.query.filter_by(tank_num='S'+tid).order_by(text('datetime desc')).first()
  6663. # 致動器_顏色感測器
  6664. tank_color = colorselect_tank_color.query.filter_by(tank_num='S'+tid).order_by(text('datetime desc')).first()
  6665. return render_template('colorselect_container_tank.html', title='[操作] S' + tid + ' 色選機操作介面', **locals())
  6666. elif request.method == 'POST':
  6667. pass
  6668. @main.route('/peel_container_tank/<tid>', methods=['GET', 'POST'])
  6669. def peel_container_tank(tid):
  6670. if request.method == 'GET':
  6671. if 'id' in session and 'uname' in session and 'status' in session:
  6672. username = session['uname']
  6673. status = session['status']
  6674. if status == 9:
  6675. return render_template('signin_disable.html')
  6676. elif status == 8:
  6677. return render_template('signin_new.html')
  6678. else:
  6679. return render_template('oops.html')
  6680. # 致動器_脫皮機_ALL
  6681. # tank_num='P'+str(tid)
  6682. tank_actuator = peel_tank_actuator.query.filter_by(tank_num='P'+str(tid)).order_by(text('datetime desc')).first()
  6683. tank_vacuum = tank_actuator.vacuum
  6684. tank_motor = tank_actuator.motor
  6685. # 感測器_脫皮機出料儲豆槽_超音波高度
  6686. tank_UltraSonic = peel_output_UltraSonic.query.filter_by(tank_num='P'+str(tid)).order_by(text('datetime desc')).first()
  6687. # 感測器_脫皮機出料儲豆槽_馬達編碼器
  6688. tank_motorEncoder = peel_output_motorEncoder.query.filter_by(tank_num='P'+str(tid)).order_by(text('datetime desc')).first()
  6689. return render_template('peel_container_tank.html', title='[操作] P' + tid + ' 脫皮機操作介面', **locals())
  6690. elif request.method == 'POST':
  6691. pass
  6692. @main.route('/peel_container/<tid>', methods=['GET', 'POST'])
  6693. def peel_container(tid):
  6694. if request.method == 'GET':
  6695. if 'id' in session and 'uname' in session and 'status' in session:
  6696. username = session['uname']
  6697. status = session['status']
  6698. if status == 9:
  6699. return render_template('signin_disable.html')
  6700. elif status == 8:
  6701. return render_template('signin_new.html')
  6702. else:
  6703. return render_template('oops.html')
  6704. # 致動器_入料儲豆槽_真空吸料機
  6705. input_vacuum = peel_input_actuator.query.filter_by(tank_num='P'+str(tid)).order_by(text('datetime desc')).first()
  6706. input_vacuum = input_vacuum.vacuum
  6707. # 致動器_脫皮機_ALL
  6708. tank_actuator = peel_tank_actuator.query.filter_by(tank_num='P'+str(tid)).order_by(text('datetime desc')).first()
  6709. tank_vacuum = tank_actuator.vacuum
  6710. tank_motor = tank_actuator.motor
  6711. # 致動器_出料儲豆槽_真空吸料機
  6712. output_vacuum = peel_output_actuator.query.filter_by(tank_num='P'+str(tid)).order_by(text('datetime desc')).first()
  6713. output_vacuum = output_vacuum.vacuum
  6714. return render_template('peel_container.html', title='脫皮機P' + tid + '總操作介面', **locals())
  6715. elif request.method == 'POST':
  6716. pass
  6717. @main.route('/clean_container/<tid>', methods=['GET', 'POST'])
  6718. def clean_container(tid):
  6719. if request.method == 'GET':
  6720. if 'id' in session and 'uname' in session and 'status' in session:
  6721. username = session['uname']
  6722. status = session['status']
  6723. if status == 9:
  6724. return render_template('signin_disable.html')
  6725. elif status == 8:
  6726. return render_template('signin_new.html')
  6727. else:
  6728. return render_template('oops.html')
  6729. # 致動器_入料儲豆槽_真空吸料機
  6730. input_vacuum = clean_input_actuator.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  6731. input_vacuum = 'ON' if (input_vacuum.vacuum == 1) else 'OFF'
  6732. # 致動器_浮選清洗_ALL
  6733. tank_actuator = clean_tank_actuator.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  6734. tank_vacuum = 'ON' if tank_actuator.vacuum == 1 else 'OFF'
  6735. tank_pump_waterInput = 'ON' if tank_actuator.pump_waterInput == 1 else 'OFF'
  6736. tank_pump_waterL2L3 = 'ON' if tank_actuator.pump_waterL2L3 == 1 else 'OFF'
  6737. tank_pump_waterL4L5 = 'ON' if tank_actuator.pump_waterL4L5 == 1 else 'OFF'
  6738. tank_solenoid_waterL2L3 = 'ON' if tank_actuator.solenoid_waterL2L3 == 1 else 'OFF'
  6739. tank_solenoid_waterL4L5 = 'ON' if tank_actuator.solenoid_waterL4L5 == 1 else 'OFF'
  6740. tank_stepping_motor = tank_actuator.stepping_motor
  6741. # 致動器_出料儲豆槽_真空吸料機
  6742. output_vacuum = clean_output_actuator.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  6743. output_vacuum = 'ON' if (output_vacuum.vacuum == 1) else 'OFF'
  6744. # 感測器_浮選清洗_超音波感測器
  6745. tank_UltraSonic = clean_tank_UltraSonic.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  6746. return render_template('clean_container.html', title='[操作] C' + tid + ' 清洗浮選槽操作介面', **locals())
  6747. elif request.method == 'POST':
  6748. pass
  6749. @main.route('/clean_container_tank/<tid>', methods=['GET', 'POST'])
  6750. def clean_container_tank(tid):
  6751. if request.method == 'GET':
  6752. if 'id' in session and 'uname' in session and 'status' in session:
  6753. username = session['uname']
  6754. status = session['status']
  6755. if status == 9:
  6756. return render_template('signin_disable.html')
  6757. elif status == 8:
  6758. return render_template('signin_new.html')
  6759. else:
  6760. return render_template('oops.html')
  6761. # 致動器_浮選清洗_ALL
  6762. tank_actuator = cleann_tank_actuator.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  6763. try:
  6764. tank_vacuum = tank_actuator.vacuum
  6765. except AttributeError:
  6766. tank_vacuum = 'noValue'
  6767. try:
  6768. tank_threewayvalve_input = tank_actuator.threewayvalve_input
  6769. except AttributeError:
  6770. tank_threewayvalve_input = 'noValue'
  6771. try:
  6772. tank_motor = tank_actuator.motor
  6773. except AttributeError:
  6774. tank_motor = 'noValue'
  6775. try:
  6776. tank_solenoid_reclaimed_in = tank_actuator.solenoid_reclaimed_in
  6777. except AttributeError:
  6778. tank_solenoid_reclaimed_in = 'noValue'
  6779. try:
  6780. tank_solenoid_water_in = tank_actuator.solenoid_water_in
  6781. except AttributeError:
  6782. tank_solenoid_water_in = 'noValue'
  6783. try:
  6784. tank_pump_water_in = tank_actuator.pump_water_in
  6785. except AttributeError:
  6786. tank_pump_water_in = 'noValue'
  6787. try:
  6788. tank_solenoid_water_out = tank_actuator.solenoid_water_out
  6789. except AttributeError:
  6790. tank_solenoid_water_out = 'noValue'
  6791. try:
  6792. tank_solenoid_reclaimed_out = tank_actuator.solenoid_reclaimed_out
  6793. except AttributeError:
  6794. tank_solenoid_reclaimed_out = 'noValue'
  6795. try:
  6796. tank_solenoid_disinfect = tank_actuator.solenoid_disinfect
  6797. except AttributeError:
  6798. tank_solenoid_disinfect = 'noValue'
  6799. try:
  6800. tank_pump_disinfect = tank_actuator.pump_disinfect
  6801. except AttributeError:
  6802. tank_pump_disinfect = 'noValue'
  6803. try:
  6804. tank_diskvalve = tank_actuator.diskvalve
  6805. except AttributeError:
  6806. tank_diskvalve = 'noValue'
  6807. # tank_pump_waterInput = 'ON' if tank_actuator.pump_waterInput == 1 else 'OFF'
  6808. # tank_pump_waterL2L3 = 'ON' if tank_actuator.pump_waterL2L3 == 1 else 'OFF'
  6809. # tank_pump_waterL4L5 = 'ON' if tank_actuator.pump_waterL4L5 == 1 else 'OFF'
  6810. # tank_solenoid_waterL2L3 = 'ON' if tank_actuator.solenoid_waterL2L3 == 1 else 'OFF'
  6811. # tank_solenoid_waterL4L5 = 'ON' if tank_actuator.solenoid_waterL4L5 == 1 else 'OFF'
  6812. # tank_stepping_motor = tank_actuator.stepping_motor
  6813. # 感測器_浮選清洗_超音波感測器
  6814. tank_UltraSonic = clean_tank_UltraSonic.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  6815. try:
  6816. UltraSonic = tank_UltraSonic.UltraSonic
  6817. except AttributeError:
  6818. UltraSonic = 'noValue'
  6819. tank_Encoder = clean_tank_Encoder.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  6820. try:
  6821. Encoder = tank_Encoder.Encoder
  6822. except AttributeError:
  6823. Encoder = 'noValue'
  6824. tank_Turbidity = clean_tank_Turbidity.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  6825. try:
  6826. tankTurbidity = tank_Turbidity.tankTurbidity
  6827. except AttributeError:
  6828. tankTurbidity = 'noValue'
  6829. filter_Turbidity = clean_filter_Turbidity.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
  6830. try:
  6831. filterTurbidity = filter_Turbidity.filterTurbidity
  6832. except AttributeError:
  6833. filterTurbidity = 'noValue'
  6834. return render_template('clean_container_tank.html', title='[操作] C' + tid + ' 清洗浮選槽操作介面', **locals())
  6835. elif request.method == 'POST':
  6836. pass
  6837. @main.route('/ferment_container/<tid>', methods=['GET', 'POST'])
  6838. def ferment_container(tid):
  6839. if request.method == 'GET':
  6840. if 'id' in session and 'uname' in session and 'status' in session:
  6841. username = session['uname']
  6842. status = session['status']
  6843. if status == 9:
  6844. return render_template('signin_disable.html')
  6845. elif status == 8:
  6846. return render_template('signin_new.html')
  6847. else:
  6848. return render_template('oops.html')
  6849. # 致動器_發酵槽_ALL
  6850. tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6851. tank_vacuum = 'ON' if tank_actuator.vacuum == 1 else 'OFF'
  6852. tank_threewayvalve_input = 'ON' if tank_actuator.threewayvalve_input == 1 else 'OFF'
  6853. tank_diskvalve = 'ON' if tank_actuator.diskvalve == 1 else 'OFF'
  6854. tank_solenoid_water_total = 'ON' if tank_actuator.solenoid_tank_water_total == 1 else 'OFF'
  6855. tank_solenoid_disinfect = 'ON' if tank_actuator.solenoid_tank_disinfect == 1 else 'OFF'
  6856. outer_solenoid_water = 'ON' if tank_actuator.solenoid_outer_water == 1 else 'OFF'
  6857. tank_solenoid_water_in = 'ON' if tank_actuator.solenoid_tank_water_in == 1 else 'OFF'
  6858. tank_pump_sensor = 'ON' if tank_actuator.pump_sensor == 1 else 'OFF'
  6859. tank_threewayvalve_bean = 'ON' if tank_actuator.threewayvalve_bean == 1 else 'OFF'
  6860. outer_threewayvalve_float = 'ON' if tank_actuator.threewayvalve_outer_float == 1 else 'OFF'
  6861. tank_motor = tank_actuator.motor
  6862. tank_heater1 = 'ON' if tank_actuator.heater1 == 1 else 'OFF'
  6863. tank_heater2 = 'ON' if tank_actuator.heater2 == 1 else 'OFF'
  6864. tank_temp_enable = 'ON' if tank_actuator.temp_enable == 1 else 'OFF'
  6865. tank_temp = tank_actuator.temp
  6866. # 感測器_發酵桶_SHT11
  6867. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6868. # 感測器_發酵桶_二氧化碳
  6869. tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6870. # 感測器_發酵桶_酸鹼值
  6871. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6872. tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6873. tank_DO = ferment_tank_DO.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6874. tank_EC = ferment_tank_EC.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6875. # 感測器_發酵桶_氣壓
  6876. tank_PA = ferment_tank_PA.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6877. # 感測器_發酵桶_超音波感測器
  6878. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6879. # 感測器_發酵桶_水位計
  6880. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6881. num_tank_WaterLevel = float(tank_WaterLevel.WaterLevel)
  6882. print('tank_WaterLevel', tank_WaterLevel.WaterLevel)
  6883. if tank_WaterLevel.WaterLevel == '1':
  6884. WaterLevel = '滿'
  6885. elif tank_WaterLevel.WaterLevel == '0':
  6886. WaterLevel = '未達滿水高度'
  6887. else:
  6888. WaterLevel = 'ERROR'
  6889. # 感測器_發酵桶_咖啡生豆高度
  6890. tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6891. LiDAR = tank_LiDAR.LiDAR
  6892. # 感測器_發酵桶_水位高度
  6893. tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6894. PressureWaterLevel = '{:.2f}'.format((float(tank_PressureWaterLevel.PressureWaterLevel) -15 -90.278)/9.4214)
  6895. if tid in ['1', '2', '3', '4', '5', '6']:
  6896. # print("1")
  6897. # 感測器_入料儲豆槽_超音波感測器
  6898. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI1').order_by(text('datetime desc')).first()
  6899. # 致動器_入料儲豆槽_真空吸引機
  6900. input_vacuum = ferment_input_actuator.query.filter_by(tank_num='FI1').order_by(text('datetime desc')).first()
  6901. input_vacuum = input_vacuum.vacuum
  6902. # 感測器_出料儲豆槽_超音波感測器
  6903. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO1').order_by(text('datetime desc')).first()
  6904. # 致動器_出料儲豆槽_真空吸引機
  6905. output_vacuum = ferment_output_actuator.query.filter_by(tank_num='FO1').order_by(text('datetime desc')).first()
  6906. output_vacuum = output_vacuum.vacuum
  6907. elif tid in ['7', '8', '9', '10', '11', '12']:
  6908. # print("2")
  6909. # 感測器_入料儲豆槽_超音波感測器
  6910. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI2').order_by(text('datetime desc')).first()
  6911. # 致動器_入料儲豆槽_真空吸引機
  6912. input_vacuum = ferment_input_actuator.query.filter_by(tank_num='FI2').order_by(text('datetime desc')).first()
  6913. input_vacuum = input_vacuum.vacuum
  6914. print("input_vacuum", input_vacuum)
  6915. # 感測器_出料儲豆槽_超音波感測器
  6916. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO2').order_by(text('datetime desc')).first()
  6917. # 致動器_出料儲豆槽_真空吸引機
  6918. output_vacuum = ferment_output_actuator.query.filter_by(tank_num='FO2').order_by(text('datetime desc')).first()
  6919. output_vacuum = output_vacuum.vacuum
  6920. print("output_vacuum", output_vacuum)
  6921. return render_template('ferment_container.html', title='發酵槽F' + tid + '總操作介面' , **locals())
  6922. elif request.method == 'POST':
  6923. pass
  6924. @main.route('/ferment_container_tank/<tid>', methods=['GET', 'POST'])
  6925. def ferment_container_tank(tid):
  6926. if request.method == 'GET':
  6927. if 'id' in session and 'uname' in session and 'status' in session:
  6928. username = session['uname']
  6929. status = session['status']
  6930. if status == 9:
  6931. return render_template('signin_disable.html')
  6932. elif status == 8:
  6933. return render_template('signin_new.html')
  6934. else:
  6935. return render_template('oops.html')
  6936. # 致動器_發酵槽_ALL
  6937. tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6938. tank_vacuum = 'ON' if tank_actuator.vacuum == 1 else 'OFF'
  6939. tank_threewayvalve_input = 'ON' if tank_actuator.threewayvalve_input == 1 else 'OFF'
  6940. tank_diskvalve = 'ON' if tank_actuator.diskvalve == 1 else 'OFF'
  6941. solenoid_tank_pump = 'ON' if tank_actuator.solenoid_tank_pump == 1 else 'OFF'
  6942. tank_solenoid_disinfect = 'ON' if tank_actuator.solenoid_tank_disinfect == 1 else 'OFF'
  6943. outer_solenoid_water = 'ON' if tank_actuator.solenoid_outer_water == 1 else 'OFF'
  6944. tank_solenoid_water_in = 'ON' if tank_actuator.solenoid_tank_water_in == 1 else 'OFF'
  6945. tank_solenoid_water_out = 'ON' if tank_actuator.solenoid_tank_water_out == 1 else 'OFF'
  6946. tank_pump_sensor = 'ON' if tank_actuator.pump_sensor == 1 else 'OFF'
  6947. outer_threewayvalve_float = 'ON' if tank_actuator.threewayvalve_outer_float == 1 else 'OFF'
  6948. tank_motor = tank_actuator.motor
  6949. tank_heater1 = 'ON' if tank_actuator.heater1 == 1 else 'OFF'
  6950. tank_heater2 = 'ON' if tank_actuator.heater2 == 1 else 'OFF'
  6951. tank_temp_enable = 'ON' if tank_actuator.temp_enable == 1 else 'OFF'
  6952. tank_temp = tank_actuator.temp
  6953. # 感測器_發酵桶_SHT11
  6954. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6955. # 感測器_發酵桶_二氧化碳
  6956. tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6957. # 感測器_發酵桶_酸鹼值
  6958. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6959. tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6960. tank_DO = ferment_tank_DO.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6961. tank_EC = ferment_tank_EC.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6962. # 感測器_發酵桶_氣壓
  6963. tank_PA = ferment_tank_PA.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6964. # 感測器_發酵桶_超音波感測器
  6965. tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6966. # 感測器_發酵桶_水位計
  6967. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6968. num_tank_WaterLevel = float(tank_WaterLevel.WaterLevel)
  6969. if tank_WaterLevel.WaterLevel == '1':
  6970. WaterLevel = '滿'
  6971. elif tank_WaterLevel.WaterLevel == '0':
  6972. WaterLevel = '未達滿水高度'
  6973. else:
  6974. WaterLevel = 'ERROR'
  6975. # 感測器_發酵桶_咖啡生豆高度
  6976. #tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6977. #LiDAR = tank_LiDAR.LiDAR
  6978. # 感測器_發酵桶_水位高度
  6979. #tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6980. #PressureWaterLevel = '{:.2f}'.format((float(tank_PressureWaterLevel.PressureWaterLevel) -15 -90.278)/9.4214)
  6981. # 感測器_發酵桶_馬達編碼器
  6982. tank_motorEncoder = ferment_tank_motorEncoder.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  6983. return render_template('ferment_container_tank.html', title='[操作] F' + tid + ' 發酵槽操作介面', **locals())
  6984. elif request.method == 'POST':
  6985. pass
  6986. @main.route('/ferment_container_input/<tid>', methods=['GET', 'POST'])
  6987. def ferment_container_input(tid):
  6988. if request.method == 'GET':
  6989. if 'id' in session and 'uname' in session and 'status' in session:
  6990. username = session['uname']
  6991. status = session['status']
  6992. if status == 9:
  6993. return render_template('signin_disable.html')
  6994. elif status == 8:
  6995. return render_template('signin_new.html')
  6996. else:
  6997. return render_template('oops.html')
  6998. # 感測器_入料儲豆槽_超音波感測器
  6999. input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI' + tid).order_by(text('datetime desc')).first()
  7000. # 致動器_入料儲豆槽_真空吸引機
  7001. input_vacuum = ferment_input_actuator.query.filter_by(tank_num='FI' + tid).order_by(text('datetime desc')).first()
  7002. input_vacuum = input_vacuum.vacuum
  7003. return render_template('ferment_container_input.html', title='[操作] FI' + tid + ' 發酵入料儲豆槽操作介面', **locals())
  7004. elif request.method == 'POST':
  7005. pass
  7006. @main.route('/ferment_container_output/<tid>', methods=['GET', 'POST'])
  7007. def ferment_container_output(tid):
  7008. if request.method == 'GET':
  7009. if 'id' in session and 'uname' in session and 'status' in session:
  7010. username = session['uname']
  7011. status = session['status']
  7012. if status == 9:
  7013. return render_template('signin_disable.html')
  7014. elif status == 8:
  7015. return render_template('signin_new.html')
  7016. else:
  7017. return render_template('oops.html')
  7018. # 感測器_出料儲豆槽_超音波感測器
  7019. output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO' + tid).order_by(text('datetime desc')).first()
  7020. # 致動器_出料儲豆槽_真空吸引機
  7021. output_vacuum = ferment_output_actuator.query.filter_by(tank_num='FO' + tid).order_by(text('datetime desc')).first()
  7022. output_vacuum = output_vacuum.vacuum
  7023. tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7024. LiDAR = tank_LiDAR.LiDAR
  7025. return render_template('ferment_container_output.html', title='[操作] FO' + tid + ' 發酵出料儲豆槽操作介面', **locals())
  7026. elif request.method == 'POST':
  7027. pass
  7028. @main.route('/dry_container_schedule', methods=['GET', 'POST'])
  7029. def dry_container_schedule():
  7030. if request.method == 'GET':
  7031. if 'id' in session and 'uname' in session:
  7032. username = session['uname']
  7033. # 感測器_入料儲豆槽_超音波感測器
  7034. input_UltraSonic = dry_input_sensor.query.order_by(text('datetime desc')).first()
  7035. # 感測器_乾燥桶_超音波感測器
  7036. tank_UltraSonic = dry_tank_UltraSonic.query.order_by(text('datetime desc')).first()
  7037. return render_template('dry_container_schedule.html', title='dry_container_schedule', **locals())
  7038. elif request.method == 'POST':
  7039. pass
  7040. @main.route('/dry_block', methods=['GET', 'POST'])
  7041. def dry_block():
  7042. if request.method == 'GET':
  7043. if 'id' in session and 'uname' in session:
  7044. username = session['uname']
  7045. DBW = dry_block_waiting.query.order_by(text('datetime desc')).first()
  7046. pin_data = coffee1_0_pin.query.order_by(text('datetime desc')).first()
  7047. return render_template('dry_block.html', title='積木設定_乾燥空桶等待', **locals())
  7048. elif request.method == 'POST':
  7049. pass
  7050. @main.route('/dry_block_empty', methods=['GET', 'POST'])
  7051. def dry_block_empty():
  7052. if request.method == 'GET':
  7053. if 'id' in session and 'uname' in session:
  7054. username = session['uname']
  7055. return render_template('dry_block_empty.html', title='積木設定空白_乾燥空桶等待', **locals())
  7056. elif request.method == 'POST':
  7057. pass
  7058. # 0323 積木程式 格式調整
  7059. @main.route('/dry_block_format', methods=['GET', 'POST'])
  7060. def dry_block_format():
  7061. if request.method == 'GET':
  7062. info = request.args.to_dict()
  7063. # print("info: ", info)
  7064. # 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'}
  7065. tank_num_data = info['tank_num'] # 桶槽編號:D1
  7066. mainLength_data = int(info['mainLength'])+1 # 總條件數量
  7067. addLength_data = int(info['addLength'])+1 # 子條件數量
  7068. comLength_data = int(info['comLength'])+1 # 子物件數量
  7069. cond_main_all_list = []
  7070. for z in range(1,mainLength_data):
  7071. # 初始
  7072. cond_main_all_dict = {}
  7073. cond_add_list = [] # 附加條件 List
  7074. cond_com_list = [] # 物件動作 List
  7075. # cond_main_dict_all = {}
  7076. # cond_add_dict_all = {}
  7077. # cond_com_dict_all = {}
  7078. # print(z)
  7079. # 總條件
  7080. try:
  7081. cond_main_all_dict['cond_main'] = info['cond_main' + str(z)]
  7082. except(KeyError):
  7083. pass
  7084. # print("cond_main_dict: ", cond_main_dict)
  7085. # 附加條件
  7086. for x in range(1,addLength_data):
  7087. try:
  7088. cond_add_list.append(info['cond_add' + str(z) + '_' + str(x)])
  7089. except(KeyError):
  7090. pass
  7091. # print("cond_add_list: ", cond_add_list)
  7092. cond_main_all_dict['cond_add'] = cond_add_list
  7093. # print("cond_main_dict: ", cond_main_dict)
  7094. # 物件動作
  7095. for y in range(1,comLength_data):
  7096. try:
  7097. cond_com_list.append(info['cond_com' + str(z) + '_' + str(y)])
  7098. except(KeyError):
  7099. pass
  7100. # print("cond_com_list: ", cond_com_list)
  7101. cond_main_all_dict['cond_com'] = cond_com_list
  7102. # print("cond_main_dict: ", cond_main_dict)
  7103. if cond_com_list != []:
  7104. cond_main_all_list.append(cond_main_all_dict)
  7105. # cond_main_all_list.append(cond_add_dict_all)
  7106. # cond_main_all_list.append(cond_com_dict_all)
  7107. print("cond_main_all_list: ", cond_main_all_list)
  7108. # 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']}]
  7109. dry_block_sehedule = {'command':'Dry_OTA', 'tank_num':tank_num_data, 'cond':cond_main_all_list}
  7110. print('dry_block_sehedule:', dry_block_sehedule)
  7111. # 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']}]}
  7112. topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
  7113. print('=========================================================')
  7114. print("json.dumps(dry_block_sehedule):", json.dumps(dry_block_sehedule))
  7115. # 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"]}]}
  7116. print('=========================================================')
  7117. # mqtt.publish(topic, json.dumps(dry_block_sehedule))
  7118. return jsonify({"response":dry_block_sehedule})
  7119. # 積木程式
  7120. @main.route('/dry_block_set', methods=['GET', 'POST'])
  7121. def dry_block_set():
  7122. if request.method == 'GET':
  7123. if 'id' in session and 'uname' in session:
  7124. username = session['uname']
  7125. info = request.args.to_dict()
  7126. # print("info: ", info, type(info)) # dict
  7127. # 傳回 總條件物件動作 數量
  7128. condition = int(info['condition'])
  7129. # 傳回 子條件 數量
  7130. cond_add_child = int(info['cond_add_child'])
  7131. # 傳回 子物件動作 數量
  7132. act_add_child = int(info['act_add_child'])
  7133. # 傳回 指令
  7134. set_Schedule = eval(info['set_Schedule']) # 字串轉成字典
  7135. # print("set_Schedule: ", set_Schedule, type(set_Schedule)) # dict
  7136. cond_data = ''
  7137. # mqtt_data("D1", "block_command_test", "condition=" + str(condition)) # 0321 TEST
  7138. # ----- 0321 註解測試 -----
  7139. # # 拆解條件 / 物件 / 動作
  7140. # # # 條件物件取值
  7141. # for z in range(1, condition+1, 1):
  7142. # # 放要執行的判斷式
  7143. # # # if / while
  7144. # cond_data = ''
  7145. # try:
  7146. # z_num = 'cond_z' + str(z) + '_1'
  7147. # # print("cond_z_value[z_num]: ", set_Schedule[z_num]) # if
  7148. # cond_data += set_Schedule[z_num]
  7149. # except KeyError:
  7150. # pass
  7151. # # # 桶槽號取值
  7152. # try:
  7153. # tank_num = 'cond_tank' + str(z) + '_1'
  7154. # except KeyError:
  7155. # pass
  7156. # # # 子條件取值
  7157. # for x in range(1, cond_add_child+1, 1):
  7158. # # d
  7159. # try:
  7160. # x_num_d = 'cond_d' + str(z) + '_' + str(x)
  7161. # # print("cond_d_value[x_num_d]: ", set_Schedule[x_num_d])
  7162. # cond_data += ' ' + set_Schedule[x_num_d]
  7163. # except KeyError:
  7164. # pass
  7165. # # a
  7166. # x_num_a = 'cond_a' + str(z) + '_' + str(x)
  7167. # try:
  7168. # x_num_a = 'cond_a' + str(z) + '_' + str(x)
  7169. # # print("cond_a_value[x_num_a]: ", set_Schedule[x_num_a])
  7170. # cond_data += ' ' + set_Schedule[x_num_a]
  7171. # if set_Schedule[x_num_a] == 'input_vacuum_status':
  7172. # input_vacuum_status = dry_input_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().vacuum
  7173. # print("input_vacuum_status: ", input_vacuum_status)
  7174. # elif set_Schedule[x_num_a] == 'tank_vacuum_status':
  7175. # tank_vacuum_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().vacuum
  7176. # print("tank_vacuum_status: ", tank_vacuum_status)
  7177. # elif set_Schedule[x_num_a] == 'tank_threewayvalve_input_status':
  7178. # tank_threewayvalve_input_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().threewayvalve_input
  7179. # print("tank_threewayvalve_input_status: ", tank_threewayvalve_input_status)
  7180. # elif set_Schedule[x_num_a] == 'tank_motor_status':
  7181. # tank_motor_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().motor
  7182. # print("tank_motor_status: ", tank_motor_status)
  7183. # elif set_Schedule[x_num_a] == 'tank_blower_status':
  7184. # tank_blower_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().blower
  7185. # print("tank_blower_status: ", tank_blower_status)
  7186. # elif set_Schedule[x_num_a] == 'tank_heater1_status':
  7187. # tank_heater1_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().heater1
  7188. # print("tank_heater1_status: ", tank_heater1_status)
  7189. # elif set_Schedule[x_num_a] == 'tank_heater2_status':
  7190. # tank_heater2_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().heater2
  7191. # print("tank_heater2_status: ", tank_heater2_status)
  7192. # elif set_Schedule[x_num_a] == 'tank_diskvalve_status':
  7193. # tank_diskvalve_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().diskvalve
  7194. # print("tank_diskvalve_status: ", tank_diskvalve_status)
  7195. # elif set_Schedule[x_num_a] == 'tank_solenoid_disinfect_status':
  7196. # tank_solenoid_disinfect_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().solenoid_disinfect
  7197. # print("tank_solenoid_disinfect_status: ", tank_solenoid_disinfect_status)
  7198. # elif set_Schedule[x_num_a] == 'tank_solenoid_water_out_status':
  7199. # 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
  7200. # print("tank_solenoid_water_out_status: ", tank_solenoid_water_out_status)
  7201. # elif set_Schedule[x_num_a] == 'outer_solenoid_water_status':
  7202. # 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
  7203. # print("outer_solenoid_water_status: ", outer_solenoid_water_status)
  7204. # elif set_Schedule[x_num_a] == 'tank_temp_enable':
  7205. # tank_temp_enable = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().temp1_enable
  7206. # print("tank_temp_enable: ", tank_temp_enable)
  7207. # elif set_Schedule[x_num_a] == 'tank_temp':
  7208. # tank_temp = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().temp1
  7209. # print("tank_temp: ", tank_temp)
  7210. # elif set_Schedule[x_num_a] == 'output_vacuum':
  7211. # output_vacuum = dry_output_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().vacuum
  7212. # print("output_vacuum: ", output_vacuum)
  7213. # elif set_Schedule[x_num_a] == 'input_UltraSonic':
  7214. # input_UltraSonic = float(dry_input_sensor.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().UltraSonic)
  7215. # print("input_UltraSonic: ", input_UltraSonic)
  7216. # elif set_Schedule[x_num_a] == 'tank_UltraSonic':
  7217. # tank_UltraSonic = float(dry_tank_UltraSonic.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().UltraSonic)
  7218. # print("tank_UltraSonic: ", tank_UltraSonic)
  7219. # elif set_Schedule[x_num_a] == 'tank_SHT11_Temp':
  7220. # tank_SHT11_Temp = float(dry_tank_SHT11.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().SHT11_Temp)
  7221. # print("tank_SHT11_Temp: ", tank_SHT11_Temp)
  7222. # elif set_Schedule[x_num_a] == 'tank_SHT11_Humidity':
  7223. # tank_SHT11_Humidity = float(dry_tank_SHT11.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().SHT11_Humidity)
  7224. # print("tank_SHT11_Humidity: ", tank_SHT11_Humidity)
  7225. # elif set_Schedule[x_num_a] == 'tank_soil_Temp':
  7226. # tank_soil_Temp = float(dry_tank_Soil.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().soil_Temp)
  7227. # print("tank_soil_Temp: ", tank_soil_Temp)
  7228. # elif set_Schedule[x_num_a] == 'tank_soil_Humidity':
  7229. # tank_soil_Humidity = float(dry_tank_Soil.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().soil_Humidity)
  7230. # print("tank_soil_Humidity: ", tank_soil_Temp)
  7231. # elif set_Schedule[x_num_a] == 'tank_soil_EC':
  7232. # tank_soil_EC = float(dry_tank_Soil.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().soil_EC)
  7233. # print("tank_soil_EC: ", tank_soil_EC)
  7234. # elif set_Schedule[x_num_a] == 'tank_PA':
  7235. # tank_PA = float(dry_tank_PA.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().PA)
  7236. # print("tank_PA: ", tank_PA)
  7237. # elif set_Schedule[x_num_a] == 'output_UltraSonic':
  7238. # output_UltraSonic = float(dry_output_sensor.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().UltraSonic)
  7239. # print("output_UltraSonic: ", output_UltraSonic)
  7240. # except KeyError:
  7241. # pass
  7242. # # b
  7243. # try:
  7244. # x_num_b = 'cond_b' + str(z) + '_' + str(x)
  7245. # # print("cond_b_value[x_num_b]: ", set_Schedule[x_num_b])
  7246. # cond_b_dict = {'morethan': ' >= ', 'lessthan': ' <= ', 'equal':' == '}
  7247. # cond_data += cond_b_dict[set_Schedule[x_num_b]] # cond_b_dict['equal'] 會輸出 ' == '
  7248. # except KeyError:
  7249. # pass
  7250. # # c
  7251. # try:
  7252. # x_num_c = 'cond_c' + str(z) + '_' + str(x)
  7253. # # print("cond_c_value[x_num_c]: ", set_Schedule[x_num_c])
  7254. # if set_Schedule[x_num_c] == 'on':
  7255. # cond_data += '1'
  7256. # elif set_Schedule[x_num_c] == 'off':
  7257. # cond_data += '0'
  7258. # else:
  7259. # cond_data += set_Schedule[x_num_c]
  7260. # except KeyError:
  7261. # pass
  7262. # if x == cond_add_child:
  7263. # cond_data += ': '
  7264. # # 子物件動作取值
  7265. # for y in range(1, act_add_child+1, 1):
  7266. # # do_obj
  7267. # try:
  7268. # y_num_obj = "do_obj" + str(z) + "_" + str(y)
  7269. # # print("y_num_obj[y_num_obj]: ", set_Schedule[y_num_obj])
  7270. # # cond_data += 'print(\'' + 'mqtt_data("D1", "' + str(set_Schedule[y_num_obj]) + '", '
  7271. # if set_Schedule[y_num_obj] == 'time.sleep':
  7272. # cond_data += '''
  7273. # time.sleep('''
  7274. # else:
  7275. # cond_data += '''
  7276. # mqtt_data('''
  7277. # cond_data += '"' + set_Schedule[tank_num] + '", "' + str(set_Schedule[y_num_obj]) + '", '
  7278. # except KeyError:
  7279. # pass
  7280. # try:
  7281. # y_num_act = "do_act" + str(z) + "_" + str(y)
  7282. # # print("y_num_act[y_num_act]: ", set_Schedule[y_num_act])
  7283. # if set_Schedule[y_num_obj] == 'time.sleep':
  7284. # cond_data += set_Schedule[y_num_act] + ')'
  7285. # else:
  7286. # cond_data += '"' + str(set_Schedule[y_num_act]) + '") '
  7287. # cond_data += '''
  7288. # time.sleep(0.5)'''
  7289. # except KeyError:
  7290. # pass
  7291. # # TODO
  7292. # # set_Schedule[z_num] → if / while
  7293. # # set_Schedule[x_num_a] → actuator / sensor
  7294. # # set_Schedule[x_num_b] → morethan / equal / lessthan
  7295. # # set_Schedule[x_num_c] → 數值 / on / off
  7296. # # set_Schedule[x_num_d] → or / and
  7297. # # set_Schedule[y_num_obj] → actuator
  7298. # # set_Schedule[y_num_act] → on / off / 對應數值
  7299. # print("cond_data: ", cond_data)
  7300. # if cond_data != ': ':
  7301. # # exec(cond_data)
  7302. # # 01/17 新增, 格式待修改
  7303. # mqtt_data("D1", "command_test", "exec(" + cond_data + ")")
  7304. return jsonify({"response":"OK"
  7305. })
  7306. elif request.method == 'POST':
  7307. pass
  7308. # 乾燥貨櫃_各致動器控制
  7309. @main.route('/ctrl_DI_<actuator>/<tid>', methods=['GET', 'POST'])
  7310. def ctrl_DI(actuator, tid):
  7311. if request.method == 'GET':
  7312. if actuator == 'Vacuum':
  7313. if 'id' in session and 'uname' in session and 'status' in session:
  7314. username = session['uname']
  7315. status = session['status']
  7316. if status == 9:
  7317. return render_template('signin_disable.html')
  7318. elif status == 8:
  7319. return render_template('signin_new.html')
  7320. else:
  7321. return render_template('oops.html')
  7322. input_brake = dry_input_brake.query.filter_by(tank_num='DI'+str(tid)).order_by(text('datetime desc')).first()
  7323. input_vacuum = input_brake.vacuum
  7324. tank_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI'+str(tid)).order_by(text('datetime desc')).first()
  7325. UltraSonic = tank_UltraSonic.UltraSonic
  7326. return render_template('ctrl_DI_Vacuum.html', title='[操作]DI' + tid + '乾燥槽入料_真空吸料機', **locals())
  7327. elif request.method == 'POST':
  7328. pass
  7329. @main.route('/ctrl_DO_<actuator>/<tid>', methods=['GET', 'POST'])
  7330. def ctrl_DO(actuator, 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. if actuator == 'Vacuum':
  7342. tank_brake = dry_output_brake.query.filter_by(tank_num='DO'+str(tid)).order_by(text('datetime desc')).first()
  7343. tank_vacuum = tank_brake.vacuum
  7344. tank_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO'+str(tid)).order_by(text('datetime desc')).first()
  7345. UltraSonic = tank_UltraSonic.UltraSonic
  7346. return render_template('ctrl_DO_Vacuum.html', title='[操作]DI' + tid + '乾燥槽出料_真空吸料機', **locals())
  7347. elif request.method == 'POST':
  7348. pass
  7349. @main.route('/ctrl_D_<actuator>/<tid>', methods=['GET', 'POST'])
  7350. def ctrl_D(actuator, tid):
  7351. if request.method == 'GET':
  7352. if 'id' in session and 'uname' in session and 'status' in session:
  7353. username = session['uname']
  7354. status = session['status']
  7355. if status == 9:
  7356. return render_template('signin_disable.html')
  7357. elif status == 8:
  7358. return render_template('signin_new.html')
  7359. else:
  7360. return render_template('oops.html')
  7361. tank_brake = dry_tank_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  7362. if actuator == 'Vacuum':
  7363. tank_vacuum = tank_brake.vacuum
  7364. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  7365. UltraSonic = tank_UltraSonic.UltraSonic
  7366. return render_template('ctrl_D_Vacuum.html', title='[操作]D' + tid + '乾燥槽_真空吸料機', **locals())
  7367. elif actuator == 'ThreeWayValveInput':
  7368. tank_threewayvalve_input = tank_brake.threewayvalve_input
  7369. return render_template('ctrl_D_ThreeWayValveInput.html', title='[操作]D' + tid + '乾燥槽_入料三通閥', **locals())
  7370. elif actuator == 'ThreeWayValveBean':
  7371. tank_threewayvalve_bean = tank_brake.threewayvalve_bean
  7372. return render_template('ctrl_D_ThreeWayValveBean.html', title='[操作]D' + tid + '乾燥槽_測豆三通閥', **locals())
  7373. elif actuator == 'DiskValve':
  7374. tank_diskvalve = tank_brake.diskvalve
  7375. return render_template('ctrl_D_DiskValve.html', title='[操作]D' + tid + '乾燥槽_蝴蝶閥', **locals())
  7376. elif actuator == 'SolenoidDisinfect':
  7377. tank_solenoid_disinfect = tank_brake.solenoid_disinfect
  7378. return render_template('ctrl_D_SolenoidDisinfect.html', title='[操作]D' + tid + '乾燥槽_消毒電磁閥', **locals())
  7379. elif actuator == 'SolenoidWater':
  7380. tank_solenoid_water = tank_brake.solenoid_water
  7381. return render_template('ctrl_D_SolenoidWater.html', title='[操作]D' + tid + '乾燥槽_排水電磁閥', **locals())
  7382. elif actuator == 'Motor':
  7383. tank_motor = tank_brake.motor
  7384. return render_template('ctrl_D_Motor.html', title='[操作]D' + tid + '乾燥槽_馬達', **locals())
  7385. elif actuator == 'Blower':
  7386. tank_blower = tank_brake.blower
  7387. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  7388. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  7389. return render_template('ctrl_D_Blower.html', title='[操作]D' + tid + '乾燥槽_鼓風機', **locals())
  7390. elif actuator == 'Heater1':
  7391. tank_heater1 = tank_brake.heater1
  7392. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  7393. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  7394. return render_template('ctrl_D_Heater1.html', title='[操作]D' + tid + '乾燥槽_加熱器 1', **locals())
  7395. elif actuator == 'Heater2':
  7396. tank_heater2 = tank_brake.heater2
  7397. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  7398. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  7399. return render_template('ctrl_D_Heater2.html', title='[操作]D' + tid + '乾燥槽_加熱器 2', **locals())
  7400. elif actuator == 'TempEnable':
  7401. tank_temp1_enable = tank_brake.temp1_enable
  7402. return render_template('ctrl_D_TempEnable.html', title='[操作]D' + tid + '乾燥槽_溫控開關', **locals())
  7403. elif actuator == 'Temp':
  7404. tank_temp1_enable = tank_brake.temp1_enable
  7405. tank_temp1 = tank_brake.temp1
  7406. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  7407. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  7408. return render_template('ctrl_D_Temp.html', title='[操作]D' + tid + '乾燥槽_設定溫度', **locals())
  7409. elif request.method == 'POST':
  7410. pass
  7411. # 發酵貨櫃_各致動器控制
  7412. @main.route('/ctrl_FI_<actuator>/<tid>', methods=['GET', 'POST'])
  7413. def ctrl_FI(actuator, tid):
  7414. if request.method == 'GET':
  7415. if 'id' in session and 'uname' in session and 'status' in session:
  7416. username = session['uname']
  7417. status = session['status']
  7418. if status == 9:
  7419. return render_template('signin_disable.html')
  7420. elif status == 8:
  7421. return render_template('signin_new.html')
  7422. else:
  7423. return render_template('oops.html')
  7424. if actuator == 'Vacuum':
  7425. if 'id' in session and 'uname' in session and 'status' in session:
  7426. username = session['uname']
  7427. status = session['status']
  7428. if status == 9:
  7429. return render_template('signin_disable.html')
  7430. elif status == 8:
  7431. return render_template('signin_new.html')
  7432. else:
  7433. return render_template('oops.html')
  7434. tank_actuator = ferment_input_actuator.query.filter_by(tank_num='FI'+str(tid)).order_by(text('datetime desc')).first()
  7435. tank_vacuum = tank_actuator.vacuum
  7436. tank_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI'+str(tid)).order_by(text('datetime desc')).first()
  7437. UltraSonic = tank_UltraSonic.UltraSonic
  7438. return render_template('ctrl_FI_Vacuum.html', title='[操作]FI' + tid + '發酵入料儲豆槽_真空吸料機', **locals())
  7439. elif request.method == 'POST':
  7440. pass
  7441. @main.route('/ctrl_FO_<actuator>/<tid>', methods=['GET', 'POST'])
  7442. def ctrl_FO(actuator, tid):
  7443. if request.method == 'GET':
  7444. if 'id' in session and 'uname' in session and 'status' in session:
  7445. username = session['uname']
  7446. status = session['status']
  7447. if status == 9:
  7448. return render_template('signin_disable.html')
  7449. elif status == 8:
  7450. return render_template('signin_new.html')
  7451. else:
  7452. return render_template('oops.html')
  7453. if actuator == 'Vacuum':
  7454. tank_actuator = ferment_output_actuator.query.filter_by(tank_num='FO'+str(tid)).order_by(text('datetime desc')).first()
  7455. tank_vacuum = tank_actuator.vacuum
  7456. tank_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO'+str(tid)).order_by(text('datetime desc')).first()
  7457. UltraSonic = tank_UltraSonic.UltraSonic
  7458. return render_template('ctrl_FO_Vacuum.html', title='[操作]FO' + tid + '發酵出料儲豆槽_真空吸料機', **locals())
  7459. elif request.method == 'POST':
  7460. pass
  7461. @main.route('/ctrl_F_<actuator>/<tid>', methods=['GET', 'POST'])
  7462. def ctrl_F(actuator, tid):
  7463. if request.method == 'GET':
  7464. if 'id' in session and 'uname' in session and 'status' in session:
  7465. username = session['uname']
  7466. status = session['status']
  7467. if status == 9:
  7468. return render_template('signin_disable.html')
  7469. elif status == 8:
  7470. return render_template('signin_new.html')
  7471. else:
  7472. return render_template('oops.html')
  7473. tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7474. if actuator == 'Vacuum':
  7475. tank_vacuum = tank_actuator.vacuum
  7476. tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
  7477. LiDAR = tank_LiDAR.LiDAR
  7478. return render_template('ctrl_F_Vacuum.html', title='[操作]F' + tid + '發酵槽_真空吸料機', **locals())
  7479. elif actuator == 'ThreeWayValveInput':
  7480. tank_threewayvalveinput = tank_actuator.threewayvalve_input
  7481. return render_template('ctrl_F_ThreeWayValveInput.html', title='[操作]F' + tid + '發酵槽_入料三通閥', **locals())
  7482. elif actuator == 'SolenoidWaterTotal':
  7483. tank_solenoid_tank_water_total = tank_actuator.solenoid_tank_water_total
  7484. return render_template('ctrl_F_SolenoidWaterTotal.html', title='[操作]F' + tid + '發酵槽_總進水電磁閥', **locals())
  7485. elif actuator == 'SolenoidOuterWater':
  7486. tank_solenoid_outer_water = tank_actuator.solenoid_outer_water
  7487. tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  7488. WaterLevel = tank_WaterLevel.WaterLevel
  7489. return render_template('ctrl_F_SolenoidOuterWater.html', title='[操作]F' + tid + '發酵槽_保溫夾層進水電磁閥', **locals())
  7490. elif actuator == 'SolenoidWaterIn':
  7491. tank_solenoid_tank_water_in = tank_actuator.solenoid_tank_water_in
  7492. tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  7493. PressureWaterLevel = tank_PressureWaterLevel.PressureWaterLevel
  7494. return render_template('ctrl_F_SolenoidWaterIn.html', title='[操作]F' + tid + '發酵槽_桶內進水電磁閥', **locals())
  7495. elif actuator == 'PumpSensor':
  7496. tank_pump_sensor = tank_actuator.pump_sensor
  7497. tank_PH = ferment_tank_PH.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  7498. tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  7499. tank_DO = ferment_tank_DO.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  7500. tank_EC = ferment_tank_EC.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  7501. PH = tank_PH.PH
  7502. ORP = tank_ORP.ORP
  7503. DO = tank_DO.DO
  7504. EC = tank_EC.EC
  7505. return render_template('ctrl_F_PumpSensor.html', title='[操作]F' + tid + '發酵槽_感測器抽水雙核隔膜泵', **locals())
  7506. elif actuator == 'ThreeWayValveBean':
  7507. tank_threewayvalve_bean = tank_actuator.threewayvalve_bean
  7508. return render_template('ctrl_F_ThreeWayValveBean.html', title='[操作]F' + tid + '發酵槽_感測模組下豆三通閥', **locals())
  7509. elif actuator == 'ThreeWayValveFloat':
  7510. tank_threewayvalve_outer_float = tank_actuator.threewayvalve_outer_float
  7511. return render_template('ctrl_F_ThreeWayValveFloat.html', title='[操作]F' + tid + '發酵槽_外桶浮選三通閥', **locals())
  7512. elif actuator == 'SolenoidDisinfect':
  7513. tank_solenoid_tank_disinfect = tank_actuator.solenoid_tank_disinfect
  7514. return render_template('ctrl_F_SolenoidDisinfect.html', title='[操作]F' + tid + '發酵槽_桶內消毒電磁閥', **locals())
  7515. elif actuator == 'Motor':
  7516. tank_motor = tank_actuator.motor
  7517. return render_template('ctrl_F_Motor.html', title='[操作]F' + tid + '發酵槽_馬達', **locals())
  7518. elif actuator == 'Heater1':
  7519. tank_heater1 = tank_actuator.heater1
  7520. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  7521. return render_template('ctrl_F_Heater1.html', title='[操作]F' + tid + '發酵槽_加熱器 1', **locals())
  7522. elif actuator == 'Heater2':
  7523. tank_heater2 = tank_actuator.heater2
  7524. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  7525. return render_template('ctrl_F_Heater2.html', title='[操作]F' + tid + '發酵槽_加熱器 2', **locals())
  7526. elif actuator == 'TempEnable':
  7527. tank_temp_enable = tank_actuator.temp_enable
  7528. return render_template('ctrl_F_TempEnable.html', title='[操作]F' + tid + '發酵槽_溫控開關', **locals())
  7529. elif actuator == 'Temp':
  7530. tank_temp = tank_actuator.temp
  7531. tank_temp_enable = tank_actuator.temp_enable
  7532. tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
  7533. return render_template('ctrl_F_Temp.html', title='[操作]F' + tid + '發酵槽_溫度設定', **locals())
  7534. elif actuator == 'DiskValve':
  7535. tank_diskvalve = tank_actuator.diskvalve
  7536. return render_template('ctrl_F_DiskValve.html', title='[操作]F' + tid + '發酵槽_蝴蝶閥', **locals())
  7537. @main.route('/dry_Temp/<tid>/<Temp_Weights_SHT11>/<Temp_Weights_Soil>/<temp_data>', methods=['GET', 'POST'])
  7538. def dry_Temp(tid, Temp_Weights_SHT11, Temp_Weights_Soil, temp_data):
  7539. if request.method == 'GET':
  7540. if 'id' in session and 'uname' in session and 'status' in session:
  7541. username = session['uname']
  7542. status = session['status']
  7543. if status == 9:
  7544. return render_template('signin_disable.html')
  7545. elif status == 8:
  7546. return render_template('signin_new.html')
  7547. else:
  7548. return render_template('oops.html')
  7549. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  7550. SHT11_Temp = float(tank_SHT11.SHT11_Temp)
  7551. SHT11_Humidity = tank_SHT11.SHT11_Humidity
  7552. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  7553. Soil_Temp = float(tank_Soil.soil_Temp)
  7554. Soil_Humidity = tank_Soil.soil_Humidity
  7555. Temp_Weights_SHT11= float(Temp_Weights_SHT11)
  7556. Temp_Weights_Soil = float(Temp_Weights_Soil)
  7557. temp_data = float(temp_data)
  7558. present_temp = math.ceil( (SHT11_Temp*Temp_Weights_SHT11 + Soil_Temp*Temp_Weights_Soil)/(Temp_Weights_SHT11+Temp_Weights_Soil) )
  7559. # Math.round((present_SHT11_Temp*Temp_Weights_SHT11 + present_SOIL_Temp*Temp_Weights_Soil)/(Temp_Weights_SHT11+Temp_Weights_Soil)*100) / 100
  7560. target_temp = math.ceil(temp_data)
  7561. TempUp = {
  7562. 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
  7563. }
  7564. if target_temp in TempUp and present_temp in TempUp:
  7565. TempUpTime = ', 預計 ' + str(TempUp[target_temp] - TempUp[present_temp]) + ' 秒達到指定溫度'
  7566. elif target_temp < 22 or present_temp < 22 :
  7567. TempUpTime = '℃, 指定溫度過低, 持續升溫中'
  7568. elif target_temp > 44 or present_temp > 44 :
  7569. TempUpTime = '℃, 指定溫度過高, 持續升溫中'
  7570. return jsonify({"SHT11_Temp":SHT11_Temp,
  7571. "SHT11_Humidity":SHT11_Humidity,
  7572. "Soil_Temp":Soil_Temp,
  7573. "Soil_Humidity":Soil_Humidity,
  7574. "present_temp":present_temp,
  7575. "TempUpTime":TempUpTime
  7576. })
  7577. else:
  7578. pass
  7579. @main.route('/dry_container_tank/<tid>', methods=['GET', 'POST'])
  7580. def dry_container_tank(tid):
  7581. if request.method == 'GET':
  7582. if 'id' in session and 'uname' in session and 'status' in session:
  7583. username = session['uname']
  7584. status = session['status']
  7585. if status == 9:
  7586. return render_template('signin_disable.html')
  7587. elif status == 8:
  7588. return render_template('signin_new.html')
  7589. else:
  7590. return render_template('oops.html')
  7591. tonow = dt.now()
  7592. print("tonow: ", tonow)
  7593. time_del = timedelta(minutes=-60)
  7594. bias_date_time = tonow + time_del
  7595. # print(dt.now() >= dt(2021,11,29,17,35,36))
  7596. # bias_min = tonow.minute + 3
  7597. # 感測器_乾燥桶_SHT11
  7598. tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid))\
  7599. .filter(dry_tank_SHT11.datetime >= bias_date_time)\
  7600. .order_by(text('datetime desc')).first()
  7601. # 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'>
  7602. if not hasattr(object, 'tank_SHT11'):
  7603. tank_SHT11 = {"SHT11_Temp":" — ", "SHT11_Humidity":" — "}
  7604. print(tank_SHT11["SHT11_Temp"])
  7605. # 感測器_乾燥桶_土壤三合一
  7606. tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  7607. if not hasattr(object, 'tank_Soil'):
  7608. tank_Soil = {"soil_Temp":" — ", "soil_Humidity":" — ", "soil_EC":" — "}
  7609. # 感測器_乾燥桶_氣壓
  7610. tank_PA = dry_tank_PA.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  7611. if not hasattr(object, 'tank_PA'):
  7612. tank_PA = {"PA":" — "}
  7613. # 感測器_乾燥桶_超音波感測器
  7614. tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  7615. if not hasattr(object, 'tank_UltraSonic'):
  7616. tank_UltraSonic = {"UltraSonic":" — "}
  7617. # 致動器_乾燥桶_ALL
  7618. tank_brake = dry_tank_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
  7619. tank_vacuum = tank_brake.vacuum
  7620. tank_threewayvalve_input = tank_brake.threewayvalve_input
  7621. tank_threewayvalve_bean = tank_brake.threewayvalve_bean
  7622. tank_diskvalve = tank_brake.diskvalve
  7623. tank_solenoid_disinfect = tank_brake.solenoid_disinfect
  7624. tank_solenoid_water = tank_brake.solenoid_water
  7625. tank_solenoid_outer_water = tank_brake.solenoid_outer_water
  7626. tank_motor = tank_brake.motor
  7627. tank_blower = tank_brake.blower
  7628. tank_heater1 = tank_brake.heater1
  7629. tank_heater2 = tank_brake.heater2
  7630. tank_temp1_enable = tank_brake.temp1_enable
  7631. tank_temp1 = tank_brake.temp1
  7632. # Temp_weight = num_SHT11_temp * 0.5 + num_Soil_temp * 0.5
  7633. return render_template('dry_container_tank.html', title='[操作] D' + tid + ' 乾燥槽操作介面', **locals())
  7634. elif request.method == 'POST':
  7635. pass
  7636. @main.route('/dry_container_input/<tid>', methods=['GET', 'POST'])
  7637. def dry_container_input(tid):
  7638. if request.method == 'GET':
  7639. if 'id' in session and 'uname' in session and 'status' in session:
  7640. username = session['uname']
  7641. status = session['status']
  7642. if status == 9:
  7643. return render_template('signin_disable.html')
  7644. elif status == 8:
  7645. return render_template('signin_new.html')
  7646. else:
  7647. return render_template('oops.html')
  7648. input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI'+str(tid)).order_by(text('datetime desc')).first()
  7649. input_vacuum = dry_input_brake.query.filter_by(tank_num='DI'+str(tid)).order_by(text('datetime desc')).first()
  7650. input_vacuum = input_vacuum.vacuum
  7651. return render_template('dry_container_input.html', title='[操作] DI' + tid + ' 乾燥入料儲豆槽操作介面', **locals())
  7652. elif request.method == 'POST':
  7653. pass
  7654. @main.route('/dry_container_output/<tid>', methods=['GET', 'POST'])
  7655. def dry_container_output(tid):
  7656. if request.method == 'GET':
  7657. if 'id' in session and 'uname' in session and 'status' in session:
  7658. username = session['uname']
  7659. status = session['status']
  7660. if status == 9:
  7661. return render_template('signin_disable.html')
  7662. elif status == 8:
  7663. return render_template('signin_new.html')
  7664. else:
  7665. return render_template('oops.html')
  7666. output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO'+str(tid)).order_by(text('datetime desc')).first()
  7667. output_vacuum = dry_output_brake.query.filter_by(tank_num='DO'+str(tid)).order_by(text('datetime desc')).first()
  7668. output_vacuum = output_vacuum.vacuum
  7669. return render_template('dry_container_output.html', title='[操作] DO' + tid + ' 乾燥出料儲豆槽操作介面', **locals())
  7670. elif request.method == 'POST':
  7671. pass
  7672. # 登入頁面的訪問路徑
  7673. @main.route('/login', methods=['GET', 'POST'])
  7674. def login_views():
  7675. if request.method == 'GET':
  7676. if 'id' in session and 'uname' in session and 'status' in session:
  7677. return redirect('/')
  7678. else:
  7679. return render_template('sign_in.html')
  7680. else:
  7681. # 接收前端傳過來的資料
  7682. username = request.form['username']
  7683. password = request.form['password']
  7684. # 使用接收的用戶和密碼到資料庫中查詢
  7685. user = User.query.filter_by(
  7686. username=username, password=password).first()
  7687. # 如果用戶存在,將信息保存置session並重定向回首頁,否則重定向回登入頁
  7688. if user:
  7689. resp = redirect('/')
  7690. # 判斷是否有記住密碼
  7691. if 'rem' in request.form:
  7692. userID = str(user.userID)
  7693. max_age = 60*60*24*365
  7694. status = str(user.status)
  7695. print('status: ', status)
  7696. # Rita 以秒為單位, 一年
  7697. # Rita 功能和 expires 很像,但此參數並非所有瀏覽器均支持,所以建議使用 expires 參數。
  7698. # Rita expires:指定 Cookie 的有效日期, 當過了有效日期後就不會儲存在瀏覽器
  7699. resp.set_cookie("username", username, max_age=max_age)
  7700. resp.set_cookie("userID", userID, max_age=max_age)
  7701. resp.set_cookie("status", status, max_age=max_age)
  7702. session['uname'] = user.username
  7703. session['id'] = user.userID
  7704. session['status'] = user.status
  7705. return resp
  7706. else:
  7707. errMsg = "Wrong login or password"
  7708. return render_template('sign_in.html', errMsg=errMsg)
  7709. # 登入重設密碼的頁面
  7710. # Rita reset_pwd1 - Email
  7711. # Rita reset_pwd2 - New password / Confirm password
  7712. @main.route('/reset_password', methods=['POST', 'GET'])
  7713. def reset_password_views():
  7714. if request.method == 'GET':
  7715. if 'mail' in session:
  7716. del session['mail']
  7717. return render_template('reset_pwd1.html')
  7718. else:
  7719. # POST
  7720. # 如果有id在session裡,代表從reset_pwd2過來的 ? 對, reset_pwd2 POST (但也有其他可能)
  7721. if "mail" in session:
  7722. new_pwd = request.form['new_pwd']
  7723. confirm_pwd = request.form['confirm_pwd']
  7724. # 判斷密碼是否一致
  7725. if new_pwd == confirm_pwd:
  7726. mail = session['mail']
  7727. user = User.query.filter_by(mail=mail).first()
  7728. print("user: ", user)
  7729. print("user.password_before: ", user.password)
  7730. print("new_pwd: ", new_pwd)
  7731. user.password = new_pwd
  7732. print("user.password_after: ", user.password)
  7733. db.session.add(user)
  7734. db.session.commit()
  7735. del session['mail']
  7736. errMsg = "Rest password success"
  7737. # 修改完後回登入頁
  7738. return render_template('sign_in.html', errMsg=errMsg)
  7739. else:
  7740. # Rita errMsg 是指網頁上的 {{errMsg}} 位置
  7741. errMsg = "Passwords does not match"
  7742. return render_template('reset_pwd2.html', errMsg=errMsg)
  7743. email = request.form['email']
  7744. user = User.query.filter_by(mail=email).first()
  7745. if user: # Rita 有找到對應 email
  7746. session['mail'] = user.mail
  7747. return render_template('reset_pwd2.html')
  7748. else:
  7749. errMsg = "Wrong email.Please try again"
  7750. return render_template('reset_pwd1.html', errMsg=errMsg)
  7751. # 註冊頁面的訪問路徑
  7752. @main.route('/register', methods=['POST', "GET"])
  7753. def register_views():
  7754. if request.method == 'GET':
  7755. return render_template('registration.html')
  7756. else:
  7757. email = request.form['email']
  7758. mail = User.query.filter_by(mail=email).first()
  7759. if mail:
  7760. # Rita email 錯誤時會顯示 Incorrect email address
  7761. errMsg = "This email is already registered"
  7762. else:
  7763. errMsg = ""
  7764. username = request.form['username']
  7765. user = User.query.filter_by(username=username).first()
  7766. if user:
  7767. errMsg1 = "This username is already registered"
  7768. else:
  7769. errMsg1 = ""
  7770. pwd = request.form['password']
  7771. confirm_pwd = request.form['confirmpwd']
  7772. if pwd != confirm_pwd:
  7773. errMsg2 = "Passwords does not match"
  7774. else:
  7775. errMsg2 = ""
  7776. if errMsg != "" or errMsg1 != "" or errMsg2 != "":
  7777. return render_template('registration.html',errMsg=errMsg,errMsg1=errMsg1,errMsg2=errMsg2)
  7778. else:
  7779. # 獲取文本框的值並賦值給user實體對象
  7780. user = User()
  7781. user.firstname = request.form['firstname']
  7782. user.lastname = request.form['lastname']
  7783. user.mail = request.form['email']
  7784. user.phone = request.form['phone']
  7785. user.username = request.form['username']
  7786. user.password = request.form['password']
  7787. user.status = 2 # Rita app\models.py 設定 0:admin;1:new;9:disable [0906 更新] 0:admin;1:superuser;2:enduser;8:new;9:disable
  7788. #將數據保存進資料庫 - 註冊
  7789. db.session.add(user)
  7790. # 手動提交,目的是為了獲取提交後的user的id
  7791. db.session.commit()
  7792. # 當user成功插入進資料庫之後,程序會自動將所有信息取出來在賦值給user
  7793. # 完成登入的操作
  7794. user = User.query.filter_by(username=user.username).first()
  7795. session['status'] = user.status
  7796. session['id'] = user.userID
  7797. session['uname'] = user.username
  7798. errMsg="Sign up success"
  7799. return render_template('sign_in.html',errMsg=errMsg)
  7800. # 驗證email訪問路徑
  7801. @main.route('/check_email')
  7802. def check_email_views():
  7803. email = request.args['email']
  7804. mail = User.query.filter_by(mail=email).first()
  7805. if mail:
  7806. # Rita email 錯誤時會顯示 Incorrect email address
  7807. result = {"errMsg": "error"}
  7808. else:
  7809. result = {"pass": ""}
  7810. return json.dumps(result)
  7811. # 驗證username訪問路徑
  7812. @main.route('/check_username')
  7813. def check_username_views():
  7814. if request.method == 'GET':
  7815. username = request.args['username']
  7816. user = User.query.filter_by(username=username).first()
  7817. if user:
  7818. result = {"errMsg": "error"}
  7819. else:
  7820. result = {"pass": " "}
  7821. return json.dumps(result)
  7822. @main.route('/check_login', methods=['GET', 'POST'])
  7823. def check_login():
  7824. if request.method == 'GET':
  7825. # 接收前端傳過來的資料
  7826. username = request.args['username']
  7827. password = request.args['password']
  7828. # 使用接收的用戶和密碼到資料庫中查詢
  7829. user = User.query.filter_by(username=username, password=password).first()
  7830. # 如果用戶存在,將信息保存置session並重定向回首頁,否則重定向回登入頁
  7831. if user:
  7832. resp = redirect('/')
  7833. # 判斷是否有記住密碼
  7834. if 'rem' in request.form:
  7835. userID = str(user.userID)
  7836. max_age = 60*60*24*365
  7837. status = str(user.status)
  7838. print('status: ', status)
  7839. # Rita 以秒為單位, 一年
  7840. # Rita 功能和 expires 很像,但此參數並非所有瀏覽器均支持,所以建議使用 expires 參數。
  7841. # Rita expires:指定 Cookie 的有效日期, 當過了有效日期後就不會儲存在瀏覽器
  7842. resp.set_cookie("username", username, max_age=max_age)
  7843. resp.set_cookie("userID", userID, max_age=max_age)
  7844. resp.set_cookie("status", status, max_age=max_age)
  7845. session['uname'] = user.username
  7846. session['id'] = user.userID
  7847. session['status'] = user.status
  7848. return resp
  7849. else:
  7850. errMsg = {"errMsg": "Wrong password"}
  7851. return json.dumps(errMsg)
  7852. # 咖啡貨櫃的訪問路徑
  7853. @main.route('/cargo_list', methods=['GET', 'POST'])
  7854. def cargo_list_views():
  7855. username = session['uname']
  7856. if request.method == 'GET':
  7857. return render_template('cargo_list.html', params=locals())
  7858. else:
  7859. pass
  7860. # 貨櫃1的訪問路徑
  7861. @main.route('/cargo1', methods=['GET', 'POST'])
  7862. def cargo1_views():
  7863. username = session['uname']
  7864. if request.method == 'GET':
  7865. return render_template('cargo1.html', params=locals())
  7866. else:
  7867. pass
  7868. # 貨櫃1排程的訪問路徑
  7869. @main.route('/cargo1_schedule', methods=['GET', 'POST'])
  7870. def cargo1_schedule_views():
  7871. username = session['uname']
  7872. if request.method == 'GET':
  7873. # 將已儲存的排程資料傳給前端
  7874. # 進豆閥
  7875. try:
  7876. bean = BeanValve.query.order_by(text('datetime desc')).first()
  7877. datetime = bean.datetime
  7878. beans = BeanValve.query.filter_by(
  7879. datetime=datetime).all()
  7880. except Exception as e:
  7881. pass
  7882. # 清洗機
  7883. try:
  7884. wash = WashMachine.query.order_by(text('datetime desc')).first()
  7885. datetime = wash.datetime
  7886. washes = WashMachine.query.filter_by(datetime=datetime).all()
  7887. except Exception as e:
  7888. pass
  7889. # 輸送帶1
  7890. try:
  7891. belt1 = ConveyorBelt1.query.order_by(text('datetime desc')).first()
  7892. datetime = belt1.datetime
  7893. belts1 = ConveyorBelt1.query.filter_by(datetime=datetime).all()
  7894. except Exception as e:
  7895. pass
  7896. # ///////////////////////////////////////////////////////////////////////////////////////////
  7897. # 消毒機
  7898. try:
  7899. disinfect = Cargo1Disinfect.query.order_by(
  7900. text('datetime desc')).first()
  7901. datetime = disinfect.datetime
  7902. disinfects = Cargo1Disinfect.query.filter_by(
  7903. datetime=datetime).all()
  7904. except Exception as e:
  7905. pass
  7906. # 色選機
  7907. try:
  7908. color = ColorMachine.query.order_by(text('datetime desc')).first()
  7909. datetime = color.datetime
  7910. colors = ColorMachine.query.filter_by(datetime=datetime).all()
  7911. except Exception as e:
  7912. pass
  7913. # 輸送帶2
  7914. try:
  7915. belt2 = ConveyorBelt2.query.order_by(text('datetime desc')).first()
  7916. datetime = belt2.datetime
  7917. belts2 = ConveyorBelt2.query.filter_by(datetime=datetime).all()
  7918. except Exception as e:
  7919. pass
  7920. # 去皮機
  7921. try:
  7922. peeling = PeelingMachine.query.order_by(
  7923. text('datetime desc')).first()
  7924. datetime = peeling.datetime
  7925. peelings = PeelingMachine.query.filter_by(datetime=datetime).all()
  7926. except Exception as e:
  7927. pass
  7928. # 輸送帶3
  7929. try:
  7930. belt3 = ConveyorBelt3.query.order_by(text('datetime desc')).first()
  7931. datetime = belt3.datetime
  7932. belts3 = ConveyorBelt3.query.filter_by(datetime=datetime).all()
  7933. except Exception as e:
  7934. pass
  7935. return render_template('cargo1_schedule.html', params=locals())
  7936. else:
  7937. current_time = dt.now()
  7938. # 循環從前端提交過來的資料
  7939. for i in request.form:
  7940. # 進豆閥
  7941. if i[:10] == 'inletValve':
  7942. if i[:19] == 'inletValve_duration':
  7943. bean = BeanValve()
  7944. bean.duration = request.form[i]
  7945. elif i[:18] == 'inletValve_from_hr':
  7946. iv_from_hr = request.form[i]
  7947. elif i[:19] == 'inletValve_from_min':
  7948. iv_from_min = request.form[i]
  7949. bean.start = iv_from_hr + ":" + iv_from_min
  7950. elif i[:16] == 'inletValve_to_hr':
  7951. iv_to_hr = request.form[i]
  7952. elif i[:17] == 'inletValve_to_min':
  7953. iv_to_min = request.form[i]
  7954. bean.end = iv_to_hr + ":" + iv_to_min
  7955. bean.datetime = current_time
  7956. db.session.add(bean)
  7957. db.session.commit()
  7958. # 清洗機
  7959. elif i[:4] == 'wash':
  7960. if i[:13] == 'wash_duration':
  7961. wash = WashMachine()
  7962. wash.duration = request.form[i]
  7963. elif i[:12] == 'wash_from_hr':
  7964. wash_from_hr = request.form[i]
  7965. elif i[:13] == 'wash_from_min':
  7966. wash_from_min = request.form[i]
  7967. wash.start = wash_from_hr + ":" + wash_from_min
  7968. elif i[:10] == 'wash_to_hr':
  7969. wash_to_hr = request.form[i]
  7970. elif i[:11] == 'wash_to_min':
  7971. wash_to_min = request.form[i]
  7972. wash.end = wash_to_hr + ":" + wash_to_min
  7973. wash.datetime = current_time
  7974. db.session.add(wash)
  7975. db.session.commit()
  7976. # 輸送帶1
  7977. elif i[:5] == 'belt1':
  7978. if i[:14] == 'belt1_duration':
  7979. belt1 = ConveyorBelt1()
  7980. belt1.duration = request.form[i]
  7981. elif i[:13] == 'belt1_from_hr':
  7982. belt1_from_hr = request.form[i]
  7983. elif i[:14] == 'belt1_from_min':
  7984. belt1_from_min = request.form[i]
  7985. belt1.start = belt1_from_hr + ":" + belt1_from_min
  7986. elif i[:11] == 'belt1_to_hr':
  7987. belt1_to_hr = request.form[i]
  7988. elif i[:12] == 'belt1_to_min':
  7989. belt1_to_min = request.form[i]
  7990. belt1.end = belt1_to_hr + ":" + belt1_to_min
  7991. belt1.datetime = current_time
  7992. db.session.add(belt1)
  7993. db.session.commit()
  7994. # 消毒
  7995. elif i[:9] == 'disinfect':
  7996. if i[:18] == 'disinfect_duration':
  7997. disinfect = Cargo1Disinfect()
  7998. disinfect.duration = request.form[i]
  7999. elif i[:17] == 'disinfect_from_hr':
  8000. di_from_hr = request.form[i]
  8001. elif i[:18] == 'disinfect_from_min':
  8002. di_from_min = request.form[i]
  8003. disinfect.start = di_from_hr + ":" + di_from_min
  8004. elif i[:15] == 'disinfect_to_hr':
  8005. di_to_hr = request.form[i]
  8006. elif i[:16] == 'disinfect_to_min':
  8007. di_to_min = request.form[i]
  8008. disinfect.end = di_to_hr + ":" + di_to_min
  8009. disinfect.datetime = current_time
  8010. db.session.add(disinfect)
  8011. db.session.commit()
  8012. # 色選機
  8013. elif i[:5] == 'color':
  8014. if i[:14] == 'color_duration':
  8015. color = ColorMachine()
  8016. color.duration = request.form[i]
  8017. elif i[:13] == 'color_from_hr':
  8018. color_from_hr = request.form[i]
  8019. elif i[:14] == 'color_from_min':
  8020. color_from_min = request.form[i]
  8021. color.start = color_from_hr + ":" + color_from_min
  8022. elif i[:11] == 'color_to_hr':
  8023. color_to_hr = request.form[i]
  8024. elif i[:12] == 'color_to_min':
  8025. color_to_min = request.form[i]
  8026. color.end = color_to_hr + ":" + color_to_min
  8027. color.datetime = current_time
  8028. db.session.add(color)
  8029. db.session.commit()
  8030. # 輸送帶2
  8031. elif i[:5] == 'belt2':
  8032. if i[:14] == 'belt2_duration':
  8033. belt2 = ConveyorBelt2()
  8034. belt2.duration = request.form[i]
  8035. elif i[:13] == 'belt2_from_hr':
  8036. belt2_from_hr = request.form[i]
  8037. elif i[:14] == 'belt2_from_min':
  8038. belt2_from_min = request.form[i]
  8039. belt2.start = belt2_from_hr + ":" + belt2_from_min
  8040. elif i[:11] == 'belt2_to_hr':
  8041. belt2_to_hr = request.form[i]
  8042. elif i[:12] == 'belt2_to_min':
  8043. belt2_to_min = request.form[i]
  8044. belt2.end = belt2_to_hr + ":" + belt2_to_min
  8045. belt2.datetime = current_time
  8046. db.session.add(belt2)
  8047. db.session.commit()
  8048. # 去皮機
  8049. elif i[:6] == 'peeled':
  8050. if i[:15] == 'peeled_duration':
  8051. peeling = PeelingMachine()
  8052. peeling.duration = request.form[i]
  8053. elif i[:14] == 'peeled_from_hr':
  8054. peeled_from_hr = request.form[i]
  8055. elif i[:15] == 'peeled_from_min':
  8056. peeled_from_min = request.form[i]
  8057. peeling.start = peeled_from_hr + ":" + peeled_from_min
  8058. elif i[:12] == 'peeled_to_hr':
  8059. peeled_to_hr = request.form[i]
  8060. elif i[:13] == 'peeled_to_min':
  8061. peeled_to_min = request.form[i]
  8062. peeling.end = peeled_to_hr + ":" + peeled_to_min
  8063. peeling.datetime = current_time
  8064. db.session.add(peeling)
  8065. db.session.commit()
  8066. # 輸送帶3
  8067. elif i[:5] == 'belt3':
  8068. if i[:14] == 'belt3_duration':
  8069. belt3 = ConveyorBelt3()
  8070. belt3.duration = request.form[i]
  8071. elif i[:13] == 'belt3_from_hr':
  8072. belt3_from_hr = request.form[i]
  8073. elif i[:14] == 'belt3_from_min':
  8074. belt3_from_min = request.form[i]
  8075. belt3.start = belt3_from_hr + ":" + belt3_from_min
  8076. elif i[:11] == 'belt3_to_hr':
  8077. belt3_to_hr = request.form[i]
  8078. elif i[:12] == 'belt3_to_min':
  8079. belt3_to_min = request.form[i]
  8080. belt3.end = belt3_to_hr + ":" + belt3_to_min
  8081. belt3.datetime = current_time
  8082. db.session.add(belt3)
  8083. db.session.commit()
  8084. return render_template('cargo1.html', params=locals())
  8085. # 貨櫃2的訪問路徑
  8086. @main.route('/cargo2', methods=['GET', 'POST'])
  8087. def cargo2_views():
  8088. username = session['uname']
  8089. if request.method == 'GET':
  8090. return render_template('cargo2.html', params=locals())
  8091. else:
  8092. pass
  8093. # 貨櫃2排程的發酵槽訪問路徑
  8094. @main.route('/cargo2_schedule_tanks', methods=['GET', 'POST'])
  8095. def cargo2_schedule_tanks_views():
  8096. username = session['uname']
  8097. if request.method == 'GET':
  8098. return render_template('cargo2_schedule_tanks.html', params=locals())
  8099. else:
  8100. pass
  8101. # 貨櫃2排程發酵槽的清單訪問路徑
  8102. @main.route('/cargo2_schedule/<tid>', methods=['GET', 'POST'])
  8103. def cargo2_schedule_views(tid):
  8104. username = session['uname']
  8105. if request.method == 'GET':
  8106. # 將已儲存的排程資料傳給前端
  8107. # 打菌
  8108. try:
  8109. bacteria = Bacteria.query.filter_by(tank_num=int(
  8110. tid)).order_by(text('datetime desc')).first()
  8111. datetime = bacteria.datetime
  8112. bacterias = Bacteria.query.filter_by(datetime=datetime).all()
  8113. except Exception as e:
  8114. pass
  8115. # 消毒
  8116. try:
  8117. disinfect = Cargo2Disinfect.query.filter_by(
  8118. tank_num=int(tid)).order_by(text('datetime desc')).first()
  8119. datetime = disinfect.datetime
  8120. disinfects = Cargo2Disinfect.query.filter_by(
  8121. datetime=datetime).all()
  8122. except Exception as e:
  8123. pass
  8124. # 加熱
  8125. try:
  8126. heating = Heating.query.filter_by(tank_num=int(
  8127. tid)).order_by(text('datetime desc')).first()
  8128. datetime = heating.datetime
  8129. heatings = Heating.query.filter_by(datetime=datetime).all()
  8130. except Exception as e:
  8131. pass
  8132. # 攪拌
  8133. try:
  8134. stir = Stir.query.filter_by(tank_num=int(tid)).order_by(
  8135. text('datetime desc')).first()
  8136. datetime = stir.datetime
  8137. stirs = Stir.query.filter_by(datetime=datetime).all()
  8138. except Exception as e:
  8139. pass
  8140. # 注水
  8141. try:
  8142. water = WaterInjection.query.filter_by(
  8143. tank_num=int(tid)).order_by(text('datetime desc')).first()
  8144. datetime = water.datetime
  8145. waters = WaterInjection.query.filter_by(datetime=datetime).all()
  8146. except Exception as e:
  8147. pass
  8148. # 開上閥
  8149. try:
  8150. top = TopValve.query.filter_by(tank_num=int(
  8151. tid)).order_by(text('datetime desc')).first()
  8152. datetime = top.datetime
  8153. tops = TopValve.query.filter_by(datetime=datetime).all()
  8154. except Exception as e:
  8155. pass
  8156. # 開下閥
  8157. try:
  8158. bottom = BottomValve.query.filter_by(tank_num=int(
  8159. tid)).order_by(text('datetime desc')).first()
  8160. datetime = bottom.datetime
  8161. bottoms = BottomValve.query.filter_by(datetime=datetime).all()
  8162. except Exception as e:
  8163. pass
  8164. # 溫度
  8165. try:
  8166. tem = Temperature.query.filter_by(tank_num=int(
  8167. tid)).order_by(text('datetime desc')).first()
  8168. datetime = tem.datetime
  8169. tems = Temperature.query.filter_by(datetime=datetime).all()
  8170. except Exception as e:
  8171. pass
  8172. return render_template('cargo2_schedule.html', params=locals())
  8173. else:
  8174. current_time = dt.now()
  8175. # 循環從前端提交過來的資料
  8176. for i in request.form:
  8177. # 打菌
  8178. if i[:8] == 'bacteria':
  8179. if i[:17] == 'bacteria_duration':
  8180. bacteria = Bacteria()
  8181. bacteria.duration = request.form[i]
  8182. elif i[:16] == 'bacteria_from_hr':
  8183. bac_from_hr = request.form[i]
  8184. elif i[:17] == 'bacteria_from_min':
  8185. bac_from_min = request.form[i]
  8186. bacteria.start = bac_from_hr + ":" + bac_from_min
  8187. elif i[:14] == 'bacteria_to_hr':
  8188. bac_to_hr = request.form[i]
  8189. elif i[:15] == 'bacteria_to_min':
  8190. bac_to_min = request.form[i]
  8191. bacteria.end = bac_to_hr + ":" + bac_to_min
  8192. bacteria.datetime = current_time
  8193. bacteria.tank_num = int(tid)
  8194. db.session.add(bacteria)
  8195. db.session.commit()
  8196. # 消毒
  8197. elif i[:9] == 'disinfect':
  8198. if i[:18] == 'disinfect_duration':
  8199. disinfect = Cargo2Disinfect()
  8200. disinfect.duration = request.form[i]
  8201. elif i[:17] == 'disinfect_from_hr':
  8202. di_from_hr = request.form[i]
  8203. elif i[:18] == 'disinfect_from_min':
  8204. di_from_min = request.form[i]
  8205. disinfect.start = di_from_hr + ":" + di_from_min
  8206. elif i[:15] == 'disinfect_to_hr':
  8207. di_to_hr = request.form[i]
  8208. elif i[:16] == 'disinfect_to_min':
  8209. di_to_min = request.form[i]
  8210. disinfect.end = di_to_hr + ":" + di_to_min
  8211. disinfect.datetime = current_time
  8212. disinfect.tank_num = int(tid)
  8213. db.session.add(disinfect)
  8214. db.session.commit()
  8215. # 加熱
  8216. elif i[:7] == 'heating':
  8217. if i[:16] == 'heating_duration':
  8218. heating = Heating()
  8219. heating.duration = request.form[i]
  8220. elif i[:15] == 'heating_from_hr':
  8221. heat_from_hr = request.form[i]
  8222. elif i[:16] == 'heating_from_min':
  8223. heat_from_min = request.form[i]
  8224. heating.start = heat_from_hr + ":" + heat_from_min
  8225. elif i[:13] == 'heating_to_hr':
  8226. heat_to_hr = request.form[i]
  8227. elif i[:14] == 'heating_to_min':
  8228. heat_to_min = request.form[i]
  8229. heating.end = heat_to_hr + ":" + heat_to_min
  8230. heating.datetime = current_time
  8231. heating.tank_num = int(tid)
  8232. db.session.add(heating)
  8233. db.session.commit()
  8234. # 攪拌
  8235. elif i[:4] == 'stir':
  8236. if i[:13] == 'stir_duration':
  8237. stir = Stir()
  8238. stir.duration = request.form[i]
  8239. elif i[:12] == 'stir_from_hr':
  8240. stir_from_hr = request.form[i]
  8241. elif i[:13] == 'stir_from_min':
  8242. stir_from_min = request.form[i]
  8243. stir.start = stir_from_hr + ":" + stir_from_min
  8244. elif i[:10] == 'stir_to_hr':
  8245. stir_to_hr = request.form[i]
  8246. elif i[:11] == 'stir_to_min':
  8247. stir_to_min = request.form[i]
  8248. stir.end = stir_to_hr + ":" + stir_to_min
  8249. stir.datetime = current_time
  8250. stir.tank_num = int(tid)
  8251. db.session.add(stir)
  8252. db.session.commit()
  8253. # 注水
  8254. elif i[:5] == 'water':
  8255. if i[:14] == 'water_duration':
  8256. water = WaterInjection()
  8257. water.duration = request.form[i]
  8258. elif i[:13] == 'water_from_hr':
  8259. water_from_hr = request.form[i]
  8260. elif i[:14] == 'water_from_min':
  8261. water_from_min = request.form[i]
  8262. water.start = water_from_hr + ":" + water_from_min
  8263. elif i[:11] == 'water_to_hr':
  8264. water_to_hr = request.form[i]
  8265. elif i[:12] == 'water_to_min':
  8266. water_to_min = request.form[i]
  8267. water.end = water_to_hr + ":" + water_to_min
  8268. water.datetime = current_time
  8269. water.tank_num = int(tid)
  8270. db.session.add(water)
  8271. db.session.commit()
  8272. # 開上閥
  8273. elif i[:9] == 'highValve':
  8274. if i[:18] == 'highValve_duration':
  8275. top = TopValve()
  8276. top.duration = request.form[i]
  8277. elif i[:17] == 'highValve_from_hr':
  8278. h_valve_from_hr = request.form[i]
  8279. elif i[:18] == 'highValve_from_min':
  8280. h_valve_from_min = request.form[i]
  8281. top.start = h_valve_from_hr + ":" + h_valve_from_min
  8282. elif i[:15] == 'highValve_to_hr':
  8283. h_valve_to_hr = request.form[i]
  8284. elif i[:16] == 'highValve_to_min':
  8285. h_valve_to_min = request.form[i]
  8286. top.end = h_valve_to_hr + ":" + h_valve_to_min
  8287. top.datetime = current_time
  8288. top.tank_num = int(tid)
  8289. db.session.add(top)
  8290. db.session.commit()
  8291. # 開下閥
  8292. elif i[:8] == 'lowValve':
  8293. if i[:17] == 'lowValve_duration':
  8294. bottom = BottomValve()
  8295. bottom.duration = request.form[i]
  8296. elif i[:16] == 'lowValve_from_hr':
  8297. l_valve_from_hr = request.form[i]
  8298. elif i[:17] == 'lowValve_from_min':
  8299. l_valve_from_min = request.form[i]
  8300. bottom.start = l_valve_from_hr + ":" + l_valve_from_min
  8301. elif i[:14] == 'lowValve_to_hr':
  8302. l_valve_to_hr = request.form[i]
  8303. elif i[:15] == 'lowValve_to_min':
  8304. l_valve_to_min = request.form[i]
  8305. bottom.end = l_valve_to_hr + ":" + l_valve_to_min
  8306. bottom.datetime = current_time
  8307. bottom.tank_num = int(tid)
  8308. db.session.add(bottom)
  8309. db.session.commit()
  8310. # 溫度
  8311. elif i[:3] == 'tem':
  8312. if i[:12] == 'tem_duration':
  8313. tem = Temperature()
  8314. tem.duration = request.form[i]
  8315. elif i[:11] == 'tem_from_hr':
  8316. tem_from_hr = request.form[i]
  8317. elif i[:12] == 'tem_from_min':
  8318. tem_from_min = request.form[i]
  8319. tem.start = tem_from_hr + ":" + tem_from_min
  8320. elif i[:9] == 'tem_to_hr':
  8321. tem_to_hr = request.form[i]
  8322. elif i[:10] == 'tem_to_min':
  8323. tem_to_min = request.form[i]
  8324. tem.end = tem_to_hr + ":" + tem_to_min
  8325. tem.datetime = current_time
  8326. tem.tank_num = int(tid)
  8327. db.session.add(tem)
  8328. db.session.commit()
  8329. return render_template('cargo2.html', params=locals())
  8330. # 貨櫃2感測器的發酵槽訪問路徑
  8331. @main.route('/cargo2_sensor_tanks', methods=['GET', 'POST'])
  8332. def cargo2_sensor_tanks_views():
  8333. username = session['uname']
  8334. if request.method == 'GET':
  8335. return render_template('cargo2_sensor_tanks.html', params=locals())
  8336. else:
  8337. pass
  8338. # 貨櫃2感測器發酵槽的清單訪問路徑
  8339. @main.route('/cargo2_sensor/<tid>', methods=['GET', 'POST'])
  8340. def s_tank_views(tid):
  8341. # 判斷用戶是否已關閉瀏覽器或登出後,在訪問這個route,如果沒有session就回登入頁
  8342. try:
  8343. username = session['uname']
  8344. except KeyError:
  8345. return redirect('/')
  8346. if request.method == 'GET':
  8347. # Rita 網頁端 params.tank_tem.tem
  8348. # Coffee/CoffeeProject/app/templates/cargo2_sensor.html
  8349. tank_tem = TankTemSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
  8350. tank_ph = TankPHSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
  8351. tank_ec = TankECSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
  8352. tank_sonic = TankSonicSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
  8353. return render_template('cargo2_sensor.html', params=locals())
  8354. else:
  8355. pass
  8356. # 貨櫃2感測器發酵槽歷史數據的訪問路徑
  8357. @main.route('/history_data', methods=['GET', 'POST'])
  8358. def history_data_views():
  8359. if request.method == 'GET':
  8360. # json
  8361. # tid:tid_D1
  8362. # sensor_name:soil_Temp
  8363. # avg:1
  8364. # max:1
  8365. # min:1
  8366. # time-interval:month
  8367. # date-start:2021-07-01
  8368. # date-end:2021-07-28
  8369. info = request.args.to_dict()
  8370. evt = info['evt']
  8371. avg = int(info['avg'])
  8372. max = int(info['max'])
  8373. min = int(info['min'])
  8374. time_interval = info['time-interval']
  8375. print(info)
  8376. # Rita {'evt': '1-溫濕度', 'avg': '1', 'max': '0', 'min': '0', 'time-interval': 'month',
  8377. # 'date-start': '2021-05-04', 'date-end': '2021-05-18'} {'all': [], 'avg': []}
  8378. # print(info)
  8379. # {'evt': '1-溫濕度', 'avg': '1', 'max': '0', 'min': '0', 'time-interval': 'hour', 'date-start': '2021-01-01', 'date-end': '2021-07-27'}
  8380. # print(D)
  8381. # {'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']],
  8382. # 'avg': [['2021-02-19 16:00:00', '24.5'], ['2021-02-19 18:00:00', '25.3']]}
  8383. # 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 -
  8384. date_start = info['date-start']
  8385. date_end_list = info['date-end'].split('-') # 先把 'date-end' 的 '2021-05-18' 拆成 ['2021', '05', '18']
  8386. date_end_list[2] = str(int(date_end_list[2]) + 1) # 18 + 1 = 19 再轉成 str → '19'
  8387. date_end = '-'.join(date_end_list) # '2021-05-19'
  8388. tank_num = evt.split('-')[0] # 1
  8389. sensor = evt.split('-')[1] # 溫濕度
  8390. L = []
  8391. D = {}
  8392. maxData = []
  8393. minData = []
  8394. avgData = []
  8395. def sensorData(data_name): # data_name = "tem"
  8396. def dataResample(time_interval, how, data_name): # dataResample('month', how???, "tem") # 下方 "hour"
  8397. interval = 0
  8398. # 設置resample的第一個參數,要按照逐月、逐日或逐時
  8399. if time_interval == 'month':
  8400. interval = "M" # interval = "M"
  8401. elif time_interval == 'day':
  8402. interval = "D"
  8403. elif time_interval == 'hour':
  8404. interval = "H"
  8405. if how == "max":
  8406. # data = df.resample(interval, how={data_name:how})
  8407. # 最新版的pandas
  8408. data = df.resample(interval).max() # 取樣頻率 "H"
  8409. # 刪除有 NaN 的列, any 任何一欄位為空則刪 (all 全部欄位為空值才刪)
  8410. data = data.dropna(axis=0, how='any')
  8411. if time_interval == ('hour' or 'day'):
  8412. data.index = pd.to_datetime(
  8413. data.index, format='%Y-%b-%d_%H:%M:%S') # 将数据类型转换为日期类型
  8414. for a in range(0, len(data.index)):
  8415. l = []
  8416. # 如果是逐時,才顯示小時分秒
  8417. if time_interval == 'hour':
  8418. l.append(str(data.index[a]))
  8419. else:
  8420. l.append(str(data.index[a]).split(' ')[0])
  8421. l.append(str(data[data_name][a]))
  8422. maxData.append(l)
  8423. D['max'] = maxData
  8424. elif how == "mean":
  8425. # data = df.resample(interval, how={data_name:how})
  8426. # 最新版的pandas
  8427. data = df.resample(interval).mean()
  8428. # 刪除具有NaN的值
  8429. data = data.dropna(axis=0, how='any')
  8430. # 將平均數取自小數1位
  8431. data = data.round({data_name: 1})
  8432. for a in range(0, len(data.index)):
  8433. l = []
  8434. # 如果是逐時,才顯示小時分秒
  8435. if time_interval == 'hour':
  8436. l.append(str(data.index[a]))
  8437. else:
  8438. l.append(str(data.index[a]).split(' ')[0])
  8439. l.append(str(data[data_name][a]))
  8440. avgData.append(l)
  8441. D['avg'] = avgData
  8442. elif how == "min":
  8443. # data = df.resample(interval, how={data_name:how})
  8444. # 最新版的pandas
  8445. data = df.resample(interval).min()
  8446. # 刪除具有NaN的值
  8447. data = data.dropna(axis=0, how='any')
  8448. for a in range(0, len(data.index)):
  8449. # print(data.index[a])
  8450. l = []
  8451. # 如果是逐時,才顯示小時分秒
  8452. if time_interval == 'hour':
  8453. l.append(str(data.index[a]))
  8454. else:
  8455. l.append(str(data.index[a]).split(' ')[0])
  8456. l.append(str(data[data_name][a]))
  8457. minData.append(l)
  8458. D['min'] = minData
  8459. df = pd.DataFrame(L, columns=["datetime", data_name]) # 指定欄標籤名稱 為 ["datetime", "tem"]
  8460. df['datetime'] = pd.to_datetime(
  8461. df['datetime'], format='%Y-%b-%d_%H:%M:%S') # 将数据类型转换为日期类型
  8462. # print(df['datetime']) # 0 2021-02-19 16:46:10
  8463. # 1 2021-02-19 16:46:20
  8464. # 2 2021-02-19 16:46:30
  8465. # 3 2021-02-19 16:46:41
  8466. df[data_name] = df[data_name].astype(float)
  8467. df = df.set_index('datetime') # 将datetime设置为index
  8468. # print(df) # datetime tem
  8469. # 2021-02-19 16:46:10 24.4
  8470. # 2021-02-19 16:46:20 24.4
  8471. if time_interval == 'month':
  8472. if max:
  8473. dataResample(time_interval, "max", data_name)
  8474. if avg:
  8475. dataResample(time_interval, "mean", data_name)
  8476. if min:
  8477. dataResample(time_interval, "min", data_name)
  8478. elif time_interval == 'day':
  8479. if max:
  8480. dataResample(time_interval, "max", data_name)
  8481. if avg:
  8482. dataResample(time_interval, "mean", data_name)
  8483. if min:
  8484. dataResample(time_interval, "min", data_name)
  8485. elif time_interval == 'hour':
  8486. if max:
  8487. dataResample(time_interval, "max", data_name)
  8488. if avg:
  8489. dataResample(time_interval, "mean", data_name)
  8490. if min:
  8491. dataResample(time_interval, "min", data_name)
  8492. if sensor == '溫濕度':
  8493. # tank_tem = TankTemSensor.query.filter_by(tank_num=int(tank_num)).order_by(text('datetime desc')).all()
  8494. # [7/27 Benson] tank_tem = TankTemSensor.query.filter_by(tank_num=int(tank_num)).filter(TankTemSensor.datetime.between(date_start, date_end)).all()
  8495. tank_tem = dry_tank_SHT11.query.filter(dry_tank_SHT11.datetime.between(date_start, date_end)).all()
  8496. # .filter_by(tank_num="D"+tank_num)
  8497. for tem in tank_tem:
  8498. l = [] # l = []
  8499. time = dt.strftime(tem.datetime, '%Y-%b-%d_%H:%M:%S') # time = '2021-Feb-19_16:46:10' 轉換時間格式
  8500. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  8501. l.append(time) # l = ['2021-Feb-19_16:46:10']
  8502. #l.append(tem.tem) # l = ['2021-Feb-19_16:46:10', '24.4']
  8503. l.append(tem.SHT11_Temp)
  8504. L.append(l) # L = [['2021-Feb-19_16:46:10', '24.4']]
  8505. # print(L)
  8506. D['all'] = L # D = {'all': [['2021-Feb-19_16:46:10', '24.4']]} # all 所有符合數據
  8507. sensorData("tem")
  8508. elif sensor == '酸鹼值':
  8509. tank_ph = TankPHSensor.query.filter_by(tank_num=int(tank_num)).filter(
  8510. TankPHSensor.datetime.between(date_start, date_end)).all()
  8511. for ph in tank_ph:
  8512. l = []
  8513. time = dt.strftime(ph.datetime, '%Y-%b-%d_%H:%M:%S')
  8514. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  8515. l.append(time)
  8516. l.append(ph.ph)
  8517. L.append(l)
  8518. # print(L)
  8519. D['all'] = L
  8520. sensorData("ph")
  8521. elif sensor == 'EC值':
  8522. tank_ec = TankECSensor.query.filter_by(tank_num=int(tank_num)).filter(
  8523. TankECSensor.datetime.between(date_start, date_end)).all()
  8524. for ec in tank_ec:
  8525. l = []
  8526. time = dt.strftime(ec.datetime, '%Y-%b-%d_%H:%M:%S')
  8527. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  8528. l.append(time)
  8529. l.append(ec.ec)
  8530. L.append(l)
  8531. # print(L)
  8532. D['all'] = L
  8533. sensorData("ec")
  8534. elif sensor == '超音波':
  8535. tank_sonic = TankSonicSensor.query.filter_by(tank_num=int(tank_num)).filter(
  8536. TankSonicSensor.datetime.between(date_start, date_end)).all()
  8537. for sonic in tank_sonic:
  8538. l = []
  8539. time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
  8540. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  8541. l.append(time)
  8542. l.append(sonic.sonic)
  8543. L.append(l)
  8544. # print(L)
  8545. D['all'] = L
  8546. sensorData("sonic")
  8547. print(D)
  8548. return json.dumps(D)
  8549. else:
  8550. pass
  8551. # Rita 改寫
  8552. @main.route('/history_data_new', methods=['GET', 'POST'])
  8553. def history_data_new_views():
  8554. if request.method == 'GET':
  8555. info = request.args.to_dict()
  8556. # evt = info['evt']
  8557. tid = info['tid']
  8558. sensor_name = info['sensor_name']
  8559. avg = int(info['avg'])
  8560. max = int(info['max'])
  8561. min = int(info['min'])
  8562. time_interval = info['time-interval']
  8563. print("info:", info)
  8564. # Rita {'evt': '1-溫濕度', 'avg': '1', 'max': '0', 'min': '0', 'time-interval': 'month',
  8565. # 'date-start': '2021-05-04', 'date-end': '2021-05-18'} {'all': [], 'avg': []}
  8566. # print(info)
  8567. # {'evt': '1-溫濕度', 'avg': '1', 'max': '0', 'min': '0', 'time-interval': 'hour', 'date-start': '2021-01-01', 'date-end': '2021-07-27'}
  8568. # print(D)
  8569. # {'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']],
  8570. # 'avg': [['2021-02-19 16:00:00', '24.5'], ['2021-02-19 18:00:00', '25.3']]}
  8571. # 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 -
  8572. date_start = info['date-start']
  8573. date_end_list = info['date-end'].split('-') # 先把 'date-end' 的 '2021-05-18' 拆成 ['2021', '05', '18']
  8574. date_end_list[2] = str(int(date_end_list[2]) + 1) # 18 + 1 = 19 再轉成 str → '19'
  8575. date_end = '-'.join(date_end_list) # '2021-05-19'
  8576. # tank_num = evt.split('-')[0] # 1
  8577. # sensor = evt.split('-')[1] # 溫濕度
  8578. tank_num = tid # D1
  8579. sensor = sensor_name # soil_Temp
  8580. L = []
  8581. D = {}
  8582. maxData = []
  8583. minData = []
  8584. avgData = []
  8585. def sensorData(data_name): # data_name = "tem"
  8586. def dataResample(time_interval, how, data_name): # dataResample('month', how???, "tem") # 下方 "hour"
  8587. interval = 0
  8588. # 設置resample的第一個參數,要按照逐月、逐日或逐時
  8589. if time_interval == 'month':
  8590. interval = "M" # interval = "M"
  8591. elif time_interval == 'day':
  8592. interval = "D"
  8593. elif time_interval == 'hour':
  8594. interval = "H"
  8595. if how == "max":
  8596. # data = df.resample(interval, how={data_name:how})
  8597. # 最新版的pandas
  8598. data = df.resample(interval).max() # 取樣頻率 'H'
  8599. # 刪除有 NaN 的列, any 任何一欄位為空則刪 (all 全部欄位為空值才刪)
  8600. data = data.dropna(axis=0, how='any')
  8601. if time_interval == ('hour' or 'day'):
  8602. data.index = pd.to_datetime(
  8603. data.index, format='%Y-%b-%d_%H:%M:%S') # 将数据类型转换为日期类型
  8604. for a in range(0, len(data.index)):
  8605. l = []
  8606. # 如果是逐時,才顯示小時分秒
  8607. if time_interval == 'hour':
  8608. l.append(str(data.index[a]))
  8609. else:
  8610. l.append(str(data.index[a]).split(' ')[0])
  8611. l.append(str(data[data_name][a]))
  8612. maxData.append(l)
  8613. D['max'] = maxData
  8614. elif how == "mean":
  8615. # data = df.resample(interval, how={data_name:how})
  8616. # 最新版的pandas
  8617. data = df.resample(interval).mean()
  8618. # 刪除具有NaN的值
  8619. data = data.dropna(axis=0, how='any')
  8620. # 將平均數取自小數1位
  8621. data = data.round({data_name: 1})
  8622. for a in range(0, len(data.index)):
  8623. l = []
  8624. # 如果是逐時,才顯示小時分秒
  8625. if time_interval == 'hour':
  8626. l.append(str(data.index[a]))
  8627. else:
  8628. l.append(str(data.index[a]).split(' ')[0])
  8629. l.append(str(data[data_name][a]))
  8630. avgData.append(l)
  8631. D['avg'] = avgData
  8632. elif how == "min":
  8633. # data = df.resample(interval, how={data_name:how})
  8634. # 最新版的pandas
  8635. data = df.resample(interval).min()
  8636. # 刪除具有NaN的值
  8637. data = data.dropna(axis=0, how='any')
  8638. for a in range(0, len(data.index)):
  8639. # print(data.index[a])
  8640. l = []
  8641. # 如果是逐時,才顯示小時分秒
  8642. if time_interval == 'hour':
  8643. l.append(str(data.index[a]))
  8644. else:
  8645. l.append(str(data.index[a]).split(' ')[0])
  8646. l.append(str(data[data_name][a]))
  8647. minData.append(l)
  8648. D['min'] = minData
  8649. df = pd.DataFrame(L, columns=["datetime", data_name]) # 指定欄標籤名稱 為 ["datetime", "tem"]
  8650. df['datetime'] = pd.to_datetime(
  8651. df['datetime'], format='%Y-%b-%d_%H:%M:%S') # 将数据类型转换为日期类型
  8652. #print(df['datetime']) # 0 2021-02-19 16:46:10
  8653. # 1 2021-02-19 16:46:20
  8654. # 2 2021-02-19 16:46:30
  8655. # 3 2021-02-19 16:46:41
  8656. df[data_name] = df[data_name].astype(float)
  8657. df = df.set_index('datetime') # 将datetime设置为index
  8658. #print(df) # datetime tem
  8659. # 2021-02-19 16:46:10 24.4
  8660. # 2021-02-19 16:46:20 24.4
  8661. if time_interval == 'month':
  8662. if max:
  8663. dataResample(time_interval, "max", data_name)
  8664. if avg:
  8665. dataResample(time_interval, "mean", data_name)
  8666. if min:
  8667. dataResample(time_interval, "min", data_name)
  8668. elif time_interval == 'day':
  8669. if max:
  8670. dataResample(time_interval, "max", data_name)
  8671. if avg:
  8672. dataResample(time_interval, "mean", data_name)
  8673. if min:
  8674. dataResample(time_interval, "min", data_name)
  8675. elif time_interval == 'hour':
  8676. if max:
  8677. dataResample(time_interval, "max", data_name)
  8678. if avg:
  8679. dataResample(time_interval, "mean", data_name)
  8680. if min:
  8681. dataResample(time_interval, "min", data_name)
  8682. if tank_num[:1] == 'R':
  8683. if sensor == 'solenoid_water_in':
  8684. tank_actuator = reclaimed_tank_actuator.query.filter(reclaimed_tank_actuator.tank_num==tank_num,reclaimed_tank_actuator.datetime>=date_start,reclaimed_tank_actuator.datetime<=date_end).all()
  8685. db.session.close()
  8686. for solenoid_water_in in tank_actuator:
  8687. l = []
  8688. time = dt.strftime(solenoid_water_in.datetime, '%Y-%b-%d_%H:%M:%S')
  8689. l.append(time)
  8690. l.append(solenoid_water_in.solenoid_water_in)
  8691. L.append(l)
  8692. D['all'] = L
  8693. sensorData("solenoid_water_in")
  8694. elif sensor == 'solenoid_reclaimed_out':
  8695. tank_actuator = reclaimed_tank_actuator.query.filter(reclaimed_tank_actuator.tank_num==tank_num,reclaimed_tank_actuator.datetime>=date_start,reclaimed_tank_actuator.datetime<=date_end).all()
  8696. db.session.close()
  8697. for solenoid_reclaimed_out in tank_actuator:
  8698. l = []
  8699. time = dt.strftime(solenoid_reclaimed_out.datetime, '%Y-%b-%d_%H:%M:%S')
  8700. l.append(time)
  8701. l.append(solenoid_reclaimed_out.solenoid_reclaimed_out)
  8702. L.append(l)
  8703. D['all'] = L
  8704. sensorData("solenoid_reclaimed_out")
  8705. elif sensor == 'solenoid_water_out':
  8706. tank_actuator = reclaimed_tank_actuator.query.filter(reclaimed_tank_actuator.tank_num==tank_num,reclaimed_tank_actuator.datetime>=date_start,reclaimed_tank_actuator.datetime<=date_end).all()
  8707. db.session.close()
  8708. for solenoid_water_out in tank_actuator:
  8709. l = []
  8710. time = dt.strftime(solenoid_water_out.datetime, '%Y-%b-%d_%H:%M:%S')
  8711. l.append(time)
  8712. l.append(solenoid_water_out.solenoid_water_out)
  8713. L.append(l)
  8714. D['all'] = L
  8715. sensorData("solenoid_water_out")
  8716. elif sensor == 'pump_reclaimed_out':
  8717. tank_actuator = reclaimed_tank_actuator.query.filter(reclaimed_tank_actuator.tank_num==tank_num,reclaimed_tank_actuator.datetime>=date_start,reclaimed_tank_actuator.datetime<=date_end).all()
  8718. db.session.close()
  8719. for pump_reclaimed_out in tank_actuator:
  8720. l = []
  8721. time = dt.strftime(pump_reclaimed_out.datetime, '%Y-%b-%d_%H:%M:%S')
  8722. l.append(time)
  8723. l.append(pump_reclaimed_out.pump_reclaimed_out)
  8724. L.append(l)
  8725. D['all'] = L
  8726. sensorData("pump_reclaimed_out")
  8727. elif sensor == 'UltraSonic':
  8728. tank_UltraSonic = reclaimed_tank_sensor.query.filter(reclaimed_tank_sensor.tank_num==tank_num,reclaimed_tank_sensor.datetime>=date_start,reclaimed_tank_sensor.datetime<=date_end).all()
  8729. db.session.close()
  8730. for sonic in tank_UltraSonic:
  8731. l = []
  8732. time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
  8733. l.append(time)
  8734. l.append(sonic.UltraSonic)
  8735. L.append(l)
  8736. D['all'] = L
  8737. sensorData("sonic")
  8738. elif sensor == 'Turbidity':
  8739. tank_sensor = reclaimed_tank_sensor.query.filter(reclaimed_tank_sensor.tank_num==tank_num,reclaimed_tank_sensor.datetime>=date_start,reclaimed_tank_sensor.datetime<=date_end).all()
  8740. db.session.close()
  8741. for Turbidity in tank_sensor:
  8742. l = []
  8743. time = dt.strftime(Turbidity.datetime, '%Y-%b-%d_%H:%M:%S')
  8744. l.append(time)
  8745. l.append(Turbidity.tankTurbidity)
  8746. L.append(l)
  8747. D['all'] = L
  8748. sensorData("Turbidity")
  8749. if tank_num[:1] == 'C':
  8750. if sensor == 'UltraSonic':
  8751. tank_UltraSonic = clean_tank_UltraSonic.query.filter(clean_tank_UltraSonic.tank_num==tank_num,clean_tank_UltraSonic.datetime>=date_start,clean_tank_UltraSonic.datetime<=date_end).all()
  8752. db.session.close()
  8753. for sonic in tank_UltraSonic:
  8754. l = []
  8755. time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
  8756. l.append(time)
  8757. l.append(sonic.UltraSonic)
  8758. L.append(l)
  8759. D['all'] = L
  8760. sensorData("sonic")
  8761. elif sensor == 'motorEncoder':
  8762. tank_motorEncoder = clean_tank_Encoder.query.filter(clean_tank_Encoder.tank_num==tank_num,clean_tank_Encoder.datetime>=date_start,clean_tank_Encoder.datetime<=date_end).all()
  8763. db.session.close()
  8764. for motorEncoder in tank_motorEncoder:
  8765. l = []
  8766. time = dt.strftime(motorEncoder.datetime, '%Y-%b-%d_%H:%M:%S')
  8767. l.append(time)
  8768. l.append(motorEncoder.Encoder)
  8769. L.append(l)
  8770. D['all'] = L
  8771. sensorData("motorEncoder")
  8772. elif sensor == 'butterflyvalve':
  8773. tank_butterflyvalve = clean_tank_butterflyvalve.query.filter(clean_tank_butterflyvalve.tank_num==tank_num,clean_tank_butterflyvalve.datetime>=date_start,clean_tank_butterflyvalve.datetime<=date_end).all()
  8774. db.session.close()
  8775. for butterflyvalve in tank_butterflyvalve:
  8776. l = []
  8777. time = dt.strftime(butterflyvalve.datetime, '%Y-%b-%d_%H:%M:%S')
  8778. l.append(time)
  8779. l.append(butterflyvalve.butterflyvalve)
  8780. L.append(l)
  8781. D['all'] = L
  8782. sensorData("butterflyvalve")
  8783. elif sensor == 'Turbidity':
  8784. tank_Turbidity = clean_tank_Turbidity.query.filter(clean_tank_Turbidity.tank_num==tank_num,clean_tank_Turbidity.datetime>=date_start,clean_tank_Turbidity.datetime<=date_end).all()
  8785. db.session.close()
  8786. for Turbidity in tank_Turbidity:
  8787. l = []
  8788. time = dt.strftime(Turbidity.datetime, '%Y-%b-%d_%H:%M:%S')
  8789. l.append(time)
  8790. l.append(Turbidity.tankTurbidity)
  8791. L.append(l)
  8792. D['all'] = L
  8793. sensorData("Turbidity")
  8794. elif sensor == 'vacuum':
  8795. tank_actuator = cleann_tank_actuator.query.filter(cleann_tank_actuator.tank_num==tank_num,cleann_tank_actuator.datetime>=date_start,cleann_tank_actuator.datetime<=date_end).all()
  8796. db.session.close()
  8797. for vacuum in tank_actuator:
  8798. l = []
  8799. time = dt.strftime(vacuum.datetime, '%Y-%b-%d_%H:%M:%S')
  8800. l.append(time)
  8801. l.append(vacuum.vacuum)
  8802. L.append(l)
  8803. D['all'] = L
  8804. sensorData("vacuum")
  8805. elif sensor == 'threewayvalve_input':
  8806. tank_actuator = cleann_tank_actuator.query.filter(cleann_tank_actuator.tank_num==tank_num,cleann_tank_actuator.datetime>=date_start,cleann_tank_actuator.datetime<=date_end).all()
  8807. db.session.close()
  8808. for threewayvalve_input in tank_actuator:
  8809. l = []
  8810. time = dt.strftime(threewayvalve_input.datetime, '%Y-%b-%d_%H:%M:%S')
  8811. l.append(time)
  8812. l.append(threewayvalve_input.threewayvalve_input)
  8813. L.append(l)
  8814. D['all'] = L
  8815. sensorData("threewayvalve_input")
  8816. elif sensor == 'diskvalve':
  8817. tank_actuator = cleann_tank_actuator.query.filter(cleann_tank_actuator.tank_num==tank_num,cleann_tank_actuator.datetime>=date_start,cleann_tank_actuator.datetime<=date_end).all()
  8818. db.session.close()
  8819. for diskvalve in tank_actuator:
  8820. l = []
  8821. time = dt.strftime(diskvalve.datetime, '%Y-%b-%d_%H:%M:%S')
  8822. l.append(time)
  8823. l.append(diskvalve.diskvalve)
  8824. L.append(l)
  8825. D['all'] = L
  8826. sensorData("diskvalve")
  8827. elif sensor == 'solenoid_tank_disinfect':
  8828. tank_actuator = cleann_tank_actuator.query.filter(cleann_tank_actuator.tank_num==tank_num,cleann_tank_actuator.datetime>=date_start,cleann_tank_actuator.datetime<=date_end).all()
  8829. db.session.close()
  8830. for solenoid_tank_disinfect in tank_actuator:
  8831. l = []
  8832. time = dt.strftime(solenoid_tank_disinfect.datetime, '%Y-%b-%d_%H:%M:%S')
  8833. l.append(time)
  8834. l.append(solenoid_tank_disinfect.solenoid_disinfect)
  8835. L.append(l)
  8836. D['all'] = L
  8837. sensorData("solenoid_disinfect")
  8838. elif sensor == 'solenoid_tank_water_in':
  8839. tank_actuator = cleann_tank_actuator.query.filter(cleann_tank_actuator.tank_num==tank_num,cleann_tank_actuator.datetime>=date_start,cleann_tank_actuator.datetime<=date_end).all()
  8840. db.session.close()
  8841. for solenoid_tank_water_in in tank_actuator:
  8842. l = []
  8843. time = dt.strftime(solenoid_tank_water_in.datetime, '%Y-%b-%d_%H:%M:%S')
  8844. l.append(time)
  8845. l.append(solenoid_tank_water_in.solenoid_water_in)
  8846. L.append(l)
  8847. D['all'] = L
  8848. sensorData("solenoid_water_in")
  8849. elif sensor == 'solenoid_tank_water_out':
  8850. tank_actuator = cleann_tank_actuator.query.filter(cleann_tank_actuator.tank_num==tank_num,cleann_tank_actuator.datetime>=date_start,cleann_tank_actuator.datetime<=date_end).all()
  8851. db.session.close()
  8852. for solenoid_tank_water_out in tank_actuator:
  8853. l = []
  8854. time = dt.strftime(solenoid_tank_water_out.datetime, '%Y-%b-%d_%H:%M:%S')
  8855. l.append(time)
  8856. l.append(solenoid_tank_water_out.solenoid_water_out)
  8857. L.append(l)
  8858. D['all'] = L
  8859. sensorData("solenoid_water_out")
  8860. elif sensor == 'solenoid_reclaimed_in':
  8861. tank_actuator = cleann_tank_actuator.query.filter( cleann_tank_actuator.tank_num==tank_num,cleann_tank_actuator.datetime>=date_start, cleann_tank_actuator.datetime<=date_end).all()
  8862. db.session.close()
  8863. for solenoid_reclaimed_in in tank_actuator:
  8864. l = []
  8865. time = dt.strftime(solenoid_reclaimed_in.datetime, '%Y-%b-%d_%H:%M:%S')
  8866. l.append(time)
  8867. l.append(solenoid_reclaimed_in.solenoid_reclaimed_in)
  8868. L.append(l)
  8869. D['all'] = L
  8870. sensorData("solenoid_reclaimed_in")
  8871. elif sensor == 'solenoid_reclaimed_out':
  8872. tank_actuator = cleann_tank_actuator.query.filter( cleann_tank_actuator.tank_num==tank_num, cleann_tank_actuator.datetime>=date_start, cleann_tank_actuator.datetime<=date_end).all()
  8873. db.session.close()
  8874. for solenoid_reclaimed_out in tank_actuator:
  8875. l = []
  8876. time = dt.strftime(solenoid_reclaimed_out.datetime, '%Y-%b-%d_%H:%M:%S')
  8877. l.append(time)
  8878. l.append(solenoid_reclaimed_out.solenoid_reclaimed_out)
  8879. L.append(l)
  8880. D['all'] = L
  8881. sensorData("solenoid_reclaimed_out")
  8882. elif sensor == 'pump_disinfect':
  8883. tank_actuator = cleann_tank_actuator.query.filter( cleann_tank_actuator.tank_num==tank_num, cleann_tank_actuator.datetime>=date_start, cleann_tank_actuator.datetime<=date_end).all()
  8884. db.session.close()
  8885. for pump_disinfect in tank_actuator:
  8886. l = []
  8887. time = dt.strftime(pump_disinfect.datetime, '%Y-%b-%d_%H:%M:%S')
  8888. l.append(time)
  8889. l.append(pump_disinfect.pump_disinfect)
  8890. L.append(l)
  8891. D['all'] = L
  8892. sensorData("pump_disinfect")
  8893. elif sensor == 'pump_water_in':
  8894. tank_actuator = cleann_tank_actuator.query.filter( cleann_tank_actuator.tank_num==tank_num, cleann_tank_actuator.datetime>=date_start, cleann_tank_actuator.datetime<=date_end).all()
  8895. db.session.close()
  8896. for pump_water_in in tank_actuator:
  8897. l = []
  8898. time = dt.strftime(pump_water_in.datetime, '%Y-%b-%d_%H:%M:%S')
  8899. l.append(time)
  8900. l.append(pump_water_in.pump_water_in)
  8901. L.append(l)
  8902. D['all'] = L
  8903. sensorData("pump_water_in")
  8904. elif sensor == 'motor':
  8905. tank_actuator = cleann_tank_actuator.query.filter( cleann_tank_actuator.tank_num==tank_num, cleann_tank_actuator.datetime>=date_start, cleann_tank_actuator.datetime<=date_end).all()
  8906. db.session.close()
  8907. for motor in tank_actuator:
  8908. l = []
  8909. time = dt.strftime(motor.datetime, '%Y-%b-%d_%H:%M:%S')
  8910. l.append(time)
  8911. l.append(motor.motor)
  8912. L.append(l)
  8913. D['all'] = L
  8914. sensorData("motor")
  8915. elif sensor == 'warning_light':
  8916. tank_actuator = cleann_tank_actuator.query.filter( cleann_tank_actuator.tank_num==tank_num, cleann_tank_actuator.datetime>=date_start, cleann_tank_actuator.datetime<=date_end).all()
  8917. db.session.close()
  8918. for warning_light in tank_actuator:
  8919. l = []
  8920. time = dt.strftime(warning_light.datetime, '%Y-%b-%d_%H:%M:%S')
  8921. l.append(time)
  8922. l.append(warning_light.warning_light)
  8923. L.append(l)
  8924. D['all'] = L
  8925. sensorData("warning_light")
  8926. if tank_num[:2] == 'CI':
  8927. print(date_start)
  8928. print(date_end)
  8929. if sensor == 'UltraSonic':
  8930. tank_UltraSonic = clean_input_sensor.query.filter( clean_input_sensor.tank_num==tank_num, clean_input_sensor.datetime>=date_start, clean_input_sensor.datetime<=date_end).all()
  8931. db.session.close()
  8932. for sonic in tank_UltraSonic:
  8933. l = []
  8934. time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
  8935. l.append(time)
  8936. l.append(sonic.UltraSonic)
  8937. L.append(l)
  8938. print( "L",L)
  8939. D['all'] = L
  8940. sensorData("UltraSonic")
  8941. elif sensor == 'vacuum':
  8942. input_actuator = clean_input_actuator.query.filter(clean_input_sensor.tank_num==tank_num,clean_input_sensor.datetime>=date_start,clean_input_sensor.datetime<=date_end).all()
  8943. db.session.close()
  8944. for vacuum in input_actuator:
  8945. l = []
  8946. time = dt.strftime(vacuum.datetime, '%Y-%b-%d_%H:%M:%S')
  8947. l.append(time)
  8948. l.append(vacuum.vacuum)
  8949. L.append(l)
  8950. D['all'] = L
  8951. sensorData("vacuum")
  8952. if tank_num[:1] == 'S':
  8953. if sensor == 'color':
  8954. tank_color = colorselect_tank_color.query.filter(colorselect_tank_color.tank_num==tank_num,colorselect_tank_color.datetime>=date_start,colorselect_tank_color.datetime<=date_end).all()
  8955. db.session.close()
  8956. for color in tank_color:
  8957. l = []
  8958. time = dt.strftime(color.datetime, '%Y-%b-%d_%H:%M:%S')
  8959. l.append(time)
  8960. l.append(color.color)
  8961. L.append(l)
  8962. D['all'] = L
  8963. sensorData("color")
  8964. elif sensor == 'vacuum':
  8965. tank_actuator = colorselect_tank_actuator.query.filter(colorselect_tank_actuator.tank_num==tank_num,colorselect_tank_actuator.datetime>=date_start,colorselect_tank_actuator.datetime<=date_end).all()
  8966. db.session.close()
  8967. for vacuum in tank_actuator:
  8968. l = []
  8969. time = dt.strftime(vacuum.datetime, '%Y-%b-%d_%H:%M:%S')
  8970. l.append(time)
  8971. l.append(vacuum.vacuum)
  8972. L.append(l)
  8973. D['all'] = L
  8974. sensorData("vacuum")
  8975. elif sensor == 'motor':
  8976. tank_actuator = colorselect_tank_actuator.query.filter(colorselect_tank_actuator.tank_num==tank_num,colorselect_tank_actuator.datetime>=date_start,colorselect_tank_actuator.datetime<=date_end).all()
  8977. db.session.close()
  8978. for motor in tank_actuator:
  8979. l = []
  8980. time = dt.strftime(motor.datetime, '%Y-%b-%d_%H:%M:%S')
  8981. l.append(time)
  8982. l.append(motor.motor)
  8983. L.append(l)
  8984. D['all'] = L
  8985. sensorData("motor")
  8986. elif sensor == 'nozzle':
  8987. tank_actuator = colorselect_tank_actuator.query.filter(colorselect_tank_actuator.tank_num==tank_num,colorselect_tank_actuator.datetime>=date_start,colorselect_tank_actuator.datetime<=date_end).all()
  8988. db.session.close()
  8989. for nozzle in tank_actuator:
  8990. l = []
  8991. time = dt.strftime(nozzle.datetime, '%Y-%b-%d_%H:%M:%S')
  8992. l.append(time)
  8993. l.append(nozzle.nozzle)
  8994. L.append(l)
  8995. D['all'] = L
  8996. sensorData("nozzle")
  8997. if tank_num[:2] == 'SO':
  8998. if sensor == 'UltraSonic':
  8999. tank_UltraSonic = colorselect_tank_UltraSonic.query.filter(colorselect_tank_UltraSonic.tank_num==tank_num,colorselect_tank_UltraSonic.datetime>=date_start,colorselect_tank_UltraSonic.datetime<=date_end).all()
  9000. db.session.close()
  9001. for sonic in tank_UltraSonic:
  9002. l = []
  9003. time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
  9004. l.append(time)
  9005. l.append(sonic.UltraSonic)
  9006. L.append(l)
  9007. D['all'] = L
  9008. sensorData("UltraSonic")
  9009. elif sensor == 'vacuum':
  9010. output_actuator = colorselect_output_actuator.query.filter(colorselect_output_actuator.tank_num==tank_num,colorselect_output_actuator.datetime>=date_start,colorselect_output_actuator.datetime<=date_end).all()
  9011. db.session.close()
  9012. for vacuum in output_actuator:
  9013. l = []
  9014. time = dt.strftime(vacuum.datetime, '%Y-%b-%d_%H:%M:%S')
  9015. l.append(time)
  9016. l.append(vacuum.vacuum)
  9017. L.append(l)
  9018. D['all'] = L
  9019. sensorData("vacuum")
  9020. if tank_num[:1] == 'P':
  9021. if sensor == 'motorEncoder':
  9022. tank_motorEncoder = peel_output_motorEncoder.query.filter(peel_output_motorEncoder.tank_num==tank_num,peel_output_motorEncoder.datetime>=date_start,peel_output_motorEncoder.datetime<=date_end).all()
  9023. db.session.close()
  9024. for motorEncoder in tank_motorEncoder:
  9025. l = []
  9026. time = dt.strftime(motorEncoder.datetime, '%Y-%b-%d_%H:%M:%S')
  9027. l.append(time)
  9028. l.append(motorEncoder.motorEncoder)
  9029. L.append(l)
  9030. D['all'] = L
  9031. sensorData("motorEncoder")
  9032. elif sensor == 'vacuum':
  9033. tank_actuator = peel_tank_actuator.query.filter(peel_tank_actuator.tank_num==tank_num,peel_tank_actuator.datetime>=date_start,peel_tank_actuator.datetime<=date_end).all()
  9034. db.session.close()
  9035. for vacuum in tank_actuator:
  9036. l = []
  9037. time = dt.strftime(vacuum.datetime, '%Y-%b-%d_%H:%M:%S')
  9038. l.append(time)
  9039. l.append(vacuum.vacuum)
  9040. L.append(l)
  9041. D['all'] = L
  9042. sensorData("vacuum")
  9043. elif sensor == 'motor':
  9044. tank_actuator = peel_tank_actuator.query.filter(peel_tank_actuator.tank_num==tank_num,peel_tank_actuator.datetime>=date_start,peel_tank_actuator.datetime<=date_end).all()
  9045. db.session.close()
  9046. for motor in tank_actuator:
  9047. l = []
  9048. time = dt.strftime(motor.datetime, '%Y-%b-%d_%H:%M:%S')
  9049. l.append(time)
  9050. l.append(motor.motor)
  9051. L.append(l)
  9052. D['all'] = L
  9053. sensorData("motor")
  9054. if tank_num[:2] == 'PO':
  9055. if sensor == 'UltraSonic':
  9056. tank_UltraSonic = peel_output_UltraSonic.query.filter(peel_output_UltraSonic.tank_num==tank_num,peel_output_UltraSonic.datetime>=date_start,peel_output_UltraSonic.datetime<=date_end).all()
  9057. db.session.close()
  9058. for sonic in tank_UltraSonic:
  9059. l = []
  9060. time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
  9061. l.append(time)
  9062. l.append(sonic.UltraSonic)
  9063. L.append(l)
  9064. D['all'] = L
  9065. sensorData("UltraSonic")
  9066. elif sensor == 'vacuum':
  9067. output_actuator = peel_output_actuator.query.filter(peel_output_actuator.tank_num==tank_num,peel_output_actuator.datetime>=date_start,peel_output_actuator.datetime<=date_end).all()
  9068. db.session.close()
  9069. for vacuum in output_actuator:
  9070. l = []
  9071. time = dt.strftime(vacuum.datetime, '%Y-%b-%d_%H:%M:%S')
  9072. l.append(time)
  9073. l.append(vacuum.vacuum)
  9074. L.append(l)
  9075. D['all'] = L
  9076. sensorData("vacuum")
  9077. if tank_num[:2] == 'DI':
  9078. # 乾燥入料儲豆槽
  9079. if sensor == 'UltraSonic':
  9080. tank_UltraSonic = dry_input_sensor.query.filter(dry_input_sensor.tank_num==tank_num,dry_input_sensor.datetime>=date_start,dry_input_sensor.datetime<=date_end).all()
  9081. db.session.close()
  9082. for sonic in tank_UltraSonic:
  9083. l = []
  9084. time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
  9085. l.append(time)
  9086. l.append(sonic.UltraSonic)
  9087. L.append(l)
  9088. D['all'] = L
  9089. sensorData("UltraSonic")
  9090. elif sensor == 'vacuum':
  9091. input_actuator = dry_input_brake.query.filter(dry_input_brake.tank_num==tank_num,dry_input_brake.datetime>=date_start,dry_input_brake.datetime<=date_end).all()
  9092. db.session.close()
  9093. for vacuum in input_actuator:
  9094. l = []
  9095. time = dt.strftime(vacuum.datetime, '%Y-%b-%d_%H:%M:%S')
  9096. l.append(time)
  9097. l.append(vacuum.vacuum)
  9098. L.append(l)
  9099. D['all'] = L
  9100. sensorData("vacuum")
  9101. elif tank_num[:2] == 'DO':
  9102. # 乾燥出料儲豆槽
  9103. if sensor == 'UltraSonic':
  9104. tank_UltraSonic = dry_output_sensor.query.filter(dry_output_sensor.tank_num==tank_num,dry_output_sensor.datetime>=date_start,dry_output_sensor.datetime<=date_end).all()
  9105. db.session.close()
  9106. for sonic in tank_UltraSonic:
  9107. l = []
  9108. time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
  9109. l.append(time)
  9110. l.append(sonic.UltraSonic)
  9111. L.append(l)
  9112. D['all'] = L
  9113. sensorData("UltraSonic")
  9114. elif sensor == 'vacuum':
  9115. output_actuator = dry_output_brake.query.filter(dry_output_brake.tank_num==tank_num,dry_output_brake.datetime>=date_start,dry_output_brake.datetime<=date_end).all()
  9116. db.session.close()
  9117. for vacuum in output_actuator:
  9118. l = []
  9119. time = dt.strftime(vacuum.datetime, '%Y-%b-%d_%H:%M:%S')
  9120. l.append(time)
  9121. l.append(vacuum.vacuum)
  9122. L.append(l)
  9123. D['all'] = L
  9124. sensorData("vacuum")
  9125. elif tank_num[:1] == 'D':
  9126. # 乾燥槽
  9127. if sensor == 'SHT11_Temp':
  9128. tank_tem = dry_tank_SHT11.query.filter(dry_tank_SHT11.tank_num==tank_num,dry_tank_SHT11.datetime>=date_start,dry_tank_SHT11.datetime<=date_end).all()
  9129. db.session.close()
  9130. for tem in tank_tem:
  9131. l = [] # l = []
  9132. time = dt.strftime(tem.datetime, '%Y-%b-%d_%H:%M:%S') # time = '2021-Feb-19_16:46:10' 轉換時間格式
  9133. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  9134. l.append(time) # l = ['2021-Feb-19_16:46:10']
  9135. #l.append(tem.tem) # l = ['2021-Feb-19_16:46:10', '24.4']
  9136. l.append(tem.SHT11_Temp)
  9137. L.append(l) # L = [['2021-Feb-19_16:46:10', '24.4']]
  9138. # print(L)
  9139. D['all'] = L # D = {'all': [['2021-Feb-19_16:46:10', '24.4']]} # all 所有符合數據
  9140. sensorData("SHT11_Temp")
  9141. elif sensor == 'SHT11_Humidity':
  9142. tank_hum = dry_tank_SHT11.query.filter(dry_tank_SHT11.tank_num==tank_num,dry_tank_SHT11.datetime>=date_start,dry_tank_SHT11.datetime<=date_end).all()
  9143. db.session.close()
  9144. for hum in tank_hum:
  9145. l = []
  9146. time = dt.strftime(hum.datetime, '%Y-%b-%d_%H:%M:%S')
  9147. l.append(time)
  9148. l.append(hum.SHT11_Humidity)
  9149. L.append(l)
  9150. D['all'] = L
  9151. sensorData("SHT11_Humidity")
  9152. elif sensor == 'UltraSonic':
  9153. tank_UltraSonic = dry_tank_UltraSonic.query.filter(dry_tank_UltraSonic.tank_num==tank_num,dry_tank_UltraSonic.datetime>=date_start,dry_tank_UltraSonic.datetime<=date_end).all()
  9154. db.session.close()
  9155. for sonic in tank_UltraSonic:
  9156. l = []
  9157. time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
  9158. l.append(time)
  9159. l.append(sonic.UltraSonic)
  9160. L.append(l)
  9161. D['all'] = L
  9162. sensorData("UltraSonic")
  9163. elif sensor == 'PA':
  9164. tank_PA = dry_tank_PA.query.filter(dry_tank_PA.tank_num==tank_num,dry_tank_PA.datetime>=date_start,dry_tank_PA.datetime<=date_end).all()
  9165. db.session.close()
  9166. for pa in tank_PA:
  9167. l = []
  9168. time = dt.strftime(pa.datetime, '%Y-%b-%d_%H:%M:%S')
  9169. l.append(time)
  9170. l.append(pa.PA)
  9171. L.append(l)
  9172. D['all'] = L
  9173. sensorData("PA")
  9174. elif sensor == 'WaterLevel':
  9175. tank_WaterLevel = dry_tank_WaterLevel.query.filter(dry_tank_WaterLevel.tank_num==tank_num,dry_tank_WaterLevel.datetime>=date_start,dry_tank_WaterLevel.datetime<=date_end).all()
  9176. db.session.close()
  9177. for WaterLevel in tank_WaterLevel:
  9178. l = []
  9179. time = dt.strftime(WaterLevel.datetime, '%Y-%b-%d_%H:%M:%S')
  9180. l.append(time)
  9181. l.append(WaterLevel.WaterLevel)
  9182. L.append(l)
  9183. D['all'] = L
  9184. sensorData("WaterLevel")
  9185. elif sensor == 'butterflyvalve':
  9186. tank_butterflyvalve = dry_tank_butterflyvalve.query.filter(dry_tank_butterflyvalve.tank_num==tank_num,dry_tank_butterflyvalve.datetime>=date_start,dry_tank_butterflyvalve.datetime<=date_end).all()
  9187. db.session.close()
  9188. for butterflyvalve in tank_butterflyvalve:
  9189. l = []
  9190. time = dt.strftime(butterflyvalve.datetime, '%Y-%b-%d_%H:%M:%S')
  9191. l.append(time)
  9192. l.append(butterflyvalve.butterflyvalve)
  9193. L.append(l)
  9194. D['all'] = L
  9195. sensorData("butterflyvalve")
  9196. elif sensor == 'motorEncoder':
  9197. tank_motorEncoder = dry_tank_motorEncoder.query.filter(dry_tank_motorEncoder.tank_num==tank_num,dry_tank_motorEncoder.datetime>=date_start,dry_tank_motorEncoder.datetime<=date_end).all()
  9198. db.session.close()
  9199. for motorEncoder in tank_motorEncoder:
  9200. l = []
  9201. time = dt.strftime(motorEncoder.datetime, '%Y-%b-%d_%H:%M:%S')
  9202. l.append(time)
  9203. l.append(motorEncoder.motorEncoder)
  9204. L.append(l)
  9205. D['all'] = L
  9206. sensorData("motorEncoder")
  9207. elif sensor == 'soil_Temp':
  9208. tank_soiltemp = dry_tank_Soil.query.filter(dry_tank_Soil.tank_num==tank_num,dry_tank_Soil.datetime>=date_start,dry_tank_Soil.datetime<=date_end).all()
  9209. db.session.close()
  9210. for temp in tank_soiltemp:
  9211. l = []
  9212. time = dt.strftime(temp.datetime, '%Y-%b-%d_%H:%M:%S')
  9213. l.append(time)
  9214. l.append(temp.soil_Temp)
  9215. L.append(l)
  9216. D['all'] = L
  9217. sensorData("soil_Temp")
  9218. elif sensor == 'soil_Humidity':
  9219. tank_soilHum = dry_tank_Soil.query.filter(dry_tank_Soil.tank_num==tank_num,dry_tank_Soil.datetime>=date_start,dry_tank_Soil.datetime<=date_end).all()
  9220. db.session.close()
  9221. for hum in tank_soilHum:
  9222. l = []
  9223. time = dt.strftime(hum.datetime, '%Y-%b-%d_%H:%M:%S')
  9224. l.append(time)
  9225. l.append(hum.soil_Humidity)
  9226. L.append(l)
  9227. D['all'] = L
  9228. sensorData("soil_Humidity")
  9229. elif sensor == 'soil_EC':
  9230. tank_soilec = dry_tank_Soil.query.filter(dry_tank_Soil.tank_num==tank_num,dry_tank_Soil.datetime>=date_start,dry_tank_Soil.datetime<=date_end).all()
  9231. db.session.close()
  9232. for ec in tank_soilec:
  9233. l = []
  9234. time = dt.strftime(ec.datetime, '%Y-%b-%d_%H:%M:%S')
  9235. # time = dt.strftime(tem.datetime, '%Y-%m-%d')
  9236. l.append(time)
  9237. l.append(ec.soil_EC)
  9238. L.append(l)
  9239. D['all'] = L
  9240. sensorData("soil_EC")
  9241. elif sensor == 'vacuum':
  9242. tank_actuator = dry_tank_brake.query.filter(dry_tank_brake.tank_num==tank_num,dry_tank_brake.datetime>=date_start,dry_tank_brake.datetime<=date_end).all()
  9243. db.session.close()
  9244. for vacuum in tank_actuator:
  9245. l = []
  9246. time = dt.strftime(vacuum.datetime, '%Y-%b-%d_%H:%M:%S')
  9247. l.append(time)
  9248. l.append(vacuum.vacuum)
  9249. L.append(l)
  9250. D['all'] = L
  9251. sensorData("vacuum")
  9252. elif sensor == 'threewayvalve_input':
  9253. tank_actuator = dry_tank_brake.query.filter(dry_tank_brake.tank_num==tank_num,dry_tank_brake.datetime>=date_start,dry_tank_brake.datetime<=date_end).all()
  9254. db.session.close()
  9255. for threewayvalve_input in tank_actuator:
  9256. l = []
  9257. time = dt.strftime(threewayvalve_input.datetime, '%Y-%b-%d_%H:%M:%S')
  9258. l.append(time)
  9259. l.append(threewayvalve_input.threewayvalve_input)
  9260. L.append(l)
  9261. D['all'] = L
  9262. sensorData("threewayvalve_input")
  9263. elif sensor == 'diskvalve':
  9264. tank_actuator = dry_tank_brake.query.filter(dry_tank_brake.tank_num==tank_num,dry_tank_brake.datetime>=date_start,dry_tank_brake.datetime<=date_end).all()
  9265. db.session.close()
  9266. for diskvalve in tank_actuator:
  9267. l = []
  9268. time = dt.strftime(diskvalve.datetime, '%Y-%b-%d_%H:%M:%S')
  9269. l.append(time)
  9270. l.append(diskvalve.diskvalve)
  9271. L.append(l)
  9272. D['all'] = L
  9273. sensorData("diskvalve")
  9274. elif sensor == 'solenoid_disinfect':
  9275. tank_actuator = dry_tank_brake.query.filter(dry_tank_brake.tank_num==tank_num,dry_tank_brake.datetime>=date_start,dry_tank_brake.datetime<=date_end).all()
  9276. db.session.close()
  9277. for solenoid_disinfect in tank_actuator:
  9278. l = []
  9279. time = dt.strftime(solenoid_disinfect.datetime, '%Y-%b-%d_%H:%M:%S')
  9280. l.append(time)
  9281. l.append(solenoid_disinfect.solenoid_disinfect)
  9282. L.append(l)
  9283. D['all'] = L
  9284. sensorData("solenoid_disinfect")
  9285. elif sensor == 'solenoid_water_out':
  9286. tank_actuator = dry_tank_brake.query.filter(dry_tank_brake.tank_num==tank_num,dry_tank_brake.datetime>=date_start,dry_tank_brake.datetime<=date_end).all()
  9287. db.session.close()
  9288. for solenoid_water_out in tank_actuator:
  9289. l = []
  9290. time = dt.strftime(solenoid_water_out.datetime, '%Y-%b-%d_%H:%M:%S')
  9291. l.append(time)
  9292. l.append(solenoid_water_out.solenoid_water_out)
  9293. L.append(l)
  9294. D['all'] = L
  9295. sensorData("solenoid_water_out")
  9296. elif sensor == 'solenoid_outer_water':
  9297. tank_actuator = dry_tank_brake.query.filter(dry_tank_brake.tank_num==tank_num,dry_tank_brake.datetime>=date_start,dry_tank_brake.datetime<=date_end).all()
  9298. db.session.close()
  9299. for solenoid_outer_water in tank_actuator:
  9300. l = []
  9301. time = dt.strftime(solenoid_outer_water.datetime, '%Y-%b-%d_%H:%M:%S')
  9302. l.append(time)
  9303. l.append(solenoid_outer_water.solenoid_outer_water)
  9304. L.append(l)
  9305. D['all'] = L
  9306. sensorData("solenoid_outer_water")
  9307. elif sensor == 'Warning_Light':
  9308. tank_actuator = dry_tank_brake.query.filter(dry_tank_brake.tank_num==tank_num,dry_tank_brake.datetime>=date_start,dry_tank_brake.datetime<=date_end).all()
  9309. db.session.close()
  9310. for warning_light in tank_actuator:
  9311. l = []
  9312. time = dt.strftime(warning_light.datetime, '%Y-%b-%d_%H:%M:%S')
  9313. l.append(time)
  9314. l.append(warning_light.warning_light)
  9315. L.append(l)
  9316. D['all'] = L
  9317. sensorData("warning_light")
  9318. elif sensor == 'vacuum_pump':
  9319. tank_actuator = dry_tank_brake.query.filter(dry_tank_brake.tank_num==tank_num,dry_tank_brake.datetime>=date_start,dry_tank_brake.datetime<=date_end).all()
  9320. db.session.close()
  9321. for vacuum_pump in tank_actuator:
  9322. l = []
  9323. time = dt.strftime(vacuum_pump.datetime, '%Y-%b-%d_%H:%M:%S')
  9324. l.append(time)
  9325. l.append(vacuum_pump.vacuum_pump)
  9326. L.append(l)
  9327. D['all'] = L
  9328. sensorData("vacuum_pump")
  9329. elif sensor == 'heater1':
  9330. tank_actuator = dry_tank_brake.query.filter(dry_tank_brake.tank_num==tank_num,dry_tank_brake.datetime>=date_start,dry_tank_brake.datetime<=date_end).all()
  9331. db.session.close()
  9332. for heater1 in tank_actuator:
  9333. l = []
  9334. time = dt.strftime(heater1.datetime, '%Y-%b-%d_%H:%M:%S')
  9335. l.append(time)
  9336. l.append(heater1.heater1)
  9337. L.append(l)
  9338. D['all'] = L
  9339. sensorData("heater1")
  9340. elif sensor == 'heater2':
  9341. tank_actuator = dry_tank_brake.query.filter(dry_tank_brake.tank_num==tank_num,dry_tank_brake.datetime>=date_start,dry_tank_brake.datetime<=date_end).all()
  9342. db.session.close()
  9343. for heater2 in tank_actuator:
  9344. l = []
  9345. time = dt.strftime(heater2.datetime, '%Y-%b-%d_%H:%M:%S')
  9346. l.append(time)
  9347. l.append(heater2.heater2)
  9348. L.append(l)
  9349. D['all'] = L
  9350. sensorData("heater2")
  9351. elif sensor == 'motor':
  9352. tank_actuator = dry_tank_brake.query.filter(dry_tank_brake.tank_num==tank_num,dry_tank_brake.datetime>=date_start,dry_tank_brake.datetime<=date_end).all()
  9353. db.session.close()
  9354. for motor in tank_actuator:
  9355. l = []
  9356. time = dt.strftime(motor.datetime, '%Y-%b-%d_%H:%M:%S')
  9357. l.append(time)
  9358. l.append(motor.motor)
  9359. L.append(l)
  9360. D['all'] = L
  9361. sensorData("motor")
  9362. elif tank_num[:2] == 'FI':
  9363. if sensor == 'UltraSonic':
  9364. input_UltraSonic = ferment_input_UltraSonic.query.filter(ferment_input_UltraSonic.tank_num==tank_num,ferment_input_UltraSonic.datetime>=date_start,ferment_input_UltraSonic.datetime<=date_end).all()
  9365. db.session.close()
  9366. for UltraSonic in input_UltraSonic:
  9367. l = []
  9368. time = dt.strftime(UltraSonic.datetime, '%Y-%b-%d_%H:%M:%S')
  9369. l.append(time)
  9370. l.append(UltraSonic.UltraSonic)
  9371. L.append(l)
  9372. D['all'] = L
  9373. sensorData("UltraSonic")
  9374. elif sensor == 'vacuum':
  9375. input_actuator = ferment_input_actuator.query.filter(ferment_input_actuator.tank_num==tank_num,ferment_input_actuator.datetime>=date_start,ferment_input_actuator.datetime<=date_end).all()
  9376. db.session.close()
  9377. for vacuum in input_actuator:
  9378. l = []
  9379. time = dt.strftime(vacuum.datetime, '%Y-%b-%d_%H:%M:%S')
  9380. l.append(time)
  9381. l.append(vacuum.vacuum)
  9382. L.append(l)
  9383. D['all'] = L
  9384. sensorData("vacuum")
  9385. elif tank_num[:2] == 'FO':
  9386. if sensor == 'UltraSonic':
  9387. output_UltraSonic = ferment_output_UltraSonic.query.filter(ferment_output_UltraSonic.tank_num==tank_num,ferment_output_UltraSonic.datetime>=date_start,ferment_output_UltraSonic.datetime<=date_end).all()
  9388. db.session.close()
  9389. for UltraSonic in output_UltraSonic:
  9390. l = []
  9391. time = dt.strftime(UltraSonic.datetime, '%Y-%b-%d_%H:%M:%S')
  9392. l.append(time)
  9393. l.append(UltraSonic.UltraSonic)
  9394. L.append(l)
  9395. D['all'] = L
  9396. sensorData("UltraSonic")
  9397. elif sensor == 'vacuum':
  9398. output_actuator = ferment_output_actuator.query.filter(ferment_output_actuator.tank_num==tank_num,ferment_output_actuator.datetime>=date_start,ferment_output_actuator.datetime<=date_end).all()
  9399. db.session.close()
  9400. for vacuum in output_actuator:
  9401. l = []
  9402. time = dt.strftime(vacuum.datetime, '%Y-%b-%d_%H:%M:%S')
  9403. l.append(time)
  9404. l.append(vacuum.vacuum)
  9405. L.append(l)
  9406. D['all'] = L
  9407. sensorData("vacuum")
  9408. elif tank_num[:1] == 'F':
  9409. if sensor == 'UltraSonic':
  9410. tank_UltraSonic = ferment_tank_UltraSonic.query.filter(ferment_tank_UltraSonic.tank_num==tank_num,ferment_tank_UltraSonic.datetime>=date_start,ferment_tank_UltraSonic.datetime<=date_end).all()
  9411. db.session.close()
  9412. for UltraSonic in tank_UltraSonic:
  9413. l = []
  9414. time = dt.strftime(UltraSonic.datetime, '%Y-%b-%d_%H:%M:%S')
  9415. l.append(time)
  9416. l.append(UltraSonic.UltraSonic)
  9417. L.append(l)
  9418. D['all'] = L
  9419. sensorData("UltraSonic")
  9420. elif sensor == 'motorEncoder':
  9421. tank_motorEncoder = ferment_tank_motorEncoder.query.filter(ferment_tank_motorEncoder.tank_num==tank_num,ferment_tank_motorEncoder.datetime>=date_start,ferment_tank_motorEncoder.datetime<=date_end).all()
  9422. db.session.close()
  9423. for motorEncoder in tank_motorEncoder:
  9424. l = []
  9425. time = dt.strftime(motorEncoder.datetime, '%Y-%b-%d_%H:%M:%S')
  9426. l.append(time)
  9427. l.append(motorEncoder.motorEncoder)
  9428. L.append(l)
  9429. D['all'] = L
  9430. sensorData("motorEncoder")
  9431. elif sensor == 'butterflyvalve':
  9432. tank_butterflyvalve = ferment_tank_butterflyvalve.query.filter(ferment_tank_butterflyvalve.tank_num==tank_num,ferment_tank_butterflyvalve.datetime>=date_start,ferment_tank_butterflyvalve.datetime<=date_end).all()
  9433. db.session.close()
  9434. for butterflyvalve in tank_butterflyvalve:
  9435. l = []
  9436. time = dt.strftime(butterflyvalve.datetime, '%Y-%b-%d_%H:%M:%S')
  9437. l.append(time)
  9438. l.append(butterflyvalve.butterflyvalve)
  9439. L.append(l)
  9440. D['all'] = L
  9441. sensorData("butterflyvalve")
  9442. elif sensor == 'WaterLevel':
  9443. tank_WaterLevel = ferment_tank_WaterLevel.query.filter(ferment_tank_WaterLevel.tank_num==tank_num,ferment_tank_WaterLevel.datetime>=date_start,ferment_tank_WaterLevel.datetime<=date_end).all()
  9444. db.session.close()
  9445. for WaterLevel in tank_WaterLevel:
  9446. l = []
  9447. time = dt.strftime(WaterLevel.datetime, '%Y-%b-%d_%H:%M:%S')
  9448. l.append(time)
  9449. l.append(WaterLevel.WaterLevel)
  9450. L.append(l)
  9451. D['all'] = L
  9452. sensorData("WaterLevel")
  9453. elif sensor == 'SHT11_Temp':
  9454. tank_Temp = ferment_tank_SHT11.query.filter(ferment_tank_SHT11.tank_num==tank_num,ferment_tank_SHT11.datetime>=date_start,ferment_tank_SHT11.datetime<=date_end).all()
  9455. db.session.close()
  9456. for Temp in tank_Temp:
  9457. l = []
  9458. time = dt.strftime(Temp.datetime, '%Y-%b-%d_%H:%M:%S')
  9459. l.append(time)
  9460. l.append(Temp.SHT11_Temp)
  9461. L.append(l)
  9462. D['all'] = L
  9463. sensorData("SHT11_Temp")
  9464. elif sensor == 'SHT11_Humidity':
  9465. tank_Humidity = ferment_tank_SHT11.query.filter(ferment_tank_SHT11.tank_num==tank_num,ferment_tank_SHT11.datetime>=date_start,ferment_tank_SHT11.datetime<=date_end).all()
  9466. db.session.close()
  9467. for Humidity in tank_Humidity:
  9468. l = []
  9469. time = dt.strftime(Humidity.datetime, '%Y-%b-%d_%H:%M:%S')
  9470. l.append(time)
  9471. l.append(Humidity.SHT11_Humidity)
  9472. L.append(l)
  9473. D['all'] = L
  9474. sensorData("SHT11_Humidity")
  9475. elif sensor == 'CO2':
  9476. tank_CO2 = ferment_tank_CO2.query.filter(ferment_tank_CO2.tank_num==tank_num,ferment_tank_CO2.datetime>=date_start,ferment_tank_CO2.datetime<=date_end).all()
  9477. db.session.close()
  9478. for CO2 in tank_CO2:
  9479. l = []
  9480. time = dt.strftime(CO2.datetime, '%Y-%b-%d_%H:%M:%S')
  9481. l.append(time)
  9482. l.append(CO2.CO2)
  9483. L.append(l)
  9484. D['all'] = L
  9485. sensorData("CO2")
  9486. elif sensor == 'PH':
  9487. tank_PH = ferment_tank_PH.query.filter(ferment_tank_PH.tank_num==tank_num,ferment_tank_PH.datetime>=date_start,ferment_tank_PH.datetime<=date_end).all()
  9488. db.session.close()
  9489. for PH in tank_PH:
  9490. l = []
  9491. time = dt.strftime(PH.datetime, '%Y-%b-%d_%H:%M:%S')
  9492. l.append(time)
  9493. l.append(PH.PH)
  9494. L.append(l)
  9495. D['all'] = L
  9496. sensorData("PH")
  9497. elif sensor == 'ORP':
  9498. tank_ORP = ferment_tank_ORP.query.filter(ferment_tank_ORP.tank_num==tank_num,ferment_tank_ORP.datetime>=date_start,ferment_tank_ORP.datetime<=date_end).all()
  9499. db.session.close()
  9500. for ORP in tank_ORP:
  9501. l = []
  9502. time = dt.strftime(ORP.datetime, '%Y-%b-%d_%H:%M:%S')
  9503. l.append(time)
  9504. l.append(ORP.ORP)
  9505. L.append(l)
  9506. D['all'] = L
  9507. sensorData("ORP")
  9508. elif sensor == 'DO':
  9509. tank_DO = ferment_tank_DO.query.filter(ferment_tank_DO.tank_num==tank_num,ferment_tank_DO.datetime>=date_start,ferment_tank_DO.datetime<=date_end).all()
  9510. db.session.close()
  9511. for DO in tank_DO:
  9512. l = []
  9513. time = dt.strftime(DO.datetime, '%Y-%b-%d_%H:%M:%S')
  9514. l.append(time)
  9515. l.append(DO.DO)
  9516. L.append(l)
  9517. D['all'] = L
  9518. sensorData("DO")
  9519. elif sensor == 'EC':
  9520. tank_EC = ferment_tank_EC.query.filter(ferment_tank_EC.tank_num==tank_num,ferment_tank_EC.datetime>=date_start,ferment_tank_EC.datetime<=date_end).all()
  9521. db.session.close()
  9522. for EC in tank_EC:
  9523. l = []
  9524. time = dt.strftime(EC.datetime, '%Y-%b-%d_%H:%M:%S')
  9525. l.append(time)
  9526. l.append(EC.EC)
  9527. L.append(l)
  9528. D['all'] = L
  9529. sensorData("EC")
  9530. elif sensor == 'PA':
  9531. tank_PA = ferment_tank_PA.query.filter(ferment_tank_PA.tank_num==tank_num,ferment_tank_PA.datetime>=date_start,ferment_tank_PA.datetime<=date_end).all()
  9532. db.session.close()
  9533. for PA in tank_PA:
  9534. l = []
  9535. time = dt.strftime(PA.datetime, '%Y-%b-%d_%H:%M:%S')
  9536. l.append(time)
  9537. l.append(PA.PA)
  9538. L.append(l)
  9539. D['all'] = L
  9540. sensorData("PA")
  9541. elif sensor == 'vacuum':
  9542. tank_actuator = ferment_tank_actuator.query.filter(ferment_tank_actuator.tank_num==tank_num,ferment_tank_actuator.datetime>=date_start,ferment_tank_actuator.datetime<=date_end).all()
  9543. db.session.close()
  9544. for vacuum in tank_actuator:
  9545. l = []
  9546. time = dt.strftime(vacuum.datetime, '%Y-%b-%d_%H:%M:%S')
  9547. l.append(time)
  9548. l.append(vacuum.vacuum)
  9549. L.append(l)
  9550. D['all'] = L
  9551. sensorData("vacuum")
  9552. elif sensor == 'threewayvalve_input':
  9553. tank_actuator = ferment_tank_actuator.query.filter(ferment_tank_actuator.tank_num==tank_num,ferment_tank_actuator.datetime>=date_start,ferment_tank_actuator.datetime<=date_end).all()
  9554. db.session.close()
  9555. for threewayvalve_input in tank_actuator:
  9556. l = []
  9557. time = dt.strftime(threewayvalve_input.datetime, '%Y-%b-%d_%H:%M:%S')
  9558. l.append(time)
  9559. l.append(threewayvalve_input.threewayvalve_input)
  9560. L.append(l)
  9561. D['all'] = L
  9562. sensorData("threewayvalve_input")
  9563. elif sensor == 'diskvalve':
  9564. tank_actuator = ferment_tank_actuator.query.filter(ferment_tank_actuator.tank_num==tank_num,ferment_tank_actuator.datetime>=date_start,ferment_tank_actuator.datetime<=date_end).all()
  9565. db.session.close()
  9566. for diskvalve in tank_actuator:
  9567. l = []
  9568. time = dt.strftime(diskvalve.datetime, '%Y-%b-%d_%H:%M:%S')
  9569. l.append(time)
  9570. l.append(diskvalve.diskvalve)
  9571. L.append(l)
  9572. D['all'] = L
  9573. sensorData("diskvalve")
  9574. elif sensor == 'solenoid_tank_pump':
  9575. tank_actuator = ferment_tank_actuator.query.filter(ferment_tank_actuator.tank_num==tank_num,ferment_tank_actuator.datetime>=date_start,ferment_tank_actuator.datetime<=date_end).all()
  9576. db.session.close()
  9577. for solenoid_tank_pump in tank_actuator:
  9578. l = []
  9579. time = dt.strftime(solenoid_tank_pump.datetime, '%Y-%b-%d_%H:%M:%S')
  9580. l.append(time)
  9581. l.append(solenoid_tank_pump.solenoid_tank_pump)
  9582. L.append(l)
  9583. D['all'] = L
  9584. sensorData("solenoid_tank_pump")
  9585. elif sensor == 'solenoid_tank_disinfect':
  9586. tank_actuator = ferment_tank_actuator.query.filter(ferment_tank_actuator.tank_num==tank_num,ferment_tank_actuator.datetime>=date_start,ferment_tank_actuator.datetime<=date_end).all()
  9587. db.session.close()
  9588. for solenoid_disinfect in tank_actuator:
  9589. l = []
  9590. time = dt.strftime(solenoid_disinfect.datetime, '%Y-%b-%d_%H:%M:%S')
  9591. l.append(time)
  9592. l.append(solenoid_disinfect.solenoid_disinfect)
  9593. L.append(l)
  9594. D['all'] = L
  9595. sensorData("solenoid_disinfect")
  9596. elif sensor == 'solenoid_outer_water':
  9597. tank_actuator = ferment_tank_actuator.query.filter(ferment_tank_actuator.tank_num==tank_num,ferment_tank_actuator.datetime>=date_start,ferment_tank_actuator.datetime<=date_end).all()
  9598. db.session.close()
  9599. for solenoid_outer_water in tank_actuator:
  9600. l = []
  9601. time = dt.strftime(solenoid_outer_water.datetime, '%Y-%b-%d_%H:%M:%S')
  9602. l.append(time)
  9603. l.append(solenoid_outer_water.solenoid_outer_water)
  9604. L.append(l)
  9605. D['all'] = L
  9606. sensorData("solenoid_outer_water")
  9607. elif sensor == 'solenoid_tank_water_in':
  9608. tank_actuator = ferment_tank_actuator.query.filter(ferment_tank_actuator.tank_num==tank_num,ferment_tank_actuator.datetime>=date_start,ferment_tank_actuator.datetime<=date_end).all()
  9609. db.session.close()
  9610. for solenoid_tank_water_in in tank_actuator:
  9611. l = []
  9612. time = dt.strftime(solenoid_tank_water_in.datetime, '%Y-%b-%d_%H:%M:%S')
  9613. l.append(time)
  9614. l.append(solenoid_tank_water_in.solenoid_water_in)
  9615. L.append(l)
  9616. D['all'] = L
  9617. sensorData("solenoid_water_in")
  9618. elif sensor == 'solenoid_tank_water_out':
  9619. tank_actuator = ferment_tank_actuator.query.filter(ferment_tank_actuator.tank_num==tank_num,ferment_tank_actuator.datetime>=date_start,ferment_tank_actuator.datetime<=date_end).all()
  9620. db.session.close()
  9621. for solenoid_tank_water_out in tank_actuator:
  9622. l = []
  9623. time = dt.strftime(solenoid_tank_water_out.datetime, '%Y-%b-%d_%H:%M:%S')
  9624. l.append(time)
  9625. l.append(solenoid_tank_water_out.solenoid_water_out)
  9626. L.append(l)
  9627. D['all'] = L
  9628. sensorData("solenoid_water_out")
  9629. elif sensor == 'pump_sensor':
  9630. tank_actuator = ferment_tank_actuator.query.filter(ferment_tank_actuator.tank_num==tank_num,ferment_tank_actuator.datetime>=date_start,ferment_tank_actuator.datetime<=date_end).all()
  9631. db.session.close()
  9632. for pump_sensor in tank_actuator:
  9633. l = []
  9634. time = dt.strftime(pump_sensor.datetime, '%Y-%b-%d_%H:%M:%S')
  9635. l.append(time)
  9636. l.append(pump_sensor.pump_sensor)
  9637. L.append(l)
  9638. D['all'] = L
  9639. sensorData("pump_sensor")
  9640. elif sensor == 'threewayvalve_outer_float':
  9641. tank_actuator = ferment_tank_actuator.query.filter(ferment_tank_actuator.tank_num==tank_num,ferment_tank_actuator.datetime>=date_start,ferment_tank_actuator.datetime<=date_end).all()
  9642. db.session.close()
  9643. for threewayvalve_outer_float in tank_actuator:
  9644. l = []
  9645. time = dt.strftime(threewayvalve_outer_float.datetime, '%Y-%b-%d_%H:%M:%S')
  9646. l.append(time)
  9647. l.append(threewayvalve_outer_float.threewayvalve_outer_float)
  9648. L.append(l)
  9649. D['all'] = L
  9650. sensorData("threewayvalve_outer_float")
  9651. elif sensor == 'heater1':
  9652. tank_actuator = ferment_tank_actuator.query.filter(ferment_tank_actuator.tank_num==tank_num,ferment_tank_actuator.datetime>=date_start,ferment_tank_actuator.datetime<=date_end).all()
  9653. db.session.close()
  9654. for heater1 in tank_actuator:
  9655. l = []
  9656. time = dt.strftime(heater1.datetime, '%Y-%b-%d_%H:%M:%S')
  9657. l.append(time)
  9658. l.append(heater1.heater1)
  9659. L.append(l)
  9660. D['all'] = L
  9661. sensorData("heater1")
  9662. elif sensor == 'heater2':
  9663. tank_actuator = ferment_tank_actuator.query.filter(ferment_tank_actuator.tank_num==tank_num,ferment_tank_actuator.datetime>=date_start,ferment_tank_actuator.datetime<=date_end).all()
  9664. db.session.close()
  9665. for heater2 in tank_actuator:
  9666. l = []
  9667. time = dt.strftime(heater2.datetime, '%Y-%b-%d_%H:%M:%S')
  9668. l.append(time)
  9669. l.append(heater2.heater2)
  9670. L.append(l)
  9671. D['all'] = L
  9672. sensorData("heater2")
  9673. elif sensor == 'Warning_Light':
  9674. tank_actuator = ferment_tank_actuator.query.filter(ferment_tank_actuator.tank_num==tank_num,ferment_tank_actuator.datetime>=date_start,ferment_tank_actuator.datetime<=date_end).all()
  9675. db.session.close()
  9676. for warning_light in tank_actuator:
  9677. l = []
  9678. time = dt.strftime(warning_light.datetime, '%Y-%b-%d_%H:%M:%S')
  9679. l.append(time)
  9680. l.append(warning_light.warning_light)
  9681. L.append(l)
  9682. D['all'] = L
  9683. sensorData("warning_light")
  9684. elif sensor == 'motor':
  9685. tank_actuator = ferment_tank_actuator.query.filter(ferment_tank_actuator.tank_num==tank_num,ferment_tank_actuator.datetime>=date_start,ferment_tank_actuator.datetime<=date_end).all()
  9686. db.session.close()
  9687. for motor in tank_actuator:
  9688. l = []
  9689. time = dt.strftime(motor.datetime, '%Y-%b-%d_%H:%M:%S')
  9690. l.append(time)
  9691. l.append(motor.motor)
  9692. L.append(l)
  9693. D['all'] = L
  9694. sensorData("motor")
  9695. print(D)
  9696. return json.dumps(D)
  9697. else:
  9698. pass
  9699. # 貨櫃2致動器的發酵槽訪問路徑
  9700. @main.route('/cargo2_actuator_tanks', methods=['GET', 'POST'])
  9701. def cargo2_actuator_tanks_views():
  9702. username = session['uname']
  9703. if request.method == 'GET':
  9704. return render_template('cargo2_actuator_tanks.html', params=locals())
  9705. else:
  9706. pass
  9707. # 貨櫃2致動器發酵槽的清單訪問路徑
  9708. @main.route('/cargo2_actuator/<tid>', methods=['GET', 'POST'])
  9709. def cargo2_actuator_views(tid):
  9710. username = session['uname']
  9711. if request.method == 'GET':
  9712. return render_template('cargo2_actuator.html', params=locals())
  9713. else:
  9714. pass
  9715. # 貨櫃3的訪問路徑
  9716. @main.route('/cargo3', methods=['GET', 'POST'])
  9717. def cargo3_views():
  9718. username = session['uname']
  9719. if request.method == 'GET':
  9720. return render_template('cargo3.html', params=locals())
  9721. else:
  9722. pass
  9723. # 貨櫃3排程的訪問路徑
  9724. @main.route('/cargo3_schedule', methods=['GET', 'POST'])
  9725. def cargo3_schedule_views():
  9726. username = session['uname']
  9727. if request.method == 'GET':
  9728. # 將已儲存的排程資料傳給前端
  9729. # 提升機
  9730. try:
  9731. hoist = Hoist.query.order_by(text('datetime desc')).first()
  9732. datetime = hoist.datetime
  9733. hoists = Hoist.query.filter_by(datetime=datetime).all()
  9734. except Exception as e:
  9735. pass
  9736. # 烘乾機
  9737. try:
  9738. dryer = Dryer.query.order_by(text('datetime desc')).first()
  9739. datetime = dryer.datetime
  9740. dryers = Dryer.query.filter_by(datetime=datetime).all()
  9741. except Exception as e:
  9742. pass
  9743. return render_template('cargo3_schedule.html', params=locals())
  9744. else:
  9745. # Rita: "POST /b_cargo3 HTTP/1.1" 404 -
  9746. current_time = dt.now()
  9747. # 循環從前端提交過來的資料
  9748. for i in request.form:
  9749. print('Rita test i :', i)
  9750. # 堤升機
  9751. if i[:5] == 'hoist':
  9752. if i[:14] == 'hoist_duration':
  9753. hoist = Hoist()
  9754. hoist.duration = request.form[i]
  9755. elif i[:13] == 'hoist_from_hr':
  9756. ho_from_hr = request.form[i]
  9757. elif i[:14] == 'hoist_from_min':
  9758. ho_from_min = request.form[i]
  9759. hoist.start = ho_from_hr + ":" + ho_from_min
  9760. elif i[:11] == 'hoist_to_hr':
  9761. ho_to_hr = request.form[i]
  9762. elif i[:12] == 'hoist_to_min':
  9763. ho_to_min = request.form[i]
  9764. hoist.end = ho_to_hr + ":" + ho_to_min
  9765. hoist.datetime = current_time
  9766. db.session.add(hoist)
  9767. db.session.commit()
  9768. # 烘乾機
  9769. elif i[:5] == 'dryer':
  9770. if i[:14] == 'dryer_duration':
  9771. dryer = Dryer()
  9772. dryer.duration = request.form[i]
  9773. elif i[:13] == 'dryer_from_hr':
  9774. dry_from_hr = request.form[i]
  9775. elif i[:14] == 'dryer_from_min':
  9776. dry_from_min = request.form[i]
  9777. dryer.start = dry_from_hr + ":" + dry_from_min
  9778. elif i[:11] == 'dryer_to_hr':
  9779. dry_to_hr = request.form[i]
  9780. elif i[:12] == 'dryer_to_min':
  9781. dry_to_min = request.form[i]
  9782. dryer.end = dry_to_hr + ":" + dry_to_min
  9783. dryer.datetime = current_time
  9784. db.session.add(dryer)
  9785. db.session.commit()
  9786. return render_template('cargo3.html', params=locals())
  9787. # 獲取relay狀態路徑
  9788. @main.route('/relay', methods=['GET', 'POST'])
  9789. def relay_views():
  9790. if request.method == 'GET':
  9791. relay = Relay.query.order_by(text('datetime desc')).first()
  9792. relay_status = relay.status
  9793. return jsonify({"relay": relay_status})
  9794. else:
  9795. pass
  9796. # 獲取脫皮機狀態路徑
  9797. @main.route('/peel', methods=['GET', 'POST'])
  9798. def peeling_views():
  9799. if request.method == 'GET':
  9800. peeling = PeelingMachineRPM.query.order_by(text('datetime desc')).first()
  9801. peeling_rpm = peeling.rpm
  9802. return jsonify({"peeling": peeling_rpm})
  9803. else:
  9804. pass
  9805. # 退出的訪問路徑
  9806. @main.route('/logout')
  9807. def logout_views():
  9808. if 'id' in session and 'uname' in session:
  9809. del session['id']
  9810. del session['uname']
  9811. return redirect('/')
  9812. @main.route("/udp_client", methods=['POST', 'GET'])
  9813. def udp_views():
  9814. # sl(0.5)
  9815. global c_sock
  9816. if request.method == 'GET':
  9817. # def close():
  9818. # global c_sock
  9819. # sl(600)
  9820. # c_sock.close()
  9821. # c_sock = 0
  9822. # print("c_sock is closing")
  9823. max_length = 65000
  9824. # max_length = 95000
  9825. # lab1的IP
  9826. host = "192.168.50.65"
  9827. # lab2的IP
  9828. # host = "192.168.51.160"
  9829. port = 8000
  9830. c_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  9831. # t = threading.Thread(target=close)
  9832. # t.daemon = True
  9833. # t.start()
  9834. print("test")
  9835. # dict = request.args.to_dict()
  9836. # nr = int(dict['nr'])
  9837. # if nr == 1:
  9838. # camara = 0
  9839. # elif nr == 2:
  9840. # camara = 'rtsp://admin:admin@192.168.50.182/av2_0'
  9841. # elif nr == 3:
  9842. # camara = 'rtsp://admin:abcd1234@192.168.51.101/av2_0'
  9843. # 地下室小兵
  9844. # cap = cv2.VideoCapture('rtsp://admin:abcd1234@192.168.51.48/av2_0')
  9845. # 主機攝像頭
  9846. # cap = cv2.VideoCapture(0)
  9847. # 外面小兵
  9848. # cap = cv2.VideoCapture('rtsp://admin:admin@192.168.50.182/av2_0')
  9849. cap = cv2.VideoCapture('rtsp://192.168.50.182/av0_0')
  9850. # cap = cv2.VideoCapture(0)
  9851. # cap = cv2.VideoCapture(camara)
  9852. ret, frame = cap.read()
  9853. while ret:
  9854. # compress frame
  9855. frame = cv2.resize(frame, (550, 400), interpolation=cv2.INTER_AREA)
  9856. retval, buffer = cv2.imencode(".jpg", frame)
  9857. if retval:
  9858. # convert to byte array
  9859. buffer = buffer.tobytes()
  9860. # get size of the frame
  9861. buffer_size = len(buffer)
  9862. num_of_packs = 1
  9863. if buffer_size > max_length:
  9864. num_of_packs = math.ceil(buffer_size / max_length)
  9865. frame_info = {"packs": num_of_packs}
  9866. # send the number of packs to be expected
  9867. # print("Number of packs:", num_of_packs)
  9868. c_sock.sendto(pickle.dumps(frame_info), (host, port))
  9869. left = 0
  9870. right = max_length
  9871. for i in range(num_of_packs):
  9872. # print("left:", left)
  9873. # print("right:", right)
  9874. # truncate data to send
  9875. data = buffer[left:right]
  9876. left = right
  9877. right += max_length
  9878. # send the frames accordingly
  9879. c_sock.sendto(data, (host, port))
  9880. ret, frame = cap.read()
  9881. print("done")
  9882. return "done"
  9883. else:
  9884. c_sock.shutdown(2)
  9885. c_sock.close()
  9886. c_sock = 0
  9887. print("c_sock is closing")
  9888. D = {"input_vacuum_status": "0",
  9889. "tank_vacuum_status": "0",
  9890. "tank_threewayvalve_input_status": "0",
  9891. "tank_threewayvalve_bean_status": "0",
  9892. "tank_solenoid_disinfect_status": "0",
  9893. "tank_pump_disinfect_status": "0",
  9894. "outer_threewayvalve_float_status": "0",
  9895. "tank_motor_status": 'none',
  9896. "tank_pump_water_in_status": "0",
  9897. "tank_pump_cleanwater_in_status": "0",
  9898. "outer_solenoid_water_status": "0",
  9899. "tank_solenoid_reclaimed_in_status": "0",
  9900. "tank_solenoid_water_in_status": "0",
  9901. "tank_solenoid_water_out_status": "0",
  9902. "tank_solenoid_reclaimed_out_status": "0",
  9903. "tank_pump_sensor_status": "0",
  9904. "solenoid_tank_pump_status": "0",
  9905. "tank_nozzle_status": "0",
  9906. "tank_blower_status": "0",
  9907. "tank_heater1_status": "0",
  9908. "tank_heater2_status": "0",
  9909. "temp1_enable": "0",
  9910. "temp1": "0",
  9911. "tank_diskvalve_status": "0",
  9912. "output_vacuum_status": "0",
  9913. "tank_temp_enable_status": "0",
  9914. "tank_temp_status": "0",
  9915. # "tank_pump_waterFloat_status": "0",
  9916. # "tank_pump_waterL2_status": "0",
  9917. # "tank_pump_waterL4_status": "0",
  9918. # "tank_solenoid_waterL3_status": "0",
  9919. # "tank_solenoid_waterL5_status": "0",
  9920. # "tank_stepping_motor_status": 'none',
  9921. }
  9922. # pub_topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
  9923. # sub_topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78/Log'
  9924. # mqttObj = MQTT('aisky-client', 'aiskyc', '60.250.156.234', 1883, 60, sub_topic)
  9925. mqttObj = MQTT()
  9926. @main.route('/mqtt_block', methods=['POST'])
  9927. def mqtt_block():
  9928. import json
  9929. dict = request.form.to_dict() # 將表單轉換成字典
  9930. print('dict:', dict)
  9931. # print('dict.keys():', dict.keys())
  9932. # dict = {
  9933. # "command":"Dry_OTA",
  9934. # "cond": [
  9935. # {
  9936. # "cond_main": "if D1 tank_SHT11_Temp == 30",
  9937. # "cond_add": ["and tank_soil_Humidity == 25","and tank_soil_Humidity == 25",],
  9938. # "cond_com": ["tank_motor_status 10", "tank_motor_status 10"]
  9939. # },
  9940. # {
  9941. # "cond_main": "if D1 tank_SHT11_Temp == 30",
  9942. # "cond_add": ["and tank_soil_Humidity == 25","and tank_soil_Humidity == 25",],
  9943. # "cond_com": ["tank_motor_status 10", "tank_motor_status 10"]
  9944. # }
  9945. # ]
  9946. # }
  9947. # 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']"}
  9948. json = json.dumps(dict)
  9949. # 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"]}]}
  9950. print('json:', json)
  9951. # 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']}]}
  9952. topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
  9953. mqtt.publish(topic, json)
  9954. return 'OK'
  9955. # mqtt發布
  9956. # @main.route('/mqtt/<tid>', methods=['POST'])
  9957. @main.route('/mqtt/<tid>', methods=['POST'])
  9958. def mqtt_views(tid):
  9959. import json
  9960. dict = request.form.to_dict() # 將表單轉換成字典
  9961. json = json.dumps(dict)
  9962. # print('dict:', dict) # dict: {'tank-number': '1', 'command': 'tank_vacuum_status', 'value': 'on'}
  9963. # print('json:', json) # json: {"tank-number": "1", "command": "tank_vacuum_status", "value": "on"}
  9964. topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
  9965. # res = mqttObj.mqttPublish(pub_topic, json)
  9966. # print(res)
  9967. # sl(2)
  9968. # print(mqttObj.res)
  9969. #
  9970. # print('test')
  9971. mqtt.publish(topic, json)
  9972. # 入料儲豆槽真空吸料機(ON吸料/OFF排氣)
  9973. if dict['command'] == 'input_vacuum_status':
  9974. time.sleep(1)
  9975. # D[input_vacuum_status]: "0"
  9976. print('D[input_vacuum_status]:', D['input_vacuum_status'])
  9977. if D['input_vacuum_status'] == 'on':
  9978. return 'on'
  9979. elif D['input_vacuum_status'] == 'off':
  9980. return 'off'
  9981. else:
  9982. return "input_vacuum_status signal was not received"
  9983. # 真空吸料機
  9984. elif dict['command'] == 'tank_vacuum_status':
  9985. time.sleep(1)
  9986. if D['tank_vacuum_status'] == 'on':
  9987. return 'on'
  9988. elif D['tank_vacuum_status'] == 'off':
  9989. return 'off'
  9990. else:
  9991. return "tank_vacuum_status signal was not received"
  9992. # 入料三通閥(ON吸料/OFF排氣)
  9993. elif dict['command'] == 'tank_threewayvalve_input_status':
  9994. time.sleep(1)
  9995. if D['tank_threewayvalve_input_status'] == 'on':
  9996. return 'on'
  9997. elif D['tank_threewayvalve_input_status'] == 'off':
  9998. return 'off'
  9999. else:
  10000. return "tank_threewayvalve_input_status signal was not received"
  10001. # 測豆三通閥(ON吸料/OFF排氣)
  10002. elif dict['command'] == 'tank_threewayvalve_bean_status':
  10003. time.sleep(1)
  10004. if D['tank_threewayvalve_bean_status'] == 'on':
  10005. return 'on'
  10006. elif D['tank_threewayvalve_bean_status'] == 'off':
  10007. return 'off'
  10008. else:
  10009. return "tank_threewayvalve_bean_status signal was not received"
  10010. # 消毒電磁閥(ON噴灑消毒/OFF關)
  10011. elif dict['command'] == 'tank_solenoid_disinfect_status':
  10012. time.sleep(1)
  10013. if D['tank_solenoid_disinfect_status'] == 'on':
  10014. return 'on'
  10015. elif D['tank_solenoid_disinfect_status'] == 'off':
  10016. return 'off'
  10017. else:
  10018. return "tank_solenoid_disinfect_status signal was not received"
  10019. # 混合槽幫浦(ON抽水消毒/OFF關)
  10020. elif dict['command'] == 'tank_pump_disinfect_status':
  10021. time.sleep(1)
  10022. if D['tank_pump_disinfect_status'] == 'on':
  10023. return 'on'
  10024. elif D['tank_pump_disinfect_status'] == 'off':
  10025. return 'off'
  10026. else:
  10027. return "tank_pump_disinfect_status signal was not received"
  10028. # 外桶浮選三通閥(ON開浮選出口/OFF關)
  10029. elif dict['command'] == 'outer_threewayvalve_float_status':
  10030. time.sleep(1)
  10031. if D['outer_threewayvalve_float_status'] == 'on':
  10032. return 'on'
  10033. elif D['outer_threewayvalve_float_status'] == 'off':
  10034. return 'off'
  10035. else:
  10036. return "outer_threewayvalve_float_status signal was not received"
  10037. # 馬達(單位RPM)
  10038. elif dict['command'] == 'tank_motor_status':
  10039. print("D['tank_motor_status']", D['tank_motor_status'])
  10040. time.sleep(1)
  10041. if D['tank_motor_status'] == '0':
  10042. return 'off'
  10043. elif type(D['tank_motor_status']) == int:
  10044. return 'on'
  10045. else:
  10046. return "tank_motor_status signal was not received"
  10047. # 幫浦(清水入水)(ON開/OFF關)
  10048. elif dict['command'] == 'tank_pump_water_in_status':
  10049. time.sleep(1)
  10050. if D['tank_pump_water_in_status'] == 'on':
  10051. return 'on'
  10052. elif D['tank_pump_water_in_status'] == 'off':
  10053. return 'off'
  10054. else:
  10055. return "tank_pump_water_in_status signal was not received"
  10056. # 幫浦(清洗槽入水)(ON開/OFF關)
  10057. elif dict['command'] == 'tank_pump_cleanwater_in_status':
  10058. time.sleep(1)
  10059. if D['tank_pump_cleanwater_in_status'] == 'on':
  10060. return 'on'
  10061. elif D['tank_pump_cleanwater_in_status'] == 'off':
  10062. return 'off'
  10063. else:
  10064. return "tank_pump_cleanwater_in_status signal was not received"
  10065. # 桶外進水電磁閥(ON開/OFF關)
  10066. elif dict['command'] == 'outer_solenoid_water_status':
  10067. time.sleep(1)
  10068. if D['outer_solenoid_water_status'] == 'on':
  10069. return 'on'
  10070. elif D['outer_solenoid_water_status'] == 'off':
  10071. return 'off'
  10072. else:
  10073. return "outer_solenoid_water_status signal was not received"
  10074. # 中水入水電磁閥(ON開/OFF關)
  10075. elif dict['command'] == 'tank_solenoid_reclaimed_in_status':
  10076. time.sleep(1)
  10077. if D['tank_solenoid_reclaimed_in_status'] == 'on':
  10078. return 'on'
  10079. elif D['tank_solenoid_reclaimed_in_status'] == 'off':
  10080. return 'off'
  10081. else:
  10082. return "tank_solenoid_reclaimed_in_status signal was not received"
  10083. # 清水入水電磁閥(ON開/OFF關)
  10084. elif dict['command'] == 'tank_solenoid_water_in_status':
  10085. time.sleep(1)
  10086. if D['tank_solenoid_water_in_status'] == 'on':
  10087. return 'on'
  10088. elif D['tank_solenoid_water_in_status'] == 'off':
  10089. return 'off'
  10090. else:
  10091. return "tank_solenoid_water_in_status signal was not received"
  10092. # 排水廢水電磁閥(ON開/OFF關)
  10093. elif dict['command'] == 'tank_solenoid_water_out_status':
  10094. time.sleep(1)
  10095. if D['tank_solenoid_water_out_status'] == 'on':
  10096. return 'on'
  10097. elif D['tank_solenoid_water_out_status'] == 'off':
  10098. return 'off'
  10099. else:
  10100. return "tank_solenoid_water_out_status signal was not received"
  10101. # 排水中水電磁閥(ON開/OFF關)
  10102. elif dict['command'] == 'tank_solenoid_reclaimed_out_status':
  10103. time.sleep(1)
  10104. if D['tank_solenoid_reclaimed_out_status'] == 'on':
  10105. return 'on'
  10106. elif D['tank_solenoid_reclaimed_out_status'] == 'off':
  10107. return 'off'
  10108. else:
  10109. return "tank_solenoid_reclaimed_out_status signal was not received"
  10110. # 雙核隔膜泵(ON開/OFF關)
  10111. elif dict['command'] == 'tank_pump_sensor_status':
  10112. time.sleep(1)
  10113. if D['tank_pump_sensor_status'] == 'on':
  10114. return 'on'
  10115. elif D['tank_pump_sensor_status'] == 'off':
  10116. return 'off'
  10117. else:
  10118. return "tank_pump_sensor_status signal was not received"
  10119. # 逆洗 pump 電磁閥(ON開/OFF關)
  10120. elif dict['command'] == 'solenoid_tank_pump_status':
  10121. time.sleep(1)
  10122. if D['solenoid_tank_pump_status'] == 'on':
  10123. return 'on'
  10124. elif D['solenoid_tank_pump_status'] == 'off':
  10125. return 'off'
  10126. else:
  10127. return "solenoid_tank_pump_status signal was not received"
  10128. # 噴嘴(ON開/OFF關)
  10129. elif dict['command'] == 'tank_nozzle_status':
  10130. time.sleep(1)
  10131. if D['tank_nozzle_status'] == 'on':
  10132. return 'on'
  10133. elif D['tank_nozzle_status'] == 'off':
  10134. return 'off'
  10135. else:
  10136. return "tank_nozzle_status signal was not received"
  10137. # 鼓風機(ON開/OFF關)
  10138. elif dict['command'] == 'tank_blower_status':
  10139. time.sleep(1)
  10140. if D['tank_blower_status'] == 'on':
  10141. return 'on'
  10142. elif D['tank_blower_status'] == 'off':
  10143. return 'off'
  10144. else:
  10145. return "tank_blower_status signal was not received"
  10146. # 加熱棒 1(ON開/OFF關)
  10147. elif dict['command'] == 'tank_heater1_status':
  10148. time.sleep(1)
  10149. if D['tank_heater1_status'] == 'on':
  10150. return 'on'
  10151. elif D['tank_heater1_status'] == 'off':
  10152. return 'off'
  10153. else:
  10154. return "tank_heater1_status signal was not received"
  10155. # 加熱棒 2(ON開/OFF關)
  10156. elif dict['command'] == 'tank_heater2_status':
  10157. time.sleep(1)
  10158. if D['tank_heater2_status'] == 'on':
  10159. return 'on'
  10160. elif D['tank_heater2_status'] == 'off':
  10161. return 'off'
  10162. else:
  10163. return "tank_heater2_status signal was not received"
  10164. # 溫度控制(ON開/OFF關)
  10165. elif dict['command'] == 'temp1_enable':
  10166. time.sleep(1)
  10167. if D['temp1_enable'] == 'on':
  10168. return 'on'
  10169. elif D['temp1_enable'] == 'off':
  10170. return 'off'
  10171. else:
  10172. return "temp1_enable_status signal was not received"
  10173. # 設定溫度
  10174. elif dict['command'] == 'temp1':
  10175. time.sleep(1)
  10176. if D['temp1'] == '0':
  10177. return 'off'
  10178. elif type(D['temp1']) == float:
  10179. return 'on'
  10180. else:
  10181. return "temp1 signal was not received"
  10182. # 發酵槽 溫控開關
  10183. elif dict['command'] == 'tank_temp_enable':
  10184. time.sleep(1)
  10185. if D['tank_temp_enable'] == 'on':
  10186. return 'on'
  10187. elif D['tank_temp_enable'] == 'off':
  10188. return 'off'
  10189. else:
  10190. return "tank_temp_enable signal was not received"
  10191. # 發酵槽 設定溫度
  10192. elif dict['command'] == 'tank_temp':
  10193. time.sleep(1)
  10194. if D['tank_temp'] == '0':
  10195. return 'off'
  10196. elif type(D['tank_temp']) == float:
  10197. return 'on'
  10198. else:
  10199. return "tank_temp signal was not received"
  10200. # 蝴蝶閥(ON開/OFF關)
  10201. elif dict['command'] == 'tank_diskvalve_status':
  10202. time.sleep(1)
  10203. if D['tank_diskvalve_status'] == 'on':
  10204. return 'on'
  10205. elif D['tank_diskvalve_status'] == 'off':
  10206. return 'off'
  10207. else:
  10208. return "tank_diskvalve_status signal was not received"
  10209. # 出料儲豆槽真空吸料機(ON吸料/OFF排氣)
  10210. elif dict['command'] == 'output_vacuum_status':
  10211. time.sleep(1)
  10212. if D['output_vacuum_status'] == 'on':
  10213. return 'on'
  10214. elif D['output_vacuum_status'] == 'off':
  10215. return 'off'
  10216. else:
  10217. return "output_vacuum_status signal was not received"
  10218. else:
  10219. return "MQTT command NOT FOUND"
  10220. # return "publish done" # 1201 test
  10221. # --- 12/10 ------------------------------------------ start
  10222. @main.route('/mqtt_data/<tid>_<command>_<value>', methods=['POST'])
  10223. def mqtt_data(tank_num, command, value):
  10224. import json
  10225. data = { "tank_num": str(tank_num), "command": str(command), "value": str(value) }
  10226. json = json.dumps(data)
  10227. # print('json:', json) # json: {"tank-number": "1", tank_vacuum_status", "value": "on"}
  10228. print('json:', json)
  10229. topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
  10230. mqtt.publish(topic, json)
  10231. # --- 12/10 ------------------------------------------ finish
  10232. # --- 10/19 ------------------------------------------ start
  10233. # mqtt發布
  10234. # @main.route('/mqtt/<tid>', methods=['POST'])
  10235. @main.route('/mqtt_f/<tid>', methods=['POST'])
  10236. def mqtt_f(data):
  10237. import json
  10238. dict = request.form.to_dict()
  10239. json = json.dumps(data)
  10240. # print('dict:', dict) # dict: {'tank-number': '1', 'command': 'tank_vacuum_status', 'value': 'on'}
  10241. # print('json:', json) # json: {"tank-number": "1", tank_vacuum_status", "value": "on"}
  10242. print('json:', json)
  10243. topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
  10244. # res = mqttObj.mqttPublish(pub_topic, json)
  10245. # print(res)
  10246. # sl(2)
  10247. # print(mqttObj.res)
  10248. #
  10249. # print('test')
  10250. mqtt.publish(topic, json)
  10251. # 入料儲豆槽真空吸料機(ON吸料/OFF排氣)
  10252. if dict['command'] == 'input_vacuum_status':
  10253. time.sleep(1)
  10254. # D[input_vacuum_status]: "0"
  10255. print('D[input_vacuum_status]:', D['input_vacuum_status'])
  10256. if D['input_vacuum_status'] == 'on':
  10257. return 'on'
  10258. elif D['input_vacuum_status'] == 'off':
  10259. return 'off'
  10260. else:
  10261. return "input_vacuum_status signal was not received"
  10262. # 真空吸料機
  10263. elif dict['command'] == 'tank_vacuum_status':
  10264. time.sleep(1)
  10265. if D['tank_vacuum_status'] == 'on':
  10266. return 'on'
  10267. elif D['tank_vacuum_status'] == 'off':
  10268. return 'off'
  10269. else:
  10270. return "tank_vacuum_status signal was not received"
  10271. # 入料三通閥(ON吸料/OFF排氣)
  10272. elif dict['command'] == 'tank_threewayvalve_input_status':
  10273. time.sleep(1)
  10274. if D['tank_threewayvalve_input_status'] == 'on':
  10275. return 'on'
  10276. elif D['tank_threewayvalve_input_status'] == 'off':
  10277. return 'off'
  10278. else:
  10279. return "tank_threewayvalve_input_status signal was not received"
  10280. # 測豆三通閥(ON吸料/OFF排氣)
  10281. elif dict['command'] == 'tank_threewayvalve_bean_status':
  10282. time.sleep(1)
  10283. if D['tank_threewayvalve_bean_status'] == 'on':
  10284. return 'on'
  10285. elif D['tank_threewayvalve_bean_status'] == 'off':
  10286. return 'off'
  10287. else:
  10288. return "tank_threewayvalve_bean_status signal was not received"
  10289. # 消毒電磁閥(ON噴灑消毒/OFF關)
  10290. elif dict['command'] == 'tank_solenoid_disinfect_status':
  10291. time.sleep(1)
  10292. if D['tank_solenoid_disinfect_status'] == 'on':
  10293. return 'on'
  10294. elif D['tank_solenoid_disinfect_status'] == 'off':
  10295. return 'off'
  10296. else:
  10297. return "tank_solenoid_disinfect_status signal was not received"
  10298. # 混合槽幫浦(ON抽水消毒/OFF關)
  10299. elif dict['command'] == 'tank_pump_disinfect_status':
  10300. time.sleep(1)
  10301. if D['tank_pump_disinfect_status'] == 'on':
  10302. return 'on'
  10303. elif D['tank_pump_disinfect_status'] == 'off':
  10304. return 'off'
  10305. else:
  10306. return "tank_pump_disinfect_status signal was not received"
  10307. # 外桶浮選三通閥(ON開浮選出口/OFF關)
  10308. elif dict['command'] == 'outer_threewayvalve_float_status':
  10309. time.sleep(1)
  10310. if D['outer_threewayvalve_float_status'] == 'on':
  10311. return 'on'
  10312. elif D['outer_threewayvalve_float_status'] == 'off':
  10313. return 'off'
  10314. else:
  10315. return "outer_threewayvalve_float_status signal was not received"
  10316. # 馬達(單位RPM)
  10317. elif dict['command'] == 'tank_motor_status':
  10318. print("D['tank_motor_status']", D['tank_motor_status'])
  10319. time.sleep(1)
  10320. if D['tank_motor_status'] == '0':
  10321. return 'off'
  10322. elif type(D['tank_motor_status']) == int:
  10323. return 'on'
  10324. else:
  10325. return "tank_motor_status signal was not received"
  10326. # 幫浦(清水入水)(ON開/OFF關)
  10327. elif dict['command'] == 'tank_pump_water_in_status':
  10328. time.sleep(1)
  10329. if D['tank_pump_water_in_status'] == 'on':
  10330. return 'on'
  10331. elif D['tank_pump_water_in_status'] == 'off':
  10332. return 'off'
  10333. else:
  10334. return "tank_pump_water_in_status signal was not received"
  10335. # 幫浦(清洗槽入水)(ON開/OFF關)
  10336. elif dict['command'] == 'tank_pump_cleanwater_in_status':
  10337. time.sleep(1)
  10338. if D['tank_pump_cleanwater_in_status'] == 'on':
  10339. return 'on'
  10340. elif D['tank_pump_cleanwater_in_status'] == 'off':
  10341. return 'off'
  10342. else:
  10343. return "tank_pump_cleanwater_in_status signal was not received"
  10344. # 桶外進水電磁閥(ON開/OFF關)
  10345. elif dict['command'] == 'outer_solenoid_water_status':
  10346. time.sleep(1)
  10347. if D['outer_solenoid_water_status'] == 'on':
  10348. return 'on'
  10349. elif D['outer_solenoid_water_status'] == 'off':
  10350. return 'off'
  10351. else:
  10352. return "outer_solenoid_water_status signal was not received"
  10353. # 中水入水電磁閥(ON開/OFF關)
  10354. elif dict['command'] == 'tank_solenoid_reclaimed_in_status':
  10355. time.sleep(1)
  10356. if D['tank_solenoid_reclaimed_in_status'] == 'on':
  10357. return 'on'
  10358. elif D['tank_solenoid_reclaimed_in_status'] == 'off':
  10359. return 'off'
  10360. else:
  10361. return "tank_solenoid_reclaimed_in_status signal was not received"
  10362. # 清水入水電磁閥(ON開/OFF關)
  10363. elif dict['command'] == 'tank_solenoid_water_in_status':
  10364. time.sleep(1)
  10365. if D['tank_solenoid_water_in_status'] == 'on':
  10366. return 'on'
  10367. elif D['tank_solenoid_water_in_status'] == 'off':
  10368. return 'off'
  10369. else:
  10370. return "tank_solenoid_water_in_status signal was not received"
  10371. # 排水廢水電磁閥(ON開/OFF關)
  10372. elif dict['command'] == 'tank_solenoid_water_out_status':
  10373. time.sleep(1)
  10374. if D['tank_solenoid_water_out_status'] == 'on':
  10375. return 'on'
  10376. elif D['tank_solenoid_water_out_status'] == 'off':
  10377. return 'off'
  10378. else:
  10379. return "tank_solenoid_water_out_status signal was not received"
  10380. # 排水中水電磁閥(ON開/OFF關)
  10381. elif dict['command'] == 'tank_solenoid_reclaimed_out_status':
  10382. time.sleep(1)
  10383. if D['tank_solenoid_reclaimed_out_status'] == 'on':
  10384. return 'on'
  10385. elif D['tank_solenoid_reclaimed_out_status'] == 'off':
  10386. return 'off'
  10387. else:
  10388. return "tank_solenoid_reclaimed_out_status signal was not received"
  10389. # 雙核隔膜泵(ON開/OFF關)
  10390. elif dict['command'] == 'tank_pump_sensor_status':
  10391. time.sleep(1)
  10392. if D['tank_pump_sensor_status'] == 'on':
  10393. return 'on'
  10394. elif D['tank_pump_sensor_status'] == 'off':
  10395. return 'off'
  10396. else:
  10397. return "tank_pump_sensor_status signal was not received"
  10398. # 逆洗 pump 電磁閥(ON開/OFF關)
  10399. elif dict['command'] == 'solenoid_tank_pump_status':
  10400. time.sleep(1)
  10401. if D['solenoid_tank_pump_status'] == 'on':
  10402. return 'on'
  10403. elif D['solenoid_tank_pump_status'] == 'off':
  10404. return 'off'
  10405. else:
  10406. return "solenoid_tank_pump_status signal was not received"
  10407. # 噴嘴(ON開/OFF關)
  10408. elif dict['command'] == 'tank_nozzle_status':
  10409. time.sleep(1)
  10410. if D['tank_nozzle_status'] == 'on':
  10411. return 'on'
  10412. elif D['tank_nozzle_status'] == 'off':
  10413. return 'off'
  10414. else:
  10415. return "tank_nozzle_status signal was not received"
  10416. # 鼓風機(ON開/OFF關)
  10417. elif dict['command'] == 'tank_blower_status':
  10418. time.sleep(1)
  10419. if D['tank_blower_status'] == 'on':
  10420. return 'on'
  10421. elif D['tank_blower_status'] == 'off':
  10422. return 'off'
  10423. else:
  10424. return "tank_blower_status signal was not received"
  10425. # 加熱棒 1(ON開/OFF關)
  10426. elif dict['command'] == 'tank_heater1_status':
  10427. time.sleep(1)
  10428. if D['tank_heater1_status'] == 'on':
  10429. return 'on'
  10430. elif D['tank_heater1_status'] == 'off':
  10431. return 'off'
  10432. else:
  10433. return "tank_heater1_status signal was not received"
  10434. # 加熱棒 2(ON開/OFF關)
  10435. elif dict['command'] == 'tank_heater2_status':
  10436. time.sleep(1)
  10437. if D['tank_heater2_status'] == 'on':
  10438. return 'on'
  10439. elif D['tank_heater2_status'] == 'off':
  10440. return 'off'
  10441. else:
  10442. return "tank_heater2_status signal was not received"
  10443. # 溫度控制(ON開/OFF關)
  10444. elif dict['command'] == 'temp1_enable':
  10445. time.sleep(1)
  10446. if D['temp1_enable'] == 'on':
  10447. return 'on'
  10448. elif D['temp1_enable'] == 'off':
  10449. return 'off'
  10450. else:
  10451. return "temp1_enable_status signal was not received"
  10452. # 設定溫度
  10453. elif dict['command'] == 'temp1':
  10454. time.sleep(1)
  10455. if D['temp1'] == '0':
  10456. return 'off'
  10457. elif type(D['temp1']) == float:
  10458. return 'on'
  10459. else:
  10460. return "temp1 signal was not received"
  10461. # 發酵槽 溫控開關
  10462. elif dict['command'] == 'tank_temp_enable':
  10463. time.sleep(1)
  10464. if D['tank_temp_enable'] == 'on':
  10465. return 'on'
  10466. elif D['tank_temp_enable'] == 'off':
  10467. return 'off'
  10468. else:
  10469. return "tank_temp_enable signal was not received"
  10470. # 發酵槽 設定溫度
  10471. elif dict['command'] == 'tank_temp':
  10472. time.sleep(1)
  10473. if D['tank_temp'] == '0':
  10474. return 'off'
  10475. elif type(D['tank_temp']) == float:
  10476. return 'on'
  10477. else:
  10478. return "tank_temp signal was not received"
  10479. # 蝴蝶閥(ON開/OFF關)
  10480. elif dict['command'] == 'tank_diskvalve_status':
  10481. time.sleep(1)
  10482. if D['tank_diskvalve_status'] == 'on':
  10483. return 'on'
  10484. elif D['tank_diskvalve_status'] == 'off':
  10485. return 'off'
  10486. else:
  10487. return "tank_diskvalve_status signal was not received"
  10488. # 出料儲豆槽真空吸料機(ON吸料/OFF排氣)
  10489. elif dict['command'] == 'output_vacuum_status':
  10490. time.sleep(1)
  10491. if D['output_vacuum_status'] == 'on':
  10492. return 'on'
  10493. elif D['output_vacuum_status'] == 'off':
  10494. return 'off'
  10495. else:
  10496. return "output_vacuum_status signal was not received"
  10497. else:
  10498. return "MQTT command NOT FOUND"
  10499. # ---10/19 ------------------------------------------- end
  10500. board_prog = {
  10501. "D1": "0",
  10502. "D2": "0",
  10503. "D3": "0",
  10504. "D4": "0",
  10505. "D5": "0",
  10506. "D6": "0",
  10507. "D7": "0",
  10508. "D8": "0",
  10509. "D9": "0",
  10510. "D10": "0",
  10511. "D11": "0",
  10512. "D12": "0",
  10513. }
  10514. # 處理mqtt訂閱的信息
  10515. # 收到訊息後我們可以用 on_message(),來讀取收到的內容:
  10516. @mqtt.on_message()
  10517. def handle_mqtt_message(client, userdata, message):
  10518. # topic = message.topic # 收到的主題 Rita 原本就沒有此行, 增加說明用
  10519. payload = message.payload.decode() # 收到的內容
  10520. payload = json.loads(payload)
  10521. # print("-------msg-------")
  10522. # print('name :', p['name'])
  10523. # print('email :', p['email'])
  10524. print('payload:', payload)
  10525. # success / upload error / no reply
  10526. # {'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'}
  10527. if payload['command'] == 'Code_upload':
  10528. board_prog[payload['tank_number']] = payload['response']
  10529. # res = "on_message" + payload['response']
  10530. # return res
  10531. # 入料儲豆槽真空吸料機(ON吸料/OFF排氣)
  10532. if payload['command'] == 'input_vacuum_status':
  10533. if payload['response'] == 'on':
  10534. D['input_vacuum_status'] = 'on'
  10535. else:
  10536. D['input_vacuum_status'] = 'off'
  10537. # 真空吸料機(ON吸料/OFF排氣)
  10538. elif payload['command'] == 'tank_vacuum_status':
  10539. if payload['response'] == 'on':
  10540. D['tank_vacuum_status'] = 'on'
  10541. else:
  10542. D['tank_vacuum_status'] = 'off'
  10543. # 入料三通閥(ON吸料/OFF排氣)
  10544. elif payload['command'] == 'tank_threewayvalve_input_status':
  10545. if payload['response'] == 'on':
  10546. D['tank_threewayvalve_input_status'] = 'on'
  10547. else:
  10548. D['tank_threewayvalve_input_status'] = 'off'
  10549. # 測豆三通閥(ON測豆/OFF排氣)
  10550. elif payload['command'] == 'tank_threewayvalve_bean_status':
  10551. if payload['response'] == 'on':
  10552. D['tank_threewayvalve_bean_status'] = 'on'
  10553. else:
  10554. D['tank_threewayvalve_bean_status'] = 'off'
  10555. # 消毒電磁閥(ON噴灑消毒/OFF關)
  10556. elif payload['command'] == 'tank_solenoid_disinfect_status':
  10557. if payload['response'] == 'on':
  10558. D['tank_solenoid_disinfect_status'] = 'on'
  10559. else:
  10560. D['tank_solenoid_disinfect_status'] = 'off'
  10561. # 混合槽幫浦(ON消毒槽抽水/OFF關)
  10562. elif payload['command'] == 'tank_pump_disinfect_status':
  10563. if payload['response'] == 'on':
  10564. D['tank_pump_disinfect_status'] = 'on'
  10565. else:
  10566. D['tank_pump_disinfect_status'] = 'off'
  10567. # 外桶浮選三通閥(ON浮選落豆/OFF桶內真空)
  10568. elif payload['command'] == 'outer_threewayvalve_float_status':
  10569. if payload['response'] == 'on':
  10570. D['outer_threewayvalve_float_status'] = 'on'
  10571. else:
  10572. D['outer_threewayvalve_float_status'] = 'off'
  10573. # 馬達(單位RPM)
  10574. elif payload['command'] == 'tank_motor_status':
  10575. if payload['response'] == 'off' or payload['response'] == '0':
  10576. D['tank_motor_status'] = '0'
  10577. else:
  10578. D['tank_motor_status'] = payload['response']
  10579. # 幫浦(清水入水)(ON開/OFF關)
  10580. elif payload['command'] == 'tank_pump_water_in_status':
  10581. if payload['response'] == 'on':
  10582. D['tank_pump_water_in_status'] = 'on'
  10583. else:
  10584. D['tank_pump_water_in_status'] = 'off'
  10585. # 幫浦(清洗槽入水)(ON開/OFF關)
  10586. elif payload['command'] == 'tank_pump_cleanwater_in_status':
  10587. if payload['response'] == 'on':
  10588. D['tank_pump_cleanwater_in_status'] = 'on'
  10589. else:
  10590. D['tank_pump_cleanwater_in_status'] = 'off'
  10591. # 桶外進水電磁閥(ON開/OFF關)
  10592. elif payload['command'] == 'outer_solenoid_water_status':
  10593. if payload['response'] == 'on':
  10594. D['outer_solenoid_water_status'] = 'on'
  10595. else:
  10596. D['outer_solenoid_water_status'] = 'off'
  10597. # 中水入水電磁閥(ON開/OFF關)
  10598. elif payload['command'] == 'tank_solenoid_reclaimed_in_status':
  10599. if payload['response'] == 'on':
  10600. D['tank_solenoid_reclaimed_in_status'] = 'on'
  10601. else:
  10602. D['tank_solenoid_reclaimed_in_status'] = 'off'
  10603. # 清水入水電磁閥(ON開/OFF關)
  10604. elif payload['command'] == 'tank_solenoid_water_in_status':
  10605. if payload['response'] == 'on':
  10606. D['tank_solenoid_water_in_status'] = 'on'
  10607. else:
  10608. D['tank_solenoid_water_in_status'] = 'off'
  10609. # 排水廢水電磁閥(ON開/OFF關)
  10610. elif payload['command'] == 'tank_solenoid_water_out_status':
  10611. if payload['response'] == 'on':
  10612. D['tank_solenoid_water_out_status'] = 'on'
  10613. else:
  10614. D['tank_solenoid_water_out_status'] = 'off'
  10615. # 排水中水電磁閥(ON開/OFF關)
  10616. elif payload['command'] == 'tank_solenoid_reclaimed_out_status':
  10617. if payload['response'] == 'on':
  10618. D['tank_solenoid_reclaimed_out_status'] = 'on'
  10619. else:
  10620. D['tank_solenoid_reclaimed_out_status'] = 'off'
  10621. # 雙核隔膜泵(ON開/OFF關)
  10622. elif payload['command'] == 'tank_pump_sensor_status':
  10623. if payload['response'] == 'on':
  10624. D['tank_pump_sensor_status'] = 'on'
  10625. else:
  10626. D['tank_pump_sensor_status'] = 'off'
  10627. # 逆洗 pump 電磁閥(ON開/OFF關)
  10628. elif payload['command'] == 'solenoid_tank_pump_status':
  10629. if payload['response'] == 'on':
  10630. D['solenoid_tank_pump_status'] = 'on'
  10631. else:
  10632. D['solenoid_tank_pump_status'] = 'off'
  10633. # 噴嘴(ON開/OFF關)
  10634. elif payload['command'] == 'tank_nozzle_status':
  10635. if payload['response'] == 'on':
  10636. D['tank_nozzle_status'] = 'on'
  10637. else:
  10638. D['tank_nozzle_status'] = 'off'
  10639. # 鼓風機(ON開/OFF關)
  10640. elif payload['command'] == 'tank_blower_status':
  10641. if payload['response'] == 'on':
  10642. D['tank_blower_status'] = 'on'
  10643. else:
  10644. D['tank_blower_status'] = 'off'
  10645. # 加熱棒 1(ON開/OFF關)
  10646. elif payload['command'] == 'tank_heater1_status':
  10647. if payload['response'] == 'on':
  10648. D['tank_heater1_status'] = 'on'
  10649. else:
  10650. D['tank_heater1_status'] = 'off'
  10651. # 加熱棒 2(ON開/OFF關)
  10652. elif payload['command'] == 'tank_heater2_status':
  10653. if payload['response'] == 'on':
  10654. D['tank_heater2_status'] = 'on'
  10655. else:
  10656. D['tank_heater2_status'] = 'off'
  10657. # 發酵槽 溫控開關
  10658. elif payload['command'] == 'tank_temp_enable':
  10659. if payload['response'] == 'on':
  10660. D['tank_temp_enable'] = 'on'
  10661. else:
  10662. D['tank_temp_enable'] = 'off'
  10663. # 發酵槽 設定溫度
  10664. elif payload['command'] == 'tank_temp':
  10665. if payload['response'] == 'off':
  10666. D['tank_temp'] = '0'
  10667. else:
  10668. D['tank_temp'] = payload['response']
  10669. # 蝴蝶閥(ON開/OFF關)
  10670. elif payload['command'] == 'tank_diskvalve_status':
  10671. if payload['response'] == 'on':
  10672. D['tank_diskvalve_status'] = 'on'
  10673. else:
  10674. D['tank_diskvalve_status'] = 'off'
  10675. # 出料儲豆槽真空吸料機(ON吸料/OFF排氣)
  10676. elif payload['command'] == 'output_vacuum_status':
  10677. if payload['response'] == 'on':
  10678. D['output_vacuum_status'] = 'on'
  10679. else:
  10680. D['output_vacuum_status'] = 'off'
  10681. else:
  10682. return "MQTT command NOT FOUND"