1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801 |
- # 主業務邏輯中的視圖和路由的定義
- import os
- import datetime
- from turtle import title
- from flask import Flask, redirect, render_template, request, session, Response, jsonify
- from sqlalchemy.sql.expression import desc, false, null
- # 導入藍圖程序,用於構建路由
- from werkzeug.utils import redirect
- from werkzeug.wrappers import response
- from . import main
- from coffee_manage import mqtt
- # 導入db,用於操作數據庫
- from coffee_manage import db
- # 導入實體類,用於操作數據庫
- from ..models import *
- import json
- from datetime import datetime as dt
- from datetime import timedelta
- from sqlalchemy import text
- import pymysql
- import pandas as pd
- from concurrent.futures import ThreadPoolExecutor
- import cv2
- import pickle
- import socket
- import time
- import threading
- import numpy as np
- import math
- from .mqtt import MQTT
- from matplotlib import pyplot as plt
- # import random
- from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg as FigureCanvas
- # import io
- # from flask import make_response
- # from distutils.util import strtobool # 將字串 string 轉成布林 boolean
- # import psutil
- import subprocess
- import shutil
- import stat
- pool = ThreadPoolExecutor(25)
- s_sock = 0
- lock = threading.Lock()
- '''
- mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffee',
- password='skyeye', database='Coffee', charset='utf8')
- mycursor = mydb.cursor()
- '''
- # 主頁的訪問路徑
- @main.route('/')
- def main_index():
- # 獲取登入信息
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- # Rita 參數 params 是用來取得參數的 locals=() 所有參數
- return render_template('index.html', params=locals())
- else:
- return render_template('sign_in.html')
- # Rita 測試
- # sql_get
- @main.route('/sql_get', methods=['GET', 'POST'])
- def sql_get():
- # 取得網頁傳回來的 SQL 指令
- # sql = "SELECT * FROM 零件表 WHERE 會計科目 = 04"
- info = request.args.to_dict('sql')
- datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
- sql = info['sql'].replace('current_timestamp()', '"' + datetime + '"')
- # ip = request.remote_addr
- # sql = info['sql'].replace('IPDATA', '"' + ip + '"')
- print("[sql_get]sql: ", sql)
- # 存入本機
- mydb = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='Gold@53743001', database='CoffeeManage', charset='utf8')
- mycursor = mydb.cursor()
- try:
- mycursor.execute(sql)
- sql_data = mycursor.fetchall()
- except pymysql.err.IntegrityError:
- sql_data = "localhost Mysql 存值錯誤"
- mydb.commit()
- mydb.close()
- # 存入 HOME
- mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffeemanage', password='skyeye', database='CoffeeManage', charset='utf8')
- mycursor = mydb.cursor()
- try:
- mycursor.execute(sql)
- sql_data = mycursor.fetchall()
- except pymysql.err.IntegrityError:
- sql_data = "Home Mysql 存值錯誤"
- mydb.commit()
- mydb.close()
-
- return jsonify({"response":sql_data})
- # @main.route('/sql_get_HOME', methods=['GET', 'POST'])
- # def sql_get_HOME():
- # mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffee', password='skyeye', database='Coffee', charset='utf8')
- # # mydb = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='Gold@53743001', database='Coffee', charset='utf8')
- # mycursor = mydb.cursor()
- # # 取得網頁傳回來的 SQL 指令
- # # sql = "SELECT * FROM 零件表 WHERE 會計科目 = 04"
- # info = request.args.to_dict('sql')
- # sql = info['sql']
- # print("[sql_get]sql: ", sql)
- # try:
- # mycursor.execute(sql)
- # sql_data = mycursor.fetchall()
- # except pymysql.err.IntegrityError:
- # sql_data = "請注意 ! 單據不可新增重複的零件"
- # mydb.commit()
- # mydb.close()
-
- # return jsonify({"response":"OK"})
- # Rita 測試
- # 使用者名稱測試
- @main.route('/test', methods=['GET', 'POST'])
- def test():
- info = request.args.to_dict()
- print(info)
- print("info[command]: ", info['command'])
- return json.dumps(info)
- # Rita 測試
- # 板子燒錄請求
- @main.route('/board_programmer')
- def board_programmer():
- prog_data = request.args.to_dict() # {'tank': 'D1'}
- CURRENT_PATH = os.path.dirname(__file__) # c:\Users\USER\Rita\Coffee\CoffeeProject\app\main
-
- # # 取得 hex 檔案內容
- file = os.path.join(CURRENT_PATH, 'CTO20220622', 'build', 'SDIO.hex') # c:\Users\USER\Rita\Coffee\CoffeeProject\app\main\CTO20220622\SDIO.hex
- f = open(file, 'r')
- ota_hex = f.read()
-
- # # MQTT 傳送燒錄
- MQTT_dict = {
- 'command':'Code_upload',
- 'tank_num':prog_data['tank'],
- 'url':ota_hex
- }
- import json
- json = json.dumps(MQTT_dict)
- # print("MQTT_dict: ", MQTT_dict) # MQTT_dict: {'command': 'Code_upload', 'tank_num': 'F1', 'url': ':020000040801F1\n:1000
- # print("json: ", json) # json: {"command": "Code_upload", "tank_num": "F1", "url": ":020000040801F1\n:1000
- # topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
- topic = 'AISKY/Coffee/MK-G/' + str(prog_data['burner_mac'])
- mqtt.publish(topic, json)
- time.sleep(3)
- if board_prog[prog_data['tank']] == 'no reply':
- board_prog[prog_data['tank']] = '0'
- return 'no reply'
- print("===== 下載 Git CoffeeProject_SourceCode ==========================================================")
- # # 先下載 Git CoffeeProject_SourceCode
- os.system('git clone --single-branch http://60.250.156.230:3000/rita/CoffeeProject_SourceCode.git ' + CURRENT_PATH + '/source_code')
- time.sleep(3)
- print("===== 將 hex 先複製更名 ==========================================================")
- # # 將 hex 先複製更名
- copy_old_path = os.path.join(CURRENT_PATH, "CTO20220622", "build", "SDIO.hex")
- currentTime = dt.now().strftime("%Y%m%d_%H%M%S")
- fileTitle_hex = "[" + currentTime + "_" + prog_data['USERNAME'] + "] " + prog_data['tank'] + "_SDIO.hex"
- copy_new_path = os.path.join(CURRENT_PATH, "CTO20220622", "build", fileTitle_hex)
- print("copy_new_path: ", copy_new_path)
- shutil.copyfile(copy_old_path, copy_new_path)
- time.sleep(3)
- print("===== 再將 hex 移動到 source_code 資料夾中 ==========================================================")
- # # 再將 hex 移動到 source_code 資料夾中
- move_new_path = os.path.join(CURRENT_PATH, "source_code", fileTitle_hex)
- print("copy_new_path: ", copy_new_path)
- print("move_new_path: ", move_new_path)
- shutil.move(copy_new_path, move_new_path)
- time.sleep(3)
- print("===== 將 main.c 先複製更名 ==========================================================")
- # # 將 main.c 先複製更名
- copy_old_path = os.path.join(CURRENT_PATH, "CTO20220622", "Src", "main.c")
- # currentTime = dt.now().strftime("%Y%m%d_%H%M%S") # 同 hex 即可
- fileTitle_c = "[" + currentTime + "_" + prog_data['USERNAME'] + "] " + prog_data['tank'] + "_main.c"
- copy_new_path = os.path.join(CURRENT_PATH, "CTO20220622", "Src", fileTitle_c)
- print("copy_new_path: ", copy_new_path)
- shutil.copyfile(copy_old_path, copy_new_path)
- time.sleep(3)
- print("===== 再將 main.c 移動到 source_code 資料夾中 ==========================================================")
- # # 再將 main.c 移動到 source_code 資料夾中
- move_new_path = os.path.join(CURRENT_PATH, "source_code", fileTitle_c)
- print("copy_new_path: ", copy_new_path)
- print("move_new_path: ", move_new_path)
- shutil.move(copy_new_path, move_new_path)
- time.sleep(3)
- print("===== 將 source_code 資料內容 push 到 Git CoffeeProject_SourceCode ==========================================================")
- # # 將 source_code 資料內容 push 到 Git CoffeeProject_SourceCode
- cwdDATA = os.path.join(CURRENT_PATH, "source_code")
- subprocess.call(["git", "add", fileTitle_hex],cwd=cwdDATA)
- subprocess.call(["git", "commit","-m", fileTitle_hex],cwd=cwdDATA)
- subprocess.call(["git", "add", fileTitle_c],cwd=cwdDATA)
- subprocess.call(["git", "commit","-m", fileTitle_c],cwd=cwdDATA)
- subprocess.call(["git", "push"],cwd=cwdDATA)
- time.sleep(3)
- print("===== 刪除 source_code 資料夾 ==========================================================")
- # # 刪除 source_code 資料夾
- # shutil.rmtree(CURRENT_PATH + "\\source_code", onerror=remove_readonly)
- shutil.rmtree(cwdDATA, onerror=remove_readonly)
- time.sleep(3)
- # # 取得燒錄回傳
- print("===== SDIO.hex 燒錄等待中 =====================================================")
- res = board_prog[prog_data['tank']]
- print("res: ", res)
- return "燒錄中..."
- # time.sleep(60)
- # res = board_prog[prog_data['tank']]
- # print("res: ", res)
- # if board_prog[prog_data['tank']] == 'no reply':
- # board_prog[prog_data['tank']] = '0'
- # return 'no reply'
- # elif board_prog[prog_data['tank']] == 'success':
- # board_prog[prog_data['tank']] = '0'
- # return 'success'
- # elif board_prog[prog_data['tank']] == 'upload error':
- # board_prog[prog_data['tank']] = '0'
- # return 'upload error'
- # else:
- # res = "Code_upload " + prog_data['tank'] + " signal was not received"
- # return res
- @main.route('/board_programmer_result_<tid>')
- def board_programmer_result(tid):
- if board_prog[tid] == 'no reply':
- board_prog[tid] = '0'
- # return board_prog[tid] # 錯誤
- return 'no reply'
- elif board_prog[tid] == 'success':
- board_prog[tid] = '0'
- return 'success'
- elif board_prog[tid] == 'upload error':
- board_prog[tid] = '0'
- return 'upload error'
- elif board_prog[tid] == '0':
- return board_prog[tid]
- else:
- # res = "Code_upload " + tid + " signal was not received"
- return board_prog[tid]
- def remove_readonly(func, path, _):
- os.chmod(path, stat.S_IWRITE) # 更改權限 stat.S_IWRITE = windows 下取消只读
- func(path)
- # Rita 測試
- # 板子介面測試
- @main.route('/board_loadertt')
- def board_loadertt():
- pin_data = coffee1_0_pin.query.order_by(text('datetime desc')).first()
- # DCD1 = block_cond_d1_t.query.order_by(text('datetime desc')).first()
- BCD = block_cond_dry_t.query.order_by(text('datetime desc')).first()
- return render_template('board_loadertt.html', title="[測試]", **locals())
- # 檢視各使用者條件
- @main.route('/block_view', methods=['GET', 'POST'])
- def block_view():
- if request.method == 'GET':
- username = session['uname']
- status = session['status']
-
- sql = 'SELECT DISTINCT `UserName` FROM `block_cond_dry_t`'
- mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffeemanage', password='skyeye', database='CoffeeManage', charset='utf8')
- mycursor = mydb.cursor()
- try:
- mycursor.execute(sql)
- username_data = mycursor.fetchall()
- except pymysql.err.IntegrityError:
- username_data = "UserName is empty"
- mydb.commit()
- mydb.close()
- return render_template('block_view.html', title="檢視積木條件", **locals())
-
- # else:
- # prog_username = request.values['prog_username']
- # prog_tank = request.values['prog_tank']
- # print("prog_username: ", prog_username)
- # print("prog_tank: ", prog_tank)
- # return redirect('/block_view')
- # 桶槽間溝通
- @main.route('/tanks_comm')
- def tanks_comm():
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- return render_template('tanks_comm.html', title="設備單元整合運作", **locals())
- else:
- print("NO session['uname']")
- return redirect('/login')
- @main.route('/select_cond', methods=['GET', 'POST'])
- def select_cond():
- info = request.args.to_dict()
- username = info['username']
- print("username: ", username)
- tank = info['tank']
- print("tank: ", tank)
- cond_data = (block_cond_dry_t.query.filter_by(UserName=str(username),tank_num=str(tank)).order_by(text('datetime desc')).first()).cond
- # print("cond_data.cond: ", cond_data.cond, "_type(cond_data.cond): ", type(cond_data.cond))
- print("cond_data: ", cond_data, type(cond_data))
- return cond_data
- @main.route('/board_loader_<tankid>')
- def board_loader(tankid):
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- # 取得桶槽編號
- TankID = tankid
- # 找到目前桶槽的入料儲豆槽
- dry_tank_io = dry_tank_relation.query.filter_by(tank_id=tankid).first()
- # 若在 dry_tank_relation 桶槽關聯內無此桶槽, 則回到 /board_loader_D1
- if dry_tank_io == None:
- return redirect("/tank_relation")
- print(dry_tank_io.tank_import) # DI1
- tank_import = dry_tank_io.tank_import
- # 找到目前桶槽的入料儲豆槽
- print(dry_tank_io.tank_export)
- tank_export = dry_tank_io.tank_export
-
- # 腳位配置
- pin_data = coffee1_0_pin.query.filter_by(tid=tankid).order_by(text('datetime desc')).first()
- print("pin_data: ", pin_data)
- # 積木條件
- BCD = block_cond_dry_t.query.filter_by(tank_num=tankid).order_by(text('datetime desc')).first()
- if BCD == None:
- # 網頁初始只需要 cond
- BCD = {"command":"Dry_OTA",
- "cond":[
- {"cond_add":[],
- "cond_com":[],
- "cond_main":""}
- ],
- "tank_num":tankid}
- print("BCD: ", BCD)
- return render_template('board_loader-1.html', title="板子燒錄介面", **locals())
- else:
- print("NO session['uname']")
- return redirect('/login')
- # if 'id' in session and 'uname' in session:
- # print("session['uname']: ", session['uname'])
- # username = session['uname']
- # print("session['status']: ", session['status'])
- # status = session['status']
- # pin_data = coffee1_0_pin.query.order_by(text('datetime desc')).first()
- # # print("pin_data.R1:", pin_data.R1)
- # block_data = dry_block_waiting.query.order_by(text('datetime desc')).first()
- # # print("block_data.cond_a1_1:", block_data.cond_a1_1)
- # DBW = dry_block_waiting.query.order_by(text('datetime desc')).first()
- # return render_template('board_loader-1.html', title="板子燒錄介面", **locals())
- # else:
- # print("NO session['uname']")
- # return redirect('/login')
- # 桶槽前後關係設定
- @main.route('/tank_relation')
- def tank_relation():
- dtr = dry_tank_relation.query.all()
- # for i in dtr:
- # print("dtr", i, ": ", i.tank_id)
-
- return render_template('tank_relation.html', title="桶槽關係建立", **locals())
- #致動器功能程式定義
- def GPIO(relay,status):
- if relay=="R1":
- if status=="on":
- act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_13, GPIO_PIN_RESET);\n"
- elif status=="off":
- act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_13, GPIO_PIN_SET);\n"
- else:
- act=""
- elif relay=="R2":
- if status=="on":
- act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_12, GPIO_PIN_RESET);\n"
- elif status=="off":
- act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_12, GPIO_PIN_SET);\n"
- else:
- act=""
- elif relay=="R3":
- if status=="on":
- act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_11, GPIO_PIN_RESET);\n"
- elif status=="off":
- act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_11, GPIO_PIN_SET);\n"
- else:
- act=""
- elif relay=="R4":
- if status=="on":
- act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_10, GPIO_PIN_RESET);\n"
- elif status=="off":
- act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_10, GPIO_PIN_SET);\n"
- else:
- act=""
- elif relay=="R5":
- if status=="on":
- act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_9, GPIO_PIN_RESET);\n"
- elif status=="off":
- act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_9, GPIO_PIN_SET);\n"
- else:
- act=""
- elif relay=="R6":
- if status=="on":
- act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_8, GPIO_PIN_RESET);\n"
- elif status=="off":
- act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_8, GPIO_PIN_SET);\n"
- else:
- act=""
- elif relay=="R7":
- if status=="on":
- act=" HAL_GPIO_WritePin(GPIOC,GPIO_PIN_9, GPIO_PIN_RESET);\n"
- elif status=="off":
- act=" HAL_GPIO_WritePin(GPIOC,GPIO_PIN_9, GPIO_PIN_SET);\n"
- else:
- act=""
- elif relay=="R8":
- if status=="on":
- act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_15, GPIO_PIN_RESET);\n"
- elif status=="off":
- act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_15, GPIO_PIN_SET);\n"
- else:
- act=""
- elif relay=="R9":
- if status=="on":
- act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_14, GPIO_PIN_RESET);\n"
- elif status=="off":
- act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_14, GPIO_PIN_SET);\n"
- else:
- act=""
- elif relay=="R10":
- if status=="on":
- act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_13, GPIO_PIN_RESET);\n"
- elif status=="off":
- act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_13, GPIO_PIN_SET);\n"
- else:
- act=""
- elif relay=="R11":
- if status=="on":
- act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_12, GPIO_PIN_RESET);\n"
- elif status=="off":
- act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_12, GPIO_PIN_SET);\n"
- else:
- act=""
- elif relay=="R12":
- if status=="on":
- act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_11, GPIO_PIN_RESET);\n"
- elif status=="off":
- act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_11, GPIO_PIN_SET);\n"
- else:
- act=""
- elif relay=="R13":
- if status=="on":
- act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_10, GPIO_PIN_RESET);\n"
- elif status=="off":
- act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_10, GPIO_PIN_SET);\n"
- else:
- act=""
- elif relay=="R14":
- if status=="on":
- act=" HAL_GPIO_WritePin(GPIOB,GPIO_PIN_15, GPIO_PIN_RESET);\n"
- elif status=="off":
- act=" HAL_GPIO_WritePin(GPIOB,GPIO_PIN_15, GPIO_PIN_SET);\n"
- else:
- act=""
- elif relay=="R15":
- if status=="on":
- act=" HAL_GPIO_WritePin(GPIOB,GPIO_PIN_14, GPIO_PIN_RESET);\n"
- elif status=="off":
- act=" HAL_GPIO_WritePin(GPIOB,GPIO_PIN_14, GPIO_PIN_SET);\n"
- else:
- act=""
- elif relay=="R16":
- if status=="on":
- act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_15, GPIO_PIN_RESET);\n"
- elif status=="off":
- act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_15, GPIO_PIN_SET);\n"
- else:
- act=""
- elif relay=="R17":
- if status=="on":
- act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_14, GPIO_PIN_RESET);\n"
- elif status=="off":
- act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_14, GPIO_PIN_SET);\n"
- else:
- act=""
- elif relay=="R18":
- if status=="on":
- act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_13, GPIO_PIN_RESET);\n"
- elif status=="off":
- act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_13, GPIO_PIN_SET);\n"
- else:
- act=""
- elif relay=="R19":
- if status=="on":
- act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_12, GPIO_PIN_RESET);\n"
- elif status=="off":
- act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_12, GPIO_PIN_SET);\n"
- else:
- act=""
- elif relay=="R20":
- if status=="on":
- act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_11, GPIO_PIN_RESET);\n"
- elif status=="off":
- act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_11, GPIO_PIN_SET);\n"
- else:
- act=""
- elif relay=="sleep":
- act=" HAL_Delay("+status+"000);\n"
- elif relay=="M10":
- if int(status)>0:
- act=(" user_pwm_setvalue2(0);\n"
- +" user_pwm_setvalue("+status+");\n")
- elif int(status)<0:
- status=-1*int(status)
- act=(" user_pwm_setvalue(0);\n"
- +" user_pwm_setvalue2("+str(status)+");\n")
- else:
- act=""
- elif relay=="M2":
- if status=="on":
- act=" user_pwm_setvalue3(50);\n"
- elif status=="off":
- act=" user_pwm_setvalue3(180);\n"
- else:
- act=""
- elif relay=="M3":
- if status=="on":
- act=" user_pwm_setvalue4(50);\n"
- elif status=="off":
- act=" user_pwm_setvalue4(180);\n"
- else:
- act=""
- else:
- act=""
- return act
- #感測器功能程式定義
- def PH(pin_position,pin_type):
- global pin_variables,pin_code
- if pin_position=="M4":
- pin="ADC_CHANNEL_0"
- elif pin_position=="M5":
- pin="ADC_CHANNEL_3"
- elif pin_position=="M7":
- pin="ADC_CHANNEL_4"
- if pin_type =="PH":
- print("PH ok")
- pin_variables=("uint16_t "+pin_position+"_AD_Value = 0;\n"
- +"float "+pin_position+"_voltage_V =0;\n"
- +"float "+pin_position+"_pH_mid = 1.500;\n"
- +"float "+pin_position+"_pH_low = 2.030;\n"
- +"float "+pin_position+"_pH_high =0.975;\n"
- +"float "+pin_position+"_"+pin_type+"=0;\n")
- pin_code=(" MX_ADC1_Init1("+pin+");\n"
- +" HAL_ADC_Start(&hadc1);\n"
- +" HAL_ADC_PollForConversion(&hadc1, 50);\n"
- +" if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
- +" {\n"
- +" "+pin_position+"_AD_Value = HAL_ADC_GetValue(&hadc1);\n"
- +" "+pin_position+"_voltage_V = "+pin_position+"_AD_Value*3.3f/4096;\n"
- +" if ("+pin_position+"_voltage_V > "+pin_position+"_pH_mid)\n"
- +" {\n"
- +" "+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"
- +" }\n"
- +" else\n"
- +" {\n"
- +" "+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"
- +" }\n"
- +" }\n"
- +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",4,10);\n")
-
- else:
- pin_variables=""
- pin_code=""
- def DO(pin_position,pin_type):
- global pin_variables,pin_code
- if pin_position=="M4":
- pin="ADC_CHANNEL_0"
- elif pin_position=="M5":
- pin="ADC_CHANNEL_3"
- elif pin_position=="M7":
- pin="ADC_CHANNEL_4"
- if pin_type =="DO":
- print("DO ok")
- pin_variables=("uint16_t "+pin_position+"_AD_Value = 0;\n"
- +"float "+pin_position+"_voltage_V =0;\n"
- +"float "+pin_position+"_DO_offset =0.44;\n"
- +"float "+pin_position+"_"+pin_type+" =0;\n")
- pin_code=(" MX_ADC1_Init1("+pin+");\n"
- +" HAL_ADC_Start(&hadc1);\n"
- +" HAL_ADC_PollForConversion(&hadc1, 50);\n"
- +" if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
- +" {\n"
- +" "+pin_position+"_AD_Value = HAL_ADC_GetValue(&hadc1);\n"
- +" "+pin_position+"_voltage_V = "+pin_position+"_AD_Value*3.3f/4096;\n"
- +" "+pin_position+"_"+pin_type+"= ((("+pin_position+"_AD_Value*3.3f/4096)*100)/"+pin_position+"_DO_offset);\n"
- +" }\n"
- +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",4,10);\n")
-
- else:
- pin_variables=""
- pin_code=""
- def WATERLEVEL(pin_position,pin_type):
- global pin_variables,pin_code
- if pin_position=="M9":
- pin="GPIO_PIN_9"
- elif pin_position=="M11":
- pin="GPIO_PIN_7"
- elif pin_position=="M12":
- pin="GPIO_PIN_8"
- elif pin_position=="M19":
- pin="GPIO_PIN_10"
- if pin_type =="WATERLEVEL":
- print("WATERLEVEL ok")
- pin_variables=("int "+pin_position+"_"+pin_type+" =0;\n")
- pin_code=(" MX_GPIO_Input1("+pin+");\n"
- +" if (HAL_GPIO_ReadPin(GPIOE, "+pin+") == GPIO_PIN_SET)\n"
- +" {\n"
- +" "+pin_position+"_"+pin_type+" =1;\n"
- +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
- +" }\n"
- +" else\n"
- +" {\n"
- +" "+pin_position+"_"+pin_type+" =0;\n"
- +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
- +" }\n")
- else:
- pin_variables=""
- pin_code=""
- def motorfeedback(pin_position,pin_type):
- global pin_variables,pin_code
- if pin_position=="M9":
- pin="GPIO_PIN_9"
- elif pin_position=="M11":
- pin="GPIO_PIN_7"
- elif pin_position=="M12":
- pin="GPIO_PIN_8"
- elif pin_position=="M19":
- pin="GPIO_PIN_10"
- if pin_type =="motorfeedback":
- print("feedback ok")
- pin_variables=("int "+pin_position+"_"+pin_type+" =0;\n")
- pin_code=(" MX_GPIO_Input1("+pin+");\n"
- +" if (HAL_GPIO_ReadPin(GPIOE, "+pin+") == GPIO_PIN_SET)\n"
- +" {\n"
- +" "+pin_position+"_"+pin_type+" =1;\n"
- +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
- +" }\n"
- +" else\n"
- +" {\n"
- +" "+pin_position+"_"+pin_type+" =0;\n"
- +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
- +" }\n")
- else:
- pin_variables=""
- pin_code=""
- def butterflyvalvefeedback(pin_position,pin_type):
- global pin_variables,pin_code
- if pin_position=="M9":
- pin="GPIO_PIN_9"
- elif pin_position=="M11":
- pin="GPIO_PIN_7"
- elif pin_position=="M12":
- pin="GPIO_PIN_8"
- elif pin_position=="M19":
- pin="GPIO_PIN_10"
- if pin_type =="butterflyvalvefeedback":
- print("butterflyvalvefeedback ok")
- pin_variables=("int "+pin_position+"_"+pin_type+" =0;\n")
- pin_code=(" MX_GPIO_Input1("+pin+");\n"
- +" if (HAL_GPIO_ReadPin(GPIOE, "+pin+") == GPIO_PIN_SET)\n"
- +" {\n"
- +" "+pin_position+"_"+pin_type+" =1;\n"
- +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
- +" }\n"
- +" else\n"
- +" {\n"
- +" "+pin_position+"_"+pin_type+" =0;\n"
- +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",1,10);\n"
- +" }\n")
- else:
- pin_variables=""
- pin_code=""
- def ORP(pin_position,pin_type):
- global pin_variables,pin_code
- if pin_position=="M4":
- pin="ADC_CHANNEL_0"
- elif pin_position=="M5":
- pin="ADC_CHANNEL_3"
- elif pin_position=="M7":
- pin="ADC_CHANNEL_4"
- if pin_type =="ORP":
- print("ORP ok")
- pin_variables=("uint16_t "+pin_position+"_AD_Value = 0;\n"
- +"float "+pin_position+"_voltage_V =0;\n"
- +"float "+pin_position+"_ORP_offset =0;\n"
- +"float "+pin_position+"_"+pin_type+" =0;\n")
- pin_code=(" MX_ADC1_Init1("+pin+");\n"
- +" HAL_ADC_Start(&hadc1);\n"
- +" HAL_ADC_PollForConversion(&hadc1, 50);\n"
- +" if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
- +" {\n"
- +" "+pin_position+"_AD_Value = HAL_ADC_GetValue(&hadc1);\n"
- +" "+pin_position+"_voltage_V = "+pin_position+"_AD_Value*3.3f/4096;\n"
- +" "+pin_position+"_"+pin_type+"= ((("+pin_position+"_AD_Value*3.3f/4096)-(1.5+"+pin_position+"_ORP_offset)));\n"
- +" }\n"
- +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",4,10);\n")
-
- else:
- pin_variables=""
- pin_code=""
- def SonicESMUS07(pin_position,pin_type):
- global pin_variables,pin_code,pin_add_code
- if pin_position=="M1":
- pin="ADC_CHANNEL_6"
- if pin_type =="SonicESMUS07":
- print("ESMUS07 ok")
- pin_variables=("uint16_t "+pin_position+"_AD_Value = 0;\n"
- +"float "+pin_position+"_voltage_V =0;\n"
- +"float "+pin_position+"_"+pin_type+" =0;\n")
- pin_code=(" MX_ADC1_Init1("+pin+");\n"
- +" HAL_ADC_Start(&hadc1);\n"
- +" HAL_ADC_PollForConversion(&hadc1, 50);\n"
- +" if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
- +" {\n"
- +" "+pin_position+"_AD_Value = HAL_ADC_GetValue(&hadc1);\n"
- +" "+pin_position+"_voltage_V = "+pin_position+"_AD_Value*5.3f/4096;\n"
- +" if ("+pin_position+"_voltage_V==0)\n"
- +" {\n"
- +" "+pin_position+"_"+pin_type+ " = 100;\n"
- +" }\n"
- +" else\n"
- +" {\n"
- +" "+pin_position+"_"+pin_type+ " = ("+pin_position+"_voltage_V*180)+100;\n"
- +" }\n"
- +" }\n"
- +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",4,10);\n")
- else:
- pin_variables=""
- pin_code=""
- pin_add_code=""
- def SEN0189(pin_position,pin_type):
- global pin_variables,pin_code,pin_add_code
- if pin_position=="M6":
- pin="ADC_CHANNEL_13"
- elif pin_position=="M13":
- pin="ADC_CHANNEL_5"
- if pin_type =="SEN0189":
- print("SEN0189 ok")
- pin_variables=("uint16_t "+pin_position+"_AD_Value = 0;\n"
- +"float "+pin_position+"_voltage_V =0;\n"
- +"float "+pin_position+"_"+pin_type+" =0;\n")
- pin_code=(" MX_ADC1_Init1("+pin+");\n"
- +" HAL_ADC_Start(&hadc1);\n"
- +" HAL_ADC_PollForConversion(&hadc1, 50);\n"
- +" if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
- +" {\n"
- +" "+pin_position+"_AD_Value = HAL_ADC_GetValue(&hadc1);\n"
- +" "+pin_position+"_voltage_V = "+pin_position+"_AD_Value*5.0f/4096;\n"
- +" if ("+pin_position+"_voltage_V>4.2)\n"
- +" {\n"
- +" "+pin_position+"_"+pin_type+ " = 0;\n"
- +" }\n"
- +" else if ("+pin_position+"_voltage_V<2.5)\n"
- +" {\n"
- +" "+pin_position+"_"+pin_type+ " = 3000;\n"
- +" }\n"
- +" else\n"
- +" {\n"
- +" "+pin_position+"_"+pin_type+"=(-1120.4*"+pin_position+"_voltage_V*"+pin_position+"_voltage_V)+(5742.3*"+pin_position+"_voltage_V)-4352.9;\n"
- +" }\n"
- +" }\n"
- +" HAL_UART_Transmit(&huart4,(unsigned char*)&"+pin_position+"_"+pin_type+",4,10);\n")
- print(pin_variables)
- print(pin_code)
- else:
- pin_variables=""
- pin_code=""
- pin_add_code=""
- def SERVO(pin_position, pin_type):
- global pin_variables, pin_code
- if pin_type == "Servo":
- print("Servo ok")
- pin_code = (
- " HAL_UART_Receive_IT(&huart1, (uint8_t *)checkfeedback,sizeof(checkfeedback));\n")
- pin_add_code = (" void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)\n"
- + "{\n"
- + " if(checkfeedback[0]==0xff && checkfeedback[6]==0x0D)\n"
- + " {\n"
- + " direction=checkfeedback[1];\n"
- + " if(direction==0)\n"
- + " {\n"
- + " HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_RESET);\n"
- + " HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, GPIO_PIN_SET);\n"
- + " user_pwm_setvalue(50);\n"
- + " }\n"
- + " else if(direction==1)\n"
- + " {\n"
- + " HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_RESET);\n"
- + " HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, GPIO_PIN_RESET);\n"
- + " user_pwm_setvalue(50);\n"
- + " }\n"
- + " else\n"
- + " {\n"
- + " HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_SET);\n"
- + " HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, GPIO_PIN_RESET);\n"
- + " user_pwm_setvalue(0);\n"
- + " }\n"
- + " }\n"
- + "}\n")
- print(pin_code)
- print(pin_add_code)
- else:
- pin_variables = ""
- pin_code = ""
- def MOTOR(pin_position, pin_type):
- global pin_variables, pin_code
- if pin_type == "Servo":
- print("Servo ok")
- pin_code = (" HAL_UART_Receive_IT(&huart1, (uint8_t *)checkfeedback,sizeof(checkfeedback));\n"
- + " HAL_Delay(100);\n"
- + " if(direction==0)\n"
- + " {\n"
- + " user_pwm_setvalue2(0);\n"
- + " user_pwm_setvalue(pwm_value);\n"
- + " }\n"
- + " else\n"
- + " {\n"
- + " user_pwm_setvalue2(pwm_value);\n"
- + " user_pwm_setvalue(0);\n"
- + " }\n")
- pin_add_code = (" void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)\n"
- + "{\n"
- + " if(checkfeedback[0]==0xff && checkfeedback[6]==0x0D)\n"
- + " {\n"
- + " pwm_value=checkfeedback[1];\n"
- + " direction=checkfeedback[2];\n"
- + ' printf("%d",pwm_value);\n'
- + " }\n"
- + "}\n")
- print(pin_code)
- print(pin_add_code)
- else:
- pin_variables = ""
- pin_code = ""
- def SOIL(pin_position,pin_type):
- global pin_variables,pin_code,pin_add_code
- if pin_type =="Soil":
- print("SOIL ok")
- pin_variables=("uint8_t soil[8] ={0x01,0x03,0x00,0x00,0x00,0x03,0x05,0xCB};\n"
- +"uint8_t data[11] ={0,0,0,0,0,0,0,0,0,0,0};\n"
- +"float "+pin_position+"_"+pin_type+" =0;\n"
- +"int rh=0;\n"
- +"int temp=0;\n"
- +"int ec=0;\n")
- pin_code=(" HAL_UART_Transmit(&huart2, (uint8_t *)soil,sizeof(soil),50);\n"
- +" HAL_UART_Receive_IT(&huart2, (uint8_t *)data,sizeof(data));\n")
-
- pin_add_code=("void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)\n"
- +"{\n"
- +" if (huart->Instance == USART2)\n"
- +" {\n"
- +" if (data[0]==0x01 && data[1]==0x03)\n"
- +" {\n"
- +" rh = (data[3] << 8) + data[4];\n"
- +" temp = (data[5] << 8) + data[6];\n"
- +" ec = (data[7] << 8) + data[8];\n"
- +" }\n"
- +" }\n"
- +"}\n")
- print(pin_code)
- print(pin_add_code)
- else:
- pin_variables=""
- pin_code=""
- pin_add_code=""
- def EC(pin_position,pin_type):
- global pin_variables,pin_code,pin_add_code
- if pin_type =="EC":
- print("EC ok")
- pin_variables=("uint8_t data[4] ={0,0,0,0};\n"
- +"float "+pin_position+"_"+pin_type+" =0;\n")
- pin_code=(" HAL_UART_Receive_IT(&huart2, (uint8_t *)data,sizeof(data));\n")
-
- pin_add_code=("void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)\n"
- +"{\n"
- +" if (huart->Instance == USART2)\n"
- +" {\n"
- +" if (data[0]==0x30 && data[1]==0x2E)\n"
- +" {\n"
- +" HAL_UART_Transmit(&huart4, (uint8_t *)data,sizeof(data),50);\n"
- +" }\n"
- +" }\n"
- +"}\n")
- print(pin_variables)
- print(pin_code)
- print(pin_add_code)
- else:
- pin_variables=""
- pin_code=""
- pin_add_code=""
- def SHT11(pin_position,pin_type):
- global pin_variables,pin_code,pin_add_code
- global sensor_code
- if pin_position=="M14":
- pin_group="GPIOB"
- pin1="GPIO_PIN_0"
- pin2="GPIO_PIN_1"
- if pin_position=="M17":
- pin_group="GPIOC"
- pin1="GPIO_PIN_6"
- pin2="GPIO_PIN_7"
- if pin_type =="SHT11":
- print("SHT11 ok")
- pin_variables=("uint8_t cmd[7]={0xFF,0x00,0x00,0x00,0x00,0x00,0x0D};\n"
- +"uint16_t i,val,value_H,value_L,Cvalue,Hvalue;\n"
- +"int error;\n"
- +"float C1=-2.0468;\n"
- +"float C2=0.0367;\n"
- +"float C3=-0.0000015955;\n"
- +"float RH_Lin;\n"
- +"float RH_Ture;\n"
- +"float d1=-39.6;\n"
- +"float d2=0.01;\n"
- +"float T1=0.01;\n"
- +"float T2=0.00008;\n"
- +"float temp_C=0;\n"
- +"int temp;\n"
- +"int RH;\n"
- +"float "+pin_position+"_"+pin_type+" =0;\n")
- sensor_code=("void SHT10_TransStart(void);\n"
- +"void SHT10_WriteByte(void);\n"
- +"void SHT10_WriteByte2(void);\n"
- +"void SHT10_ReadByte(void);\n"
- +"void SHT10_Calculate(void);\n"
- +"void MX_GPIO_Input1(unsigned long pin);\n")
- pin_code=(" Cvalue=0;\n"
- +" Hvalue=0;\n"
- +" value_H=0;\n"
- +" value_L=0;\n"
- +" SHT10_TransStart();\n"
- +" SHT10_WriteByte();\n"
- +" MX_GPIO_Input1("+pin1+");\n"
- +" HAL_Delay(250);\n"
- +" if (HAL_GPIO_ReadPin("+pin_group+","+pin1+")==0)\n"
- +" {\n"
- +" SHT10_ReadByte();\n"
- +" value_H=val;\n"
- +" SHT10_ReadByte();\n"
- +" value_L=val;\n"
- +" Cvalue = (value_H<< 8 | value_L);\n"
- +" }\n"
- +" SHT10_TransStart();\n"
- +" SHT10_WriteByte2();\n"
- +" MX_GPIO_Input1("+pin1+");\n"
- +" HAL_Delay(250);\n"
- +" if (HAL_GPIO_ReadPin("+pin_group+","+pin1+")==0)\n"
- +" {\n"
- +" SHT10_ReadByte();\n"
- +" value_H=val;\n"
- +" SHT10_ReadByte();\n"
- +" value_L=val;\n"
- +" Hvalue = (value_H<< 8 | value_L);\n"
- +" }\n"
- +" SHT10_Calculate();\n")
-
- pin_add_code=(" void SHT10_TransStart(void)\n"
- +"{\n"
- +" MX_GPIO_Init();\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_SET);\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
- +" HAL_Delay(10);\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
- +" HAL_Delay(10);\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_RESET);\n"
- +" HAL_Delay(10);\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
- +" HAL_Delay(10);\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
- +" HAL_Delay(10);\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_SET);\n"
- +" HAL_Delay(10);\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
- +" HAL_Delay(10);\n"
- +"}\n"
- +" void SHT10_WriteByte(void)\n"
- +"{\n"
- +" MX_GPIO_Init();\n"
- +" for (i=0x80;i>0;i/=2)\n"
- +" {\n"
- +" if (i & 0x03)\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_SET);\n"
- +" else\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_RESET);\n"
- +" HAL_Delay(10);\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
- +" HAL_Delay(10);\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
- +" HAL_Delay(10);\n"
- +" }\n"
- +" MX_GPIO_Input1("+pin1+");\n"
- +" HAL_Delay(10);\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
- +" HAL_Delay(10);\n"
- +" error=HAL_GPIO_ReadPin("+pin_group+","+pin1+");\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
- +" HAL_Delay(10);\n"
- +"}\n"
- +" void SHT10_WriteByte2(void)\n"
- +"{\n"
- +" MX_GPIO_Init();\n"
- +" for (i=0x80;i>0;i/=2)\n"
- +" {\n"
- +" if (i & 0x05)\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_SET);\n"
- +" else\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_RESET);\n"
- +" HAL_Delay(10);\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
- +" HAL_Delay(10);\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
- +" HAL_Delay(10);\n"
- +" }\n"
- +" MX_GPIO_Input1("+pin1+");\n"
- +" HAL_Delay(10);\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
- +" HAL_Delay(10);\n"
- +" error=HAL_GPIO_ReadPin("+pin_group+", "+pin1+");\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
- +" HAL_Delay(10);\n"
- +"}\n"
- +" void SHT10_ReadByte(void)\n"
- +"{\n"
- +" val=0;\n"
- +" MX_GPIO_Input1("+pin1+");\n"
- +" for (i=0x80;i>0;i/=2)\n"
- +" {\n"
- +" HAL_Delay(10);\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
- +" HAL_Delay(10);\n"
- +" if(HAL_GPIO_ReadPin("+pin_group+","+pin1+"))\n"
- +" val=( val | i );\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
- +" }\n"
- +" MX_GPIO_Init();\n"
- +" if (1)\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_RESET);\n"
- +" else\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin1+",GPIO_PIN_SET);\n"
- +" HAL_Delay(10);\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_SET);\n"
- +" HAL_Delay(10);\n"
- +" HAL_GPIO_WritePin("+pin_group+","+pin2+",GPIO_PIN_RESET);\n"
- +" HAL_Delay(10);\n"
- +"}\n"
- +" void SHT10_Calculate(void)\n"
- +"{\n"
- +" temp_C=d1+d2*Cvalue;\n"
- +" RH_Lin = C1+C2*Hvalue+C3*Hvalue*Hvalue;\n"
- +" RH_Ture= (temp_C-25)*(T1+T2*Hvalue)+RH_Lin;\n"
- +" if (RH_Ture>100)\n"
- +" RH_Ture= 100;\n"
- +" if (RH_Ture<0.1)\n"
- +" RH_Ture=0.1;\n"
- +" if (temp_C<0)\n"
- +" {\n"
- +" cmd[1]=1;\n"
- +" cmd[2]=-1*temp_C;\n"
- +" temp=(-10*temp_C);\n"
- +" cmd[3]=temp%10;\n"
- +" cmd[4]=RH_Ture;\n"
- +" RH=RH_Ture*10;\n"
- +" cmd[5]=RH%10;\n"
- +" }\n"
- +" else\n"
- +" {\n"
- +" cmd[1]=0;\n"
- +" cmd[2]=temp_C;\n"
- +" temp=(10*temp_C);\n"
- +" cmd[3]=temp%10;\n"
- +" cmd[4]=RH_Ture;\n"
- +" RH=RH_Ture*10;\n"
- +" cmd[5]=RH%10;\n"
- +" }\n"
- +"}\n")
- else:
- pin_variables=""
- pin_code=""
- pin_add_code=""
- sensor_code=""
- def DS18B20(pin_position,pin_type):
- global pin_variables,pin_code,pin_add_code
- global sensor_code
- if pin_position=="M14":
- pin1="GPIO_PIN_0"
- if pin_position=="M16":
- pin1="GPIO_PIN_7"
- if pin_type =="DS18B20":
- print("DS18B20 ok")
- pin_variables=("#define CLR_DS18B20() HAL_GPIO_WritePin (GPIOB, "+pin1+",GPIO_PIN_RESET )\n"
- +"#define SET_DS18B20() HAL_GPIO_WritePin (GPIOB, "+pin1+",GPIO_PIN_SET )\n"
- +"#define DS18B20_DQ_IN HAL_GPIO_ReadPin(GPIOB, "+pin1+")\n"
- +"int16_t temp;\n"
- +"int error;\n"
- +"float "+pin_position+"_"+pin_type+" =0;\n")
- sensor_code=("uint8_t DS18B20_Init(void);\n"
- +"short DS18B20_Get_Temp(void);\n"
- +"void DS18B20_Start(void);\n"
- +"void DS18B20_Write_Byte(uint8_t dat);\n"
- +"uint8_t DS18B20_Read_Byte(void);\n"
- +"uint8_t DS18B20_Read_Bit(void);\n"
- +"uint8_t DS18B20_Check(void);\n"
- +"void DS18B20_Rst(void);\n")
- pin_code=(" temp=DS18B20_Get_Temp();\n")
-
- pin_add_code=(" void delay_us(uint32_t value)\n"
- +"{\n"
- +" uint32_t i;\n"
- +" i = value * 3;\n"
- +" while(i--);\n"
- +"}\n"
- +" void DS18B20_Rst(void)\n"
- +"{\n"
- +" CLR_DS18B20();\n"
- +" delay_us(750);\n"
- +" SET_DS18B20();\n"
- +" delay_us(15);\n"
- +"}\n"
- +" uint8_t DS18B20_Check(void)\n"
- +"{\n"
- +" uint8_t retry=0;\n"
- +" while (DS18B20_DQ_IN&&retry<200)\n"
- +" {\n"
- +" retry++;\n"
- +" delay_us(1);\n"
- +" }\n"
- +" if(retry>=200)return 1;\n"
- +" else retry=0;\n"
- +" while (!DS18B20_DQ_IN&&retry<240)\n"
- +" {\n"
- +" retry++;\n"
- +" delay_us(1);\n"
- +" }\n"
- +" if(retry>=240)return 1;\n"
- +" return 0;\n"
- +"}\n"
- +" uint8_t DS18B20_Read_Bit(void)\n"
- +"{\n"
- +" uint8_t data;\n"
- +" CLR_DS18B20();\n"
- +" delay_us(2);\n"
- +" SET_DS18B20();\n"
- +" delay_us(12);\n"
- +" if(DS18B20_DQ_IN)data=1;\n"
- +" else data=0;\n"
- +" delay_us(50);\n"
- +" return data;\n"
- +"}\n"
- +" uint8_t DS18B20_Read_Byte(void)\n"
- +"{\n"
- +" uint8_t i,j,dat;\n"
- +" dat=0;\n"
- +" for (i=1;i<=8;i++)\n"
- +" {\n"
- +" j=DS18B20_Read_Bit();\n"
- +" dat=(j<<7)|(dat>>1);\n"
- +" }\n"
- +" return dat;\n"
- +"}\n"
- +" void DS18B20_Write_Byte(uint8_t dat)\n"
- +"{\n"
- +" uint8_t j;\n"
- +" uint8_t testb;\n"
- +" for (j=1;j<=8;j++)\n"
- +" {\n"
- +" testb=dat&0x01;\n"
- +" dat=dat>>1;\n"
- +" if (testb)\n"
- +" {\n"
- +" CLR_DS18B20();\n"
- +" delay_us(2);\n"
- +" SET_DS18B20();\n"
- +" delay_us(60);\n"
- +" }\n"
- +" else\n"
- +" {\n"
- +" CLR_DS18B20();\n"
- +" delay_us(60);\n"
- +" SET_DS18B20();\n"
- +" delay_us(2);\n"
- +" }\n"
- +" }\n"
- +"}\n"
- +" uint8_t DS18B20_Init(void)\n"
- +"{\n"
- +" SET_DS18B20();\n"
- +" DS18B20_Rst();\n"
- +" return DS18B20_Check();\n"
- +"}\n"
- +" void DS18B20_Start(void)\n"
- +"{\n"
- +" DS18B20_Rst();\n"
- +" DS18B20_Check();\n"
- +" DS18B20_Write_Byte(0xcc);\n"
- +" DS18B20_Write_Byte(0x44);\n"
- +"}\n"
- +" short DS18B20_Get_Temp(void)\n"
- +"{\n"
- +" uint8_t temp;\n"
- +" uint8_t TL,TH;\n"
- +" short tem;\n"
- +" DS18B20_Start();\n"
- +" DS18B20_Rst();\n"
- +" DS18B20_Check();\n"
- +" DS18B20_Write_Byte(0xcc);\n"
- +" DS18B20_Write_Byte(0xbe);\n"
- +" TL=DS18B20_Read_Byte();\n"
- +" TH=DS18B20_Read_Byte();\n"
- +" if(TH>7)\n"
- +" {\n"
- +" TH=~TH;\n"
- +" TL=~TL;\n"
- +" temp=0;\n"
- +" }\n"
- +" else temp=1;\n"
- +" tem=TH;\n"
- +" tem<<=8;\n"
- +" tem+=TL;\n"
- +" tem=(float)tem*0.625f;\n"
- +" if(temp)return tem;\n"
- +" else return -tem;\n"
- +"}\n")
- else:
- pin_variables=""
- pin_code=""
- pin_add_code=""
- sensor_code=""
- def BMP280(pin_position,pin_type):
- global pin_variables,pin_code,pin_add_code,init_code
- global sensor_code
- if pin_type =="BMP280":
- print("BMP280 ok")
- pin_variables=("uint8_t cmd[7]={0xFF,0x00,0x00,0x00,0x00,0x00,0x0D};\n"
- +"HAL_StatusTypeDef Status;\n"
- +"#define ADDR_AT24C04_WRITE_FIRST_16_PAGES 0xEC\n"
- +"#define ADDR_AT24C04_WRITE_FIRST_16_PAGES 0xEC\n"
- +"#define ADDR_AT24C04_READ 0xED\n"
- +"#define AT24C04_TIMEOUT 0xED\n"
- +"#define AT24C04_PAGE_SIZE 16\n"
- +"#define BUFFER_SIZE 1\n"
- +"uint16_t dig_T1;\n"
- +"uint16_t dig_T2;\n"
- +"uint16_t dig_T3;\n"
- +"uint16_t dig_P1;\n"
- +"uint16_t dig_P2;\n"
- +"uint16_t dig_P3;\n"
- +"uint16_t dig_P4;\n"
- +"uint16_t dig_P5;\n"
- +"uint16_t dig_P6;\n"
- +"uint16_t dig_P7;\n"
- +"uint16_t dig_P8;\n"
- +"uint16_t dig_P9;\n"
- +"uint32_t adc_P=0;\n"
- +"uint32_t adc_T=0;\n"
- +"uint8_t WriteBuffer[BUFFER_SIZE]={0xb6};\n"
- +"uint8_t WriteBuffer1[BUFFER_SIZE]={0xff};\n"
- +"uint8_t WriteBuffer2[BUFFER_SIZE]={0x00};\n"
- +"uint8_t ReadBuffer[BUFFER_SIZE];\n"
- +"int RH;\n"
- +"float "+pin_position+"_"+pin_type+" =0;\n")
- sensor_code=("HAL_StatusTypeDef AT24C04_Write(I2C_HandleTypeDef *hi2c,uint16_t MemAddress,uint8_t *pData);\n"
- +"HAL_StatusTypeDef AT24C04_Read(I2C_HandleTypeDef *hi2c,uint16_t MemAddress,uint8_t *pData);\n"
- +"long bmp280_T_MultipleReadThree(void);\n"
- +"long bmp280_P_MultipleReadThree(void);\n"
- +"short bmp280_MultipleReadTwo(uint16_t addr);\n")
- init_code=(" AT24C04_Write(&hi2c1,0xe0,WriteBuffer);\n"
- +" AT24C04_Write(&hi2c1,0xf4,WriteBuffer1);\n"
- +" AT24C04_Write(&hi2c1,0xf5,WriteBuffer2);\n"
- +" dig_T1 = bmp280_MultipleReadTwo(0x88);\n"
- +" dig_T2 = bmp280_MultipleReadTwo(0x8A);\n"
- +" dig_T3 = bmp280_MultipleReadTwo(0x8C);\n"
- +" dig_P1 = bmp280_MultipleReadTwo(0x8E);\n"
- +" dig_P2 = bmp280_MultipleReadTwo(0x90);\n"
- +" dig_P3 = bmp280_MultipleReadTwo(0x92);\n"
- +" dig_P4 = bmp280_MultipleReadTwo(0x94);\n"
- +" dig_P5 = bmp280_MultipleReadTwo(0x96);\n"
- +" dig_P6 = bmp280_MultipleReadTwo(0x98);\n"
- +" dig_P7 = bmp280_MultipleReadTwo(0x9A);\n"
- +" dig_P8 = bmp280_MultipleReadTwo(0x9C);\n"
- +" dig_P9 = bmp280_MultipleReadTwo(0x9E);\n")
-
- pin_code=(" adc_T=bmp280_T_MultipleReadThree();\n"
- +" adc_P=bmp280_P_MultipleReadThree();\n"
- +" double var1, var2,t_fine;\n"
- +" var1 = (((double) adc_T) / 16384.0 - ((double) dig_T1) / 1024.0)* ((double) dig_T2);\n"
- +" 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"
- +" t_fine = (int32_t) (var1 + var2);\n"
- +" double temperature = (var1 + var2) / 5120.0;\n"
- +" double pressure;\n"
- +" var1 = (t_fine / 2.0) - 64000.0;\n"
- +" var2 = var1 * var1 * ((double) dig_P6) / 32768.0;\n"
- +" var2 = var2 + var1 * ((double) dig_P5) * 2.0;\n"
- +" var2 = (var2 / 4.0) + (((double) dig_P4) * 65536.0);\n"
- +" var1 = (((double) dig_P3) * var1 * var1 / 524288.0+ ((double) dig_P2) * var1) / 524288.0;\n"
- +" var1 = (1.0 + var1 / 32768.0) * ((double) dig_P1);\n"
- +" if (var1 == 0.0)\n"
- +" {\n"
- +" var1 = 0;\n"
- +" }\n"
- +" pressure = 1048576.0 - (double) adc_P;\n"
- +" pressure = (pressure - (var2 / 4096.0)) * 6250.0 / var1;\n"
- +" var1 = ((double) dig_P9) * pressure * pressure / 2147483648.0;"
- +" var2 = pressure * ((double) dig_P8) / 32768.0;\n"
- +" pressure = pressure + (var1 + var2 + ((double) dig_P7)) / 16.0;\n"
- +" cmd[1]=pressure/10000; \n"
- +" int pa =pressure;\n"
- +" cmd[2]=(pa%10000)/100;\n"
- +" cmd[3]=(pa%10000)%100;\n"
- +" HAL_UART_Transmit(&huart4, (uint8_t *)cmd, sizeof(cmd),1);\n")
- pin_add_code=("HAL_StatusTypeDef AT24C04_Write(I2C_HandleTypeDef *hi2c,uint16_t MemAddress,uint8_t *pData)\n"
- +"{\n"
- +" Status = HAL_I2C_Mem_Write(&hi2c1, ADDR_AT24C04_WRITE_FIRST_16_PAGES, MemAddress, I2C_MEMADD_SIZE_8BIT, pData, AT24C04_PAGE_SIZE, AT24C04_TIMEOUT);\n"
- +" return Status;\n"
- +"}\n"
- +"HAL_StatusTypeDef AT24C04_Read(I2C_HandleTypeDef *hi2c,uint16_t MemAddress,uint8_t *pData)\n"
- +"{\n"
- +" Status = HAL_I2C_Mem_Read(&hi2c1, ADDR_AT24C04_READ, MemAddress, I2C_MEMADD_SIZE_8BIT, pData, BUFFER_SIZE, AT24C04_TIMEOUT);\n"
- +" return Status;\n"
- +"}\n"
- +" long bmp280_T_MultipleReadThree()\n"
- +"{\n"
- +" uint8_t msb, lsb, xlsb;\n"
- +" int32_t temp = 0;\n"
- +" AT24C04_Read(&hi2c1,0xfa,ReadBuffer);\n"
- +" msb=ReadBuffer[0];\n"
- +" AT24C04_Read(&hi2c1,0xfb,ReadBuffer);\n"
- +" lsb=ReadBuffer[0];\n"
- +" AT24C04_Read(&hi2c1,0xfc,ReadBuffer);\n"
- +" xlsb=ReadBuffer[0];\n"
- +" temp = ((msb << 12)|(lsb << 4)|(xlsb >> 4));\n"
- +" return temp;\n"
- +"}\n"
- +"long bmp280_P_MultipleReadThree()\n"
- +"{\n"
- +" uint8_t msb, lsb, xlsb;\n"
- +" int32_t pressure = 0;\n"
- +" AT24C04_Read(&hi2c1,0xf7,ReadBuffer);\n"
- +" msb=ReadBuffer[0];\n"
- +" AT24C04_Read(&hi2c1,0xf8,ReadBuffer);\n"
- +" lsb=ReadBuffer[0];\n"
- +" AT24C04_Read(&hi2c1,0xf9,ReadBuffer);\n"
- +" xlsb=ReadBuffer[0];\n"
- +" pressure = ((msb << 12)|(lsb << 4)|(xlsb >> 4));\n"
- +" return pressure;\n"
- +"}\n"
- +" short bmp280_MultipleReadTwo(uint16_t addr )\n"
- +"{\n"
- +" uint8_t msb, lsb;\n"
- +" uint16_t temp = 0;\n"
- +" AT24C04_Read(&hi2c1,addr,ReadBuffer);\n"
- +" lsb = ReadBuffer[0];\n"
- +" AT24C04_Read(&hi2c1,addr+1,ReadBuffer);\n"
- +" msb = ReadBuffer[0];\n"
- +" temp = msb << 8|lsb;\n"
- +" return temp;\n"
- +"}\n")
- else:
- pin_variables=""
- pin_code=""
- pin_add_code=""
- init_code=""
- sensor_code=""
- def motor(pin_position,pin_type):
- global act_code,init_code
- global sensor_code
- if pin_type =="Motor":
- print("motor ok")
- sensor_code=("void user_pwm_setvalue(uint16_t value);\n"
- +"void user_pwm_setvalue2(uint16_t value);\n")
- act_code=("void user_pwm_setvalue(uint16_t value)\n"
- +"{\n"
- +" TIM_OC_InitTypeDef sConfigOC;\n"
- +" sConfigOC.OCMode = TIM_OCMODE_PWM1;\n"
- +" sConfigOC.Pulse = value;\n"
- +" sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;\n"
- +" sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;\n"
- +" HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1);\n"
- +" HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);\n"
- +"}\n")
-
- init_code=(" MX_TIM2_Init();\n")
- else:
- act_code=""
- init_code=""
- sensor_code=""
-
-
- def zigbee(pin_type):
- global pin_variables,pin_code,init_code
- if pin_type =="ON":
- print("zigbee ok")
- pin_variables=("uint8_t zigbeecmd1[5]={0xFE,0x00,0x01,0x00,0x01};\n"
- +"uint8_t zigbeecmd2[5]={0xFE,0x00,0x02,0x00,0x02};\n"
- +"uint8_t zigbeestatu[20];\n"
- +"uint8_t zigbeestatu1[5];\n"
- +'uint8_t zigbeecon[7]="connect";\n'
- +'uint8_t zigbeenotcon[11]="not connect";\n'
- +'uint8_t zigbeechang[14]="change is down";\n')
- init_code=(" HAL_UART_Transmit(&huart2, (uint8_t *)zigbeecmd2, sizeof(zigbeecmd2), 10);\n"
- +" HAL_UART_Receive(&huart2, (uint8_t *)zigbeestatu,sizeof(zigbeestatu),2000);\n"
- +" HAL_UART_Transmit(&huart4, (uint8_t *)zigbeestatu, sizeof(zigbeestatu),10);\n"
- +" HAL_UART_Transmit(&huart2, (uint8_t *)zigbeecmd1, sizeof(zigbeecmd1), 10);\n"
- +" HAL_UART_Receive(&huart2, (uint8_t *)zigbeestatu,sizeof(zigbeestatu),2000);\n"
- +" HAL_UART_Transmit(&huart4, (uint8_t *)zigbeestatu, sizeof(zigbeestatu),10);\n"
- +" if (zigbeestatu[18]== 0x01)\n"
- +" {\n"
- +" HAL_UART_Transmit(&huart4, (uint8_t *)zigbeecon, sizeof(zigbeecon),10);\n"
- +" }\n"
- +" else if(zigbeestatu[18]== 0x05 || zigbeestatu[18]== 0x00)\n"
- +" {\n"
- +" HAL_UART_Transmit(&huart4, (uint8_t *)zigbeenotcon, sizeof(zigbeenotcon),10);\n"
- +" }\n")
- else:
- pin_variables=""
- pin_code=""
- init_code=""
-
- # 控制板燒錄:生成 main.c
- @main.route('/creat_hex')
- def creat_hex():
- info = request.args.to_dict()
- print("info: ", info)
- # 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'}
- # 'mainLength': '1', 'addLength': '0', 'comLength': '22', '
- z_range = int(info['mainLength']) + 1
- x_range = int(info['addLength']) + 1
- y_range = int(info['comLength']) + 1
- tank_num_data = info['tank_num']
- # print("tank_num_data: ", tank_num_data)
- cond_main_all_list = []
- for z in range(1, z_range):
- # 初始
- cond_main_all_dict = {}
- cond_add_list = [] # 附加條件 List
- cond_com_list = [] # 物件動作 List
- # cond_main_dict_all = {}
- # cond_add_dict_all = {}
- # cond_com_dict_all = {}
-
- # print(z)
- # 總條件
- try:
- cond_main_all_dict['cond_main'] = info['cond_main' + str(z)]
- except(KeyError):
- pass
- # print("cond_main_dict: ", cond_main_dict)
- # 附加條件
- for x in range(1, x_range):
- try:
- cond_add_list.append(info['cond_add' + str(z) + '_' + str(x)])
- except(KeyError):
- pass
- # print("cond_add_list: ", cond_add_list)
- cond_main_all_dict['cond_add'] = cond_add_list
- # print("cond_main_dict: ", cond_main_dict)
- # 物件動作
- for y in range(1, y_range):
- try:
- cond_com_list.append(info['cond_com' + str(z) + '_' + str(y)])
- except(KeyError):
- pass
- # print("cond_com_list: ", cond_com_list)
- cond_main_all_dict['cond_com'] = cond_com_list
- # print("cond_main_dict: ", cond_main_dict)
- if cond_com_list != []:
- cond_main_all_list.append(cond_main_all_dict)
- # cond_main_all_list.append(cond_add_dict_all)
- # cond_main_all_list.append(cond_com_dict_all)
- print("cond_main_all_list: ", cond_main_all_list)
- # 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']}]
-
- dry_block_sehedule = {'command':'Dry_OTA', 'tank_num':tank_num_data, 'cond':cond_main_all_list}
- msg = dry_block_sehedule
- # ===== 阿超 CTO.py 程式碼 start ========================================================================================
- # msg = request.args.to_dict()
- print("/creat_hex/<msg> msg: ", msg)
- CURRENT_PATH = os.path.dirname(__file__)
- print("CURRENT_PATH: ", CURRENT_PATH)
- f = open(CURRENT_PATH + "//CTO20220622//Src//main.c", mode='w')
- f.write("/* USER CODE BEGIN Header */\n"
- +"/**\n"
- +" ******************************************************************************\n"
- +" * @file : main.c\n"
- +" * @brief : Main program body\n"
- +" * @attention\n"
- +" *\n"
- +" * <h2><center>© Copyright (c) 2019 STMicroelectronics.\n"
- +" * All rights reserved.</center></h2>\n"
- +" *\n"
- +" * This software component is licensed by ST under BSD 3-Clause license,\n"
- +" * the License; You may not use this file except in compliance with the\n"
- +" * License. You may obtain a copy of the License at:\n"
- +" * www.st.com/SLA0044\n"
- +" *\n"
- +" ******************************************************************************\n"
- +" */\n"
- +"/* USER CODE END Header */\n"
- +"\n"
- +"/* Includes ------------------------------------------------------------------*/\n")
- # 添加標題檔
- header = ('#include"main.h"\n'
- +'#include "adc.h"\n'
- +'#include "usart.h"\n'
- +'#include "i2c.h"\n'
- +'#include "tim.h"\n'
- +'#include "stm32f4xx_hal.h"\n'
- +'#include "gpio.h"\n')
- f.write(header)
- # 變數宣告說明
- f.write("\n"
- + "/* Private variables ---------------------------------------------------------*/\n")
- f.write("\n"
- + "/* Private variables ---------------------------------------------------------*/\n"
- + "#define VECT_TAB_OFFSET 0x10000\n"
- + "int tankstatus = 0;\n")
- # 連接資料庫
- #conn = sqlite3.connect('/home/pi/coffee.db')
- # conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffeemanage', passwd='skyeye', database='CoffeeManage', charset='utf8')
- conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='Gold@53743001', database='CoffeeManage', charset='utf8')
- c = conn.cursor()
- print("connect success")
- # 搜尋最新腳位配置時間
- c.execute("SELECT *from coffee1_0_pin ORDER BY datetime ASC")
- results = c.fetchall()
- for row in results:
- time = row[1]
- c.execute("SELECT *from coffee1_0_pin where datetime='%s'"\
- %(time))
- results=c.fetchall()
- for row in results:
- for i in range (19):
- row[i+26]
- if(row[5]=="ON"):
- print("zigbee on")
- zigbee(row[5])
- f.write(pin_variables)
- for i in range (19):
- if(i==3 or i==4 or i==6):
- PH("M"+str(i+1),row[i+26])
- f.write(pin_variables)
- DO("M"+str(i+1),row[i+26])
- f.write(pin_variables)
- ORP("M"+str(i+1),row[i+26])
- f.write(pin_variables)
- if(i==13 or i== 16):
- SHT11("M"+str(i+1),row[i+26])
- f.write(pin_variables)
- if(i==13 or i== 15):
- DS18B20("M"+str(i+1),row[i+26])
- f.write(pin_variables)
- if(i==14):
- BMP280("M"+str(i+1),row[i+26])
- f.write(pin_variables)
- if(i==5 or i==12):
- SEN0189("M"+str(i+1),row[i+26])
- f.write(pin_variables)
- if(i==0):
- SonicESMUS07("M"+str(i+1),row[i+26])
- f.write(pin_variables)
- if(i==7):
- SOIL("M"+str(i+1),row[i+26])
- f.write(pin_variables)
- if(i==8 or i==11 or i==18 or i==10):
- WATERLEVEL("M"+str(i+1),row[i+26])
- f.write(pin_variables)
- motorfeedback("M"+str(i+1),row[i+26])
- f.write(pin_variables)
- butterflyvalvefeedback("M"+str(i+1),row[i+26])
- f.write(pin_variables)
- if(i==15):
- EC("M"+str(i+1),row[i+26])
- f.write(pin_variables)
- #感測器和致動器副函式宣告----------------------------------------------------------------
- f.write("/* USER CODE BEGIN PV */\n"
- +"typedef void (*pFunction)(void);\n"
- +"/* USER CODE END PV */\n"
- +"/* Private function prototypes -----------------------------------------------*/\n"
- +"void SystemClock_Config(void);\n"
- +"void MX_ADC1_Init1(char pin);\n"
- +"void sensor(void);\n")
- #感測器和致動器副函式宣告----------------------------------------------------------------
- #連接資料庫
- conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='Gold@53743001', database='CoffeeManage', charset='utf8')
- c = conn.cursor()
- print ("connect success")
- #搜尋最新腳位配置時間
- c.execute("SELECT *from coffee1_0_pin ORDER BY datetime ASC")
- results=c.fetchall()
- for row in results:
- time = row[1]
- #腳位配置加入
- c.execute("SELECT *from coffee1_0_pin where datetime='%s'"\
- %(time))
- results=c.fetchall()
- for row in results:
- for i in range (19):
- row[i+26]
- for i in range (19):
- if(i==13 or i== 16):
- SHT11("M"+str(i+1),row[i+26])
- f.write(sensor_code)
- if(i==13 or i== 15):
- DS18B20("M"+str(i+1),row[i+26])
- f.write(sensor_code)
- if(i==14):
- BMP280("M"+str(i+1),row[i+26])
- f.write(sensor_code)
- if(i==9):
- motor("M"+str(i+1),row[i+26])
- f.write(sensor_code)
- f.write("/* USER CODE BEGIN PFP */\n"
- +"/* USER CODE END PFP */\n"
- +"/* Private user code ---------------------------------------------------------*/\n"
- +"/* USER CODE BEGIN 0 */\n"
- +"/* USER CODE END 0 */\n"
- +"/**\n"
- +"* @brief The application entry point.\n"
- +"* @retval int\n"
- +"*/\n")
- #主程式撰寫--------------------------------------------------------------------------------
- #main宣告
- f.write("int main(void)\n"
- +"{\n"
- +" SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET;\n")
- #致能週邊---------------------------------------------------------------------------------------
- enable=(" HAL_Init();\n"
- +" SystemClock_Config();\n"
- +" MX_GPIO_Init();\n"
- +" MX_USART2_UART_Init();\n"
- +" MX_UART4_Init();\n"
- +" MX_USART1_UART_Init();\n")
- f.write(enable)
- #連接資料庫
- # conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffeemanage', passwd='skyeye', database='CoffeeManage', charset='utf8')
- conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='Gold@53743001', database='CoffeeManage', charset='utf8')
- #conn = sqlite3.connect('/home/pi/coffee.db')
- c = conn.cursor()
- print("connect success")
- #搜尋最新腳位配置時間
- c.execute("SELECT *from coffee1_0_pin ORDER BY datetime ASC")
- results = c.fetchall()
- for row in results:
- time = row[1]
- # 腳位配置加入
- c.execute("SELECT *from coffee1_0_pin where datetime='%s'"
- % (time))
- results = c.fetchall()
- for row in results:
- for i in range(19):
- row[i+26]
- if(row[5]=="ON"):
- print("zigbee on")
- zigbee(row[5])
- f.write(init_code)
- for i in range (19):
- if(i==14):
- BMP280("M"+str(i+1),row[i+26])
- f.write(init_code)
- if(i==9):
- motor("M"+str(i+1),row[i+26])
- f.write(init_code)
- #---------------------------------------------------------------------------------------------
- code=(" while (1)\n"
- +" {\n"
- +" sensor();\n")
- f.write(code)
- #MQTT條件分析寫入--------------------------------------------------------------------------------
- for i in range (len(msg['cond'])):
- m=msg['cond'][i]['cond_main'].split(" ")
- if(m[0]=="else" and m[1]=="if"):
- m[0]=m[0]+" "+m[1]
- m[1]=m[1]
- m[2]=m[2]
- m[3]=m[3]
- m[4]=m[4]
- m=""+m[0]+"("+m[1]+m[2]+m[3]
- f.write(" "+m)
- if(m[0] == " "):
- m = ""
- else:
- print(len(msg['cond'][i]['cond_add']))
- if(len(msg['cond'][i]['cond_add'])==0):
- add=")\n"
- f.write(add)
- else:
- for j in range (len(msg['cond'][i]['cond_add'])):
- if(j==len(msg['cond'][i]['cond_add'])-1):
- if(msg['cond'][i]['cond_add'][j]==" "):
- add=")\n"
- else:
- add=" "+str(msg['cond'][i]['cond_add'][j])+")\n"
- f.write(add)
- else:
- if(msg['cond'][i]['cond_add'][j]==" "):
- add=""
- else:
- add=" "+str(msg['cond'][i]['cond_add'][j])
- f.write(add)
- f.write(" {\n")
- for j in range(len(msg['cond'][i]['cond_com'])):
- if(j == len(msg['cond'][i]['cond_com'])-1):
- if(msg['cond'][i]['cond_com'][j] == " "):
- com = "\n}\n"
- else:
- com = msg['cond'][i]['cond_com'][j].split("_")
- comm = msg['cond'][i]['cond_com'][j].split(" ")
- if(comm[0] == "sleep"):
- com[0] = comm[0]
- com = " "+GPIO(com[0], comm[1])+"\n }\n"
- f.write(com)
- else:
- if(msg['cond'][i]['cond_com'][j] == " "):
- com = ""
- else:
- com = msg['cond'][i]['cond_com'][j].split("_")
- comm = msg['cond'][i]['cond_com'][j].split(" ")
- if(comm[0] == "sleep"):
- com[0] = comm[0]
- com = " "+GPIO(com[0], comm[1])+"\n"
- f.write(com)
- f.write(" }\n")
- f.write("}\n")
- # 系統時鐘宣告
- time = ("void SystemClock_Config(void)\n"
- + "{\n"
- + " RCC_OscInitTypeDef RCC_OscInitStruct = {0};\n"
- + " RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};\n"
- + " __HAL_RCC_PWR_CLK_ENABLE();\n"
- + " __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);\n"
- + " RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;\n"
- + " RCC_OscInitStruct.HSIState = RCC_HSI_ON;\n"
- + " RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;\n"
- + " RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;\n"
- + " RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;\n"
- + " RCC_OscInitStruct.PLL.PLLM = 8;\n"
- + " RCC_OscInitStruct.PLL.PLLN = 72;\n"
- + " RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;\n"
- + " RCC_OscInitStruct.PLL.PLLQ = 3;\n"
- + " RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;\n"
- + " if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)\n"
- + " {\n"
- + " Error_Handler();\n"
- + " }\n"
- + " RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK\n"
- + " |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;\n"
- + " RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;\n"
- + " RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;\n"
- + " RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;\n"
- + " RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;\n"
- + " if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)\n"
- + " {\n"
- + " Error_Handler();\n"
- + " }\n"
- + "}\n")
- f.write(time)
- #馬達和伺服馬達副函式------------------------------------------------------------------------------
- add_code2=("void user_pwm_setvalue(uint16_t value)\n"
- +"{\n"
- +" TIM_OC_InitTypeDef sConfigOC;\n"
- +" sConfigOC.OCMode = TIM_OCMODE_PWM1;\n"
- +" sConfigOC.Pulse = value;\n"
- +" sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;\n"
- +" sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;\n"
- +" HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1);\n"
- +" HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);\n"
- +"}\n"
- +"void user_pwm_setvalue2(uint16_t value)\n"
- +"{\n"
- +" TIM_OC_InitTypeDef sConfigOC;\n"
- +" sConfigOC.OCMode = TIM_OCMODE_PWM1;\n"
- +" sConfigOC.Pulse = value;\n"
- +" sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;\n"
- +" sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;\n"
- +" HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_2);\n"
- +" HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_2);\n"
- +"}\n")
- f.write(add_code2)
- #感測器程式-----------------------------------------------------------------------------------------------------
- sensor=("void sensor(void)\n"
- +"{\n")
- f.write(sensor)
-
- conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='Gold@53743001', database='CoffeeManage', charset='utf8')
- #conn = sqlite3.connect('/home/pi/coffee.db')
- c = conn.cursor()
- print ("connect success")
- #搜尋最新腳位配置時間
- c.execute("SELECT *from coffee1_0_pin ORDER BY datetime ASC")
- results = c.fetchall()
- for row in results:
- time = row[1]
- #腳位配置加入
- c.execute("SELECT *from coffee1_0_pin where datetime='%s'"\
- %(time))
- results = c.fetchall()
- for row in results:
- for i in range (19):
- row[i+26]
- if(row[5]=="ON"):
- print("zigbee on")
- zigbee(row[5])
- f.write(pin_code)
- for i in range (19):
- if(i==3 or i==4 or i==6):
- PH("M"+str(i+1),row[i+26])
- f.write(pin_code)
- DO("M"+str(i+1),row[i+26])
- f.write(pin_code)
- ORP("M"+str(i+1),row[i+26])
- f.write(pin_code)
- if(i==13 or i== 16):
- SHT11("M"+str(i+1),row[i+26])
- f.write(pin_code)
- if(i==13 or i== 15):
- DS18B20("M"+str(i+1),row[i+26])
- f.write(pin_code)
- if(i==14):
- BMP280("M"+str(i+1),row[i+26])
- f.write(pin_code)
- if(i==5 or i==12):
- SEN0189("M"+str(i+1),row[i+26])
- f.write(pin_code)
- if(i==0):
- SonicESMUS07("M"+str(i+1),row[i+26])
- f.write(pin_code)
- if(i==7):
- SOIL("M"+str(i+1),row[i+26])
- f.write(pin_code)
- if(i==8 or i==11 or i==18 or i==10):
- WATERLEVEL("M"+str(i+1),row[i+26])
- f.write(pin_code)
- motorfeedback("M"+str(i+1),row[i+26])
- f.write(pin_code)
- butterflyvalvefeedback("M"+str(i+1),row[i+26])
- f.write(pin_code)
- if(i==15):
- EC("M"+str(i+1),row[i+26])
- f.write(pin_code)
- sensor=(" HAL_Delay(10000);\n"
- +"}\n")
- f.write(sensor)
- #加入感測器副函式程式碼-------------------------------------------------------------------------------
- conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='Gold@53743001', database='CoffeeManage', charset='utf8')
- c = conn.cursor()
- print ("connect success")
- #搜尋最新腳位配置時間
- c.execute("SELECT *from coffee1_0_pin ORDER BY datetime ASC")
- results = c.fetchall()
- for row in results:
- time = row[1]
- #腳位配置加入
- c.execute("SELECT *from coffee1_0_pin where datetime='%s'"\
- %(time))
- results = c.fetchall()
- for row in results:
- for i in range (19):
- row[i+26]
- for i in range (19):
- if(i==13 or i== 16):
- SHT11("M"+str(i+1),row[i+26])
- f.write(pin_add_code)
- if(i==13 or i== 15):
- DS18B20("M"+str(i+1),row[i+26])
- f.write(pin_add_code)
- if(i==14):
- BMP280("M"+str(i+1),row[i+26])
- f.write(pin_add_code)
- if(i==0):
- SonicESMUS07("M"+str(i+1),row[i+26])
- f.write(pin_add_code)
- if(i==7):
- SOIL("M"+str(i+1),row[i+26])
- f.write(pin_add_code)
- if(i==15):
- EC("M"+str(i+1),row[i+26])
- f.write(pin_add_code)
- #ADC程式宣告----------------------------------------------------------------------------------
- gpio=("void MX_ADC1_Init1(char pin)\n"
- +"{\n"
- +" ADC_ChannelConfTypeDef sConfig = {0};\n"
- +" hadc1.Instance = ADC1;\n"
- +" hadc1.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;\n"
- +" hadc1.Init.Resolution = ADC_RESOLUTION_12B;\n"
- +" hadc1.Init.ScanConvMode = DISABLE;\n"
- +" hadc1.Init.ContinuousConvMode = DISABLE;\n"
- +" hadc1.Init.DiscontinuousConvMode = DISABLE;\n"
- +" hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;\n"
- +" hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;\n"
- +" hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;\n"
- +" hadc1.Init.NbrOfConversion = 1;\n"
- +" hadc1.Init.DMAContinuousRequests = DISABLE;\n"
- +" hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;\n"
- +" if (HAL_ADC_Init(&hadc1) != HAL_OK)\n"
- +" {\n"
- +" Error_Handler();\n"
- +" }\n"
- +" sConfig.Channel = pin;\n"
- +" sConfig.Rank = 1;\n"
- +" sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;\n"
- +" if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)\n"
- +" {\n"
- +" Error_Handler();\n"
- +" }\n"
- +"}\n")
- f.write(gpio)
-
- #GPIO input程式宣告----------------------------------------------------------------------------------
- gpio2=("void MX_GPIO_Input1(unsigned long pin)\n"
- +"{\n"
- +" GPIO_InitTypeDef GPIO_InitStruct = {0};\n"
- +" __HAL_RCC_GPIOE_CLK_ENABLE();\n"
- +" GPIO_InitStruct.Pin = pin;\n"
- +" GPIO_InitStruct.Mode = GPIO_MODE_INPUT;\n"
- +" GPIO_InitStruct.Pull = GPIO_PULLDOWN;\n"
- +" HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);\n"
- +"}\n")
- f.write(gpio2)
- #錯誤程式-------------------------------------------------------------------------------------
- f.write("void Error_Handler(void)\n{\n}\n")
- f.close()
- f = open(CURRENT_PATH + "//CTO20220622//Src//main.c", mode='r')
- words = f.read()
- # print(words)
- f.close()
- # server_log(msg['command'], "D1", "ok") # 06/15 Rita 原為阿超丟 MQTT 給網頁, 先註解
- # ===== 阿超 CTO.py 程式碼 end ========================================================================================
- # ===== 編譯 CTO20220622整個資料夾並在build資料夾生成所需的hex檔 start ========================
- cwdDATA = os.path.join(CURRENT_PATH, "CTO20220622")
- print("cwdDATA: ", cwdDATA)
- # 以下指令要在 Linux 上測試, Windows 未安裝會報錯
- # make_result = 0
- make_result = subprocess.call(["sudo", "make"],cwd = cwdDATA)
- # ===== 編譯 CTO20220622整個資料夾並在build資料夾生成所需的hex檔 end ========================
- if make_result == 0:
- return "OK"
- else:
- return "NG"
- #
- @main.route('/loader', methods=['GET', 'POST'])
- def loader():
- info = request.args.to_dict()
- # print("info: ", info)
- ethernet_list = info['ethernet_list']
- print("ethernet_list: ", ethernet_list, type(ethernet_list))
- wifi_list = info['wifi_list']
- print("wifi_list: ", wifi_list, type(wifi_list))
- zigbee_list = info['zigbee_list']
- print("zigbee_list: ", zigbee_list, type(zigbee_list))
- # 將 string 以 , 分割成 list
- relay_list = info['relay_list'].split(',')
- print("relay_list: ", relay_list, type(relay_list))
- pwm_list = info['pwm_list'].split(',')
- print("pwm_list: ", pwm_list, type(pwm_list))
- digital_list = info['digital_list'].split(',')
- print("digital_list: ", digital_list, type(digital_list))
- uart_list = info['uart_list'].split(',')
- print("uart_list: ", uart_list, type(uart_list))
- i2c_list = info['i2c_list'].split(',')
- print("i2c_list: ", i2c_list, type(i2c_list))
- s485_list = info['s485_list'].split(',')
- print("s485_list: ", s485_list, type(s485_list))
- ppa_list = info['ppa_list'].split(',')
- print("ppa_list: ", ppa_list, type(ppa_list))
- return jsonify({"response":"OK" })
- # # Rita 測試
- @main.route('/drop_down_list')
- def drop_down_list():
- # 獲取登入信息
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- # TODO
- mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffee',
- password='skyeye', database='Coffee', charset='utf8')
- mycursor = mydb.cursor()
- conn = pymysql.connect(
- host='52.69.200.169',
- port=3306,
- user='coffee',
- password='skyeye',
- database='Coffee',
- charset='utf8'
- )
- cur = conn.cursor()
- #獲取欄位資料
- sql = "select * from product_info"
- cur.execute(sql)
- content = cur.fetchall()
- #獲取欄位名稱
- sql = "SHOW FIELDS FROM product_info"
- cur.execute(sql)
- labels = cur.fetchall()
- # print("labels: ", labels) # labels: (('產品', 'varchar(4)', 'YES', '', None, ''), ('系統', 'varchar(5)', 'YES', '', None, ''),
- labels = [g[0] for g in labels]
- # print("labels: ", labels) # labels: ['產品', '系統', '系統圖號', '狀態', '進貨狀態', '序號', '組序號',
- return render_template('drop_down_list.html', labels=labels, content=content)
- else:
- return render_template('sign_in.html')
- # !!! AttributeError: 'NoneType' object has no attribute 'vacuum'
- @main.route('/loading/container', methods=['GET', 'POST'])
- def container_loading():
- if request.method == 'GET':
- # 清洗浮選狀態
- clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
- Clean_container_status_list = [clean_status.Clean_Tank_1,
- clean_status.Clean_Tank_2,
- clean_status.Clean_Tank_3,
- clean_status.Clean_Tank_4]
- CLEAN_Waiting_number = int(Clean_container_status_list.count('C_Waiting'))
- CLEAN_Warning_number = int(Clean_container_status_list.count('C_Warning'))
- if CLEAN_Waiting_number == len(Clean_container_status_list): Clean_container = 'Waiting'
- elif CLEAN_Warning_number >= 1: Clean_container = 'Warning'
- else: Clean_container = 'Working'
- # 清洗浮選狀態
- ColorSelect_container_status_list = [clean_status.ColorSelect_Tank_1,
- clean_status.ColorSelect_Tank_2]
- COLORSELECT_Waiting_number = int(ColorSelect_container_status_list.count('S_Waiting'))
- COLORSELECT_Warning_number = int(ColorSelect_container_status_list.count('S_Warning'))
- if COLORSELECT_Waiting_number == len(ColorSelect_container_status_list): ColorSelect_container = 'Waiting'
- elif COLORSELECT_Warning_number >= 1: ColorSelect_container = 'Warning'
- else: ColorSelect_container = 'Working'
- # 脫皮機
- Peel_container_status_list = [clean_status.Peel_Tank_1,
- clean_status.Peel_Tank_2]
- PEEL_Waiting_number = int(Peel_container_status_list.count('P_Waiting'))
- PEEL_Warning_number = int(Peel_container_status_list.count('P_Warning'))
- if PEEL_Waiting_number == len(Peel_container_status_list): Peel_container = 'Waiting'
- elif PEEL_Warning_number >= 1: Peel_container = 'Warning'
- else: Peel_container = 'Working'
- # 發酵槽
- ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
- Ferment_container_status_list = [ferment_status.Ferment_Tank_1,
- ferment_status.Ferment_Tank_2,
- ferment_status.Ferment_Tank_3,
- ferment_status.Ferment_Tank_4,
- ferment_status.Ferment_Tank_5,
- ferment_status.Ferment_Tank_6,
- ferment_status.Ferment_Tank_7,
- ferment_status.Ferment_Tank_8,
- ferment_status.Ferment_Tank_9,
- ferment_status.Ferment_Tank_10,
- ferment_status.Ferment_Tank_11,
- ferment_status.Ferment_Tank_12]
- FERMENT_Waiting_number = int(Ferment_container_status_list.count('F_Waiting'))
- FERMENT_Warning_number = int(Ferment_container_status_list.count('F_Warning'))
- if FERMENT_Waiting_number == len(Ferment_container_status_list): Ferment_container = 'Waiting'
- elif FERMENT_Warning_number >= 1: Ferment_container = 'Warning'
- else: Ferment_container = 'Working'
- # 乾燥槽
- dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
- Dry_container_status_list = [dry_status.Dry_Tank_1,
- dry_status.Dry_Tank_2,
- dry_status.Dry_Tank_3,
- dry_status.Dry_Tank_4,
- dry_status.Dry_Tank_5,
- dry_status.Dry_Tank_6,
- dry_status.Dry_Tank_7,
- dry_status.Dry_Tank_8,
- dry_status.Dry_Tank_9,
- dry_status.Dry_Tank_10,
- dry_status.Dry_Tank_11,
- dry_status.Dry_Tank_12]
- DRY_Waiting_number= int(Dry_container_status_list.count('D_Waiting'))
- DRY_Warning_number= int(Dry_container_status_list.count('D_Warning'))
- if DRY_Waiting_number == len(Dry_container_status_list): Dry_container = 'Waiting'
- elif DRY_Warning_number >= 1: Dry_container = 'Warning'
- else: Dry_container = 'Working'
- return jsonify({"Clean_container":Clean_container,
- "ColorSelect_container":ColorSelect_container,
- "Peel_container":Peel_container,
- "Ferment_container":Ferment_container,
- "Dry_container":Dry_container
- })
- @main.route('/loading_sensors', methods=['GET', 'POST'])
- def loading_sensors():
- C1_UltraSonic = (clean_tank_UltraSonic.query.filter_by(tank_num='C1').order_by(text('datetime desc')).first()).UltraSonic
- C2_UltraSonic = (clean_tank_UltraSonic.query.filter_by(tank_num='C2').order_by(text('datetime desc')).first()).UltraSonic
- PO1_UltraSonic = (peel_output_UltraSonic.query.filter_by(tank_num='PO1').order_by(text('datetime desc')).first()).UltraSonic
- PO2_UltraSonic = (peel_output_UltraSonic.query.filter_by(tank_num='PO2').order_by(text('datetime desc')).first()).UltraSonic
- F1_UltraSonic = (ferment_tank_UltraSonic.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()).UltraSonic
- F1_SHT11Temp = (ferment_tank_SHT11.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()).SHT11_Temp
- F1_SHT11Humidity = (ferment_tank_SHT11.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()).SHT11_Humidity
- F2_UltraSonic = (ferment_tank_UltraSonic.query.filter_by(tank_num='F2').order_by(text('datetime desc')).first()).UltraSonic
- D1_UltraSonic = (dry_tank_UltraSonic.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()).UltraSonic
- D1_SHT11Temp = (dry_tank_SHT11.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()).SHT11_Temp
- D1_SHT11Humidity = (dry_tank_SHT11.query.filter_by(tank_num='D1').order_by(text('datetime desc')).first()).SHT11_Humidity
- D2_UltraSonic = (dry_tank_UltraSonic.query.filter_by(tank_num='D2').order_by(text('datetime desc')).first()).UltraSonic
- DO1_UltraSonic = (dry_output_sensor.query.filter_by(tank_num='DO1').order_by(text('datetime desc')).first()).UltraSonic
- DO2_UltraSonic = (dry_output_sensor.query.filter_by(tank_num='DO2').order_by(text('datetime desc')).first()).UltraSonic
-
- return jsonify({"C1_UltraSonic":C1_UltraSonic,
- "C2_UltraSonic":C2_UltraSonic,
- "PO1_UltraSonic":PO1_UltraSonic,
- "PO2_UltraSonic":PO2_UltraSonic,
- "F1_UltraSonic":F1_UltraSonic,
- "F1_SHT11Temp":F1_SHT11Temp,
- "F1_SHT11Humidity":F1_SHT11Humidity,
- "F2_UltraSonic":F2_UltraSonic,
- "D1_UltraSonic":D1_UltraSonic,
- "D1_SHT11Temp":D1_SHT11Temp,
- "D1_SHT11Humidity":D1_SHT11Humidity,
- "D2_UltraSonic":D2_UltraSonic,
- "DO1_UltraSonic":DO1_UltraSonic,
- "DO2_UltraSonic":DO2_UltraSonic
- })
- @main.route('/demo', methods=['GET', 'POST'])
- def demo():
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
- CI1 = clean_status.Clean_Input_1
- CI2 = clean_status.Clean_Input_2
- C1 = clean_status.Clean_Tank_1
- C2 = clean_status.Clean_Tank_2
- R1 = clean_status.Reclaimed_Tank_1
- S1 = clean_status.ColorSelect_Tank_1
- S2 = clean_status.ColorSelect_Tank_2
- SOg1 = clean_status.ColorSelect_Output_g1
- SOb1 = clean_status.ColorSelect_Output_b1
- SOg2 = clean_status.ColorSelect_Output_g2
- SOb2 = clean_status.ColorSelect_Output_b2
- P1 = clean_status.Peel_Tank_1
- P2 = clean_status.Peel_Tank_2
- PO1 = clean_status.Peel_Output_1
- PO2 = clean_status.Peel_Output_2
- ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
- F1 = ferment_status.Ferment_Tank_1
- F2 = ferment_status.Ferment_Tank_2
- dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
- D1 = dry_status.Dry_Tank_1
- D2 = dry_status.Dry_Tank_2
- DO1 = dry_status.Dry_Output_1
- DO2 = dry_status.Dry_Output_2
- POb1 = clean_status.Peel_Output_b1
- return render_template('demo.html', title="[測試] DEMO 貨櫃自動化", **locals())
- else:
- return render_template('sign_in.html')
- @main.route('/demo_auto', methods=['GET', 'POST'])
- def demo_auto():
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
- CI1 = clean_status.Clean_Input_1
- CI2 = clean_status.Clean_Input_2
- C1 = clean_status.Clean_Tank_1
- C2 = clean_status.Clean_Tank_2
- # 中水桶
- S1 = clean_status.ColorSelect_Tank_1
- S2 = clean_status.ColorSelect_Tank_2
- SOg1 = clean_status.ColorSelect_Output_g1
- SOb1 = clean_status.ColorSelect_Output_b1
- SOg2 = clean_status.ColorSelect_Output_g2
- SOb2 = clean_status.ColorSelect_Output_b2
- P1 = clean_status.Peel_Tank_1
- P2 = clean_status.Peel_Tank_2
- PO1 = clean_status.Peel_Output_1
- PO2 = clean_status.Peel_Output_2
- ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
- F1 = ferment_status.Ferment_Tank_1
- F2 = ferment_status.Ferment_Tank_2
- dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
- D1 = dry_status.Dry_Tank_1
- D2 = dry_status.Dry_Tank_2
- DO1 = dry_status.Dry_Output_1
- DO2 = dry_status.Dry_Output_2
- POb1 = clean_status.Peel_Output_b1
- return render_template('demo_auto.html', title="[測試] DEMO 貨櫃自動化", **locals())
- else:
- return render_template('sign_in.html')
- # 脫皮機自動化測試頁
- @main.route('/peel_auto_status', methods=['GET', 'POST'])
- def peel_auto_test():
- info = request.args.to_dict()
- # 寫定出料的空桶標準, 若 <= 2 則為空桶
- Peel_Output_bean_empty = 2
- # 從介面取得 指定生豆高度
- Peel_Tank_bean_height = float(info['Peel_Tank_bean_height'])
- Peel_Tank_motor_rpm = float(info['Peel_Tank_motor_rpm'])
- Peel_Tank_vacuumON_time = float(info['Peel_Tank_vacuumON_time'])
- Peel_Tank_vacuumOFF_time = float(info['Peel_Tank_vacuumOFF_time'])
- clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
- P1 = clean_status.Peel_Tank_1
- P2 = clean_status.Peel_Tank_2
- PO1 = clean_status.Peel_Output_1
- PO2 = clean_status.Peel_Output_2
- SO1 = 'SO_OutputtingBean' # SO_OutputtingBean SO_Waiting
- SO2 = 'SO_Waiting'
- # -- 取得脫皮機 P1~P2 桶內高度 UltraSonic -------------
- PO_UP_tank_UltraSonic = []
- for i in range(1, 3, 1):
- output_UltraSonic = peel_output_UltraSonic.query.filter_by(tank_num='PO' + str(i)).order_by(text('datetime desc')).first()
- UltraSonic = float(output_UltraSonic.UltraSonic)
- PO_UP_tank_UltraSonic.append(UltraSonic)
- print('PO_UP_tank_UltraSonic: ', PO_UP_tank_UltraSonic)
- # -- 取得脫皮機 P1~P2 桶內高度 UltraSonic -------------
- if P1 == 'P_Waiting' and PO1 != 'PO_OutputtingBean' and SO1 == 'SO_OutputtingBean':
- P1 = 'P_Peeling'
- PO1 = 'PO_InputtingBean'
- print('------- P1 狀態更新:脫皮中 -------')
- print('------- PO1 狀態更新:入豆中 -------')
- # [致動器] 馬達 指定轉速
- data = { "tank_num": "P1", "command": "tank_motor_status", "value": Peel_Tank_motor_rpm}
- print('data: ', data)
- # mqtt_f(data)
- if P1 == 'P_Peeling':
- if PO_UP_tank_UltraSonic[0] >= Peel_Tank_bean_height:
- # [致動器] 真空吸料機 OFF
- data = { "tank_num": "P1", "command": "tank_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 0
- data = { "tank_num": "P1", "command": "tank_motor_status", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- P1 = 'P_Waiting'
- PO1 = 'PO_OutputtingBean'
- print('------- P1 狀態更新:等待中 -------')
- print('------- PO1 狀態更新:可出豆 -------')
- elif PO_UP_tank_UltraSonic[0] < Peel_Tank_bean_height:
- # [致動器] 真空吸料機 ON
- data = { "tank_num": "P1", "command": "tank_vacuum_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- while True:
- if (time.time() - timer) > Peel_Tank_vacuumON_time:
- # [致動器] 真空吸料機 OFF
- data = { "tank_num": "P1", "command": "tank_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- break
- while True:
- if (time.time() - timer) > Peel_Tank_vacuumOFF_time:
- break
- if PO1 == 'PO_OutputtingBean' and PO_UP_tank_UltraSonic[0] <= Peel_Output_bean_empty:
- PO1 = 'PO_Waiting'
- print('------- PO1 狀態更新:空桶等待 -------')
-
- CI1 = 'CI_Warning'
- CI2 = 'CI_Waiting'
- C1 = 'C_Warning'
- C2 = 'C_Waiting'
- C3 = 'C_Waiting'
- C4 = 'C_Waiting'
- SI1 = 'SI_Warning'
- SI2 = 'SI_Waiting'
- S1 = 'S_Warning'
- S2 = 'S_Waiting'
- SOg1 = 'SO_Warning'
- SOb1 = 'SO_Warning'
- SOg2 = 'SO_Waiting'
- SOb2 = 'SO_Waiting'
- POb1 = 'PO_Waiting'
-
- # ----- 將狀態寫入資料庫 ------------------------------
- # 獲取文本框的值並賦值給user實體對象
- C_status = clean_container_status()
- C_status.Clean_Input_1 = CI1
- C_status.Clean_Input_2 = CI2
- C_status.Clean_Tank_1 = C1
- C_status.Clean_Tank_2 = C2
- C_status.Clean_Tank_3 = C3
- C_status.Clean_Tank_4 = C4
- C_status.ColorSelect_Input_1 = SI1
- C_status.ColorSelect_Input_2 = SI2
- C_status.ColorSelect_Tank_1 = S1
- C_status.ColorSelect_Tank_2 = S2
- C_status.ColorSelect_Output_g1 = SOg1
- C_status.ColorSelect_Output_b1 = SOb1
- C_status.ColorSelect_Output_g2 = SOg2
- C_status.ColorSelect_Output_b2 = SOb2
- C_status.Peel_Tank_1 = P1
- C_status.Peel_Tank_2 = P2
- C_status.Peel_Output_1 = PO1
- C_status.Peel_Output_2 = PO2
- C_status.Peel_Output_b1 = POb1
- #將數據保存進資料庫
- db.session.add(C_status)
- # 手動提交
- db.session.commit()
- # ----- 將狀態寫入資料庫 ------------------------------
-
- return jsonify({"Peel_Tank_1":P1,
- "Peel_Tank_2":P2,
- "Peel_Output_1":PO1,
- "Peel_Output_2":PO2
- })
- # 乾燥槽狀態更新
- @main.route('/dry_status_update', methods=['GET', 'POST'])
- def dry_status_update():
- dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
- DI1 = dry_status.Dry_Input_1
- DI2 = dry_status.Dry_Input_2
- D1 = dry_status.Dry_Tank_1
- D2 = dry_status.Dry_Tank_2
- D3 = dry_status.Dry_Tank_3
- D4 = dry_status.Dry_Tank_4
- D5 = dry_status.Dry_Tank_5
- D6 = dry_status.Dry_Tank_6
- D7 = dry_status.Dry_Tank_7
- D8 = dry_status.Dry_Tank_8
- D9 = dry_status.Dry_Tank_9
- D10 = dry_status.Dry_Tank_10
- D11 = dry_status.Dry_Tank_11
- D12 = dry_status.Dry_Tank_12
- DO1 = dry_status.Dry_Output_1
- DO2 = dry_status.Dry_Output_2
- return jsonify({"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
- })
- # 乾燥槽自動化測試頁
- @main.route('/dry_auto', methods=['GET', 'POST'])
- def dry_auto():
- # 獲取登入信息
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
- DI1 = dry_status.Dry_Input_1
- DI2 = dry_status.Dry_Input_2
- D1 = dry_status.Dry_Tank_1
- D2 = dry_status.Dry_Tank_2
- D3 = dry_status.Dry_Tank_3
- D4 = dry_status.Dry_Tank_4
- D5 = dry_status.Dry_Tank_5
- D6 = dry_status.Dry_Tank_6
- D7 = dry_status.Dry_Tank_7
- D8 = dry_status.Dry_Tank_8
- D9 = dry_status.Dry_Tank_9
- D10 = dry_status.Dry_Tank_10
- D11 = dry_status.Dry_Tank_11
- D12 = dry_status.Dry_Tank_12
- DO1 = dry_status.Dry_Output_1
- DO2 = dry_status.Dry_Output_2
-
- return render_template('dry_auto.html', title="[測試] 乾燥自動化", **locals())
- else:
- return render_template('sign_in.html')
- # 乾燥槽 乾燥暫停 出料
- @main.route('/dryDEMO_outputtingBean', methods=['GET', 'POST'])
- def dryDEMO_outputtingBean():
- info = request.args.to_dict()
- Dry_Output_bean_height = float(info['Dry_Output_bean_height'])
- Dry_Output_vacuumON_time = float(info['Dry_Output_vacuumON_time'])
- Dry_Output_vacuumOFF_time = float(info['Dry_Output_vacuumOFF_time'])
- dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
- DI1 = dry_status.Dry_Input_1 # DI1 == 'DI_OutputtingBean'
- DI2 = dry_status.Dry_Input_2
- D1 = dry_status.Dry_Tank_1
- D2 = dry_status.Dry_Tank_2
- D3 = dry_status.Dry_Tank_3
- D4 = dry_status.Dry_Tank_4
- D5 = dry_status.Dry_Tank_5
- D6 = dry_status.Dry_Tank_6
- D7 = dry_status.Dry_Tank_7
- D8 = dry_status.Dry_Tank_8
- D9 = dry_status.Dry_Tank_9
- D10 = dry_status.Dry_Tank_10
- D11 = dry_status.Dry_Tank_11
- D12 = dry_status.Dry_Tank_12
- DO1 = dry_status.Dry_Output_1
- DO2 = dry_status.Dry_Output_2
- # # -- 取得乾燥出料儲豆槽 DO1~DO2 桶內高度 UltraSonic -------------
- # DO_UP_UltraSoniclist = []
- # for i in range(1, 3, 1):
- # output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO' + str(i)).order_by(text('datetime desc')).first()
- # UltraSonic = float(output_UltraSonic.UltraSonic)
- # DO_UP_UltraSoniclist.append(UltraSonic)
- # print('DO_UP_UltraSoniclist: ', DO_UP_UltraSoniclist)
- # # -- 取得乾燥出料儲豆槽 DO1~DO2 桶內高度 UltraSonic -------------
- # 將桶槽 D1 狀態轉換成可出豆, DO1 狀態轉換成可入豆
- D1 = 'D_OutputtingBean'
- # [致動器] 設定溫度 0.0
- data = { "tank_num": "D1", "command": "tank_temp", "value": "0.0" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 溫控開關 OFF
- data = { "tank_num": "D1", "command": "tank_temp_enable", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 0
- data = { "tank_num": "D1", "command": "tank_motor_status", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 排水電磁閥 OFF
- data = { "tank_num": "D1", "command": "tank_solenoid_water_out_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] D1 蝴蝶閥 ON
- data = { "tank_num": "D1", "command": "tank_diskvalve_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
-
- # ----- 將狀態寫入資料庫 ------------------------------
- # 獲取文本框的值並賦值給user實體對象
- D_status = dry_container_status()
- D_status.Dry_Input_1 = DI1
- D_status.Dry_Input_2 = DI2
- D_status.Dry_Tank_1 = D1
- D_status.Dry_Tank_2 = D2
- D_status.Dry_Tank_3 = D3
- D_status.Dry_Tank_4 = D4
- D_status.Dry_Tank_5 = D5
- D_status.Dry_Tank_6 = D6
- D_status.Dry_Tank_7 = D7
- D_status.Dry_Tank_8 = D8
- D_status.Dry_Tank_9 = D9
- D_status.Dry_Tank_10 = D10
- D_status.Dry_Tank_11 = D11
- D_status.Dry_Tank_12 = D12
- D_status.Dry_Output_1 = DO1
- D_status.Dry_Output_2 = DO2
- #將數據保存進資料庫
- db.session.add(D_status)
- # 手動提交
- db.session.commit()
- # ----- 將狀態寫入資料庫 ------------------------------
-
- return jsonify({"Dry_Tank_1":D1,
- "Dry_Tank_2":D2,
- "Dry_Output_1":DO1,
- "Dry_Output_2":DO2
- })
- @main.route('/dryDEMO_auto_status', methods=['GET', 'POST'])
- def dryDEMO_auto_status():
- info = request.args.to_dict()
- # 寫定入料、桶槽、出料的空桶標準, 若 <= 2 則為空桶
- Dry_Tank_bean_empty = 2
- Dry_Output_bean_empty = 2
- # 從介面取得 指定生豆高度/發酵桶槽排程:發酵、清洗、校正 EC、校正攪拌棒
- Dry_Tank_bean_height = float(info['Dry_Tank_bean_height'])
- Dry_Tank_vacuumON_time = float(info['Dry_Tank_vacuumON_time'])
- Dry_Tank_vacuumOFF_time = float(info['Dry_Tank_vacuumOFF_time'])
- Dry_Tank_drying_temp = float(info['Dry_Tank_drying_temp'])
- Dry_Tank_drying_time = float(info['Dry_Tank_drying_time'])
- Dry_Tank_motor_rpm = float(info['Dry_Tank_motor_rpm'])
- Dry_Tank_drying_Humidity = float(info['Dry_Tank_drying_Humidity'])
- Dry_Output_bean_height = float(info['Dry_Output_bean_height'])
- Dry_Output_vacuumON_time = float(info['Dry_Output_vacuumON_time'])
- Dry_Output_vacuumOFF_time = float(info['Dry_Output_vacuumOFF_time'])
- Dry_Tank_Disinfect_time = float(info['Dry_Tank_Disinfect_timef'])
- # [介面] 讓使用者可以選擇排程內有乾燥/清洗/校正, 此處預設為 True
- Dry_btn = True
- # 從資料庫資料表中取得最新狀態
- # ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
- # FO1 = 'FO_OutputtingBean'
- # FO2 = 'FO_Waiting'
- # FO1 = 'FO_OutputtingBean' # 'FO_OutputtingBean' FO_Waiting
- # FO2 = 'FO_Waiting'
- dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
- DI1 = dry_status.Dry_Input_1 # DI1 == 'DI_OutputtingBean'
- DI2 = dry_status.Dry_Input_2
- D1 = dry_status.Dry_Tank_1
- D2 = dry_status.Dry_Tank_2
- D3 = dry_status.Dry_Tank_3
- D4 = dry_status.Dry_Tank_4
- D5 = dry_status.Dry_Tank_5
- D6 = dry_status.Dry_Tank_6
- D7 = dry_status.Dry_Tank_7
- D8 = dry_status.Dry_Tank_8
- D9 = dry_status.Dry_Tank_9
- D10 = dry_status.Dry_Tank_10
- D11 = dry_status.Dry_Tank_11
- D12 = dry_status.Dry_Tank_12
- DO1 = dry_status.Dry_Output_1
- DO2 = dry_status.Dry_Output_2
- D_UP_tanklist = [D1, D2, D3, D4, D5, D6]
- D_DOWN_tanklist = [D7, D8, D9, D10, D11, D12]
- DOutputtingBean_Tank = '' # 出料桶槽號
- DryAuto_cleaning = 0 # 清洗次數
- # 目前乾燥槽 D1~D6 正在入豆的桶槽數量 (應小於一桶)
- DryUp_Waiting_number = int(D_UP_tanklist.count('D_Waiting'))
- DryUp_InputtingBean_number = int(D_UP_tanklist.count('D_InputtingBean'))
- DryUp_InputtingBeanPause_number = int(D_UP_tanklist.count('D_InputtingBean_Pause'))
- # -- 取得乾燥入料儲豆槽 FI1~FI2 桶內高度 UltraSonic -------------
- DI_UP_UltraSoniclist = []
- for i in range(1, 3, 1):
- input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI' + str(i)).order_by(text('datetime desc')).first()
- UltraSonic = float(input_UltraSonic.UltraSonic)
- DI_UP_UltraSoniclist.append(UltraSonic)
- print('DI_UP_UltraSoniclist: ', DI_UP_UltraSoniclist)
- # -- 取得乾燥入料儲豆槽 FI1~FI2 桶內高度 UltraSonic -------------
- # -- 取得乾燥桶槽 D1~D6 超音波生豆高度 UltraSonic -------------
- D_UP_tank_UltraSonic = []
- for i in range(1, 7, 1):
- tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
- UltraSonic = float(tank_UltraSonic.UltraSonic)
- D_UP_tank_UltraSonic.append(UltraSonic)
- print('D_UP_tank_UltraSonic: ', D_UP_tank_UltraSonic)
- # -- 取得乾燥桶槽 D1~D6 超音波生豆高度 UltraSonic -------------
- # -- 取得乾燥出料儲豆槽 DO1~DO2 桶內高度 UltraSonic -------------
- DO_UP_UltraSoniclist = []
- for i in range(1, 3, 1):
- output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO' + str(i)).order_by(text('datetime desc')).first()
- UltraSonic = float(output_UltraSonic.UltraSonic)
- DO_UP_UltraSoniclist.append(UltraSonic)
- print('DO_UP_UltraSoniclist: ', DO_UP_UltraSoniclist)
- # -- 取得乾燥出料儲豆槽 DO1~DO2 桶內高度 UltraSonic -------------
- # -- 取得乾燥桶槽 D1~D6 桶內溫濕度計 SHT11 -------------
- D_UP_tank_SHT11Temp = []
- D_UP_tank_SHT11Humidity = []
- for i in range(1, 7, 1):
- tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
- SHT11_Temp = float(tank_SHT11.SHT11_Temp)
- D_UP_tank_SHT11Temp.append(SHT11_Temp)
- SHT11_Humidity = float(tank_SHT11.SHT11_Humidity)
- D_UP_tank_SHT11Humidity.append(SHT11_Humidity)
- print('D_UP_tank_SHT11Temp: ', D_UP_tank_SHT11Temp)
- print('D_UP_tank_SHT11Humidity: ', D_UP_tank_SHT11Humidity)
- # -- 取得乾燥桶槽 D1~D6 桶內溫濕度計 SHT11 -------------
- # -- 取得乾燥桶槽 D1~D6 三合一土壤感測器 Soil -------------
- D_UP_tank_SoilTemp = []
- D_UP_tank_SoilHumidity = []
- D_UP_tank_SoilEC = []
- for i in range(1, 7, 1):
- tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
- soil_Temp = float(tank_Soil.soil_Temp)
- D_UP_tank_SoilTemp.append(soil_Temp)
- soil_Humidity = float(tank_Soil.soil_Humidity)
- D_UP_tank_SoilHumidity.append(soil_Humidity)
- soil_EC = float(tank_Soil.soil_EC)
- D_UP_tank_SoilEC.append(soil_EC)
- # print('D_UP_tank_SoilTemp: ', D_UP_tank_SoilTemp)
- # print('D_UP_tank_SoilHumidity: ', D_UP_tank_SoilHumidity)
- # print('D_UP_tank_SoilEC: ', D_UP_tank_SoilEC)
- # -- 取得乾燥桶槽 D1~D6 三合一土壤感測器 SHT11 -------------
- # ----- 發酵排程動作 start ------------------------------------------------------------------
- # if D1 == 'D_InputtingBean': D_UP_tank_UltraSonic[0] >= Dry_Tank_bean_height:
- def DInputtingBean_TO_DInputtingBeanFinish(tid):
- # [致動器] 真空吸料機 OFF
- data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 蝴蝶閥 OFF
- data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # # [致動器] F1 蝴蝶閥 OFF [ 1109 測試用 ]
- # data = { "tank_num": "F1", "command": "tank_diskvalve_status", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- # [致動器] 馬達 0
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 入料三通閥 ON排氣
- data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid,' 狀態更新:入豆完成 -------')
- # if D1 == 'D_InputtingBean': elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
- def DInputtingBean_AND_notfilled(tid):
- # [致動器] 蝴蝶閥 OFF
- data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 入料三通閥 OFF入豆
- data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 真空吸料機 ON
- data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- while True:
- if (time.time() - timer) > Dry_Tank_vacuumON_time:
- # [致動器] 真空吸料機 OFF
- data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- break
- while True:
- if (time.time() - timer) > Dry_Tank_vacuumOFF_time:
- break
- # if D1 == 'D_InputtingBean': elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
- def DInputtingBean_TO_DInputtingBeanPause(tid):
- # [致動器] 蝴蝶閥 OFF
- data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 真空吸料機 OFF
- data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 0
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid,' 狀態更新:入豆暫停 -------')
- # elif DryUp_InputtingBeanPause_number == 1 and DI1 == 'DI_OutputtingBean': if D1 == 'D_InputtingBean_Pause':
- def DInputtingBeanPause_TO_DInputtingBean(tid):
- # [致動器] 入料三通閥 OFF入豆
- data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 5
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid, ' 狀態更新:入豆中 -------')
- # elif DryUp_InputtingBean_number == 0 and DryUp_InputtingBeanPause_number == 0 and DI1 == 'DI_OutputtingBean' and DryUp_Waiting_number >= 1:
- def DWaiting_TO_DInputtingBean(tid):
- # [致動器] F1 蝴蝶閥 ON
- data = { "tank_num": "F1", "command": "tank_diskvalve_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 蝴蝶閥 OFF
- data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 入料三通閥 OFF入豆
- data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 5
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid, ' 狀態更新:入豆中 -------')
- # else: if D1 == 'D_InputtingBean_Finish':
- def DInputtingBeanFinish_TO_DDrying(tid):
- # [致動器] 馬達 指定轉速
- data = { "tank_num": tid, "command": "tank_motor_status", "value": Dry_Tank_motor_rpm }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 排水電磁閥 ON
- data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # # [致動器] 鼓風機 ON
- # data = { "tank_num": tid, "command": "tank_blower_status", "value": "on" }
- # print('data: ', data)
- # # mqtt_f(data)
- # # [致動器] 加熱器 1 ON
- # data = { "tank_num": tid, "command": "tank_heater1_status", "value": "on" }
- # print('data: ', data)
- # # mqtt_f(data)
- # # [致動器] 加熱器 2 ON
- # data = { "tank_num": tid, "command": "tank_heater2_status", "value": "on" }
- # print('data: ', data)
- # # mqtt_f(data)
- # [致動器] 溫控開關 ON
- data = { "tank_num": tid, "command": "tank_temp_enable", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 設定溫度 (指定溫度)
- data = { "tank_num": tid, "command": "tank_temp", "value": Dry_Tank_drying_temp }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid, ' 狀態更新:乾燥中 -------')
- # 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:
- def DDrying_TO_DOutputtingBean(tid):
- # # [致動器] 鼓風機 OFF
- # data = { "tank_num": tid, "command": "tank_blower_status", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- # # [致動器] 加熱器 1 OFF
- # data = { "tank_num": tid, "command": "tank_heater1_status", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- # # [致動器] 加熱器 2 OFF
- # data = { "tank_num": tid, "command": "tank_heater2_status", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- # [致動器] 設定溫度 0
- data = { "tank_num": tid, "command": "tank_temp", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 溫控開關 OFF
- data = { "tank_num": tid, "command": "tank_temp_enable", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 0
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- print("乾燥結束, 返潮暫停 ", Dry_Tank_drying_time, " 秒")
- timer = time.time()
- while True:
- if (time.time() - timer) > Dry_Tank_drying_time:
- # [致動器] 排水電磁閥 OFF
- data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- break
- print('------- ', tid, ' 狀態更新:可出豆 -------')
- # else: if D1 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[0] <= Dry_Tank_bean_empty):
- def DOutputtingBean_TO_DWaiting(tid):
- # [致動器] D1 蝴蝶閥 OFF
- data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # D_Cleaning
- def DCleaning(tid):
- # [致動器] 馬達 10
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "10" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 消毒電磁閥 ON
- data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 排水電磁閥 OFF
- data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] TODO 消毒抽水 pump ON
- print("消毒 ", Dry_Tank_Disinfect_time, " 秒")
- timer = time.time()
- while True:
- if (time.time() - timer) > Dry_Tank_Disinfect_time:
- # [致動器] TODO 消毒抽水 pump OFF
- break
- # [致動器] 消毒電磁閥 OFF
- data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 0
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 排水電磁閥 ON
- data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- print("桶內排水 ", Dry_Tank_Disinfect_time, " 秒")
- timer = time.time()
- while True:
- if (time.time() - timer) > Dry_Tank_Disinfect_time:
- break
- # [致動器] 排水電磁閥 OFF
- data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid, ' 狀態更新:空桶等待 -------')
- # ----- 發酵排程動作 end ------------------------------------------------------------------
-
- # [介面] 若啟用 乾燥 狀態
- if Dry_btn:
- # ----- 乾燥桶槽 D1~D6 入料桶槽優先入料判斷 ------------------------------
- # 若 D1~D6 桶槽中有一個桶槽入豆中
- if DryUp_InputtingBean_number == 1:
- # 若 D1 桶槽為入豆中
- if D1 == 'D_InputtingBean':
- # 若桶槽生豆高度大於指定生豆高度, 則狀態轉換成 入料完成
- if D_UP_tank_UltraSonic[0] >= Dry_Tank_bean_height:
- DInputtingBean_TO_DInputtingBeanFinish("D1")
- D1 = 'D_InputtingBean_Finish'
- # 若桶槽生豆高度未達指定生豆高度, 且 入料儲豆槽可出豆
- elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
- DInputtingBean_AND_notfilled("D1")
- # 若桶槽生豆高度未達指定生豆高度, 且 入料儲豆槽 非可出豆
- elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
- DInputtingBean_TO_DInputtingBeanPause("D1")
- D1 = 'D_InputtingBean_Pause'
- # 若 D1~D6 桶槽中有一個桶槽入豆暫停
- elif DryUp_InputtingBeanPause_number == 1 and DI1 == 'DI_OutputtingBean':
- if D1 == 'D_InputtingBean_Pause':
- DInputtingBeanPause_TO_DInputtingBean("D1")
- D1 = 'D_InputtingBean'
- # 若 D1~D6 桶槽中皆無 入豆中 和 入豆暫停, 且入料儲豆槽可出豆
- elif DryUp_InputtingBean_number == 0 and DryUp_InputtingBeanPause_number == 0 and DI1 == 'DI_OutputtingBean' and DryUp_Waiting_number >= 1:
- if D1 == 'D_Waiting':
- DWaiting_TO_DInputtingBean("D1")
- D1 = 'D_InputtingBean'
- # 其他
- # else:
- # 以下內容原在此 else 內, 測試無誤後維持
- # 如果桶槽為 入豆完成, 將狀態轉換成 乾燥中
- if D1 == 'D_InputtingBean_Finish':
- DInputtingBeanFinish_TO_DDrying("D1")
- D1 = 'D_Drying'
- # 如果桶槽為 乾燥中, 達乾燥條件後, 將狀態轉換成 可出豆
- if D1 == 'D_Drying' and D_UP_tank_SHT11Temp[0] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[0] <= Dry_Tank_drying_Humidity:
- DDrying_TO_DOutputtingBean("D1")
- D1 = 'D_OutputtingBean'
- if DOutputtingBean_Tank == '': DOutputtingBean_Tank = 'D1'
-
- # 如果桶槽 D1~D6 可出豆 且 桶槽內為空桶 且 有指定清洗排程, 進行清洗桶槽
- # TODO 發酵次數計算、消毒次數、校正
- if D1 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[0] <= Dry_Tank_bean_empty):
- if DOutputtingBean_Tank == 'D1':
- DOutputtingBean_TO_DWaiting('D1')
- DOutputtingBean_Tank = ''
- if (DryAuto_cleaning == 0): D1 = 'D_Waiting'
- elif (DryAuto_cleaning != 0): D1 = 'D_Cleaning'
- # 避免桶槽可出豆時未賦值
- if DOutputtingBean_Tank == '':
- if D1 == 'D_OutputtingBean': DOutputtingBean_Tank = 'D1'
-
- # 乾燥槽消毒
- if D1 == 'D_Cleaning':
- DCleaning("D1")
- D1 = 'D_Waiting'
- else:
- print('未啟用乾燥流程')
- # ----- 乾燥出料儲豆槽 DO1~DO2 入豆→可出豆判斷 ------------------------------
- # 若出料儲豆槽狀態為 空桶等待 且 桶槽狀態為 D_OutputtingBean 可出豆, 與 FO1 配合開始出豆
-
- # # 1109 註解實驗用
- # if DO1 == 'DO_Waiting' and DOutputtingBean_Tank != '':
- # # 判斷要對應出料的桶槽為何, 設定成 DOutputtingBean_Tank = 'D1', 待出完料再把 DOutputtingBean_Tank = ''
- # DO1 = 'DO_InputtingBean'
- # print('------- ' + DOutputtingBean_Tank + ' 狀態更新:出豆中 -------')
- # print('------- DO1 狀態更新:入豆中 -------')
- # # [致動器] D1 蝴蝶閥 ON
- # data = { "tank_num": DOutputtingBean_Tank, "command": "tank_diskvalve_status", "value": "on" }
- # print('data: ', data)
- # # mqtt_f(data)
- # elif DO1 == 'DO_InputtingBean' and DOutputtingBean_Tank != '':
- # if DO_UP_UltraSoniclist[0] >= Dry_Output_bean_height:
- # # [致動器] 出料真空吸料機 OFF
- # data = { "tank_num": DOutputtingBean_Tank, "command": "output_vacuum_status", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- # # [致動器] D1 蝴蝶閥 OFF
- # data = { "tank_num": DOutputtingBean_Tank, "command": "tank_diskvalve_status", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- # DO1 = 'DO_OutputtingBean'
- # print('------- DO1 狀態更新:可出豆 -------')
- # elif DO_UP_UltraSoniclist[0] < Dry_Output_bean_height:
- # # [致動器] 出料真空吸料機 ON
- # data = { "tank_num": DOutputtingBean_Tank, "command": "output_vacuum_status", "value": "on" }
- # print('data: ', data)
- # # mqtt_f(data)
- # timer = time.time()
- # while True:
- # if (time.time() - timer) > Dry_Output_vacuumON_time:
- # # [致動器] 出料真空吸料機 OFF
- # data = { "tank_num": DOutputtingBean_Tank, "command": "output_vacuum_status", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- # timer = time.time()
- # break
- # while True:
- # if (time.time() - timer) > Dry_Output_vacuumOFF_time:
- # break
- # # 若是無桶槽可入豆, 出料儲豆槽判斷是否可出豆或空桶等待入豆
- # elif DO1 == 'DO_InputtingBean' and DOutputtingBean_Tank == '':
- # if DO_UP_UltraSoniclist[0] > Dry_Output_bean_empty:
- # DO1 = 'DO_OutputtingBean'
- # print('------- DO1 狀態更新:可出豆 -------')
- # elif DO_UP_UltraSoniclist[0] <= Dry_Output_bean_empty:
- # DO1 = 'DO_Waiting'
- # print('------- DO1 狀態更新:空桶等待 -------')
- # elif DO1 == 'DO_OutputtingBean' and DO_UP_UltraSoniclist[0] <= Dry_Output_bean_empty:
- # DO1 = 'DO_Waiting'
- # # [致動器] D1 蝴蝶閥 OFF
- # data = { "tank_num": "D1", "command": "tank_diskvalve_status", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- # print('------- DO1 狀態更新:空桶等待 -------')
- # # 1109 註解實驗用
-
- # # ----- [測試用] !!!!! D1~D6 入料完成→可出豆 判斷 ------------------------------
- # if D1 == 'D_InputtingBean_Finish': D1 = 'D_OutputtingBean'
- # if D2 == 'D_InputtingBean_Finish': D2 = 'D_OutputtingBean'
- # if D3 == 'D_InputtingBean_Finish': D3 = 'D_OutputtingBean'
- # if D4 == 'D_InputtingBean_Finish': D4 = 'D_OutputtingBean'
- # if D5 == 'D_InputtingBean_Finish': D5 = 'D_OutputtingBean'
- # if D6 == 'D_InputtingBean_Finish': D6 = 'D_OutputtingBean'
- # # ----- [測試用] !!!!! D1~D6 入料完成→可出豆 判斷 ------------------------------
- # ----- 將狀態寫入資料庫 ------------------------------
- # 獲取文本框的值並賦值給user實體對象
- D_status = dry_container_status()
- D_status.Dry_Input_1 = DI1
- D_status.Dry_Input_2 = DI2
- D_status.Dry_Tank_1 = D1
- D_status.Dry_Tank_2 = D2
- D_status.Dry_Tank_3 = D3
- D_status.Dry_Tank_4 = D4
- D_status.Dry_Tank_5 = D5
- D_status.Dry_Tank_6 = D6
- D_status.Dry_Tank_7 = D7
- D_status.Dry_Tank_8 = D8
- D_status.Dry_Tank_9 = D9
- D_status.Dry_Tank_10 = D10
- D_status.Dry_Tank_11 = D11
- D_status.Dry_Tank_12 = D12
- D_status.Dry_Output_1 = DO1
- D_status.Dry_Output_2 = DO2
- #將數據保存進資料庫
- db.session.add(D_status)
- # 手動提交
- db.session.commit()
- # ----- 將狀態寫入資料庫 ------------------------------
-
- return jsonify({"Dry_Tank_1":D1,
- "Dry_Tank_2":D2,
- "Dry_Output_1":DO1,
- "Dry_Output_2":DO2
- })
- @main.route('/dry_auto_status', methods=['GET', 'POST'])
- def dry_auto_status():
- info = request.args.to_dict()
- # 寫定入料、桶槽、出料的空桶標準, 若 <= 2 則為空桶
- Dry_Input_bean_empty = 2
- Dry_Tank_bean_empty = 2
- Dry_Output_bean_empty = 2
- # 從介面取得 指定生豆高度/發酵桶槽排程:發酵、清洗、校正 EC、校正攪拌棒
- Dry_Input_bean_height = float(info['Dry_Input_bean_height'])
- Dry_Input_vacuumON_time = float(info['Dry_Input_vacuumON_time'])
- Dry_Input_vacuumOFF_time = float(info['Dry_Input_vacuumOFF_time'])
- Dry_Tank_bean_height = float(info['Dry_Tank_bean_height'])
- Dry_Tank_vacuumON_time = float(info['Dry_Tank_vacuumON_time'])
- Dry_Tank_vacuumOFF_time = float(info['Dry_Tank_vacuumOFF_time'])
- Dry_Tank_drying_temp = float(info['Dry_Tank_drying_temp'])
- Dry_Tank_drying_time = float(info['Dry_Tank_drying_time'])
- Dry_Tank_drying_EC = float(info['Dry_Tank_drying_EC'])
- Dry_Tank_motor_rpm = float(info['Dry_Tank_motor_rpm'])
- Dry_Tank_TempWeight_SHT11 = float(info['Dry_Tank_TempWeight_SHT11'])
- Dry_Tank_TempWeight_soil = float(info['Dry_Tank_TempWeight_soil'])
- Dry_Tank_drying_Humidity = float(info['Dry_Tank_drying_Humidity'])
- Dry_Output_bean_height = float(info['Dry_Output_bean_height'])
- Dry_Output_vacuumON_time = float(info['Dry_Output_vacuumON_time'])
- Dry_Output_vacuumOFF_time = float(info['Dry_Output_vacuumOFF_time'])
- Dry_Tank_Disinfect_time = float(info['Dry_Tank_Disinfect_time'])
- # [介面] 讓使用者可以選擇排程內有乾燥/清洗/校正, 此處預設為 True
- Dry_btn = True
- # 從資料庫資料表中取得最新狀態
- ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
- FO1 = ferment_status.Ferment_Output_1
- FO2 = ferment_status.Ferment_Output_2
- # FO1 = 'FO_OutputtingBean' # 'FO_OutputtingBean' FO_Waiting
- # FO2 = 'FO_Waiting'
- dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
- DI1 = dry_status.Dry_Input_1
- DI2 = dry_status.Dry_Input_2
- D1 = dry_status.Dry_Tank_1
- D2 = dry_status.Dry_Tank_2
- D3 = dry_status.Dry_Tank_3
- D4 = dry_status.Dry_Tank_4
- D5 = dry_status.Dry_Tank_5
- D6 = dry_status.Dry_Tank_6
- D7 = dry_status.Dry_Tank_7
- D8 = dry_status.Dry_Tank_8
- D9 = dry_status.Dry_Tank_9
- D10 = dry_status.Dry_Tank_10
- D11 = dry_status.Dry_Tank_11
- D12 = dry_status.Dry_Tank_12
- DO1 = dry_status.Dry_Output_1
- DO2 = dry_status.Dry_Output_2
- D_UP_tanklist = [D1, D2, D3, D4, D5, D6]
- D_DOWN_tanklist = [D7, D8, D9, D10, D11, D12]
- DOutputtingBean_Tank = '' # 出料桶槽號
- DryAuto_cleaning = 0 # 清洗次數
- # 目前乾燥槽 D1~D6 正在入豆的桶槽數量 (應小於一桶)
- DryUp_Waiting_number = int(D_UP_tanklist.count('D_Waiting'))
- DryUp_InputtingBean_number = int(D_UP_tanklist.count('D_InputtingBean'))
- DryUp_InputtingBeanPause_number = int(D_UP_tanklist.count('D_InputtingBean_Pause'))
- # -- 取得乾燥入料儲豆槽 FI1~FI2 桶內高度 UltraSonic -------------
- DI_UP_UltraSoniclist = []
- for i in range(1, 3, 1):
- input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI' + str(i)).order_by(text('datetime desc')).first()
- UltraSonic = float(input_UltraSonic.UltraSonic)
- DI_UP_UltraSoniclist.append(UltraSonic)
- print('DI_UP_UltraSoniclist: ', DI_UP_UltraSoniclist)
- # -- 取得乾燥入料儲豆槽 FI1~FI2 桶內高度 UltraSonic -------------
- # -- 取得乾燥桶槽 D1~D6 超音波生豆高度 UltraSonic -------------
- D_UP_tank_UltraSonic = []
- for i in range(1, 7, 1):
- tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
- UltraSonic = float(tank_UltraSonic.UltraSonic)
- D_UP_tank_UltraSonic.append(UltraSonic)
- print('D_UP_tank_UltraSonic: ', D_UP_tank_UltraSonic)
- # -- 取得乾燥桶槽 D1~D6 超音波生豆高度 UltraSonic -------------
- # -- 取得乾燥出料儲豆槽 DO1~DO2 桶內高度 UltraSonic -------------
- DO_UP_UltraSoniclist = []
- for i in range(1, 3, 1):
- output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO' + str(i)).order_by(text('datetime desc')).first()
- UltraSonic = float(output_UltraSonic.UltraSonic)
- DO_UP_UltraSoniclist.append(UltraSonic)
- print('DO_UP_UltraSoniclist: ', DO_UP_UltraSoniclist)
- # -- 取得乾燥出料儲豆槽 DO1~DO2 桶內高度 UltraSonic -------------
- # -- 取得乾燥桶槽 D1~D6 桶內溫濕度計 SHT11 -------------
- D_UP_tank_SHT11Temp = []
- D_UP_tank_SHT11Humidity = []
- for i in range(1, 7, 1):
- tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
- SHT11_Temp = float(tank_SHT11.SHT11_Temp)
- D_UP_tank_SHT11Temp.append(SHT11_Temp)
- SHT11_Humidity = float(tank_SHT11.SHT11_Humidity)
- D_UP_tank_SHT11Humidity.append(SHT11_Humidity)
- # print('D_UP_tank_SHT11Temp: ', D_UP_tank_SHT11Temp)
- # print('D_UP_tank_SHT11Humidity: ', D_UP_tank_SHT11Humidity)
- # -- 取得乾燥桶槽 D1~D6 桶內溫濕度計 SHT11 -------------
- # -- 取得乾燥桶槽 D1~D6 三合一土壤感測器 Soil -------------
- D_UP_tank_SoilTemp = []
- D_UP_tank_SoilHumidity = []
- D_UP_tank_SoilEC = []
- for i in range(1, 7, 1):
- tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
- soil_Temp = float(tank_Soil.soil_Temp)
- D_UP_tank_SoilTemp.append(soil_Temp)
- soil_Humidity = float(tank_Soil.soil_Humidity)
- D_UP_tank_SoilHumidity.append(soil_Humidity)
- soil_EC = float(tank_Soil.soil_EC)
- D_UP_tank_SoilEC.append(soil_EC)
- # print('D_UP_tank_SoilTemp: ', D_UP_tank_SoilTemp)
- # print('D_UP_tank_SoilHumidity: ', D_UP_tank_SoilHumidity)
- # print('D_UP_tank_SoilEC: ', D_UP_tank_SoilEC)
- # -- 取得乾燥桶槽 D1~D6 三合一土壤感測器 SHT11 -------------
- # -- 取得乾燥桶槽 D1~D6 權重後溫度值 -------------
- D_UP_tank_weightTemp = []
- for i in range(1, 7, 1):
- tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
- tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
- 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)
- D_UP_tank_weightTemp.append(Temp)
- print('D_UP_tank_weightTemp: ', D_UP_tank_weightTemp)
- # -- 取得乾燥桶槽 D1~D6 權重後溫度值 -------------
- # ----- 發酵排程動作 start ------------------------------------------------------------------
- # if D1 == 'D_InputtingBean': D_UP_tank_UltraSonic[0] >= Dry_Tank_bean_height:
- def DInputtingBean_TO_DInputtingBeanFinish(tid):
- # [致動器] 真空吸料機 OFF
- data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 0
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 入料三通閥 ON排氣
- data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid,' 狀態更新:入豆完成 -------')
- # if D1 == 'D_InputtingBean': elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
- def DInputtingBean_AND_notfilled(tid):
- # [致動器] 入料三通閥 OFF入豆
- data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 真空吸料機 ON
- data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- while True:
- if (time.time() - timer) > Dry_Tank_vacuumON_time:
- # [致動器] 真空吸料機 OFF
- data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- break
- while True:
- if (time.time() - timer) > Dry_Tank_vacuumOFF_time:
- break
- # if D1 == 'D_InputtingBean': elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
- def DInputtingBean_TO_DInputtingBeanPause(tid):
- # [致動器] 真空吸料機 OFF
- data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 0
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid,' 狀態更新:入豆暫停 -------')
- # elif DryUp_InputtingBeanPause_number == 1 and DI1 == 'DI_OutputtingBean': if D1 == 'D_InputtingBean_Pause':
- def DInputtingBeanPause_TO_DInputtingBean(tid):
- # [致動器] 入料三通閥 OFF入豆
- data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 5
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid, ' 狀態更新:入豆中 -------')
- # elif DryUp_InputtingBean_number == 0 and DryUp_InputtingBeanPause_number == 0 and DI1 == 'DI_OutputtingBean' and DryUp_Waiting_number >= 1:
- def DWaiting_TO_DInputtingBean(tid):
- # [致動器] 入料三通閥 OFF入豆
- data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 5
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid, ' 狀態更新:入豆中 -------')
- # else: if D1 == 'D_InputtingBean_Finish':
- def DInputtingBeanFinish_TO_DDrying(tid):
- # [致動器] 馬達 指定轉速
- data = { "tank_num": tid, "command": "tank_motor_status", "value": Dry_Tank_motor_rpm }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 排水電磁閥 ON
- data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 鼓風機 ON
- data = { "tank_num": tid, "command": "tank_blower_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 加熱器 1 ON
- data = { "tank_num": tid, "command": "tank_heater1_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 加熱器 2 ON
- data = { "tank_num": tid, "command": "tank_heater2_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid, ' 狀態更新:乾燥中 -------')
- # 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:
- def DDrying_TO_DOutputtingBean(tid):
- # [致動器] 鼓風機 OFF
- data = { "tank_num": tid, "command": "tank_blower_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 加熱器 1 OFF
- data = { "tank_num": tid, "command": "tank_heater1_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 加熱器 2 OFF
- data = { "tank_num": tid, "command": "tank_heater2_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 0
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- print("乾燥結束, 返潮暫停 ", Dry_Tank_drying_time, " 秒")
- timer = time.time()
- while True:
- if (time.time() - timer) > Dry_Tank_drying_time:
- # [致動器] 排水電磁閥 OFF
- data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- break
- print('------- ', tid, ' 狀態更新:可出豆 -------')
- # else: if D1 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[0] <= Dry_Tank_bean_empty):
- def DOutputtingBean_TO_DWaiting(tid):
- # [致動器] D1 蝴蝶閥 OFF
- data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # D_Cleaning
- def DCleaning(tid):
- # [致動器] 馬達 10
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "10" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 消毒電磁閥 ON
- data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 排水電磁閥 OFF
- data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] TODO 消毒抽水 pump ON
- print("消毒 ", Dry_Tank_Disinfect_time, " 秒")
- timer = time.time()
- while True:
- if (time.time() - timer) > Dry_Tank_Disinfect_time:
- # [致動器] TODO 消毒抽水 pump OFF
- break
- # [致動器] 消毒電磁閥 OFF
- data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 0
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 排水電磁閥 ON
- data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- print("桶內排水 ", Dry_Tank_Disinfect_time, " 秒")
- timer = time.time()
- while True:
- if (time.time() - timer) > Dry_Tank_Disinfect_time:
- break
- # [致動器] 排水電磁閥 OFF
- data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid, ' 狀態更新:空桶等待 -------')
- # ----- 發酵排程動作 end ------------------------------------------------------------------
- # ----- 乾燥入料儲豆槽 DI1~DI2 入豆→可出豆判斷 ------------------------------
- # 如果入料儲豆槽 空桶等待, 且發酵出料儲豆槽 FO1 為可出豆, 則開始入豆
- if DI1 == 'DI_Waiting' and FO1 == 'FO_OutputtingBean':
- DI1 = 'DI_InputtingBean'
- print('------- DI1 狀態更新:入料中 -------')
- # 如果入料儲豆槽 入豆中
- elif DI1 == 'DI_InputtingBean':
- # 如果入豆儲豆槽達指定高度時
- if DI_UP_UltraSoniclist[0] >= Dry_Input_bean_height:
- # [致動器] 入料真空吸料機 OFF
- data = { "tank_num": "D1", "command": "input_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- DI1 = 'DI_OutputtingBean'
- print('------- DI1 狀態更新:可出豆 -------')
- # 如果入豆儲豆槽未達指定高度, 且 發酵出料儲豆槽 可出豆
- elif DI_UP_UltraSoniclist[0] < Dry_Input_bean_height and FO1 == 'FO_OutputtingBean':
- # [致動器] 入料真空吸料機 ON
- data = { "tank_num": "D1", "command": "input_vacuum_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- while True:
- if (time.time() - timer) > Dry_Input_vacuumON_time:
- # [致動器] 入料真空吸料機 OFF
- data = { "tank_num": "D1", "command": "input_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- break
- while True:
- if (time.time() - timer) > Dry_Input_vacuumOFF_time:
- break
- # 如果入料儲豆槽生豆大於空桶高度, 且 前方 FO1 非可出豆, 將狀態轉為可出豆
- elif (DI_UP_UltraSoniclist[0] > Dry_Input_bean_empty) and FO1 != 'FO_OutputtingBean':
- DI1 = 'DI_OutputtingBean'
- print('------- DI1 狀態更新:可出豆 -------')
- # 桶槽內小於空桶高度, 且 前方 FO1 非可出豆, 將狀態轉為空桶等待
- elif (DI_UP_UltraSoniclist[0] <= Dry_Input_bean_empty) and FO1 != 'PO_OutputtingBean':
- DI1 = 'DI_Waiting'
- print('------- FI1 狀態更新:空桶等待 -------')
- # 入料儲豆槽出豆時, 桶槽高度為 空桶高度時, 狀態轉為 空桶等待
- elif DI1 == 'DI_OutputtingBean' and (DI_UP_UltraSoniclist[0] <= Dry_Input_bean_empty):
- DI1 = 'DI_Waiting'
- print('------- DI1 狀態更新:空桶等待 -------')
-
- # [介面] 若啟用 乾燥 狀態
- if Dry_btn:
- # ----- 乾燥桶槽 D1~D6 入料桶槽優先入料判斷 ------------------------------
- # 若 D1~D6 桶槽中有一個桶槽入豆中
- if DryUp_InputtingBean_number == 1:
- # 若 D1 桶槽為入豆中
- if D1 == 'D_InputtingBean':
- # 若桶槽生豆高度大於指定生豆高度, 則狀態轉換成 入料完成
- if D_UP_tank_UltraSonic[0] >= Dry_Tank_bean_height:
- DInputtingBean_TO_DInputtingBeanFinish("D1")
- D1 = 'D_InputtingBean_Finish'
- # 若桶槽生豆高度未達指定生豆高度, 且 入料儲豆槽可出豆
- elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
- DInputtingBean_AND_notfilled("D1")
- # 若桶槽生豆高度未達指定生豆高度, 且 入料儲豆槽 非可出豆
- elif D_UP_tank_UltraSonic[0] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
- DInputtingBean_TO_DInputtingBeanPause("D1")
- D1 = 'D_InputtingBean_Pause'
- elif D2 == 'D_InputtingBean':
- if D_UP_tank_UltraSonic[1] >= Dry_Tank_bean_height:
- DInputtingBean_TO_DInputtingBeanFinish("D2")
- D2 = 'D_InputtingBean_Finish'
- elif D_UP_tank_UltraSonic[1] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
- DInputtingBean_AND_notfilled("D2")
- elif D_UP_tank_UltraSonic[1] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
- DInputtingBean_TO_DInputtingBeanPause("D2")
- D2 = 'D_InputtingBean_Pause'
- elif D3 == 'D_InputtingBean':
- if D_UP_tank_UltraSonic[2] >= Dry_Tank_bean_height:
- DInputtingBean_TO_DInputtingBeanFinish("D3")
- D3 = 'D_InputtingBean_Finish'
- elif D_UP_tank_UltraSonic[2] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
- DInputtingBean_AND_notfilled("D2")
- elif D_UP_tank_UltraSonic[2] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
- DInputtingBean_TO_DInputtingBeanPause("D2")
- D3 = 'D_InputtingBean_Pause'
- elif D4 == 'D_InputtingBean':
- if D_UP_tank_UltraSonic[3] >= Dry_Tank_bean_height:
- DInputtingBean_TO_DInputtingBeanFinish("D4")
- D4 = 'D_InputtingBean_Finish'
- elif D_UP_tank_UltraSonic[3] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
- DInputtingBean_AND_notfilled("D4")
- elif D_UP_tank_UltraSonic[3] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
- DInputtingBean_TO_DInputtingBeanPause("D4")
- D4 = 'D_InputtingBean_Pause'
- elif D5 == 'D_InputtingBean':
- if D_UP_tank_UltraSonic[4] >= Dry_Tank_bean_height:
- DInputtingBean_TO_DInputtingBeanFinish("D5")
- D5 = 'D_InputtingBean_Finish'
- elif D_UP_tank_UltraSonic[4] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
- DInputtingBean_AND_notfilled("D5")
- elif D_UP_tank_UltraSonic[4] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
- DInputtingBean_TO_DInputtingBeanPause("D5")
- D5 = 'D_InputtingBean_Pause'
- elif D6 == 'D_InputtingBean':
- if D_UP_tank_UltraSonic[5] >= Dry_Tank_bean_height:
- DInputtingBean_TO_DInputtingBeanFinish("D6")
- D6 = 'D_InputtingBean_Finish'
- elif D_UP_tank_UltraSonic[5] < Dry_Tank_bean_height and DI1 == 'DI_OutputtingBean':
- DInputtingBean_AND_notfilled("D6")
- elif D_UP_tank_UltraSonic[5] < Dry_Tank_bean_height and DI1 != 'DI_OutputtingBean':
- DInputtingBean_TO_DInputtingBeanPause("D6")
- D6 = 'D_InputtingBean_Pause'
- # 若 D1~D6 桶槽中有一個桶槽入豆暫停
- elif DryUp_InputtingBeanPause_number == 1 and DI1 == 'DI_OutputtingBean':
- if D1 == 'D_InputtingBean_Pause':
- DInputtingBeanPause_TO_DInputtingBean("D1")
- D1 = 'D_InputtingBean'
- elif D2 == 'D_InputtingBean_Pause':
- DInputtingBeanPause_TO_DInputtingBean("D2")
- D2 = 'D_InputtingBean'
- elif D3 == 'D_InputtingBean_Pause':
- DInputtingBeanPause_TO_DInputtingBean("D3")
- D3 = 'D_InputtingBean'
- elif D4 == 'D_InputtingBean_Pause':
- DInputtingBeanPause_TO_DInputtingBean("D4")
- D4 = 'D_InputtingBean'
- elif D5 == 'D_InputtingBean_Pause':
- DInputtingBeanPause_TO_DInputtingBean("D5")
- D5 = 'D_InputtingBean'
- elif D6 == 'D_InputtingBean_Pause':
- DInputtingBeanPause_TO_DInputtingBean("D6")
- D6 = 'D_InputtingBean'
- # 若 D1~D6 桶槽中皆無 入豆中 和 入豆暫停, 且入料儲豆槽可出豆
- elif DryUp_InputtingBean_number == 0 and DryUp_InputtingBeanPause_number == 0 and DI1 == 'DI_OutputtingBean' and DryUp_Waiting_number >= 1:
- if D1 == 'D_Waiting':
- DWaiting_TO_DInputtingBean("D1")
- D1 = 'D_InputtingBean'
- elif D2 == 'D_Waiting':
- DWaiting_TO_DInputtingBean("D2")
- D2 = 'D_InputtingBean'
- elif D3 == 'D_Waiting':
- DWaiting_TO_DInputtingBean("D3")
- D3 = 'D_InputtingBean'
- elif D4 == 'D_Waiting':
- DWaiting_TO_DInputtingBean("D4")
- D4 = 'D_InputtingBean'
- elif D5 == 'D_Waiting':
- DWaiting_TO_DInputtingBean("D5")
- D5 = 'D_InputtingBean'
- elif D6 == 'D_Waiting':
- DWaiting_TO_DInputtingBean("D6")
- D6 = 'D_InputtingBean'
- # 其他
- else:
- # 如果桶槽為 入豆完成, 將狀態轉換成 乾燥中
- if D1 == 'D_InputtingBean_Finish':
- DInputtingBeanFinish_TO_DDrying("D1")
- D1 = 'D_Drying'
- if D2 == 'D_InputtingBean_Finish':
- DInputtingBeanFinish_TO_DDrying("D2")
- D2 = 'D_Drying'
- if D3 == 'D_InputtingBean_Finish':
- DInputtingBeanFinish_TO_DDrying("D3")
- D3 = 'D_Drying'
- if D4 == 'D_InputtingBean_Finish':
- DInputtingBeanFinish_TO_DDrying("D4")
- D4 = 'D_Drying'
- if D5 == 'D_InputtingBean_Finish':
- DInputtingBeanFinish_TO_DDrying("D5")
- D5 = 'D_Drying'
- if D6 == 'D_InputtingBean_Finish':
- DInputtingBeanFinish_TO_DDrying("D6")
- D6 = 'D_Drying'
-
- # 如果桶槽為 乾燥中, 達乾燥條件後, 將狀態轉換成 可出豆
- if D1 == 'D_Drying' and D_UP_tank_weightTemp[0] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[0] <= Dry_Tank_drying_Humidity:
- DDrying_TO_DOutputtingBean("D1")
- D1 = 'D_OutputtingBean'
- if DOutputtingBean_Tank == '': DOutputtingBean_Tank = 'D1'
- if D2 == 'D_Drying' and D_UP_tank_weightTemp[1] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[1] <= Dry_Tank_drying_Humidity:
- DDrying_TO_DOutputtingBean("D2")
- D2 = 'D_OutputtingBean'
- if DOutputtingBean_Tank == '': DOutputtingBean_Tank = 'D2'
- if D3 == 'D_Drying' and D_UP_tank_weightTemp[2] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[2] <= Dry_Tank_drying_Humidity:
- DDrying_TO_DOutputtingBean("D3")
- D3 = 'D_OutputtingBean'
- if DOutputtingBean_Tank == '': DOutputtingBean_Tank = 'D3'
- if D4 == 'D_Drying' and D_UP_tank_weightTemp[3] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[3] <= Dry_Tank_drying_Humidity:
- DDrying_TO_DOutputtingBean("D4")
- D4 = 'D_OutputtingBean'
- if DOutputtingBean_Tank == '': DOutputtingBean_Tank = 'D4'
- if D5 == 'D_Drying' and D_UP_tank_weightTemp[4] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[4] <= Dry_Tank_drying_Humidity:
- DDrying_TO_DOutputtingBean("D5")
- D5 = 'D_OutputtingBean'
- if DOutputtingBean_Tank == '': DOutputtingBean_Tank = 'D5'
- if D6 == 'D_Drying' and D_UP_tank_weightTemp[5] >= Dry_Tank_drying_temp and D_UP_tank_SHT11Humidity[5] <= Dry_Tank_drying_Humidity:
- DDrying_TO_DOutputtingBean("D6")
- D6 = 'D_OutputtingBean'
- if DOutputtingBean_Tank == '': DOutputtingBean_Tank = 'D6'
-
- # 如果桶槽 D1~D6 可出豆 且 桶槽內為空桶 且 有指定清洗排程, 進行清洗桶槽
- # TODO 發酵次數計算、消毒次數、校正
- if D1 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[0] <= Dry_Tank_bean_empty):
- if DOutputtingBean_Tank == 'D1':
- DOutputtingBean_TO_DWaiting('D1')
- DOutputtingBean_Tank = ''
- if (DryAuto_cleaning == 0): D1 = 'D_Waiting'
- elif (DryAuto_cleaning != 0): D1 = 'D_Cleaning'
- if D2 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[1] <= Dry_Tank_bean_empty):
- if DOutputtingBean_Tank == 'D2':
- DOutputtingBean_TO_DWaiting('D2')
- DOutputtingBean_Tank = ''
- if (DryAuto_cleaning == 0): D2 = 'D_Waiting'
- elif (DryAuto_cleaning != 0): D2 = 'D_Cleaning'
- if D3 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[2] <= Dry_Tank_bean_empty):
- if DOutputtingBean_Tank == 'D2':
- DOutputtingBean_TO_DWaiting('D2')
- DOutputtingBean_Tank = ''
- if (DryAuto_cleaning == 0): D3 = 'D_Waiting'
- elif (DryAuto_cleaning != 0): D3 = 'D_Cleaning'
- if D4 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[3] <= Dry_Tank_bean_empty):
- if DOutputtingBean_Tank == 'D4':
- DOutputtingBean_TO_DWaiting('D4')
- DOutputtingBean_Tank = ''
- if (DryAuto_cleaning == 0): D4 = 'D_Waiting'
- elif (DryAuto_cleaning != 0): D4 = 'D_Cleaning'
- if D5 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[4] <= Dry_Tank_bean_empty):
- if DOutputtingBean_Tank == 'D5':
- DOutputtingBean_TO_DWaiting('D5')
- DOutputtingBean_Tank = ''
- if (DryAuto_cleaning == 0): D5 = 'D_Waiting'
- elif (DryAuto_cleaning != 0): D5 = 'D_Cleaning'
- if D6 == 'D_OutputtingBean' and (D_UP_tank_UltraSonic[5] <= Dry_Tank_bean_empty):
- if DOutputtingBean_Tank == 'D6':
- DOutputtingBean_TO_DWaiting('D6')
- DOutputtingBean_Tank = ''
- if (DryAuto_cleaning == 0): D6 = 'D_Waiting'
- elif (DryAuto_cleaning != 0): D6 = 'D_Cleaning'
-
- # 避免桶槽可出豆時未賦值
- if DOutputtingBean_Tank == '':
- if D1 == 'D_OutputtingBean': DOutputtingBean_Tank = 'D1'
- elif D2 == 'D_OutputtingBean': DOutputtingBean_Tank = 'D2'
- elif D3 == 'D_OutputtingBean': DOutputtingBean_Tank = 'D3'
- elif D4 == 'D_OutputtingBean': DOutputtingBean_Tank = 'D4'
- elif D5 == 'D_OutputtingBean': DOutputtingBean_Tank = 'D5'
- elif D6 == 'D_OutputtingBean': DOutputtingBean_Tank = 'D6'
- # 乾燥槽消毒
- if D1 == 'D_Cleaning':
- DCleaning("D1")
- D1 = 'D_Waiting'
- if D2 == 'D_Cleaning':
- DCleaning("D2")
- D2 = 'D_Waiting'
- if D3 == 'D_Cleaning':
- DCleaning("D3")
- D3 = 'D_Waiting'
- if D4 == 'D_Cleaning':
- DCleaning("D4")
- D4 = 'D_Waiting'
- if D5 == 'D_Cleaning':
- DCleaning("D5")
- D5 = 'D_Waiting'
- if D6 == 'D_Cleaning':
- DCleaning("D6")
- D6 = 'D_Waiting'
- else:
- print('未啟用乾燥流程')
- # ----- 乾燥出料儲豆槽 DO1~DO2 入豆→可出豆判斷 ------------------------------
- # 若出料儲豆槽狀態為 空桶等待 且 桶槽狀態為 D_OutputtingBean 可出豆, 與 FO1 配合開始出豆
-
- if DO1 == 'DO_Waiting' and DOutputtingBean_Tank != '':
- # 判斷要對應出料的桶槽為何, 設定成 DOutputtingBean_Tank = 'D1', 待出完料再把 DOutputtingBean_Tank = ''
- DO1 = 'DO_InputtingBean'
- print('------- ' + DOutputtingBean_Tank + ' 狀態更新:出豆中 -------')
- print('------- DO1 狀態更新:入豆中 -------')
- # [致動器] D1 蝴蝶閥 ON
- data = { "tank_num": DOutputtingBean_Tank, "command": "tank_diskvalve_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- elif DO1 == 'DO_InputtingBean' and DOutputtingBean_Tank != '':
- if DO_UP_UltraSoniclist[0] >= Dry_Output_bean_height:
- # [致動器] 出料真空吸料機 OFF
- data = { "tank_num": DOutputtingBean_Tank, "command": "output_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] D1 蝴蝶閥 OFF
- data = { "tank_num": DOutputtingBean_Tank, "command": "tank_diskvalve_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- DO1 = 'DO_OutputtingBean'
- print('------- DO1 狀態更新:可出豆 -------')
- elif DO_UP_UltraSoniclist[0] < Dry_Output_bean_height:
- # [致動器] 出料真空吸料機 ON
- data = { "tank_num": DOutputtingBean_Tank, "command": "output_vacuum_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- while True:
- if (time.time() - timer) > Dry_Output_vacuumON_time:
- # [致動器] 出料真空吸料機 OFF
- data = { "tank_num": DOutputtingBean_Tank, "command": "output_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- break
- while True:
- if (time.time() - timer) > Dry_Output_vacuumOFF_time:
- break
- # 若是無桶槽可入豆, 出料儲豆槽判斷是否可出豆或空桶等待入豆
- elif DOutputtingBean_Tank == '':
- if DO_UP_UltraSoniclist[0] > Dry_Output_bean_empty:
- DO1 = 'DO_OutputtingBean'
- print('------- DO1 狀態更新:可出豆 -------')
- elif DO_UP_UltraSoniclist[0] <= Dry_Output_bean_empty:
- DO1 = 'DO_Waiting'
- print('------- DO1 狀態更新:空桶等待 -------')
- elif DO1 == 'DO_OutputtingBean' and DO_UP_UltraSoniclist[0] <= Dry_Output_bean_empty:
- DO1 = 'DO_Waiting'
- print('------- DO1 狀態更新:空桶等待 -------')
-
- # # ----- [測試用] !!!!! D1~D6 入料完成→可出豆 判斷 ------------------------------
- # if D1 == 'D_InputtingBean_Finish': D1 = 'D_OutputtingBean'
- # if D2 == 'D_InputtingBean_Finish': D2 = 'D_OutputtingBean'
- # if D3 == 'D_InputtingBean_Finish': D3 = 'D_OutputtingBean'
- # if D4 == 'D_InputtingBean_Finish': D4 = 'D_OutputtingBean'
- # if D5 == 'D_InputtingBean_Finish': D5 = 'D_OutputtingBean'
- # if D6 == 'D_InputtingBean_Finish': D6 = 'D_OutputtingBean'
- # # ----- [測試用] !!!!! D1~D6 入料完成→可出豆 判斷 ------------------------------
- # ----- 將狀態寫入資料庫 ------------------------------
- # 獲取文本框的值並賦值給user實體對象
- D_status = dry_container_status()
- D_status.Dry_Input_1 = DI1
- D_status.Dry_Input_2 = DI2
- D_status.Dry_Tank_1 = D1
- D_status.Dry_Tank_2 = D2
- D_status.Dry_Tank_3 = D3
- D_status.Dry_Tank_4 = D4
- D_status.Dry_Tank_5 = D5
- D_status.Dry_Tank_6 = D6
- D_status.Dry_Tank_7 = D7
- D_status.Dry_Tank_8 = D8
- D_status.Dry_Tank_9 = D9
- D_status.Dry_Tank_10 = D10
- D_status.Dry_Tank_11 = D11
- D_status.Dry_Tank_12 = D12
- D_status.Dry_Output_1 = DO1
- D_status.Dry_Output_2 = DO2
- #將數據保存進資料庫
- db.session.add(D_status)
- # 手動提交
- db.session.commit()
- # ----- 將狀態寫入資料庫 ------------------------------
-
- return jsonify({"Dry_Input_1":DI1,
- "Dry_Tank_1":D1,
- "Dry_Tank_2":D2,
- "Dry_Tank_3":D3,
- "Dry_Tank_4":D4,
- "Dry_Tank_5":D5,
- "Dry_Tank_6":D6,
- "Dry_Output_1":DO1
- })
- # 1101 以流程圖判斷, 改寫 def dry_auto_status, 以下為原備份
- @main.route('/dry_auto_status_1101backup', methods=['GET', 'POST'])
- def dry_auto_test_1101backup():
- # [介面] 讓使用者可以選擇排程內有乾燥/清洗/校正, 此處預設為 True
- Dry_btn = True
- # 從資料庫資料表中取得最新狀態
- dry_status = dry_container_status.query.order_by(text('datetime desc')).first()
- DI1 = dry_status.Dry_Input_1
- DI2 = dry_status.Dry_Input_2
- D1 = dry_status.Dry_Tank_1
- D2 = dry_status.Dry_Tank_2
- D3 = dry_status.Dry_Tank_3
- D4 = dry_status.Dry_Tank_4
- D5 = dry_status.Dry_Tank_5
- D6 = dry_status.Dry_Tank_6
- D7 = dry_status.Dry_Tank_7
- D8 = dry_status.Dry_Tank_8
- D9 = dry_status.Dry_Tank_9
- D10 = dry_status.Dry_Tank_10
- D11 = dry_status.Dry_Tank_11
- D12 = dry_status.Dry_Tank_12
- DO1 = dry_status.Dry_Output_1
- DO2 = dry_status.Dry_Output_2
- FO1 = 'FO_Waiting' # 'FO_OutputtingBean'
- FO2 = 'FO_Waiting'
- D_UP_tanklist = [D1, D2, D3, D4, D5, D6]
- D_DOWN_tanklist = [D7, D8, D9, D10, D11, D12]
- # ----- 乾燥桶槽 D1~D6 入料暫停→入料判斷 ------------------------------
- Dry_InputtingBeanPause_number = int(D_UP_tanklist.count('D_InputtingBean_Pause'))
- # 若入料儲豆槽可出豆, 且 D1~D6 其中有桶槽入料暫停 (就是入料時桶槽豆子未滿 or 儲豆槽=='DI_Waiting' 已空) 時, 優先入豆
- if DI1 == 'DI_OutputtingBean' and Dry_InputtingBeanPause_number >= 1:
- if D1 == 'D_InputtingBean_Pause':
- D1 = 'D_InputtingBean'
- print('------- D1 狀態更新:入料中 -------')
- elif D2 == 'D_InputtingBean_Pause':
- D2 = 'D_InputtingBean'
- print('------- D2 狀態更新:入料中 -------')
- elif D3 == 'D_InputtingBean_Pause':
- D3 = 'D_InputtingBean'
- print('------- D3 狀態更新:入料中 -------')
- elif D4 == 'D_InputtingBean_Pause':
- D4 = 'D_InputtingBean'
- print('------- D4 狀態更新:入料中 -------')
- elif D5 == 'D_InputtingBean_Pause':
- D5 = 'D_InputtingBean'
- print('------- D5 狀態更新:入料中 -------')
- elif D6 == 'D_InputtingBean_Pause':
- D6 = 'D_InputtingBean'
- print('------- D6 狀態更新:入料中 -------')
- # ----- 乾燥桶槽 D1~D6 等待→入料判斷 ------------------------------
- # 目前乾燥槽 D1~D6 正在入豆的桶槽數量 (應小於一桶)
- Dry_InputtingBean_number = int(D_UP_tanklist.count('D_InputtingBean'))
- # [介面] 若未啟用 發酵 狀態
- if not Dry_btn:
- print('未指定乾燥流程')
- # 入料儲豆槽 非可出料狀態
- elif Dry_btn and DI1 != 'DI_OutputtingBean':
- print('入料儲豆槽非可出豆, 無法入料')
- # 若 D1~D6 乾燥桶槽為 入豆暫停, 則狀態改為入豆優先入豆
- elif Dry_btn and DI1 == 'DI_OutputtingBean' and Dry_InputtingBeanPause_number >= 1:
- print('乾燥槽 D', D_UP_tanklist.index('D_InputtingBean_Pause')+1, '優先入料中')
- print('------- D', D_UP_tanklist.index('D_InputtingBean_Pause')+1, ' 入料中 -------')
- # 若 D1~D6 發酵桶槽為 入豆, 則桶槽數字小者 優先入豆
- elif Dry_btn and DI1 == 'DI_OutputtingBean' and Dry_InputtingBean_number >= 1:
- print('乾燥槽 D', D_UP_tanklist.index('D_InputtingBean')+1, '優先入料中')
- print('------- D', D_UP_tanklist.index('D_InputtingBean')+1, ' 入料中 -------')
- elif Dry_btn and DI1 == 'DI_OutputtingBean' \
- and Dry_InputtingBean_number == 0 and Dry_InputtingBeanPause_number == 0:
- # 當達標準入料條件
- if D1 == 'D_Waiting':
- D1 = 'D_InputtingBean'
- print('------- D1 狀態更新:入料中 -------')
- elif D2 == 'D_Waiting':
- D2 = 'D_InputtingBean'
- print('------- D2 狀態更新:入料中 -------')
- elif D3 == 'D_Waiting':
- D3 = 'D_InputtingBean'
- print('------- D3 狀態更新:入料中 -------')
- elif D4 == 'D_Waiting':
- D4 = 'D_InputtingBean'
- print('------- D4 狀態更新:入料中 -------')
- elif D5 == 'D_Waiting':
- D5 = 'D_InputtingBean'
- print('------- D5 狀態更新:入料中 -------')
- elif D6 == 'D_Waiting':
- D6 = 'D_InputtingBean'
- print('------- D6 狀態更新:入料中 -------')
- # ----- 乾燥桶槽 D1~D6 入料→入料暫停判斷 ------------------------------
- Dry_InputtingBean_number = int(D_UP_tanklist.count('D_InputtingBean'))
- # -- 取得乾燥桶槽 D1~D6 超音波生豆高度 UltraSonic -------------
- D_UP_tank_UltraSonic = []
- for i in range(1, 7, 1):
- tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
- UltraSonic = int(tank_UltraSonic.UltraSonic)
- D_UP_tank_UltraSonic.append(UltraSonic)
- print('D_UP_tank_UltraSonic: ', D_UP_tank_UltraSonic)
- # -- 取得乾燥桶槽 D1~D6 超音波生豆高度 UltraSonic -------------
- if DI1 != 'DI_OutputtingBean' and Dry_InputtingBean_number >= 1:
- if D1 == 'D_InputtingBean' and D_UP_tank_UltraSonic[0] < 110:
- D1 = 'D_InputtingBean_Pause'
- print('------- D1 狀態更新:入料暫停 -------')
- else:
- D1 = 'D_InputtingBean_Finish'
- print('------- D1 狀態更新:入料完成 -------')
- if D2 == 'D_InputtingBean' and D_UP_tank_UltraSonic[1] < 110:
- D2 = 'D_InputtingBean_Pause'
- print('------- D2 狀態更新:入料暫停 -------')
- else:
- D2 = 'D_InputtingBean_Finish'
- print('------- D2 狀態更新:入料完成 -------')
- if D3 == 'D_InputtingBean' and D_UP_tank_UltraSonic[2] < 110:
- D3 = 'D_InputtingBean_Pause'
- print('------- D3 狀態更新:入料暫停 -------')
- else:
- D3 = 'D_InputtingBean_Finish'
- print('------- D3 狀態更新:入料完成 -------')
- if D4 == 'D_InputtingBean' and D_UP_tank_UltraSonic[3] < 110:
- D4 = 'D_InputtingBean_Pause'
- print('------- D4 狀態更新:入料暫停 -------')
- else:
- D4 = 'D_InputtingBean_Finish'
- print('------- D4 狀態更新:入料完成 -------')
- if D5 == 'D_InputtingBean' and D_UP_tank_UltraSonic[4] < 110:
- D5 = 'D_InputtingBean_Pause'
- print('------- D5 狀態更新:入料暫停 -------')
- else:
- D5 = 'D_InputtingBean_Finish'
- print('------- D5 狀態更新:入料完成 -------')
- if D6 == 'D_InputtingBean' and D_UP_tank_UltraSonic[5] < 110:
- D6 = 'D_InputtingBean_Pause'
- print('------- D6 狀態更新:入料暫停 -------')
- else:
- D6 = 'D_InputtingBean_Finish'
- print('------- D6 狀態更新:入料完成 -------')
- # # ----- 乾燥桶槽 D1~D6 入料完成→乾燥判斷 ------------------------------
- # Dry_InputtingBeanFinish_number = int(D_UP_tanklist.count('D_InputtingBean_Finish'))
- # # 乾燥條件:當前桶槽入豆達指定高度, 則開始乾燥 (可以多桶乾燥)
- # # !!! 乾燥槽 D_Drying 狀態應該請硬體判斷
- # # !!! 若狀態為 D_InputtingBean 且 超音波值>指定生豆高度, 狀態改為 D_Drying 乾燥
- # if D1 == 'D_InputtingBean_Finish' or D1 == 'D_InputtingBean_Pause' and D_UP_tank_UltraSonic[0] >= 110:
- # D1 = 'D_Drying'
- # print('------- D1 狀態更新:乾燥中 -------')
- # if D2 == 'D_InputtingBean_Finish' and D_UP_tank_UltraSonic[1] >= 110:
- # D2 = 'D_Drying'
- # print('------- D2 狀態更新:乾燥中 -------')
- # if D3 == 'D_InputtingBean_Finish' and D_UP_tank_UltraSonic[2] >= 110:
- # D3 = 'D_Drying'
- # print('------- D3 狀態更新:乾燥中 -------')
- # if D4 == 'D_InputtingBean_Finish' and D_UP_tank_UltraSonic[3] >= 110:
- # D4 = 'D_Drying'
- # print('------- D4 狀態更新:乾燥中 -------')
- # if D5 == 'D_InputtingBean_Finish' and D_UP_tank_UltraSonic[4] >= 110:
- # D5 = 'D_Drying'
- # print('------- D5 狀態更新:乾燥中 -------')
- # if D6 == 'D_InputtingBean_Finish' and D_UP_tank_UltraSonic[5] >= 110:
- # D6 = 'D_Drying'
- # print('------- D6 狀態更新:乾燥中 -------')
-
- # ----- 乾燥桶槽 D1~D6 發酵→可出豆 判斷 ------------------------------
- # !!! 發酵槽 D_OutputtingBean 狀態應該請硬體判斷
- # !!! 若狀態為 D_Drying 且 達指定乾燥條件, 狀態改為 D_OutputtingBean 可出豆
- # 可以多桶各自執行發酵排程
- # ----- [測試用] !!!!! D1~D6 入料完成→可出豆 判斷 ------------------------------
- if D1 == 'D_InputtingBean_Finish': D1 = 'D_OutputtingBean'
- if D2 == 'D_InputtingBean_Finish': D2 = 'D_OutputtingBean'
- if D3 == 'D_InputtingBean_Finish': D3 = 'D_OutputtingBean'
- if D4 == 'D_InputtingBean_Finish': D4 = 'D_OutputtingBean'
- if D5 == 'D_InputtingBean_Finish': D5 = 'D_OutputtingBean'
- if D6 == 'D_InputtingBean_Finish': D6 = 'D_OutputtingBean'
- # ----- [測試用] !!!!! D1~D6 入料完成→可出豆 判斷 ------------------------------
- # # ----- 乾燥桶槽 D1~D6 可出豆→出料儲豆槽 DO1 判斷 ------------------------------
- Dry_OutputtingBean_number = int(D_UP_tanklist.count('D_OutputtingBean'))
- # # !!! 若出料儲豆槽狀態為 DO_Waiting(空桶等待) 且 桶槽狀態為 D_OutputtingBean 可出豆, 與 DO1 配合開始出豆
- # if DO1 == 'DO_Waiting' and Dry_OutputtingBean_number >= 1:
- # if D1 == 'D_OutputtingBean':
- # DO1 = 'DO_InputtingBean'
- # print('------- D1 狀態更新:出豆中 -------')
- # print('------- DO1 狀態更新:入豆中 -------')
- # elif D2 == 'D_OutputtingBean':
- # DO1 = 'DO_InputtingBean'
- # print('------- D2 狀態更新:出豆中 -------')
- # print('------- DO1 狀態更新:入豆中 -------')
- # elif D3 == 'D_OutputtingBean':
- # DO1 = 'DO_InputtingBean'
- # print('------- D3 狀態更新:出豆中 -------')
- # print('------- DO1 狀態更新:入豆中 -------')
- # elif D4 == 'D_OutputtingBean':
- # DO1 = 'DO_InputtingBean'
- # print('------- D4 狀態更新:出豆中 -------')
- # print('------- DO1 狀態更新:入豆中 -------')
- # elif D5 == 'D_OutputtingBean':
- # DO1 = 'DO_InputtingBean'
- # print('------- D5 狀態更新:出豆中 -------')
- # print('------- DO1 狀態更新:入豆中 -------')
- # elif D6 == 'D_OutputtingBean':
- # DO1 = 'DO_InputtingBean'
- # print('------- D6 狀態更新:出豆中 -------')
- # print('------- DO1 狀態更新:入豆中 -------')
- # ----- 乾燥入料儲豆槽 DI1~DI2 入豆→可出豆判斷 ------------------------------
- # -- 取得乾燥入料儲豆槽 FI1~FI2 桶內高度 UltraSonic -------------
- DI_UP_UltraSoniclist = []
- for i in range(1, 3, 1):
- input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI' + str(i)).order_by(text('datetime desc')).first()
- UltraSonic = int(input_UltraSonic.UltraSonic)
- DI_UP_UltraSoniclist.append(UltraSonic)
- print('DI_UP_UltraSoniclist: ', DI_UP_UltraSoniclist)
- # !!! 乾燥入料儲豆槽 D_OutputtingBean 狀態應該請硬體判斷
- # 入料儲豆槽等待中、且發酵槽出料儲豆槽可出豆時, 入料儲豆槽入豆
- if DI1 == 'DI_Waiting' and FO1 == 'FO_OutputtingBean':
- DI1 = 'DI_InputtingBean'
- print('------- DI1 狀態更新:入豆中 -------')
- # 入料儲豆槽入豆時 且 (發酵儲豆槽有入料 或者 前方儲豆槽非可出豆), 則停止入豆
- elif DI1 == 'DI_InputtingBean' and (DI_UP_UltraSoniclist[0] > 35) and (FO1 != 'FO_OutputtingBean') :
- DI1 = 'DI_OutputtingBean'
- print('------- DI1 狀態更新:可出豆 -------')
- # 若入料儲豆槽可出豆 且 儲豆槽內高度低於 40 且 前方脫皮機儲豆槽可出豆 且 目前無桶槽需入料時
- elif DI1 == 'DI_OutputtingBean' and (DI_UP_UltraSoniclist[0] < 40) and FO1 == 'FO_OutputtingBean' and Dry_InputtingBean_number == 0 and Dry_InputtingBeanPause_number == 0:
- DI1 = 'DI_InputtingBean'
- print('------- DI1 狀態更新:入豆中 -------')
- # if DI2 == 'DI_Waiting' and FO2 == 'FO_OutputtingBean':
- # DI2 = 'DI_InputtingBean'
- # print('------- DI2 狀態更新:入豆中 -------')
- # elif DI2 == 'DI_InputtingBean' and ((DI_DOWN_UltraSoniclist[1] > 35) or (FO2 == 'FO_OutputtingBean')) :
- # DI2 = 'DI_OutputtingBean'
- # print('------- DI2 狀態更新:可出豆 -------')
- # elif DI2 == 'DI_OutputtingBean' and (DI_DOWN_UltraSoniclist[1] < 40) and FO2 == 'FO_OutputtingBean' and Dry_InputtingBean_number == 0 and Dry_InputtingBeanPause_number == 0:
- # DI2 = 'DI_InputtingBean'
- # print('------- DI2 狀態更新:入豆中 -------')
- # ----- 乾燥出料儲豆槽 DO1~DO2 入豆→可出豆判斷 ------------------------------
- # -- 取得乾燥出料儲豆槽 DO1~DO2 桶內高度 UltraSonic -------------
- DO_UP_UltraSoniclist = []
- for i in range(1, 3, 1):
- output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO' + str(i)).order_by(text('datetime desc')).first()
- UltraSonic = int(output_UltraSonic.UltraSonic)
- DO_UP_UltraSoniclist.append(UltraSonic)
- print('DO_UP_UltraSoniclist: ', DO_UP_UltraSoniclist)
- # 桶槽可出豆, 且出料儲豆槽等待時, 出料儲豆槽入豆
- # 參考 -- 乾燥桶槽 F1~F6 可出豆→出料儲豆槽 FO1 判斷 --
- # 出料儲豆槽入料 且滿時, 出料儲豆槽可出豆
- if DO1 == ('DO_InputtingBean' and DO_UP_UltraSoniclist[0] > 35):
- DO1 = 'DO_OutputtingBean'
- # 出料儲豆槽入料 且未滿, 桶槽可出豆已空
- # -- 取得乾燥桶槽 D1~D6 桶內高度 UltraSonic -------------
- D_UP_UltraSoniclist = []
- for i in range(1, 7, 1):
- tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D' + str(i)).order_by(text('datetime desc')).first()
- UltraSonic = int(tank_UltraSonic.UltraSonic)
- D_UP_UltraSoniclist.append(UltraSonic)
- print('D_UP_UltraSoniclist: ', D_UP_UltraSoniclist)
- # -- 取得乾燥桶槽 D1~D6 桶內高度 UltraSonic -------------
- if DO1 == 'DO_InputtingBean' and Dry_OutputtingBean_number >= 1:
- if D1 == 'D_OutputtingBean' and D_UP_UltraSoniclist[0] < 5:
- D1 = 'D_Waiting'
- DO1 = 'DO_OutputtingBean'
- print('------- D1 狀態更新:空桶等待 -------')
- print('------- DO1 狀態更新:可出豆 -------')
- elif D2 == 'D_OutputtingBean' and D_UP_UltraSoniclist[1] < 5:
- D2 = 'D_Waiting'
- DO1 = 'DO_OutputtingBean'
- print('------- D2 狀態更新:空桶等待 -------')
- print('------- DO1 狀態更新:可出豆 -------')
- elif D3 == 'D_OutputtingBean' and D_UP_UltraSoniclist[2] < 5:
- D3 = 'D_Waiting'
- DO1 = 'DO_OutputtingBean'
- print('------- D3 狀態更新:空桶等待 -------')
- print('------- DO1 狀態更新:可出豆 -------')
- elif D4 == 'D_OutputtingBean' and D_UP_UltraSoniclist[3] < 5:
- D4 = 'D_Waiting'
- DO1 = 'DO_OutputtingBean'
- print('------- D4 狀態更新:空桶等待 -------')
- print('------- DO1 狀態更新:可出豆 -------')
- elif D5 == 'D_OutputtingBean' and D_UP_UltraSoniclist[4] < 5:
- D5 = 'D_Waiting'
- DO1 = 'DO_OutputtingBean'
- print('------- D5 狀態更新:空桶等待 -------')
- print('------- DO1 狀態更新:可出豆 -------')
- elif D6 == 'D_OutputtingBean' and D_UP_UltraSoniclist[5] < 5:
- D6 = 'D_Waiting'
- DO1 = 'DO_OutputtingBean'
- print('------- D6 狀態更新:空桶等待 -------')
- print('------- DO1 狀態更新:可出豆 -------')
- elif DO1 == 'DO_OutputtingBean' and DO_UP_UltraSoniclist[0] < 5:
- DO1 = 'DO_Waiting'
- # # ----- 將狀態寫入資料庫 ------------------------------
- # # 獲取文本框的值並賦值給user實體對象
- # D_status = dry_container_status()
- # D_status.Dry_Input_1 = DI1
- # D_status.Dry_Input_2 = DI2
- # D_status.Dry_Tank_1 = D1
- # D_status.Dry_Tank_2 = D2
- # D_status.Dry_Tank_3 = D3
- # D_status.Dry_Tank_4 = D4
- # D_status.Dry_Tank_5 = D5
- # D_status.Dry_Tank_6 = D6
- # D_status.Dry_Tank_7 = D7
- # D_status.Dry_Tank_8 = D8
- # D_status.Dry_Tank_9 = D9
- # D_status.Dry_Tank_10 = D10
- # D_status.Dry_Tank_11 = D11
- # D_status.Dry_Tank_12 = D12
- # D_status.Dry_Output_1 = DO1
- # D_status.Dry_Output_2 = DO2
- # #將數據保存進資料庫
- # db.session.add(D_status)
- # # 手動提交
- # db.session.commit()
- # # ----- 將狀態寫入資料庫 ------------------------------
-
- return jsonify({"Dry_Input_1":DI1,
- "Dry_Tank_1":D1,
- "Dry_Tank_2":D2,
- "Dry_Tank_3":D3,
- "Dry_Tank_4":D4,
- "Dry_Tank_5":D5,
- "Dry_Tank_6":D6,
- "Dry_Output_1":DO1
- })
- # 1101 以流程圖判斷, 改寫 def dry_auto_status, 以上為原備份
- # 發酵槽自動化測試頁
- @main.route('/ferment_auto', methods=['GET', 'POST'])
- def ferment_auto():
- # 獲取登入信息
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
- FI1 = ferment_status.Ferment_Input_1
- FI2 = ferment_status.Ferment_Input_2
- F1 = ferment_status.Ferment_Tank_1
- F2 = ferment_status.Ferment_Tank_2
- F3 = ferment_status.Ferment_Tank_3
- F4 = ferment_status.Ferment_Tank_4
- F5 = ferment_status.Ferment_Tank_5
- F6 = ferment_status.Ferment_Tank_6
- F7 = ferment_status.Ferment_Tank_7
- F8 = ferment_status.Ferment_Tank_8
- F9 = ferment_status.Ferment_Tank_9
- F10 = ferment_status.Ferment_Tank_10
- F11 = ferment_status.Ferment_Tank_11
- F12 = ferment_status.Ferment_Tank_12
- FO1 = ferment_status.Ferment_Output_1
- FO2 = ferment_status.Ferment_Output_2
- clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
- PO1 = clean_status.Peel_Output_1 # PO_Waiting # PO_OutputtingBean
- PO2 = clean_status.Peel_Output_2
- # 感測器_發酵桶_SHT11
- tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- SHT11_Temp = float(tank_SHT11.SHT11_Temp)
- SHT11_Humidity = float(tank_SHT11.SHT11_Humidity)
- # 感測器_發酵桶_二氧化碳
- tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- CO2 = float(tank_CO2.CO2)
- # 感測器_發酵桶_酸鹼值
- tank_PH = ferment_tank_PH.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- tank_DO = ferment_tank_DO.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- tank_EC = ferment_tank_EC.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- PH = float(tank_PH.PH)
- ORP = float(tank_ORP.ORP)
- DO = float(tank_DO.DO)
- EC = float(tank_EC.EC)
- # 感測器_發酵桶_氣壓
- tank_PA = ferment_tank_PA.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- PA = float(tank_PA.PA)
- # 感測器_發酵桶_超音波感測器
- tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- UltraSonic= (float(tank_UltraSonic.UltraSonic))
- # 感測器_發酵桶_保溫夾層水位計
- tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- WaterLevel = tank_WaterLevel.WaterLevel
- return render_template('ferment_auto.html', title="[測試] 發酵自動化", **locals())
- else:
- return render_template('sign_in.html')
- @main.route('/fermentDEMO_auto_status', methods=['GET', 'POST'])
- def fermentDEMO_auto_status():
- info = request.args.to_dict()
- Ferment_Tank_bean_height = float(info['Ferment_Tank_bean_height'])
- Ferment_Tank_vacuumON_time = float(info['Ferment_Tank_vacuumON_time'])
- Ferment_Tank_vacuumOFF_time = float(info['Ferment_Tank_vacuumOFF_time'])
- Ferment_Tank_water_height = float(info['Ferment_Tank_water_height'])
- Ferment_Tank_fermenting_temp = float(info['Ferment_Tank_fermenting_temp'])
- Ferment_Tank_fermenting_time = float(info['Ferment_Tank_fermenting_time'])
- Ferment_Tank_motor_rpm = float(info['Ferment_Tank_motor_rpm'])
- Ferment_Tank_WaterOut_time = float(info['Ferment_Tank_WaterOut_time'])
- Ferment_btn = True
- # 從資料庫資料表中取得最新狀態
- ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
- FI1 = ferment_status.Ferment_Input_1 # FI1 = 'FI_OutputtingBean'
- FI2 = ferment_status.Ferment_Input_2
- F1 = ferment_status.Ferment_Tank_1
- F2 = ferment_status.Ferment_Tank_2
- F3 = ferment_status.Ferment_Tank_3
- F4 = ferment_status.Ferment_Tank_4
- F5 = ferment_status.Ferment_Tank_5
- F6 = ferment_status.Ferment_Tank_6
- F7 = ferment_status.Ferment_Tank_7
- F8 = ferment_status.Ferment_Tank_8
- F9 = ferment_status.Ferment_Tank_9
- F10 = ferment_status.Ferment_Tank_10
- F11 = ferment_status.Ferment_Tank_11
- F12 = ferment_status.Ferment_Tank_12
- FO1 = ferment_status.Ferment_Output_1
- FO2 = ferment_status.Ferment_Output_2
- F_UP_tanklist = [F1, F2, F3, F4, F5, F6]
- FOutputtingBean_Tank = '' # 這是給出料儲豆槽判斷目前出豆的桶槽
- # 寫定入料、桶槽、出料的空桶標準, 若 <= 2 則為空桶
- Ferment_Input_bean_empty = 2
- Ferment_Tank_bean_empty = 2
- Ferment_Output_bean_empty = 2
- # 目前發酵槽 F1~F6 正在入豆、入水的桶槽數量 (應小於一桶)
- FermentUp_Waiting_number = int(F_UP_tanklist.count('F_Waiting'))
- FermentUp_InputtingBean_number = int(F_UP_tanklist.count('F_InputtingBean'))
- FermentUp_InputtingBeanPause_number = int(F_UP_tanklist.count('F_InputtingBean_Pause'))
- FermentUp_InputtingBeanFinish_number = int(F_UP_tanklist.count('F_InputtingBean_Finish'))
- FermentUp_InputtingWater_number = int(F_UP_tanklist.count('F_InputtingWater'))
- # -- 取得發酵 入料儲豆槽 FI1~FI2 / 桶槽 F1~F6 / 出料 FO1~FO2 桶內高度 UltraSonic start -------------
- FI_UP_UltraSoniclist = []
- for i in range(1, 3, 1):
- input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
- # UltraSonic = float("{:.2f}".format(34.6 - float(input_UltraSonic.UltraSonic)))
- UltraSonic = float(input_UltraSonic.UltraSonic)
- FI_UP_UltraSoniclist.append(UltraSonic)
- print('FI_UP_UltraSoniclist: ', FI_UP_UltraSoniclist)
- F_UP_UltraSoniclist = []
- for i in range(1, 7, 1):
- tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
- UltraSonic = (float(tank_UltraSonic.UltraSonic))
- F_UP_UltraSoniclist.append(UltraSonic)
- print('F_UP_UltraSoniclist: ', F_UP_UltraSoniclist)
- FO_UP_UltraSoniclist = []
- for i in range(1, 3, 1):
- output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO' + str(i)).order_by(text('datetime desc')).first()
- UltraSonic = float(output_UltraSonic.UltraSonic)
- FO_UP_UltraSoniclist.append(UltraSonic)
- print('FO_UP_UltraSoniclist: ', FO_UP_UltraSoniclist)
- # -- 取得發酵 入料儲豆槽 FI1~FI2 / 桶槽 F1~F6 / 出料 FO1~FO2 桶內高度 UltraSonic end -------------
- # -- 取得發酵桶槽 F1~F6 夾層水位高度 WaterLevel start -------------
- F_UP_tank_WaterLevel = []
- for i in range(1, 7, 1):
- tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
- WaterLevel = float(tank_WaterLevel.WaterLevel)
- F_UP_tank_WaterLevel.append(WaterLevel)
- print('F_UP_tank_WaterLevel: ', F_UP_tank_WaterLevel)
- # -- 取得發酵桶槽 F1~F6 夾層水位高度 WaterLevel end -------------
- # -- 取得發酵桶槽 F1~F6 pH -------------
- F_UP_tank_PH = []
- for i in range(1, 7, 1):
- tank_PH = ferment_tank_PH.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
- PH = float(tank_PH.PH)
- F_UP_tank_PH.append(PH)
- print('F_UP_tank_PH: ', F_UP_tank_PH)
- # -- 取得發酵桶槽 F1~F6 pH -------------
- # -- 取得發酵桶槽 F1~F6 SHT11_TEMP -------------
- F_UP_tank_SHT11_Temp = []
- for i in range(1, 7, 1):
- tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
- SHT11_Temp = float(tank_SHT11.SHT11_Temp)
- F_UP_tank_SHT11_Temp.append(SHT11_Temp)
- print('F_UP_tank_SHT11_Temp: ', F_UP_tank_SHT11_Temp)
- # -- 取得發酵桶槽 F1~F6 SHT11_TEMP -------------
- # ----- 發酵排程動作 start ------------------------------------------------------------------
- # F1 == 'F_InputtingBean' AND (F_UP_UltraSoniclist[0] >= Ferment_Tank_bean_height):
- def FInputtingBean_TO_FInputtingBeanFinish(tid): # 1108 [測試] 入豆後直接出豆
- # [致動器] 蝴蝶閥 OFF
- data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 真空吸料機 OFF
- data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 0
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 入料三通閥 ON排氣
- data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # print('------- ', tid,' 狀態更新:入料完成 -------')
- print('------- ', tid,' 狀態更新:可出豆 -------')
- # (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height) AND FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height):
- def FInputtingBean_AND_notfilled(tid):
- # [致動器] 蝴蝶閥 OFF
- data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 入料三通閥 OFF入豆
- data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 真空吸料機 ON
- data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- while True:
- if (time.time() - timer) > Ferment_Tank_vacuumON_time:
- # [致動器] 入料真空吸料機 OFF
- data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- break
- while True:
- if (time.time() - timer) > Ferment_Tank_vacuumOFF_time:
- break
- # (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height) AND FI1 != 'FI_OutputtingBean'
- def FInputtingBean_TO_FInputtingBeanPause(tid):
- # [致動器] 蝴蝶閥 OFF
- data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 真空吸料機 OFF
- data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 入料三通閥 OFF入豆
- data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 0
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid,' 狀態更新:入豆暫停 -------')
-
- # FermentUp_InputtingBeanPause_number == 1 and FI1 == 'FI_OutputtingBean'
- # if F1 == 'F_InputtingBean_Pause' AND FI1 == 'FI_OutputtingBean'
- def FInputtingBeanPause_AND_FIOutputtingBean(tid):
- # [致動器] 入料三通閥 OFF入豆
- data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 5
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid, ' 狀態更新:入料中 -------')
- # elif FermentUp_InputtingBean_number == 0 and FermentUp_InputtingBeanPause_number == 0 and FI1 == 'FI_OutputtingBean' and FermentUp_Waiting_number >= 1
- def FWaiting_TO_FInputtingBean(tid):
- # [致動器] 蝴蝶閥 OFF
- data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 入料三通閥 OFF入豆
- data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 5
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid, ' 狀態更新:入料中 -------')
-
- # elif FermentUp_InputtingWater_number == 0 and FermentUp_InputtingBeanFinish_number >= 1:
- def FInputtingBeanFinish_TO_FInputtingWater_UP(tid, sn):
- print('------- ', tid,' 狀態更新:入水中 -------')
- # # [致動器] 浮選三通閥 ON
- # data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "on" }
- # print('data: ', data)
- # # # mqtt_f(data)
- # if (F_UP_tank_WaterLevel[sn] == 0):
- # # [致動器] 桶外進水電磁閥 ON
- # data = { "tank_num": tid, "command": "outer_solenoid_water_status", "value": "on" }
- # print('data: ', data)
- # # mqtt_f(data)
- if (F_UP_UltraSoniclist[sn] < Ferment_Tank_water_height):
- # 桶內高度若低於水位指定高度, [致動器] 桶內進水電磁閥 ON
- data = { "tank_num": tid, "command": "tank_solenoid_water_in_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # elif FermentUp_InputtingWater_number == 1:
- # 'F_InputtingWater' if (F_UP_tank_WaterLevel[0] == 1) and (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height):
- def FInputtingWater_TO_FFermenting(tid):
- # 若夾層入水達水位計高度 且 桶內入水達指定水位高度, 狀態轉換為發酵中
- # 桶外水位高度高於水位計高度, [致動器] 桶外進水電磁閥 OFF
- # data = { "tank_num": tid, "command": "outer_solenoid_water_status", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- # 桶內高度若高於水位指定高度, [致動器] 桶內進水電磁閥 OFF
- data = { "tank_num": tid, "command": "tank_solenoid_water_in_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid, ' 狀態更新:發酵中 -------')
- # [致動器] 馬達 (指定轉速)
- data = { "tank_num": tid, "command": "tank_motor_status", "value": Ferment_Tank_motor_rpm }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 溫控開關 ON
- # data = { "tank_num": tid, "command": "tank_temp_enable", "value": "on", "duration": Ferment_Tank_fermenting_time}
- # print('data: ', data)
- # # mqtt_f(data)
- # [致動器] 設定溫度、持溫時間
- # [致動器] 加熱器 1 ON
- # data = { "tank_num": tid, "command": "tank_heater1_status", "value": "on" }
- # print('data: ', data)
- # mqtt_f(data)
- # [致動器] 加熱器 2 ON
- # data = { "tank_num": tid, "command": "tank_heater2_status", "value": "on" }
- # print('data: ', data)
- # mqtt_f(data)
- # # [致動器] 雙核薄膜泵 水質檢測 ON
- # data = { "tank_num": tid, "command": "tank_pump_sensor_status", "value": "on"}
- # print('data: ', data)
- # # mqtt_f(data)
- # TODO 增加發酵條件等
- # 'F_InputtingWater' AND (F_UP_tank_WaterLevel[0] == 1)
- def FInputtingWater_AND_WaterLevel1(tid):
- # # [致動器] 桶外進水電磁閥 OFF
- # data = { "tank_num": tid, "command": "outer_solenoid_water_status", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- pass
- # 'F_InputtingWater' AND (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height)
- def FInputtingWater_AND_tankwaterfilled(tid):
- # 桶內高度若高於水位指定高度, [致動器] 桶內進水電磁閥 OFF
- data = { "tank_num": tid, "command": "tank_solenoid_water_in_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # else
- # F1 == 'F_Fermenting' and F_UP_tank_SHT11_Temp[0] >= Ferment_Tank_fermenting_temp and F_UP_tank_PH[0] <= Ferment_Tank_fermenting_pH:
- def FFermenting_TO_FOutputtingBean(tid):
- print(tid, ' 發酵等待 ', Ferment_Tank_fermenting_time, ' 秒')
- timer = time.time()
- while True:
- if (time.time() - timer) > Ferment_Tank_fermenting_time :
- # [致動器] 外桶浮選三通閥 OFF
- data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 0
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 設定溫度 0
- # data = { "tank_num": tid, "command": "tank_temp", "value": "0" }
- # print('data: ', data)
- # # mqtt_f(data)
- # [致動器] 溫控開關 OFF
- # data = { "tank_num": tid, "command": "tank_temp_enable", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- # [致動器] 加熱器 1 OFF
- data = { "tank_num": tid, "command": "tank_heater1_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 加熱器 2 OFF
- data = { "tank_num": tid, "command": "tank_heater2_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # # [致動器] 雙核薄膜泵 水質檢測 OFF
- # data = { "tank_num": tid, "command": "tank_pump_sensor_status", "value": "off"}
- # print('data: ', data)
- # # mqtt_f(data)
- # TODO 增加發酵條件等
- break
- # [致動器] 廢水排水閥 (桶內) ON
- data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- print(tid, '桶內廢水排水 ', Ferment_Tank_WaterOut_time, ' 秒')
- timer = time.time()
- while True:
- if (time.time() - timer) > Ferment_Tank_WaterOut_time:
- # [致動器] 廢水排水閥 (桶內) OFF
- data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- break
- print('------- ', tid, ' 狀態更新:可出豆 -------')
- # else: if F1 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[0] <= Ferment_Tank_bean_empty):
- def FOutputtingBean_TO_FWaiting(tid):
- # [致動器] F1 蝴蝶閥 ON
- data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # ----- 發酵排程動作 end ------------------------------------------------------------------
- # [介面] 若啟用 發酵 狀態
- if Ferment_btn:
- # ----- 發酵桶槽 F1~F6 入料桶槽優先入料判斷 ------------------------------
- # 若 F1~F6 桶槽中有一個桶槽入豆中
- if FermentUp_InputtingBean_number == 1:
- # 若 F1 桶槽為入豆中
- if F1 == 'F_InputtingBean':
- if (F_UP_UltraSoniclist[0] >= Ferment_Tank_bean_height):
- FInputtingBean_TO_FInputtingBeanFinish("F1")
- # F1 = 'F_InputtingBean_Finish'
- F1 = 'F_OutputtingBean'
- elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height):
- FInputtingBean_AND_notfilled("F1")
- elif FI1 != 'FI_OutputtingBean':
- FInputtingBean_TO_FInputtingBeanPause("F1")
- F1 = 'F_InputtingBean_Pause'
- # 若 F1~F6 桶槽中有一個桶槽入豆暫停中, 且 FI1 可出豆
- elif FermentUp_InputtingBeanPause_number == 1 and FI1 == 'FI_OutputtingBean':
- # 若 F1 桶槽為入豆暫停 且 FI1 可出料
- if F1 == 'F_InputtingBean_Pause':
- FInputtingBeanPause_AND_FIOutputtingBean("F1")
- F1 = 'F_InputtingBean'
- # 若 F1~F6 桶槽中 無桶槽正在入料或入料等待, 且 FI1 可出豆時
- elif FermentUp_InputtingBean_number == 0 and FermentUp_InputtingBeanPause_number == 0 and FI1 == 'FI_OutputtingBean' and FermentUp_Waiting_number >= 1:
- if F1 == 'F_Waiting':
- FWaiting_TO_FInputtingBean("F1")
- F1 = 'F_InputtingBean'
- # 若 F1~F6 桶槽中 無桶槽正在入水, 則入豆完成者轉換狀態 開始入水
- elif FermentUp_InputtingWater_number == 0 and FermentUp_InputtingBeanFinish_number >= 1:
- if F1 == 'F_InputtingBean_Finish':
- F1 = 'F_InputtingWater'
- FInputtingBeanFinish_TO_FInputtingWater_UP("F1", 0)
- elif FermentUp_InputtingWater_number == 1:
- if F1 == 'F_InputtingWater':
- if (F_UP_tank_WaterLevel[0] == 1) and (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height):
- F1 = 'F_Fermenting'
- FInputtingWater_TO_FFermenting("F1")
- elif (F_UP_tank_WaterLevel[0] == 1):
- FInputtingWater_AND_WaterLevel1("F1")
- elif (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height):
- FInputtingWater_AND_tankwaterfilled("F1")
- else:
- if F1 == 'F_Fermenting' and F_UP_tank_SHT11_Temp[0] >= Ferment_Tank_fermenting_temp:
- FFermenting_TO_FOutputtingBean("F1")
- F1 = 'F_OutputtingBean'
- # 將可出豆桶槽賦值
- if FOutputtingBean_Tank == '': FOutputtingBean_Tank = 'F1'
- # 若桶槽 F1~F6 可出豆 且 桶槽內為空桶 且 有指定清洗排程, 進行清洗桶槽
- # TODO 發酵次數計算、消毒次數、校正
- if F1 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[0] <= Ferment_Tank_bean_empty):
- if FOutputtingBean_Tank == 'F1':
- FOutputtingBean_TO_FWaiting('F1')
- FOutputtingBean_Tank = ''
- F1 = 'F_Waiting'
- print('------- F1 狀態更新:空桶等待 -------')
- # 避免桶槽可出豆時未賦值
- if FOutputtingBean_Tank == '':
- if F1 == 'F_OutputtingBean': FOutputtingBean_Tank = 'F1'
-
- # 若桶槽 F1~F6 為清洗中
- if F1 == 'F_Cleaning':
- # FCleaning("F1")
- F1 = 'F_Waiting'
- print('------- F1 狀態更新:空桶等待 -------')
-
- # # ----- [測試用] !!!!! F1~F6 入料完成→可出豆 判斷 ------------------------------
- # if F1 == 'F_InputtingBean_Finish': F1 = 'F_OutputtingBean'
- # if F2 == 'F_InputtingBean_Finish': F2 = 'F_OutputtingBean'
- # if F3 == 'F_InputtingBean_Finish': F3 = 'F_OutputtingBean'
- # if F4 == 'F_InputtingBean_Finish': F4 = 'F_OutputtingBean'
- # if F5 == 'F_InputtingBean_Finish': F5 = 'F_OutputtingBean'
- # if F6 == 'F_InputtingBean_Finish': F6 = 'F_OutputtingBean'
- # # ----- [測試用] !!!!! F1~F6 入料完成→可出豆 判斷 ------------------------------
- else:
- # [介面] 若未啟用 發酵 狀態
- print('未啟用發酵流程')
- # ----- 將狀態寫入資料庫 ------------------------------
- # 獲取文本框的值並賦值給user實體對象
- F_status = ferment_container_status()
- F_status.Ferment_Input_1 = FI1
- F_status.Ferment_Input_2 = FI2
- F_status.Ferment_Tank_1 = F1
- F_status.Ferment_Tank_2 = F2
- F_status.Ferment_Tank_3 = F3
- F_status.Ferment_Tank_4 = F4
- F_status.Ferment_Tank_5 = F5
- F_status.Ferment_Tank_6 = F6
- F_status.Ferment_Tank_7 = F7
- F_status.Ferment_Tank_8 = F8
- F_status.Ferment_Tank_9 = F9
- F_status.Ferment_Tank_10 = F10
- F_status.Ferment_Tank_11 = F11
- F_status.Ferment_Tank_12 = F12
- F_status.Ferment_Output_1 = FO1
- F_status.Ferment_Output_2 = FO2
- #將數據保存進資料庫
- db.session.add(F_status)
- # 手動提交
- db.session.commit()
- # ----- 將狀態寫入資料庫 ------------------------------
- return jsonify({"Ferment_Tank_1":F1,
- "Ferment_Tank_2":F2
- })
- @main.route('/ferment_auto_status', methods=['GET', 'POST'])
- def ferment_auto_test():
- info = request.args.to_dict()
- # 寫定入料、桶槽、出料的空桶標準, 若 <= 2 則為空桶
- Ferment_Input_bean_empty = 2
- Ferment_Tank_bean_empty = 2
- Ferment_Output_bean_empty = 2
- # 從介面取得 指定生豆高度/發酵桶槽排程:發酵、清洗、校正 EC、校正攪拌棒
- FermentAuto_fermenting = int(info['FermentAuto_fermenting'])
- FermentAuto_cleaning = int(info['FermentAuto_cleaning'])
- FermentAuto_calibratingEC = int(info['FermentAuto_calibratingEC'])
- FermentAuto_calibratingSTIR = int(info['FermentAuto_calibratingSTIR'])
- Ferment_Input_bean_height = float(info['Ferment_Input_bean_height'])
- Ferment_Input_vacuumON_time = float(info['Ferment_Input_vacuumON_time'])
- Ferment_Input_vacuumOFF_time = float(info['Ferment_Input_vacuumOFF_time'])
- Ferment_Tank_bean_height = float(info['Ferment_Tank_bean_height'])
- Ferment_Tank_vacuumON_time = float(info['Ferment_Tank_vacuumON_time'])
- Ferment_Tank_vacuumOFF_time = float(info['Ferment_Tank_vacuumOFF_time'])
- Ferment_Tank_water_height = float(info['Ferment_Tank_water_height'])
- Ferment_Tank_fermenting_temp = float(info['Ferment_Tank_fermenting_temp'])
- Ferment_Tank_fermenting_time = float(info['Ferment_Tank_fermenting_time'])
- Ferment_Tank_motor_rpm = float(info['Ferment_Tank_motor_rpm'])
- Ferment_Tank_motor_time = float(info['Ferment_Tank_motor_time'])
- Ferment_Tank_fermenting_pH = float(info['Ferment_Tank_fermenting_pH'])
- Ferment_Output_bean_height = float(info['Ferment_Output_bean_height'])
- Ferment_Output_vacuumON_time = float(info['Ferment_Output_vacuumON_time'])
- Ferment_Output_vacuumOFF_time = float(info['Ferment_Output_vacuumOFF_time'])
- Ferment_Tank_WaterOut_time = float(info['Ferment_Tank_WaterOut_time'])
- Ferment_Tank_Disinfect_time = float(info['Ferment_Tank_Disinfect_time'])
- Ferment_cb_vacuum = info['Ferment_cb_vacuum'] # 'true' 'false'
- Ferment_cb_vacuum_time = float(info['Ferment_cb_vacuum_time'])
-
- # [介面] 讓使用者可以選擇排程內有發酵/清洗/校正, 此處預設為 True
- Ferment_btn = FermentAuto_fermenting # Ferment_btn = True
- # 從資料庫資料表中取得最新狀態
- ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
- FI1 = ferment_status.Ferment_Input_1
- FI2 = ferment_status.Ferment_Input_2
- F1 = ferment_status.Ferment_Tank_1
- F2 = ferment_status.Ferment_Tank_2
- F3 = ferment_status.Ferment_Tank_3
- F4 = ferment_status.Ferment_Tank_4
- F5 = ferment_status.Ferment_Tank_5
- F6 = ferment_status.Ferment_Tank_6
- F7 = ferment_status.Ferment_Tank_7
- F8 = ferment_status.Ferment_Tank_8
- F9 = ferment_status.Ferment_Tank_9
- F10 = ferment_status.Ferment_Tank_10
- F11 = ferment_status.Ferment_Tank_11
- F12 = ferment_status.Ferment_Tank_12
- FO1 = ferment_status.Ferment_Output_1
- FO2 = ferment_status.Ferment_Output_2
- clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
- PO1 = clean_status.Peel_Output_1 # PO_Waiting # PO_OutputtingBean
- PO2 = clean_status.Peel_Output_2
- F_UP_tanklist = [F1, F2, F3, F4, F5, F6]
- F_DOWN_tanklist = [F7, F8, F9, F10, F11, F12]
- FOutputtingBean_Tank = '' # 這是給出料儲豆槽判斷目前出豆的桶槽
- # 目前發酵槽 F1~F6 正在入豆、入水的桶槽數量 (應小於一桶)
- FermentUp_Waiting_number = int(F_UP_tanklist.count('F_Waiting'))
- FermentUp_InputtingBean_number = int(F_UP_tanklist.count('F_InputtingBean'))
- FermentUp_InputtingBeanPause_number = int(F_UP_tanklist.count('F_InputtingBean_Pause'))
- FermentUp_InputtingBeanFinish_number = int(F_UP_tanklist.count('F_InputtingBean_Finish'))
- FermentUp_InputtingWater_number = int(F_UP_tanklist.count('F_InputtingWater'))
- # -- 取得發酵 入料儲豆槽 FI1~FI2 / 桶槽 F1~F6 / 出料 FO1~FO2 桶內高度 UltraSonic start -------------
- FI_UP_UltraSoniclist = []
- for i in range(1, 3, 1):
- input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
- # UltraSonic = float("{:.2f}".format(34.6 - float(input_UltraSonic.UltraSonic)))
- UltraSonic = float(input_UltraSonic.UltraSonic)
- FI_UP_UltraSoniclist.append(UltraSonic)
- print('FI_UP_UltraSoniclist: ', FI_UP_UltraSoniclist)
- F_UP_UltraSoniclist = []
- for i in range(1, 7, 1):
- tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
- UltraSonic = (float(tank_UltraSonic.UltraSonic))
- F_UP_UltraSoniclist.append(UltraSonic)
- print('F_UP_UltraSoniclist: ', F_UP_UltraSoniclist)
- FO_UP_UltraSoniclist = []
- for i in range(1, 3, 1):
- output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO' + str(i)).order_by(text('datetime desc')).first()
- UltraSonic = float(output_UltraSonic.UltraSonic)
- FO_UP_UltraSoniclist.append(UltraSonic)
- print('FO_UP_UltraSoniclist: ', FO_UP_UltraSoniclist)
- # -- 取得發酵 入料儲豆槽 FI1~FI2 / 桶槽 F1~F6 / 出料 FO1~FO2 桶內高度 UltraSonic end -------------
- # -- 取得發酵桶槽 F1~F6 夾層水位高度 WaterLevel start -------------
- F_UP_tank_WaterLevel = []
- for i in range(1, 7, 1):
- tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
- WaterLevel = float(tank_WaterLevel.WaterLevel)
- F_UP_tank_WaterLevel.append(WaterLevel)
- print('F_UP_tank_WaterLevel: ', F_UP_tank_WaterLevel)
- # -- 取得發酵桶槽 F1~F6 夾層水位高度 WaterLevel end -------------
- # -- 取得發酵桶槽 F1~F6 pH -------------
- F_UP_tank_PH = []
- for i in range(1, 7, 1):
- tank_PH = ferment_tank_PH.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
- PH = float(tank_PH.PH)
- F_UP_tank_PH.append(PH)
- print('F_UP_tank_PH: ', F_UP_tank_PH)
- # -- 取得發酵桶槽 F1~F6 pH -------------
- # -- 取得發酵桶槽 F1~F6 SHT11_TEMP -------------
- F_UP_tank_SHT11_Temp = []
- for i in range(1, 7, 1):
- tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
- SHT11_Temp = float(tank_SHT11.SHT11_Temp)
- F_UP_tank_SHT11_Temp.append(SHT11_Temp)
- print('F_UP_tank_SHT11_Temp: ', F_UP_tank_SHT11_Temp)
- # -- 取得發酵桶槽 F1~F6 SHT11_TEMP -------------
- # ----- 發酵排程動作 start ------------------------------------------------------------------
- # FI1 == 'FI_InputtingBean' AND if (FI_UP_UltraSoniclist[0] >= Ferment_Input_bean_height):
- def FIInputtingBean_filled(tid):
- # [致動器] 入料真空吸料機 OFF
- data = { "tank_num": tid, "command": "input_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid, ' 狀態更新:可出豆 -------')
- # FI1 == 'FI_InputtingBean' AND elif (FI_UP_UltraSoniclist[0] < Ferment_Input_bean_height) and PO1 == 'PO_OutputtingBean':
- def FIInputtingBean_AND_notfilled(tid):
- # [致動器] 入料真空吸料機 ON
- data = { "tank_num": tid, "command": "input_vacuum_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # 暫停 (指定吸料時間) 秒
- time.sleep(Ferment_Input_vacuumON_time)
- # [致動器] 入料真空吸料機 OFF
- data = { "tank_num": tid, "command": "input_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # 暫停 (指定放料時間) 秒
- time.sleep(Ferment_Input_vacuumOFF_time)
- # F1 == 'F_InputtingBean' AND (F_UP_UltraSoniclist[0] >= Ferment_Tank_bean_height):
- def FInputtingBean_TO_FInputtingBeanFinish(tid):
- # [致動器] 真空吸料機 OFF
- data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 0
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 入料三通閥 ON排氣
- data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid,' 狀態更新:入料完成 -------')
- # (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height) AND FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height):
- def FInputtingBean_AND_notfilled(tid):
- # [致動器] 入料三通閥 OFF入豆
- data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 真空吸料機 ON
- data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # 暫停 (指定吸料時間) 秒
- time.sleep(Ferment_Tank_vacuumON_time)
- # [致動器] 入料真空吸料機 OFF
- data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # 暫停 (指定吸料時間) 秒
- time.sleep(Ferment_Tank_vacuumOFF_time)
- # # [致動器] 真空吸料機 ON
- # data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "on" }
- # print('data: ', data)
- # # mqtt_f(data)
- # timer = time.time()
- # while True:
- # if (time.time() - timer) > Ferment_Tank_vacuumON_time:
- # # [致動器] 入料真空吸料機 OFF
- # data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- # timer = time.time()
- # break
- # while True:
- # if (time.time() - timer) > Ferment_Tank_vacuumOFF_time:
- # break
- # (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height) AND FI1 != 'FI_OutputtingBean'
- def FInputtingBean_TO_FInputtingBeanPause(tid):
- # [致動器] 真空吸料機 OFF
- data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 入料三通閥 OFF入豆
- data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 0
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid,' 狀態更新:入豆暫停 -------')
-
- # FermentUp_InputtingBeanPause_number == 1 and FI1 == 'FI_OutputtingBean'
- # if F1 == 'F_InputtingBean_Pause' AND FI1 == 'FI_OutputtingBean'
- def FInputtingBeanPause_AND_FIOutputtingBean(tid):
- # [致動器] 入料三通閥 OFF入豆
- data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 5
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid, ' 狀態更新:入料中 -------')
- # elif FermentUp_InputtingBean_number == 0 and FermentUp_InputtingBeanPause_number == 0 and FI1 == 'FI_OutputtingBean' and FermentUp_Waiting_number >= 1
- def FWaiting_TO_FInputtingBean(tid):
- # [致動器] 入料三通閥 OFF入豆
- data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 5
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "5" }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid, ' 狀態更新:入料中 -------')
-
- # elif FermentUp_InputtingWater_number == 0 and FermentUp_InputtingBeanFinish_number >= 1:
- def FInputtingBeanFinish_TO_FInputtingWater_UP(tid, sn):
- print('------- ', tid,' 狀態更新:入水中 -------')
- # [致動器] 浮選三通閥 ON
- data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- if (F_UP_tank_WaterLevel[sn] == 0):
- # [致動器] 桶外進水電磁閥 ON
- data = { "tank_num": tid, "command": "outer_solenoid_water_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- if (F_UP_UltraSoniclist[sn] < Ferment_Tank_water_height):
- # 桶內高度若低於水位指定高度, [致動器] 桶內進水電磁閥 ON
- data = { "tank_num": tid, "command": "tank_solenoid_water_in_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # elif FermentUp_InputtingWater_number == 1:
- # 'F_InputtingWater' if (F_UP_tank_WaterLevel[0] == 1) and (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height):
- def FInputtingWater_TO_FFermenting(tid):
- # 若夾層入水達水位計高度 且 桶內入水達指定水位高度, 狀態轉換為發酵中
- # 桶外水位高度高於水位計高度, [致動器] 桶外進水電磁閥 OFF
- data = { "tank_num": tid, "command": "outer_solenoid_water_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # 桶內高度若高於水位指定高度, [致動器] 桶內進水電磁閥 OFF
- data = { "tank_num": tid, "command": "tank_solenoid_water_in_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- print('------- ', tid, ' 狀態更新:發酵中 -------')
- # 若勾選 發酵時桶內抽真空?
- if Ferment_cb_vacuum == 'true':
- # [致動器] 入料三通閥 ON排氣
- data = { "tank_num": tid, "command": "tank_threewayvalve_input_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 外桶浮選三通閥 OFF
- data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 真空吸料機 ON
- data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # 暫停 (桶內抽氣時間) 秒
- print(tid, '真空發酵, 桶槽抽氣 ' , Ferment_cb_vacuum_time, ' 秒')
- time.sleep(Ferment_cb_vacuum_time)
- # timer = time.time()
- # while True:
- # if (time.time() - timer) > Ferment_cb_vacuum_time:
- # # [致動器] 入料真空吸料機 OFF
- # data = { "tank_num": tid, "command": "tank_vacuum_status", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- # break
- # [致動器] 馬達 (指定轉速)
- data = { "tank_num": tid, "command": "tank_motor_status", "value": Ferment_Tank_motor_rpm }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 溫控開關 ON
- # data = { "tank_num": tid, "command": "tank_temp_enable", "value": "on", "duration": Ferment_Tank_fermenting_time}
- # print('data: ', data)
- # # mqtt_f(data)
- # [致動器] 設定溫度、持溫時間
- # [致動器] 加熱器 1 ON
- data = { "tank_num": tid, "command": "tank_heater1_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 加熱器 2 ON
- data = { "tank_num": tid, "command": "tank_heater2_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 雙核薄膜泵 水質檢測 ON
- data = { "tank_num": tid, "command": "tank_pump_sensor_status", "value": "on"}
- print('data: ', data)
- # mqtt_f(data)
- # TODO 增加發酵條件等
- # 'F_InputtingWater' AND (F_UP_tank_WaterLevel[0] == 1)
- def FInputtingWater_AND_WaterLevel1(tid):
- # [致動器] 桶外進水電磁閥 OFF
- data = { "tank_num": tid, "command": "outer_solenoid_water_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # 'F_InputtingWater' AND (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height)
- def FInputtingWater_AND_tankwaterfilled(tid):
- # 桶內高度若高於水位指定高度, [致動器] 桶內進水電磁閥 OFF
- data = { "tank_num": tid, "command": "tank_solenoid_water_in_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # else
- # F1 == 'F_Fermenting' and F_UP_tank_SHT11_Temp[0] >= Ferment_Tank_fermenting_temp and F_UP_tank_PH[0] <= Ferment_Tank_fermenting_pH:
- def FFermenting_TO_FOutputtingBean(tid):
- # 暫停 (桶內抽氣時間) 秒
- print(tid, ' 發酵等待 ', Ferment_Tank_fermenting_time, ' 秒')
- time.sleep(Ferment_Tank_fermenting_time)
- # [致動器] 外桶浮選三通閥 OFF
- data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 0
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 設定溫度 0
- data = { "tank_num": tid, "command": "tank_temp", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 溫控開關 OFF
- # data = { "tank_num": tid, "command": "tank_temp_enable", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- # [致動器] 加熱器 1 OFF
- data = { "tank_num": tid, "command": "tank_heater1_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 加熱器 2 OFF
- data = { "tank_num": tid, "command": "tank_heater2_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 雙核薄膜泵 水質檢測 OFF
- data = { "tank_num": tid, "command": "tank_pump_sensor_status", "value": "off"}
- print('data: ', data)
- # mqtt_f(data)
- # timer = time.time()
- # while True:
- # if (time.time() - timer) > Ferment_Tank_fermenting_time :
- # # [致動器] 外桶浮選三通閥 OFF
- # data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- # # [致動器] 馬達 0
- # data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
- # print('data: ', data)
- # # mqtt_f(data)
- # # [致動器] 設定溫度 0
- # data = { "tank_num": tid, "command": "tank_temp", "value": "0" }
- # print('data: ', data)
- # # mqtt_f(data)
- # # [致動器] 溫控開關 OFF
- # # data = { "tank_num": tid, "command": "tank_temp_enable", "value": "off" }
- # # print('data: ', data)
- # # # mqtt_f(data)
- # # [致動器] 加熱器 1 OFF
- # data = { "tank_num": tid, "command": "tank_heater1_status", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- # # [致動器] 加熱器 2 OFF
- # data = { "tank_num": tid, "command": "tank_heater2_status", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- # # [致動器] 雙核薄膜泵 水質檢測 OFF
- # data = { "tank_num": tid, "command": "tank_pump_sensor_status", "value": "off"}
- # print('data: ', data)
- # # mqtt_f(data)
- # # TODO 增加發酵條件等
- # break
- # [致動器] 廢水排水閥 (桶內) ON
- data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # 暫停 (桶內抽氣時間) 秒
- print(tid, '桶內廢水排水 ', Ferment_Tank_WaterOut_time, ' 秒')
- time.sleep(Ferment_Tank_WaterOut_time)
- # [致動器] 廢水排水閥 (桶內) OFF
- data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # timer = time.time()
- # while True:
- # if (time.time() - timer) > Ferment_Tank_WaterOut_time:
- # # [致動器] 廢水排水閥 (桶內) OFF
- # data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- # break
- print('------- ', tid, ' 狀態更新:可出豆 -------')
- # else: if F1 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[0] <= Ferment_Tank_bean_empty):
- def FOutputtingBean_TO_FWaiting(tid):
- # [致動器] F1 蝴蝶閥 ON
- data = { "tank_num": tid, "command": "tank_diskvalve_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # F_Cleaning
- def FCleaning(tid):
- # [致動器] 浮選三通閥 OFF
- data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 逆洗雙核薄膜泵電磁閥 ON
- data = { "tank_num": tid, "command": "solenoid_tank_pump_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 10
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "10" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 消毒電磁閥 ON
- data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 消毒抽水 Pump ON TODO
- # 暫停 (消毒時間) 秒
- print(tid, ' 桶內消毒 ', Ferment_Tank_Disinfect_time, ' 秒')
- time.sleep(Ferment_Tank_Disinfect_time)
- # [致動器] 消毒電磁閥 OFF
- data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # timer = time.time()
- # while True:
- # if (time.time() - timer) > Ferment_Tank_Disinfect_time :
- # # [致動器] 消毒電磁閥 OFF
- # data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- # break
- # [致動器] 消毒抽水 Pump OFF TODO
- # [致動器] 馬達 0
- data = { "tank_num": tid, "command": "tank_motor_status", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 浮選三通閥 ON
- data = { "tank_num": tid, "command": "outer_threewayvalve_float_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 逆洗雙核薄膜泵電磁閥 OFF
- data = { "tank_num": tid, "command": "solenoid_tank_pump_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 消毒電磁閥 OFF
- data = { "tank_num": tid, "command": "tank_solenoid_disinfect_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 廢水排水閥 (桶內) ON
- data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- print(tid, ' 桶內廢水排水 ', Ferment_Tank_WaterOut_time, ' 秒')
- time.sleep(Ferment_Tank_WaterOut_time)
- # [致動器] 廢水排水閥 (桶內) OFF
- data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # timer = time.time()
- # while True:
- # if (time.time() - timer) > Ferment_Tank_WaterOut_time:
- # # [致動器] 廢水排水閥 (桶內) OFF
- # data = { "tank_num": tid, "command": "tank_solenoid_water_out_status", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- # break
- print('------- ', tid, ' 狀態更新:空桶等待 -------')
- # elif FO1 == 'FO_InputtingBean' and FOutputtingBean_Tank != '': AND elif FO_UP_UltraSoniclist[0] < Ferment_Output_bean_height:
- def FOInputtingBean_filled(tid):
- # [致動器] 出料真空吸料機 ON
- data = { "tank_num": FOutputtingBean_Tank, "command": "input_vacuum_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # 暫停 (指定吸料時間) 秒
- time.sleep(Ferment_Output_vacuumON_time)
- # [致動器] 出料真空吸料機 OFF
- data = { "tank_num": FOutputtingBean_Tank, "command": "input_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # 暫停 (指定放料時間) 秒
- time.sleep(Ferment_Output_vacuumOFF_time)
- # # [致動器] 出料真空吸料機 ON
- # data = { "tank_num": FOutputtingBean_Tank, "command": "input_vacuum_status", "value": "on" }
- # print('data: ', data)
- # # mqtt_f(data)
- # timer = time.time()
- # while True:
- # if (time.time() - timer) > Ferment_Output_vacuumON_time:
- # # [致動器] 出料真空吸料機 OFF
- # data = { "tank_num": FOutputtingBean_Tank, "command": "input_vacuum_status", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- # timer = time.time()
- # break
- # while True:
- # if (time.time() - timer) > Ferment_Output_vacuumOFF_time:
- # break
-
- # ----- 發酵排程動作 end ------------------------------------------------------------------
- # ----- 發酵入料儲豆槽 FI1~FI2 入豆→可出豆判斷 ------------------------------
- # 入料儲豆槽等待中、且脫皮機儲豆槽可出豆時, 入料儲豆槽入豆
- if FI1 == 'FI_Waiting' and PO1 == 'PO_OutputtingBean':
- FI1 = 'FI_InputtingBean'
- print('------- FI1 狀態更新:入豆中 -------')
- # 入料儲豆槽入豆時
- elif FI1 == 'FI_InputtingBean':
- # 桶槽內達指定生豆高度時, 入料儲豆槽狀態轉為 可出豆
- if (FI_UP_UltraSoniclist[0] >= Ferment_Input_bean_height):
- FIInputtingBean_filled("FI1")
- FI1 = 'FI_OutputtingBean'
- # 桶槽內未達指定生豆高度, 且 前方 PO1 可出豆, 就執行入料動作
- elif (FI_UP_UltraSoniclist[0] < Ferment_Input_bean_height) and PO1 == 'PO_OutputtingBean':
- FI1_thread = threading.Thread(target=FIInputtingBean_AND_notfilled, args=["FI1"])
- FI1_thread.start()
- # 桶槽內大於空桶高度, 且 前方 PO1 非可出豆, 將狀態轉為可出豆
- elif (FI_UP_UltraSoniclist[0] > Ferment_Input_bean_empty) and PO1 != 'PO_OutputtingBean':
- FI1 = 'FI_OutputtingBean'
- print('------- FI1 狀態更新:可出豆 -------')
- # 桶槽內小於空桶高度, 且 前方 PO1 非可出豆, 將狀態轉為空桶等待
- elif (FI_UP_UltraSoniclist[0] <= Ferment_Input_bean_empty) and PO1 != 'PO_OutputtingBean':
- FI1 = 'FI_Waiting'
- print('------- FI1 狀態更新:空桶等待 -------')
- # 入料儲豆槽出豆時, 桶槽高度為 空桶高度時, 狀態轉為 空桶等待
- elif FI1 == 'FI_OutputtingBean' and (FI_UP_UltraSoniclist[0] <= Ferment_Input_bean_empty):
- FI1 = 'FI_Waiting'
- print('------- FI1 狀態更新:空桶等待 -------')
- # [介面] 若啟用 發酵 狀態
- if Ferment_btn:
- # ----- 發酵桶槽 F1~F6 入料桶槽優先入料判斷 ------------------------------
- # 若 F1~F6 桶槽中有一個桶槽入豆中
- if FermentUp_InputtingBean_number == 1:
- # 若 F1 桶槽為入豆中
- if F1 == 'F_InputtingBean':
- if (F_UP_UltraSoniclist[0] >= Ferment_Tank_bean_height):
- FInputtingBean_TO_FInputtingBeanFinish("F1")
- F1 = 'F_InputtingBean_Finish'
- elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height):
- F1_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F1"])
- F1_thread.start()
- elif FI1 != 'FI_OutputtingBean':
- FInputtingBean_TO_FInputtingBeanPause("F1")
- F1 = 'F_InputtingBean_Pause'
- elif F2 == 'F_InputtingBean':
- if (F_UP_UltraSoniclist[1] >= Ferment_Tank_bean_height):
- FInputtingBean_TO_FInputtingBeanFinish("F2")
- F2 = 'F_InputtingBean_Finish'
- elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[1] < Ferment_Tank_bean_height):
- F2_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F2"])
- F2_thread.start()
- elif FI1 != 'FI_OutputtingBean':
- FInputtingBean_TO_FInputtingBeanPause("F2")
- F2 = 'F_InputtingBean_Pause'
- elif F3 == 'F_InputtingBean':
- if (F_UP_UltraSoniclist[2] >= Ferment_Tank_bean_height):
- FInputtingBean_TO_FInputtingBeanFinish("F3")
- F3 = 'F_InputtingBean_Finish'
- elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[2] < Ferment_Tank_bean_height):
- F3_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F3"])
- F3_thread.start()
- elif FI1 != 'FI_OutputtingBean':
- FInputtingBean_TO_FInputtingBeanPause("F3")
- F3 = 'F_InputtingBean_Pause'
- elif F4 == 'F_InputtingBean':
- if (F_UP_UltraSoniclist[3] >= Ferment_Tank_bean_height):
- FInputtingBean_TO_FInputtingBeanFinish("F4")
- F4 = 'F_InputtingBean_Finish'
- elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[3] < Ferment_Tank_bean_height):
- F4_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F4"])
- F4_thread.start()
- elif FI1 != 'FI_OutputtingBean':
- FInputtingBean_TO_FInputtingBeanPause("F4")
- F4 = 'F_InputtingBean_Pause'
- elif F5 == 'F_InputtingBean':
- if (F_UP_UltraSoniclist[4] >= Ferment_Tank_bean_height):
- FInputtingBean_TO_FInputtingBeanFinish("F5")
- F5 = 'F_InputtingBean_Finish'
- elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[4] < Ferment_Tank_bean_height):
- F5_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F5"])
- F5_thread.start()
- elif FI1 != 'FI_OutputtingBean':
- FInputtingBean_TO_FInputtingBeanPause("F5")
- F5 = 'F_InputtingBean_Pause'
- elif F6 == 'F_InputtingBean':
- if (F_UP_UltraSoniclist[5] >= Ferment_Tank_bean_height):
- FInputtingBean_TO_FInputtingBeanFinish("F6")
- F6 = 'F_InputtingBean_Finish'
- elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[5] < Ferment_Tank_bean_height):
- F6_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F6"])
- F6_thread.start()
- elif FI1 != 'FI_OutputtingBean':
- FInputtingBean_TO_FInputtingBeanPause("F6")
- F6 = 'F_InputtingBean_Pause'
- # 若 F1~F6 桶槽中有一個桶槽入豆暫停中, 且 FI1 可出豆
- elif FermentUp_InputtingBeanPause_number == 1 and FI1 == 'FI_OutputtingBean':
- # 若 F1 桶槽為入豆暫停 且 FI1 可出料
- if F1 == 'F_InputtingBean_Pause':
- FInputtingBeanPause_AND_FIOutputtingBean("F1")
- F1 = 'F_InputtingBean'
- elif F2 == 'F_InputtingBean_Pause':
- FInputtingBeanPause_AND_FIOutputtingBean("F2")
- F2 = 'F_InputtingBean'
- elif F3 == 'F_InputtingBean_Pause':
- FInputtingBeanPause_AND_FIOutputtingBean("F3")
- F3 = 'F_InputtingBean'
- elif F4 == 'F_InputtingBean_Pause':
- FInputtingBeanPause_AND_FIOutputtingBean("F4")
- F4 = 'F_InputtingBean'
- elif F5 == 'F_InputtingBean_Pause':
- FInputtingBeanPause_AND_FIOutputtingBean("F5")
- F5 = 'F_InputtingBean'
- elif F6 == 'F_InputtingBean_Pause':
- FInputtingBeanPause_AND_FIOutputtingBean("F6")
- F6 = 'F_InputtingBean'
- # 若 F1~F6 桶槽中, 兩個桶槽皆為 入料中, 則桶號小者優先入料
- elif FermentUp_InputtingBean_number >= 2:
- if F1 == 'F_InputtingBean':
- if (F_UP_UltraSoniclist[0] >= Ferment_Tank_bean_height):
- FInputtingBean_TO_FInputtingBeanFinish("F1")
- F1 = 'F_InputtingBean_Finish'
- elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height):
- F1_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F1"])
- F1_thread.start()
- elif FI1 != 'FI_OutputtingBean':
- FInputtingBean_TO_FInputtingBeanPause("F1")
- F1 = 'F_InputtingBean_Pause'
- elif F2 == 'F_InputtingBean':
- if (F_UP_UltraSoniclist[1] >= Ferment_Tank_bean_height):
- FInputtingBean_TO_FInputtingBeanFinish("F2")
- F2 = 'F_InputtingBean_Finish'
- elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[1] < Ferment_Tank_bean_height):
- F2_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F2"])
- F2_thread.start()
- elif FI1 != 'FI_OutputtingBean':
- FInputtingBean_TO_FInputtingBeanPause("F2")
- F2 = 'F_InputtingBean_Pause'
- elif F3 == 'F_InputtingBean':
- if (F_UP_UltraSoniclist[2] >= Ferment_Tank_bean_height):
- FInputtingBean_TO_FInputtingBeanFinish("F3")
- F3 = 'F_InputtingBean_Finish'
- elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[2] < Ferment_Tank_bean_height):
- F3_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F3"])
- F3_thread.start()
- elif FI1 != 'FI_OutputtingBean':
- FInputtingBean_TO_FInputtingBeanPause("F3")
- F3 = 'F_InputtingBean_Pause'
- elif F4 == 'F_InputtingBean':
- if (F_UP_UltraSoniclist[3] >= Ferment_Tank_bean_height):
- FInputtingBean_TO_FInputtingBeanFinish("F4")
- F4 = 'F_InputtingBean_Finish'
- elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[3] < Ferment_Tank_bean_height):
- F4_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F4"])
- F4_thread.start()
- elif FI1 != 'FI_OutputtingBean':
- FInputtingBean_TO_FInputtingBeanPause("F4")
- F4 = 'F_InputtingBean_Pause'
- elif F5 == 'F_InputtingBean':
- if (F_UP_UltraSoniclist[4] >= Ferment_Tank_bean_height):
- FInputtingBean_TO_FInputtingBeanFinish("F5")
- F5 = 'F_InputtingBean_Finish'
- elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[4] < Ferment_Tank_bean_height):
- F5_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F5"])
- F5_thread.start()
- elif FI1 != 'FI_OutputtingBean':
- FInputtingBean_TO_FInputtingBeanPause("F5")
- F5 = 'F_InputtingBean_Pause'
- elif F6 == 'F_InputtingBean':
- if (F_UP_UltraSoniclist[5] >= Ferment_Tank_bean_height):
- FInputtingBean_TO_FInputtingBeanFinish("F6")
- F6 = 'F_InputtingBean_Finish'
- elif FI1 == 'FI_OutputtingBean' and (F_UP_UltraSoniclist[5] < Ferment_Tank_bean_height):
- F6_thread = threading.Thread(target=FInputtingBean_AND_notfilled, args=["F6"])
- F6_thread.start()
- elif FI1 != 'FI_OutputtingBean':
- FInputtingBean_TO_FInputtingBeanPause("F6")
- F6 = 'F_InputtingBean_Pause'
- # 若 F1~F6 桶槽中, 兩個桶槽皆為 入料暫停中, 則桶號小者優先入料
- elif FermentUp_InputtingBeanPause_number >= 2 and FI1 == 'FI_OutputtingBean':
- # 若 F1 桶槽為入豆暫停 且 FI1 可出料
- if F1 == 'F_InputtingBean_Pause':
- FInputtingBeanPause_AND_FIOutputtingBean("F1")
- F1 = 'F_InputtingBean'
- elif F2 == 'F_InputtingBean_Pause':
- FInputtingBeanPause_AND_FIOutputtingBean("F2")
- F2 = 'F_InputtingBean'
- elif F3 == 'F_InputtingBean_Pause':
- FInputtingBeanPause_AND_FIOutputtingBean("F3")
- F3 = 'F_InputtingBean'
- elif F4 == 'F_InputtingBean_Pause':
- FInputtingBeanPause_AND_FIOutputtingBean("F4")
- F4 = 'F_InputtingBean'
- elif F5 == 'F_InputtingBean_Pause':
- FInputtingBeanPause_AND_FIOutputtingBean("F5")
- F5 = 'F_InputtingBean'
- elif F6 == 'F_InputtingBean_Pause':
- FInputtingBeanPause_AND_FIOutputtingBean("F6")
- F6 = 'F_InputtingBean'
- # 若 F1~F6 桶槽中 無桶槽正在入料或入料等待, 且 FI1 可出豆時
- elif FermentUp_InputtingBean_number == 0 and FermentUp_InputtingBeanPause_number == 0 and FI1 == 'FI_OutputtingBean' and FermentUp_Waiting_number >= 1:
- if F1 == 'F_Waiting':
- FWaiting_TO_FInputtingBean("F1")
- F1 = 'F_InputtingBean'
- elif F2 == 'F_Waiting':
- FWaiting_TO_FInputtingBean("F2")
- F2 = 'F_InputtingBean'
- elif F3 == 'F_Waiting':
- FWaiting_TO_FInputtingBean("F3")
- F3 = 'F_InputtingBean'
- elif F4 == 'F_Waiting':
- FWaiting_TO_FInputtingBean("F4")
- F4 = 'F_InputtingBean'
- elif F5 == 'F_Waiting':
- FWaiting_TO_FInputtingBean("F5")
- F5 = 'F_InputtingBean'
- elif F6 == 'F_Waiting':
- FWaiting_TO_FInputtingBean("F6")
- F6 = 'F_InputtingBean'
- # 若 F1~F6 桶槽中 無桶槽正在入水, 則入豆完成者轉換狀態 開始入水
- if FermentUp_InputtingWater_number == 0 and FermentUp_InputtingBeanFinish_number >= 1:
- if F1 == 'F_InputtingBean_Finish':
- F1 = 'F_InputtingWater'
- FInputtingBeanFinish_TO_FInputtingWater_UP("F1", 0)
- elif F2 == 'F_InputtingBean_Finish':
- F2 = 'F_InputtingWater'
- FInputtingBeanFinish_TO_FInputtingWater_UP("F2", 1)
- elif F3 == 'F_InputtingBean_Finish':
- F3 = 'F_InputtingWater'
- FInputtingBeanFinish_TO_FInputtingWater_UP("F3", 2)
- elif F4 == 'F_InputtingBean_Finish':
- F4 = 'F_InputtingWater'
- FInputtingBeanFinish_TO_FInputtingWater_UP("F4", 3)
- elif F5 == 'F_InputtingBean_Finish':
- F5 = 'F_InputtingWater'
- FInputtingBeanFinish_TO_FInputtingWater_UP("F5", 4)
- elif F6 == 'F_InputtingBean_Finish':
- F6 = 'F_InputtingWater'
- FInputtingBeanFinish_TO_FInputtingWater_UP("F6", 5)
- # 若 F1~F6 桶槽中 無桶槽正在入水, 則入豆完成者轉換狀態 開始入水
- if FermentUp_InputtingWater_number == 1:
- if F1 == 'F_InputtingWater':
- if (F_UP_tank_WaterLevel[0] == 1) and (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height):
- F1 = 'F_Fermenting'
- F1_thread = threading.Thread(target=FInputtingWater_TO_FFermenting, args=["F1"])
- F1_thread.start()
- elif (F_UP_tank_WaterLevel[0] == 1):
- FInputtingWater_AND_WaterLevel1("F1")
- elif (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height):
- FInputtingWater_AND_tankwaterfilled("F1")
- elif F2 == 'F_InputtingWater':
- if (F_UP_tank_WaterLevel[1] == 1) and (F_UP_UltraSoniclist[1] >= Ferment_Tank_water_height):
- F2 = 'F_Fermenting'
- F2_thread = threading.Thread(target=FInputtingWater_TO_FFermenting, args=["F2"])
- F2_thread.start()
- elif (F_UP_tank_WaterLevel[1] == 1):
- FInputtingWater_AND_WaterLevel1("F2")
- elif (F_UP_UltraSoniclist[1] >= Ferment_Tank_water_height):
- FInputtingWater_AND_tankwaterfilled("F2")
- elif F3 == 'F_InputtingWater':
- if (F_UP_tank_WaterLevel[2] == 1) and (F_UP_UltraSoniclist[2] >= Ferment_Tank_water_height):
- F3 = 'F_Fermenting'
- F3_thread = threading.Thread(target=FInputtingWater_TO_FFermenting, args=["F3"])
- F3_thread.start()
- elif (F_UP_tank_WaterLevel[2] == 1):
- FInputtingWater_AND_WaterLevel1("F3")
- elif (F_UP_UltraSoniclist[2] >= Ferment_Tank_water_height):
- FInputtingWater_AND_tankwaterfilled("F3")
- elif F4 == 'F_InputtingWater':
- if (F_UP_tank_WaterLevel[3] == 1) and (F_UP_UltraSoniclist[3] >= Ferment_Tank_water_height):
- F4 = 'F_Fermenting'
- F4_thread = threading.Thread(target=FInputtingWater_TO_FFermenting, args=["F4"])
- F4_thread.start()
- elif (F_UP_tank_WaterLevel[3] == 1):
- FInputtingWater_AND_WaterLevel1("F4")
- elif (F_UP_UltraSoniclist[3] >= Ferment_Tank_water_height):
- FInputtingWater_AND_tankwaterfilled("F4")
- elif F5 == 'F_InputtingWater':
- if (F_UP_tank_WaterLevel[4] == 1) and (F_UP_UltraSoniclist[4] >= Ferment_Tank_water_height):
- F5 = 'F_Fermenting'
- F5_thread = threading.Thread(target=FInputtingWater_TO_FFermenting, args=["F5"])
- F5_thread.start()
- elif (F_UP_tank_WaterLevel[0] == 1):
- FInputtingWater_AND_WaterLevel1("F5")
- elif (F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height):
- FInputtingWater_AND_tankwaterfilled("F5")
- elif F6 == 'F_InputtingWater':
- if (F_UP_tank_WaterLevel[5] == 1) and (F_UP_UltraSoniclist[5] >= Ferment_Tank_water_height):
- F6 = 'F_Fermenting'
- F6_thread = threading.Thread(target=FInputtingWater_TO_FFermenting, args=["F6"])
- F6_thread.start()
- elif (F_UP_tank_WaterLevel[5] == 1):
- FInputtingWater_AND_WaterLevel1("F6")
- elif (F_UP_UltraSoniclist[5] >= Ferment_Tank_water_height):
- FInputtingWater_AND_tankwaterfilled("F6")
- else:
- print("else ---------------------------- ")
- 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:
- F1_thread = threading.Thread(target=FFermenting_TO_FOutputtingBean, args=["F1"])
- F1_thread.start()
- F1 = 'F_OutputtingBean'
- # 將可出豆桶槽賦值
- if FOutputtingBean_Tank == '': FOutputtingBean_Tank = 'F1'
- if F2 == 'F_Fermenting':
- F2_thread = threading.Thread(target=FFermenting_TO_FOutputtingBean, args=["F2"])
- F2_thread.start()
- F2 = 'F_OutputtingBean'
- if FOutputtingBean_Tank == '': FOutputtingBean_Tank = 'F2'
- if F3 == 'F_Fermenting':
- F3_thread = threading.Thread(target=FFermenting_TO_FOutputtingBean, args=["F3"])
- F3_thread.start()
- F3 = 'F_OutputtingBean'
- if FOutputtingBean_Tank == '': FOutputtingBean_Tank = 'F3'
- if F4 == 'F_Fermenting':
- F4_thread = threading.Thread(target=FFermenting_TO_FOutputtingBean, args=["F4"])
- F4_thread.start()
- F4 = 'F_OutputtingBean'
- if FOutputtingBean_Tank == '': FOutputtingBean_Tank = 'F4'
- if F5 == 'F_Fermenting':
- F5_thread = threading.Thread(target=FFermenting_TO_FOutputtingBean, args=["F5"])
- F5_thread.start()
- F5 = 'F_OutputtingBean'
- if FOutputtingBean_Tank == '': FOutputtingBean_Tank = 'F5'
- if F6 == 'F_Fermenting':
- F6_thread = threading.Thread(target=FFermenting_TO_FOutputtingBean, args=["F6"])
- F6_thread.start()
- F6 = 'F_OutputtingBean'
- if FOutputtingBean_Tank == '': FOutputtingBean_Tank = 'F6'
-
- # 若桶槽 F1~F6 可出豆 且 桶槽內為空桶 且 有指定清洗排程, 進行清洗桶槽
- # TODO 發酵次數計算、消毒次數、校正
- if F1 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[0] <= Ferment_Tank_bean_empty):
- if FOutputtingBean_Tank == 'F1':
- FOutputtingBean_TO_FWaiting('F1')
- FOutputtingBean_Tank = ''
- if (FermentAuto_cleaning == 0): F1 = 'F_Waiting'
- elif (FermentAuto_cleaning != 0): F1 = 'F_Cleaning'
- if F2 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[1] <= Ferment_Tank_bean_empty):
- if FOutputtingBean_Tank == 'F2':
- FOutputtingBean_TO_FWaiting('F2')
- FOutputtingBean_Tank = ''
- if (FermentAuto_cleaning == 0): F2 = 'F_Waiting'
- elif (FermentAuto_cleaning != 0): F2 = 'F_Cleaning'
- if F3 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[2] <= Ferment_Tank_bean_empty):
- if FOutputtingBean_Tank == 'F3':
- FOutputtingBean_TO_FWaiting('F3')
- FOutputtingBean_Tank = ''
- if (FermentAuto_cleaning == 0): F3 = 'F_Waiting'
- elif (FermentAuto_cleaning != 0): F3 = 'F_Cleaning'
- if F4 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[3] <= Ferment_Tank_bean_empty):
- if FOutputtingBean_Tank == 'F4':
- FOutputtingBean_TO_FWaiting('F4')
- FOutputtingBean_Tank = ''
- if (FermentAuto_cleaning == 0): F4 = 'F_Waiting'
- elif (FermentAuto_cleaning != 0): F4 = 'F_Cleaning'
- if F5 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[4] <= Ferment_Tank_bean_empty):
- if FOutputtingBean_Tank == 'F5':
- FOutputtingBean_TO_FWaiting('F5')
- FOutputtingBean_Tank = ''
- if (FermentAuto_cleaning == 0): F5 = 'F_Waiting'
- elif (FermentAuto_cleaning != 0): F5 = 'F_Cleaning'
- if F6 == 'F_OutputtingBean' and (F_UP_UltraSoniclist[5] <= Ferment_Tank_bean_empty):
- if FOutputtingBean_Tank == 'F6':
- FOutputtingBean_TO_FWaiting('F6')
- FOutputtingBean_Tank = ''
- if (FermentAuto_cleaning == 0): F6 = 'F_Waiting'
- elif (FermentAuto_cleaning != 0): F6 = 'F_Cleaning'
- # 避免桶槽可出豆時未賦值
- if FOutputtingBean_Tank == '':
- if F1 == 'F_OutputtingBean': FOutputtingBean_Tank = 'F1'
- elif F2 == 'F_OutputtingBean': FOutputtingBean_Tank = 'F2'
- elif F3 == 'F_OutputtingBean': FOutputtingBean_Tank = 'F3'
- elif F4 == 'F_OutputtingBean': FOutputtingBean_Tank = 'F4'
- elif F5 == 'F_OutputtingBean': FOutputtingBean_Tank = 'F5'
- elif F6 == 'F_OutputtingBean': FOutputtingBean_Tank = 'F6'
-
- # 若桶槽 F1~F6 為清洗中
- if F1 == 'F_Cleaning':
- F1_thread = threading.Thread(target=FCleaning, args=["F1"])
- F1_thread.start()
- F1 = 'F_Waiting'
- if F2 == 'F_Cleaning':
- F2_thread = threading.Thread(target=FCleaning, args=["F2"])
- F2_thread.start()
- F2 = 'F_Waiting'
- if F3 == 'F_Cleaning':
- F3_thread = threading.Thread(target=FCleaning, args=["F3"])
- F3_thread.start()
- F3 = 'F_Waiting'
- if F4 == 'F_Cleaning':
- F4_thread = threading.Thread(target=FCleaning, args=["F4"])
- F4_thread.start()
- F4 = 'F_Waiting'
- if F5 == 'F_Cleaning':
- F5_thread = threading.Thread(target=FCleaning, args=["F5"])
- F5_thread.start()
- F5 = 'F_Waiting'
- if F6 == 'F_Cleaning':
- F6_thread = threading.Thread(target=FCleaning, args=["F6"])
- F6_thread.start()
- F6 = 'F_Waiting'
-
- # # ----- [測試用] !!!!! F1~F6 入料完成→可出豆 判斷 ------------------------------
- # if F1 == 'F_InputtingBean_Finish': F1 = 'F_OutputtingBean'
- # if F2 == 'F_InputtingBean_Finish': F2 = 'F_OutputtingBean'
- # if F3 == 'F_InputtingBean_Finish': F3 = 'F_OutputtingBean'
- # if F4 == 'F_InputtingBean_Finish': F4 = 'F_OutputtingBean'
- # if F5 == 'F_InputtingBean_Finish': F5 = 'F_OutputtingBean'
- # if F6 == 'F_InputtingBean_Finish': F6 = 'F_OutputtingBean'
- # # ----- [測試用] !!!!! F1~F6 入料完成→可出豆 判斷 ------------------------------
- else:
- # [介面] 若未啟用 發酵 狀態
- print('未啟用發酵流程')
- # ----- 發酵出料儲豆槽 FO1~FO2 入豆→可出豆判斷 ------------------------------
- # 目前發酵槽 F1~F6 正在入豆、入水的桶槽數量 (應小於一桶)
- # Ferment_OutputtingBean_number = int(F_UP_tanklist.count('F_OutputtingBean'))
- # 若出料儲豆槽狀態為 空桶等待 且 桶槽狀態為 F_OutputtingBean 可出豆, 與 FO1 配合開始出豆
-
- if FO1 == 'FO_Waiting' and FOutputtingBean_Tank != '':
- # 判斷要對應出料的桶槽為何, 設定成 FOutputtingBean_Tank = 'F1', 待出完料再把 FOutputtingBean_Tank = ''
- FO1 = 'FO_InputtingBean'
- print('------- ' + FOutputtingBean_Tank + ' 狀態更新:出豆中 -------')
- print('------- FO1 狀態更新:入豆中 -------')
- # [致動器] F1 蝴蝶閥 ON
- data = { "tank_num": FOutputtingBean_Tank, "command": "tank_diskvalve_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- elif FO1 == 'FO_InputtingBean' and FOutputtingBean_Tank != '':
- if FO_UP_UltraSoniclist[0] >= Ferment_Output_bean_height:
- # [致動器] 出料真空吸料機 OFF
- data = { "tank_num": FOutputtingBean_Tank, "command": "input_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] F1 蝴蝶閥 OFF
- data = { "tank_num": FOutputtingBean_Tank, "command": "tank_diskvalve_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- FO1 = 'FO_OutputtingBean'
- print('------- FO1 狀態更新:出豆中 -------')
- elif FO_UP_UltraSoniclist[0] < Ferment_Output_bean_height:
- FO1_thread = threading.Thread(target=FOInputtingBean_filled, args=["FO1"])
- FO1_thread.start()
- # 若是無桶槽可入豆, 出料儲豆槽判斷是否可出豆或空桶等待入豆
- elif FOutputtingBean_Tank == '':
- if FO_UP_UltraSoniclist[0] > Ferment_Output_bean_empty:
- FO1 = 'FO_OutputtingBean'
- print('------- FO1 狀態更新:可出豆 -------')
- elif FO_UP_UltraSoniclist[0] <= Ferment_Output_bean_empty:
- FO1 = 'FO_Waiting'
- print('------- FO1 狀態更新:空桶等待 -------')
- elif FO1 == 'FO_OutputtingBean' and FO_UP_UltraSoniclist[0] <= Ferment_Output_bean_empty:
- FO1 = 'FO_Waiting'
- print('------- FO1 狀態更新:空桶等待 -------')
- # ----- 等待 thread 多執行緒執行完成 --------
- # 若 FI1_thread 有被定義, 則執行 FI1_thread.join() 等待執行完成 (當入料儲豆槽入料時)
- # 若 FI1_thread 有被定義, 會出現 UnboundLocalError: local variable 'FO1_thread' referenced before assignment 錯誤訊息
- # (非入料儲豆槽入料時) 此時就不進行任何處理
- try:
- FI1_thread.join()
- print("-- FI1_thread complete! --")
- except UnboundLocalError:
- pass
- try:
- F1_thread.join()
- print("-- F1_thread complete! --")
- except UnboundLocalError:
- pass
- try:
- F2_thread.join()
- print("-- F2_thread complete! --")
- except UnboundLocalError:
- pass
- try:
- F3_thread.join()
- print("-- F3_thread complete! --")
- except UnboundLocalError:
- pass
- try:
- F4_thread.join()
- print("-- F4_thread complete! --")
- except UnboundLocalError:
- pass
- try:
- F5_thread.join()
- print("-- F5_thread complete! --")
- except UnboundLocalError:
- pass
- try:
- F6_thread.join()
- print("-- F6_thread complete! --")
- except UnboundLocalError:
- pass
- try:
- FO1_thread.join()
- print("-- FO1_thread complete! --")
- except UnboundLocalError:
- pass
- # ----- 將狀態寫入資料庫 ------------------------------
- # 獲取文本框的值並賦值給user實體對象
- F_status = ferment_container_status()
- F_status.Ferment_Input_1 = FI1
- F_status.Ferment_Input_2 = FI2
- F_status.Ferment_Tank_1 = F1
- F_status.Ferment_Tank_2 = F2
- F_status.Ferment_Tank_3 = F3
- F_status.Ferment_Tank_4 = F4
- F_status.Ferment_Tank_5 = F5
- F_status.Ferment_Tank_6 = F6
- F_status.Ferment_Tank_7 = F7
- F_status.Ferment_Tank_8 = F8
- F_status.Ferment_Tank_9 = F9
- F_status.Ferment_Tank_10 = F10
- F_status.Ferment_Tank_11 = F11
- F_status.Ferment_Tank_12 = F12
- F_status.Ferment_Output_1 = FO1
- F_status.Ferment_Output_2 = FO2
- #將數據保存進資料庫
- db.session.add(F_status)
- # 手動提交
- db.session.commit()
- # ----- 將狀態寫入資料庫 ------------------------------
- return jsonify({"Peel_Output_1":PO1,
- "Ferment_Input_1":FI1,
- "Ferment_Tank_1":F1,
- "Ferment_Tank_2":F2,
- "Ferment_Tank_3":F3,
- "Ferment_Tank_4":F4,
- "Ferment_Tank_5":F5,
- "Ferment_Tank_6":F6,
- "Ferment_Output_1":FO1
- })
- # 1026 以流程圖判斷, 改寫 def ferment_auto_test, 以下為原備份
- @main.route('/ferment_auto_test_1026backup')
- def ferment_auto_test_1026backup():
- info = request.args.to_dict()
- # 從介面取得 指定生豆高度/發酵桶槽排程:發酵、清洗、校正 EC、校正攪拌棒
- Ferment_Input_bean_empty = 2
- Ferment_Tank_bean_empty = 2
- Ferment_Output_bean_empty = 2
- FermentAuto_fermenting = int(info['FermentAuto_fermenting'])
- FermentAuto_cleaning = int(info['FermentAuto_cleaning'])
- FermentAuto_calibratingEC = int(info['FermentAuto_calibratingEC'])
- FermentAuto_calibratingSTIR = int(info['FermentAuto_calibratingSTIR'])
- Ferment_Input_bean_height = float(info['Ferment_Input_bean_height'])
- Ferment_Input_vacuumON_time = float(info['Ferment_Input_vacuumON_time'])
- Ferment_Input_vacuumOFF_time = float(info['Ferment_Input_vacuumOFF_time'])
- Ferment_Tank_bean_height = float(info['Ferment_Tank_bean_height'])
- Ferment_Tank_vacuumON_time = float(info['Ferment_Tank_vacuumON_time'])
- Ferment_Tank_vacuumOFF_time = float(info['Ferment_Tank_vacuumOFF_time'])
- Ferment_Tank_water_height = float(info['Ferment_Tank_water_height'])
- Ferment_Tank_fermenting_temp = float(info['Ferment_Tank_fermenting_temp'])
- Ferment_Tank_fermenting_time = float(info['Ferment_Tank_fermenting_time'])
- Ferment_Tank_motor_rpm = float(info['Ferment_Tank_motor_rpm'])
- Ferment_Tank_motor_time = float(info['Ferment_Tank_motor_time'])
- Ferment_Tank_fermenting_pH = float(info['Ferment_Tank_fermenting_pH'])
- Ferment_Output_bean_height = float(info['Ferment_Output_bean_height'])
- Ferment_Output_vacuumON_time = float(info['Ferment_Output_vacuumON_time'])
- Ferment_Output_vacuumOFF_time = float(info['Ferment_Output_vacuumOFF_time'])
- Ferment_Tank_WaterOut_time = float(info['Ferment_Tank_WaterOut_time'])
- Ferment_Tank_Disinfect_time = float(info['Ferment_Tank_Disinfect_time'])
- # print('發酵自動化_指定生豆高度: ', Ferment_Tank_bean_height)
- # print('發酵自動化_發酵排程: ', FermentAuto_fermenting, type(FermentAuto_fermenting))
- # print('發酵自動化_清洗排程: ', FermentAuto_cleaning, type(FermentAuto_cleaning))
- # print('發酵自動化_校正 EC 排程: ', FermentAuto_calibratingEC, type(FermentAuto_calibratingEC))
- # print('發酵自動化_校正攪拌棒排程: ', FermentAuto_calibratingSTIR, type(FermentAuto_calibratingSTIR))
- # [介面] 讓使用者可以選擇排程內有發酵/清洗/校正, 此處預設為 True
- Ferment_btn = FermentAuto_fermenting # Ferment_btn = True
- # 從資料庫資料表中取得最新狀態
- ferment_status = ferment_container_status.query.order_by(text('datetime desc')).first()
- FI1 = ferment_status.Ferment_Input_1
- FI2 = ferment_status.Ferment_Input_2
- F1 = ferment_status.Ferment_Tank_1
- F2 = ferment_status.Ferment_Tank_2
- F3 = ferment_status.Ferment_Tank_3
- F4 = ferment_status.Ferment_Tank_4
- F5 = ferment_status.Ferment_Tank_5
- F6 = ferment_status.Ferment_Tank_6
- F7 = ferment_status.Ferment_Tank_7
- F8 = ferment_status.Ferment_Tank_8
- F9 = ferment_status.Ferment_Tank_9
- F10 = ferment_status.Ferment_Tank_10
- F11 = ferment_status.Ferment_Tank_11
- F12 = ferment_status.Ferment_Tank_12
- FO1 = ferment_status.Ferment_Output_1
- FO2 = ferment_status.Ferment_Output_2
- clean_status = clean_container_status.query.order_by(text('datetime desc')).first()
- PO1 = clean_status.Peel_Output_1 # PO_Waiting # PO_OutputtingBean
- PO2 = clean_status.Peel_Output_2
- F_UP_tanklist = [F1, F2, F3, F4, F5, F6]
- F_DOWN_tanklist = [F7, F8, F9, F10, F11, F12]
- # ----- 發酵入料儲豆槽 FI1~FI2 入豆→可出豆判斷 ------------------------------
- # 目前發酵槽 F1~F6 正在入豆的桶槽數量 (應小於一桶)
- FermentUp_InputtingBean_number = int(F_UP_tanklist.count('F_InputtingBean'))
- FermentUp_InputtingBeanPause_number = int(F_UP_tanklist.count('F_InputtingBean_Pause'))
- # -- 取得發酵入料儲豆槽 FI1~FI2 桶內高度 UltraSonic -------------
- FI_UP_UltraSoniclist = []
- for i in range(1, 3, 1):
- input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
- # UltraSonic = float("{:.2f}".format(34.6 - float(input_UltraSonic.UltraSonic)))
- UltraSonic = float(input_UltraSonic.UltraSonic)
- FI_UP_UltraSoniclist.append(UltraSonic)
- print('FI_UP_UltraSoniclist: ', FI_UP_UltraSoniclist)
- # -- 取得發酵入料儲豆槽 FI1~FI2 桶內高度 UltraSonic -------------
- # 入料儲豆槽等待中、且脫皮機儲豆槽可出豆時, 入料儲豆槽入豆
- if FI1 == 'FI_Waiting' and PO1 == 'PO_OutputtingBean':
- FI1 = 'FI_InputtingBean'
- print('------- FI1 狀態更新:入豆中 -------')
- # [致動器] 入料真空吸料機 ON
- data = { "tank_num": "F1", "command": "input_vacuum_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- while True:
- if (time.time() - timer) > Ferment_Input_vacuumON_time:
- # [致動器] 入料真空吸料機 OFF
- data = { "tank_num": "F1", "command": "input_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- break
- while True:
- if (time.time() - timer) > Ferment_Input_vacuumOFF_time:
- break
- # 入料儲豆槽入豆時
- elif FI1 == 'FI_InputtingBean':
- # 桶槽內未達指定生豆高度, 且 前方 PO1 可出豆, 就執行入料動作
- if (FI_UP_UltraSoniclist[0] < Ferment_Input_bean_height) and PO1 == 'PO_OutputtingBean':
- # [致動器] 入料真空吸料機 ON
- data = { "tank_num": "F1", "command": "input_vacuum_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- while True:
- if (time.time() - timer) > Ferment_Input_vacuumON_time:
- # [致動器] 入料真空吸料機 OFF
- data = { "tank_num": "F1", "command": "input_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- break
- while True:
- if (time.time() - timer) > Ferment_Input_vacuumOFF_time:
- break
- # 桶槽內達指定生豆高度時, 入料儲豆槽狀態轉為 可出豆
- if (FI_UP_UltraSoniclist[0] >= Ferment_Input_bean_height):
- FI1 = 'FI_OutputtingBean'
- print('------- FI1 狀態更新:可出豆 -------')
-
- # 入料儲豆槽出豆時, 桶槽高度為 空桶高度時, 狀態轉為 空桶等待
- elif FI1 == 'FI_OutputtingBean' and (FI_UP_UltraSoniclist[0] <= Ferment_Input_bean_empty):
- FI1 = 'FI_Waiting'
- print('------- FI1 狀態更新:空桶等待 -------')
- # [1012 刪除, 避免混豆]若入料儲豆槽可出豆 且 儲豆槽內高度低於 40 且 前方脫皮機儲豆槽可出豆 且 目前無桶槽需入料時
- # elif FI1 == 'FI_OutputtingBean' and (FI_UP_UltraSoniclist[0] < 40) and PO1 == 'PO_OutputtingBean' and FermentUp_InputtingBean_number == 0 and FermentUp_InputtingBeanPause_number == 0:
- # FI1 = 'FI_InputtingBean'
- # print('------- FI1 狀態更新:入豆中 -------')
-
- # if FI2 == 'FI_Waiting' and PO2 == 'PO_OutputtingBean':
- # FI2 = 'FI_InputtingBean'
- # print('------- FI2 狀態更新:入豆中 -------')
- # elif FI2 == 'FI_InputtingBean' and ((FI_UP_UltraSoniclist[1] >= 35) or (PO2 != 'PO_OutputtingBean')) :
- # FI2 = 'FI_OutputtingBean'
- # print('------- FI2 狀態更新:可出豆 -------')
- # elif FI2 == 'FI_OutputtingBean' and (FI_UP_UltraSoniclist[1] < 40) and PO2 == 'PO_OutputtingBean' and FermentUp_InputtingBean_number == 0 and FermentUp_InputtingBeanPause_number == 0:
- # FI2 = 'FI_InputtingBean'
- # print('------- FI2 狀態更新:入豆中 -------')
-
- # ----- 發酵桶槽 F1~F6 入料暫停→入料判斷 ------------------------------
- ### 移到入料
- # ----- 發酵桶槽 F1~F6 等待→入料判斷 ------------------------------
- # -- 取得發酵桶槽 F1~F6 桶內高度 UltraSonic -------------
- F_UP_UltraSoniclist = []
- for i in range(1, 7, 1):
- tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
- UltraSonic = (float(tank_UltraSonic.UltraSonic))
- F_UP_UltraSoniclist.append(UltraSonic)
- print('F_UP_UltraSoniclist: ', F_UP_UltraSoniclist)
- # -- 取得發酵桶槽 F1~F6 桶內高度 UltraSonic -------------
- # [介面] 若啟用 發酵 狀態
- if Ferment_btn:
- # 若入料儲豆槽可出料狀態
- if FI1 == 'FI_OutputtingBean':
- # 若 F1~F6 發酵桶槽為 入豆中, 繼續入豆, 當高度 > 指定生豆高度 時入豆完成
- if F1 == 'F_InputtingBean':
- if (F_UP_UltraSoniclist[0] >= Ferment_Tank_bean_height):
- F1 = 'F_InputtingBean_Finish'
- print('------- F1 狀態更新:入料完成 -------')
- # [致動器] 入料三通閥 ON排氣
- data = { "tank_num": "F1", "command": "tank_threewayvalve_input_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 0
- data = { "tank_num": "F1", "command": "tank_motor_status", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 真空吸料機 OFF
- data = { "tank_num": "F1", "command": "tank_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- else:
- # [致動器] 真空吸料機 ON
- data = { "tank_num": "F1", "command": "tank_vacuum_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- while True:
- if (time.time() - timer) > Ferment_Tank_vacuumON_time:
- # [致動器] 入料真空吸料機 OFF
- data = { "tank_num": "F1", "command": "tank_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- break
- while True:
- if (time.time() - timer) > Ferment_Tank_vacuumOFF_time:
- break
- if F2 == 'F_InputtingBean' and (F_UP_UltraSoniclist[1] >= Ferment_Tank_bean_height):
- F2 = 'F_InputtingBean_Finish'
- print('------- F2 狀態更新:入料完成 -------')
- if F3 == 'F_InputtingBean' and (F_UP_UltraSoniclist[2] >= Ferment_Tank_bean_height):
- F3 = 'F_InputtingBean_Finish'
- print('------- F3 狀態更新:入料完成 -------')
- if F4 == 'F_InputtingBean' and (F_UP_UltraSoniclist[3] >= Ferment_Tank_bean_height):
- F4 = 'F_InputtingBean_Finish'
- print('------- F4 狀態更新:入料完成 -------')
- if F5 == 'F_InputtingBean' and (F_UP_UltraSoniclist[4] >= Ferment_Tank_bean_height):
- F5 = 'F_InputtingBean_Finish'
- print('------- F5 狀態更新:入料完成 -------')
- if F6 == 'F_InputtingBean' and (F_UP_UltraSoniclist[5] >= Ferment_Tank_bean_height):
- F6 = 'F_InputtingBean_Finish'
- print('------- F6 狀態更新:入料完成 -------')
- # 若有兩個以上桶槽入料中, 則桶號最小者優先入料 ←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←← 1021 優先入豆判斷
- if FermentUp_InputtingBean_number == 1:
- if F1 == 'F_InputtingBean':
- # [致動器] 桶槽真空吸料機 ON
- data = { "tank_num": "F1", "command": "tank_vacuum_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- while True:
- if (time.time() - timer) > Ferment_Tank_vacuumON_time:
- # [致動器] 桶槽真空吸料機 OFF
- data = { "tank_num": "F1", "command": "tank_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- break
- while True:
- if (time.time() - timer) > Ferment_Tank_vacuumOFF_time:
- break
- # else if F2 == ''...
- # 若 F1~F6 發酵桶槽為 入豆暫停, 則狀態改為優先入豆 ←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←← 1021 優先入豆判斷
- elif FermentUp_InputtingBeanPause_number >= 1:
- if F1 == 'F_InputtingBean_Pause':
- F1 = 'F_InputtingBean'
- print('------- F1 狀態更新:入料中 -------')
- # [致動器] 桶槽真空吸料機 ON
- data = { "tank_num": "F1", "command": "tank_vacuum_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- while True:
- if (time.time() - timer) > Ferment_Tank_vacuumON_time:
- # [致動器] 桶槽真空吸料機 OFF
- data = { "tank_num": "F1", "command": "tank_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- break
- while True:
- if (time.time() - timer) > Ferment_Tank_vacuumOFF_time:
- break
- elif F2 == 'F_InputtingBean_Pause':
- F2 = 'F_InputtingBean'
- print('------- F2 狀態更新:入料中 -------')
- elif F3 == 'F_InputtingBean_Pause':
- F3 = 'F_InputtingBean'
- print('------- F3 狀態更新:入料中 -------')
- elif F4 == 'F_InputtingBean_Pause':
- F4 = 'F_InputtingBean'
- print('------- F4 狀態更新:入料中 -------')
- elif F5 == 'F_InputtingBean_Pause':
- F5 = 'F_InputtingBean'
- print('------- F5 狀態更新:入料中 -------')
- elif F6 == 'F_InputtingBean_Pause':
- F6 = 'F_InputtingBean'
- print('------- F6 狀態更新:入料中 -------')
- # 若 F1~F6 皆無入豆 無入豆暫停, 則桶號最小者開始入豆
- elif FermentUp_InputtingBean_number == 0 and FermentUp_InputtingBeanPause_number == 0:
- if F1 == 'F_Waiting':
- F1 = 'F_InputtingBean'
- print('------- F1 狀態更新:入料中 -------')
- # [致動器] 入料入料三通閥 OFF入豆
- data = { "tank_num": "F1", "command": "tank_threewayvalve_input_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 5
- data = { "tank_num": "F1", "command": "tank_motor_status", "value": "5" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 桶槽真空吸料機 ON
- data = { "tank_num": "F1", "command": "tank_vacuum_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- while True:
- if (time.time() - timer) > Ferment_Tank_vacuumON_time:
- # [致動器] 桶槽真空吸料機 OFF
- data = { "tank_num": "F1", "command": "tank_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- break
- while True:
- if (time.time() - timer) > Ferment_Tank_vacuumON_time:
- break
- elif F2 == 'F_Waiting':
- F2 = 'F_InputtingBean'
- print('------- F2 狀態更新:入料中 -------')
- elif F3 == 'F_Waiting':
- F3 = 'F_InputtingBean'
- print('------- F3 狀態更新:入料中 -------')
- elif F4 == 'F_Waiting':
- F4 = 'F_InputtingBean'
- print('------- F4 狀態更新:入料中 -------')
- elif F5 == 'F_Waiting':
- F5 = 'F_InputtingBean'
- print('------- F5 狀態更新:入料中 -------')
- elif F6 == 'F_Waiting':
- F6 = 'F_InputtingBean'
- print('------- F6 狀態更新:入料中 -------')
- # 若入料儲豆槽非可出豆, 且 F1~F6 其中有桶槽入料中, 若桶槽未滿則入料暫停
- elif FI1 != 'FI_InputtingBean' and FermentUp_InputtingBean_number >= 1:
- if F1 == 'F_InputtingBean' and F_UP_UltraSoniclist[0] < Ferment_Tank_bean_height:
- F1 = 'F_InputtingBean_Pause'
- print('------- F1 狀態更新:入料暫停 -------')
- # [致動器] 桶槽真空吸料機 OFF
- data = { "tank_num": "F1", "command": "tank_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- elif F1 == 'F_InputtingBean' and F_UP_UltraSoniclist[0] >= Ferment_Tank_bean_height:
- F1 = 'F_InputtingBean_Finish'
- print('------- F1 狀態更新:入料完成 -------')
- # [致動器] 入料三通閥 ON排氣
- data = { "tank_num": "F1", "command": "tank_threewayvalve_input_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 0
- data = { "tank_num": "F1", "command": "tank_motor_status", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 入料真空吸料機 OFF
- data = { "tank_num": "F1", "command": "input_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- if F2 == 'F_InputtingBean' and F_UP_UltraSoniclist[1] < Ferment_Tank_bean_height:
- F2 = 'F_InputtingBean_Pause'
- print('------- F2 狀態更新:入料暫停 -------')
- elif F2 == 'F_InputtingBean' and F_UP_UltraSoniclist[1] >= Ferment_Tank_bean_height:
- F2 = 'F_InputtingBean_Finish'
- print('------- F2 狀態更新:入料完成 -------')
- if F3 == 'F_InputtingBean' and F_UP_UltraSoniclist[2] < Ferment_Tank_bean_height:
- F3 = 'F_InputtingBean_Pause'
- print('------- F3 狀態更新:入料暫停 -------')
- elif F3 == 'F_InputtingBean' and F_UP_UltraSoniclist[2] >= Ferment_Tank_bean_height:
- F3 = 'F_InputtingBean_Finish'
- print('------- F3 狀態更新:入料完成 -------')
- if F4 == 'F_InputtingBean' and F_UP_UltraSoniclist[3] < Ferment_Tank_bean_height:
- F4 = 'F_InputtingBean_Pause'
- print('------- F4 狀態更新:入料暫停 -------')
- elif F4 == 'F_InputtingBean' and F_UP_UltraSoniclist[3] >= Ferment_Tank_bean_height:
- F4 = 'F_InputtingBean_Finish'
- print('------- F4 狀態更新:入料完成 -------')
- if F5 == 'F_InputtingBean' and F_UP_UltraSoniclist[4] < Ferment_Tank_bean_height:
- F5 = 'F_InputtingBean_Pause'
- print('------- F5 狀態更新:入料暫停 -------')
- elif F5 == 'F_InputtingBean' and F_UP_UltraSoniclist[4] >= Ferment_Tank_bean_height:
- F5 = 'F_InputtingBean_Finish'
- print('------- F5 狀態更新:入料完成 -------')
- if F6 == 'F_InputtingBean' and F_UP_UltraSoniclist[5] < Ferment_Tank_bean_height:
- F6 = 'F_InputtingBean_Pause'
- print('------- F6 狀態更新:入料暫停 -------')
- elif F6 == 'F_InputtingBean' and F_UP_UltraSoniclist[5] >= Ferment_Tank_bean_height:
- F6 = 'F_InputtingBean_Finish'
- print('------- F6 狀態更新:入料完成 -------')
- else:
- # 若入料儲豆槽非可出料狀態
- print('發酵入料儲豆槽空, 桶槽無法入料')
- else:
- # [介面] 若未啟用 發酵 狀態
- print('未啟用發酵流程')
- # ----- 10/07 --------------------------------------------------------------------------------------------------------------------------------
- # ----- 發酵桶槽 F1~F6 入料→入料暫停判斷 ------------------------------
- ### 移到入料
- # ----- 發酵桶槽 F1~F6 入料→入水判斷 ------------------------------
- # -- 取得發酵桶槽 F1~F6 夾層水位高度 WaterLevel -------------
- F_UP_tank_WaterLevel = []
- for i in range(1, 7, 1):
- tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
- WaterLevel = float(tank_WaterLevel.WaterLevel)
- F_UP_tank_WaterLevel.append(WaterLevel)
- print('F_UP_tank_WaterLevel: ', F_UP_tank_WaterLevel)
- # -- 取得發酵桶槽 F1~F6 夾層水位高度 WaterLevel -------------
- Ferment_InputtingBeanFinish_number = int(F_UP_tanklist.count('F_InputtingBean_Finish'))
- Ferment_InputtingWater_number = int(F_UP_tanklist.count('F_InputtingWater'))
- # 入水條件:當前桶槽入豆 + 沒有其他桶槽入水
- if Ferment_InputtingBeanFinish_number >= 1 and Ferment_InputtingWater_number == 0:
- # 當入豆到指定高度時, 狀態轉換為入水 (桶槽編號小者優先)
- # !!! 發酵槽 F_InputtingBean_Finish 狀態應該請硬體判斷
- # !!! 若狀態為 F_InputtingBean 且 超音波值>指定生豆高度, 狀態改為 F_InputtingBean_Finish 並等待入水 F_InputtingWater
- # 這邊是考慮一次僅一個桶槽入水, 多桶入水會不會速度變慢?
- if F1 == 'F_InputtingBean_Finish':
- F1 = 'F_InputtingWater'
- print('------- F1 狀態更新:入水中 -------')
- # [致動器] 外桶浮選三通閥 ON
- data = { "tank_num": "F1", "command": "outer_threewayvalve_float_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # 桶內高度若低於水位指定高度, [致動器] 桶內進水電磁閥 ON
- if F_UP_UltraSoniclist[0] < Ferment_Tank_water_height:
- data = { "tank_num": "F1", "command": "tank_solenoid_water_in_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 桶內進水電磁閥 OFF
- else:
- data = { "tank_num": "F1", "command": "tank_solenoid_water_in_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # 桶外水位高度若低於水位計高度, [致動器] 桶外進水電磁閥 ON
- if F_UP_tank_WaterLevel[0] != 1:
- data = { "tank_num": "F1", "command": "outer_solenoid_water_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 桶外進水電磁閥 OFF
- else:
- data = { "tank_num": "F1", "command": "outer_solenoid_water_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- elif F2 == 'F_InputtingBean_Finish':
- F2 = 'F_InputtingWater'
- print('------- F2 狀態更新:入水中 -------')
- elif F3 == 'F_InputtingBean_Finish':
- F3 = 'F_InputtingWater'
- print('------- F3 狀態更新:入水中 -------')
- elif F4 == 'F_InputtingBean_Finish':
- F4 = 'F_InputtingWater'
- print('------- F4 狀態更新:入水中 -------')
- elif F5 == 'F_InputtingBean_Finish':
- F5 = 'F_InputtingWater'
- print('------- F5 狀態更新:入水中 -------')
- elif F6 == 'F_InputtingBean_Finish':
- F6 = 'F_InputtingWater'
- print('------- F6 狀態更新:入水中 -------')
- # ----- 發酵桶槽 F1~F6 入水→發酵判斷 ------------------------------
- # !!! 發酵槽 F_Fermenting 狀態應該請硬體判斷
- # !!! 若狀態為 F_InputtingWater 且 超音波值>指定水位高度 且 夾層水位計 == 1, 狀態改為 F_Fermenting 發酵
- if F1 == 'F_InputtingWater':
- if F_UP_tank_WaterLevel[0] == 1 and F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height:
- # 桶外水位高度高於水位計高度, [致動器] 桶外進水電磁閥 OFF
- data = { "tank_num": "F1", "command": "outer_solenoid_water_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # 桶內高度若高於水位指定高度, [致動器] 桶內進水電磁閥 OFF
- data = { "tank_num": "F1", "command": "tank_solenoid_water_in_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- F1 = 'F_Fermenting'
- print('------- F1 狀態更新:發酵中 -------')
- # [致動器] 馬達 (指定轉速)
- data = { "tank_num": "F1", "command": "tank_motor_status", "value": Ferment_Tank_motor_rpm }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 溫控開關 ON
- # data = { "tank_num": "F1", "command": "tank_temp_enable", "value": "on" }
- # print('data: ', data)
- # # mqtt_f(data)
- # [致動器] 設定溫度、持溫時間
- # [致動器] 加熱器 1 ON
- data = { "tank_num": "F1", "command": "tank_heater1_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- elif F_UP_tank_WaterLevel[0] == 1:
- # 桶外水位高度高於水位計高度, [致動器] 桶外進水電磁閥 OFF
- data = { "tank_num": "F1", "command": "outer_solenoid_water_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- elif F_UP_UltraSoniclist[0] >= Ferment_Tank_water_height:
- # 桶內高度若高於水位指定高度, [致動器] 桶內進水電磁閥 OFF
- data = { "tank_num": "F1", "command": "tank_solenoid_water_in_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- if F2 == 'F_InputtingWater' and F_UP_tank_WaterLevel[1] == 1 and F_UP_UltraSoniclist[1] >= Ferment_Tank_water_height:
- F2 = 'F_Fermenting'
- print('------- F2 狀態更新:發酵中 -------')
- if F3 == 'F_InputtingWater' and F_UP_tank_WaterLevel[2] == 1 and F_UP_UltraSoniclist[2] >= Ferment_Tank_water_height:
- F3 = 'F_Fermenting'
- print('------- F3 狀態更新:發酵中 -------')
- if F4 == 'F_InputtingWater' and F_UP_tank_WaterLevel[3] == 1 and F_UP_UltraSoniclist[3] >= Ferment_Tank_water_height:
- F4 = 'F_Fermenting'
- print('------- F4 狀態更新:發酵中 -------')
- if F5 == 'F_InputtingWater' and F_UP_tank_WaterLevel[4] == 1 and F_UP_UltraSoniclist[4] >= Ferment_Tank_water_height:
- F5 = 'F_Fermenting'
- print('------- F5 狀態更新:發酵中 -------')
- if F6 == 'F_InputtingWater' and F_UP_tank_WaterLevel[5] == 1 and F_UP_UltraSoniclist[5] >= Ferment_Tank_water_height:
- F6 = 'F_Fermenting'
- print('------- F6 狀態更新:發酵中 -------')
-
- # ----- 發酵桶槽 F1~F6 發酵→可出豆 判斷 ------------------------------
- # TODO
- # !!! 發酵槽 F_Fermenting 狀態應該請硬體判斷
- # !!! 若狀態為 F_InputtingWater 且 超音波值>指定水位高度 且 夾層水位計 == 1, 狀態改為 F_Fermenting 發酵
- # 可以多桶各自執行發酵排程
- # -- 取得發酵桶槽 F1~F6 pH -------------
- F_UP_tank_PH = []
- for i in range(1, 7, 1):
- tank_PH = ferment_tank_PH.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
- PH = float(tank_PH.PH)
- F_UP_tank_PH.append(PH)
- print('F_UP_tank_PH: ', F_UP_tank_PH)
- # -- 取得發酵桶槽 F1~F6 pH -------------
- # -- 取得發酵桶槽 F1~F6 SHT11_TEMP -------------
- F_UP_tank_SHT11_Temp = []
- for i in range(1, 7, 1):
- tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + str(i)).order_by(text('datetime desc')).first()
- SHT11_Temp = float(tank_SHT11.SHT11_Temp)
- F_UP_tank_SHT11_Temp.append(SHT11_Temp)
- print('F_UP_tank_SHT11_Temp: ', F_UP_tank_SHT11_Temp)
- # -- 取得發酵桶槽 F1~F6 SHT11_TEMP -------------
- #
- 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:
- print('發酵等待 ', Ferment_Tank_fermenting_time, ' 秒')
- timer = time.time()
- while True:
- if (time.time() - timer) > Ferment_Tank_fermenting_time :
- # [致動器] 外桶浮選三通閥 OFF
- data = { "tank_num": "F1", "command": "outer_threewayvalve_float_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 馬達 0
- data = { "tank_num": "F1", "command": "tank_motor_status", "value": "0" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 溫控開關 OFF
- # data = { "tank_num": "F1", "command": "tank_temp_enable", "value": "off" }
- # print('data: ', data)
- # # mqtt_f(data)
- # [致動器] 加熱器 1 OFF
- data = { "tank_num": "F1", "command": "tank_heater1_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- break
- # [致動器] 廢水排水閥 (桶內) ON
- data = { "tank_num": "F1", "command": "tank_solenoid_water_out_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- print('桶內廢水排水 ', Ferment_Tank_WaterOut_time, ' 秒')
- timer = time.time()
- while True:
- if (time.time() - timer) > Ferment_Tank_WaterOut_time:
- # [致動器] 廢水排水閥 (桶內) OFF
- data = { "tank_num": "F1", "command": "tank_solenoid_water_out_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- break
- F1 = 'F_OutputtingBean'
- print('------- F1 狀態更新:可出豆 -------')
- if F2 == 'F_Fermenting' and F_UP_tank_SHT11_Temp[1] >= Ferment_Tank_fermenting_temp and F_UP_tank_PH[1] <= Ferment_Tank_fermenting_pH:
- F2 = 'F_OutputtingBean'
- print('------- F2 狀態更新:可出豆 -------')
- if F3 == 'F_Fermenting' and F_UP_tank_PH[2] <= Ferment_Tank_fermenting_pH:
- F3 = 'F_OutputtingBean'
- print('------- F3 狀態更新:可出豆 -------')
- if F4 == 'F_Fermenting' and F_UP_tank_PH[3] <= Ferment_Tank_fermenting_pH:
- F4 = 'F_OutputtingBean'
- print('------- F4 狀態更新:可出豆 -------')
- if F5 == 'F_Fermenting' and F_UP_tank_PH[4] <= Ferment_Tank_fermenting_pH:
- F5 = 'F_OutputtingBean'
- print('------- F5 狀態更新:可出豆 -------')
- if F6 == 'F_Fermenting' and F_UP_tank_PH[5] <= Ferment_Tank_fermenting_pH:
- F6 = 'F_OutputtingBean'
- print('------- F6 狀態更新:可出豆 -------')
-
- if F1 == 'F_OutputtingBean' and F_UP_UltraSoniclist[0] < Ferment_Tank_bean_empty:
- # 增加消毒電磁閥開關
- # [致動器] 消毒電磁閥 ON
- data = { "tank_num": "F1", "command": "tank_solenoid_disinfect_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # 暫停 (消毒時間) 秒
- timer = time.time()
- while True:
- if (time.time() - timer) > Ferment_Tank_Disinfect_time :
- # [致動器] 消毒電磁閥 OFF
- data = { "tank_num": "F1", "command": "tank_solenoid_disinfect_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- break
- print('------- F1 狀態更新:空桶等待 -------')
- F1 = 'F_Waiting'
- # # ----- [測試用] !!!!! F1~F6 入料完成→可出豆 判斷 ------------------------------
- # if F1 == 'F_InputtingBean_Finish': F1 = 'F_OutputtingBean'
- # if F2 == 'F_InputtingBean_Finish': F2 = 'F_OutputtingBean'
- # if F3 == 'F_InputtingBean_Finish': F3 = 'F_OutputtingBean'
- # if F4 == 'F_InputtingBean_Finish': F4 = 'F_OutputtingBean'
- # if F5 == 'F_InputtingBean_Finish': F5 = 'F_OutputtingBean'
- # if F6 == 'F_InputtingBean_Finish': F6 = 'F_OutputtingBean'
- # # ----- [測試用] !!!!! F1~F6 入料完成→可出豆 判斷 ------------------------------
- # ----- 發酵桶槽 F1~F6 可出豆→出料儲豆槽 FO1 判斷 ------------------------------
- # ----- 發酵出料儲豆槽 FO1~FO2 入豆→可出豆判斷 ------------------------------
- # -- 取得發酵出料儲豆槽 FO1~FO2 桶內高度 UltraSonic -------------
- FO_UP_UltraSoniclist = []
- for i in range(1, 3, 1):
- output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO' + str(i)).order_by(text('datetime desc')).first()
- UltraSonic = float(output_UltraSonic.UltraSonic)
- FO_UP_UltraSoniclist.append(UltraSonic)
- print('FO_UP_UltraSoniclist: ', FO_UP_UltraSoniclist)
- # 桶槽可出豆, 且出料儲豆槽等待時, 出料儲豆槽入豆
- # 參考 -- 發酵桶槽 F1~F6 可出豆→出料儲豆槽 FO1 判斷 --
- Ferment_OutputtingBean_number = int(F_UP_tanklist.count('F_OutputtingBean'))
- # !!! 若出料儲豆槽狀態為 FO_Waiting(空桶等待) 且 桶槽狀態為 F_OutputtingBean 可出豆, 與 FO1 配合開始出豆
- if FO1 == 'FO_Waiting' and Ferment_OutputtingBean_number >= 1:
- if F1 == 'F_OutputtingBean':
- FO1 = 'FO_InputtingBean'
- print('------- F1 狀態更新:出豆中 -------')
- print('------- FO1 狀態更新:入豆中 -------')
- # [致動器] 出料真空吸料機 ON
- data = { "tank_num": "F1", "command": "input_vacuum_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # 暫停 3 秒
- timer = time.time()
- while True:
- if (time.time() - timer) > 3 :
- # [致動器] 蝴蝶閥 ON
- data = { "tank_num": "F1", "command": "tank_diskvalve_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- break
- timer = time.time()
- while True:
- if (time.time() - timer) > Ferment_Output_vacuumON_time:
- # [致動器] 出料真空吸料機 OFF
- data = { "tank_num": "F1", "command": "input_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- break
- while True:
- if (time.time() - timer) > Ferment_Output_vacuumOFF_time:
- break
- elif F2 == 'F_OutputtingBean':
- FO1 = 'FO_InputtingBean'
- print('------- F2 狀態更新:出豆中 -------')
- print('------- FO1 狀態更新:入豆中 -------')
- elif F3 == 'F_OutputtingBean':
- FO1 = 'FO_InputtingBean'
- print('------- F3 狀態更新:出豆中 -------')
- print('------- FO1 狀態更新:入豆中 -------')
- elif F4 == 'F_OutputtingBean':
- FO1 = 'FO_InputtingBean'
- print('------- F4 狀態更新:出豆中 -------')
- print('------- FO1 狀態更新:入豆中 -------')
- elif F5 == 'F_OutputtingBean':
- FO1 = 'FO_InputtingBean'
- print('------- F5 狀態更新:出豆中 -------')
- print('------- FO1 狀態更新:入豆中 -------')
- elif F6 == 'F_OutputtingBean':
- FO1 = 'FO_InputtingBean'
- print('------- F6 狀態更新:出豆中 -------')
- print('------- FO1 狀態更新:入豆中 -------')
- # 出料儲豆槽入料滿時, 出料儲豆槽狀態改為可出豆 (需判斷是哪個桶槽, 好關閉蝴蝶閥)
- elif FO1 == 'FO_InputtingBean' and FO_UP_UltraSoniclist[0] >= Ferment_Output_bean_height:
- if F1 == 'F_OutputtingBean':
- FO1 = 'FO_OutputtingBean'
- print('------- FO1 狀態更新:可出豆 -------')
- # [致動器] 出料真空吸料機 OFF
- data = { "tank_num": "F1", "command": "input_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- # [致動器] 蝴蝶閥 OFF
- data = { "tank_num": "F1", "command": "tank_diskvalve_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- elif F2 == 'F_OutputtingBean':
- pass # TODO ←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←←← 1020 TODO
- # 出料儲豆槽入料時, 桶槽已空, 則桶槽回到空桶等待, 出料儲豆槽可出豆 ←←←←←←←←←←←←←←←←←←←←←←←←←← 1012 這段怪怪的
- elif FO1 == 'FO_InputtingBean' and Ferment_OutputtingBean_number == 1:
- if F1 == 'F_OutputtingBean':
- if F_UP_UltraSoniclist[0] < Ferment_Tank_bean_empty:
- FO1 = 'FO_OutputtingBean'
- print('------- FO1 狀態更新:可出豆 -------')
- # 增加消毒電磁閥開關
- # [致動器] 消毒電磁閥 ON
- data = { "tank_num": "F1", "command": "tank_solenoid_disinfect_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # 暫停 (消毒時間) 秒
- timer = time.time()
- while True:
- if (time.time() - timer) > Ferment_Tank_Disinfect_time :
- # [致動器] 消毒電磁閥 OFF
- data = { "tank_num": "F1", "command": "tank_solenoid_disinfect_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- break
- print('------- F1 狀態更新:空桶等待 -------')
- F1 = 'F_Waiting'
- else:
- # [致動器] 出料真空吸料機 ON
- data = { "tank_num": "F1", "command": "input_vacuum_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- # 暫停 3 秒
- timer = time.time()
- while True:
- if (time.time() - timer) > 3 :
- # [致動器] 蝴蝶閥 ON
- data = { "tank_num": "F1", "command": "tank_diskvalve_status", "value": "on" }
- print('data: ', data)
- # mqtt_f(data)
- break
- timer = time.time()
- while True:
- if (time.time() - timer) > Ferment_Output_vacuumON_time:
- # [致動器] 出料真空吸料機 OFF
- data = { "tank_num": "F1", "command": "input_vacuum_status", "value": "off" }
- print('data: ', data)
- # mqtt_f(data)
- timer = time.time()
- break
- while True:
- if (time.time() - timer) > Ferment_Output_vacuumOFF_time:
- break
- elif F2 == 'F_OutputtingBean' and F_UP_UltraSoniclist[1] < 5:
- F2 = 'F_Waiting'
- FO1 = 'FO_OutputtingBean'
- print('------- F2 狀態更新:空桶等待 -------')
- print('------- FO1 狀態更新:可出豆 -------')
- elif F3 == 'F_OutputtingBean' and F_UP_UltraSoniclist[2] < 5:
- F3 = 'F_Waiting'
- FO1 = 'FO_OutputtingBean'
- print('------- F3 狀態更新:空桶等待 -------')
- print('------- FO1 狀態更新:可出豆 -------')
- elif F4 == 'F_OutputtingBean' and F_UP_UltraSoniclist[3] < 5:
- F4 = 'F_Waiting'
- FO1 = 'FO_OutputtingBean'
- print('------- F4 狀態更新:空桶等待 -------')
- print('------- FO1 狀態更新:可出豆 -------')
- elif F5 == 'F_OutputtingBean' and F_UP_UltraSoniclist[4] < 5:
- F5 = 'F_Waiting'
- FO1 = 'FO_OutputtingBean'
- print('------- F5 狀態更新:空桶等待 -------')
- print('------- FO1 狀態更新:可出豆 -------')
- elif F6 == 'F_OutputtingBean' and F_UP_UltraSoniclist[5] < 5:
- F6 = 'F_Waiting'
- FO1 = 'FO_OutputtingBean'
- print('------- F6 狀態更新:空桶等待 -------')
- print('------- FO1 狀態更新:可出豆 -------')
- # 出料儲豆槽出料 且 儲豆槽內高度低於 5 , 為空桶等待
- elif FO1 == 'FO_OutputtingBean' and FO_UP_UltraSoniclist[0] < Ferment_Output_bean_empty:
- FO1 = 'FO_Waiting'
- # ----- 發酵入料儲豆槽 FI1~FI2 入豆→可出豆判斷 ------------------------------
- # 1008 移到桶槽前面
- # ----- 發酵出料儲豆槽 FO1~FO2 入豆→可出豆判斷 ------------------------------
- # 1012 移到桶槽可出豆內
- # ----- 將狀態寫入資料庫 ------------------------------
- # 獲取文本框的值並賦值給user實體對象
- F_status = ferment_container_status()
- F_status.Ferment_Input_1 = FI1
- F_status.Ferment_Input_2 = FI2
- F_status.Ferment_Tank_1 = F1
- F_status.Ferment_Tank_2 = F2
- F_status.Ferment_Tank_3 = F3
- F_status.Ferment_Tank_4 = F4
- F_status.Ferment_Tank_5 = F5
- F_status.Ferment_Tank_6 = F6
- F_status.Ferment_Tank_7 = F7
- F_status.Ferment_Tank_8 = F8
- F_status.Ferment_Tank_9 = F9
- F_status.Ferment_Tank_10 = F10
- F_status.Ferment_Tank_11 = F11
- F_status.Ferment_Tank_12 = F12
- F_status.Ferment_Output_1 = FO1
- F_status.Ferment_Output_2 = FO2
- #將數據保存進資料庫
- db.session.add(F_status)
- # 手動提交
- db.session.commit()
- # ----- 將狀態寫入資料庫 ------------------------------
- return jsonify({"Peel_Output_1":PO1,
- "Ferment_Input_1":FI1,
- "Ferment_Tank_1":F1,
- "Ferment_Tank_2":F2,
- "Ferment_Tank_3":F3,
- "Ferment_Tank_4":F4,
- "Ferment_Tank_5":F5,
- "Ferment_Tank_6":F6,
- "Ferment_Output_1":FO1
- })
- '''
- return jsonify({"Ferment_Input_1":FI1,
- "Ferment_Input_2":FI2,
- "Ferment_Tank_1":F1,
- "Ferment_Tank_2":F2,
- "Ferment_Tank_3":F3,
- "Ferment_Tank_4":F4,
- "Ferment_Tank_5":F5,
- "Ferment_Tank_6":F6,
- "Ferment_Tank_7":F7,
- "Ferment_Tank_8":F8,
- "Ferment_Tank_9":F9,
- "Ferment_Tank_10":F10,
- "Ferment_Tank_11":F11,
- "Ferment_Tank_12":F12,
- "Ferment_Output_1":FO1,
- "Ferment_Output_2":FO2
- })
- '''
- # 1026 以流程圖判斷, 改寫 def ferment_auto_test, 以上為原備份
- # 舊有 video 介面
- @main.route('/video')
- def main_video():
- # 獲取登入信息
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- return render_template('video.html', params=locals())
- else:
- return render_template('sign_in.html')
- @main.route('/sitemap')
- def sitemap():
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- print('username: ', username)
- print('status: ', status)
- if status == 9:
- return render_template('signin_disable.html', **locals())
- elif status == 8:
- return render_template('signin_new.html', **locals())
- return render_template('sitemap.html', **locals())
- else:
- return render_template('sign_in.html')
- @main.route('/index_navbar', methods=['GET'])
- def index_navbar():
- return render_template('index_navbar.html')
- @main.route('/camera_dry', methods=['GET', 'POST'])
- def camera_dry():
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- return render_template('camera_dry.html', title='乾燥貨櫃攝影機', **locals())
- else:
- return render_template('sign_in.html')
- @main.route('/camera_ferment', methods=['GET', 'POST'])
- def camera_ferment():
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- return render_template('camera_ferment.html', title='發酵貨櫃攝影機', **locals())
- else:
- return render_template('sign_in.html')
-
- @main.route('/camera_clean', methods=['GET', 'POST'])
- def camera_clean():
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- return render_template('camera_clean.html', title='清洗貨櫃攝影機', **locals())
- else:
- return render_template('sign_in.html')
- @main.route('/camera_dry_1', methods=['GET', 'POST'])
- def camera_dry_2():
- if request.method == 'GET':
- return render_template('camera_dry_1.html', title='乾燥貨櫃攝影機', **locals())
- @main.route('/camera_<tid>', methods=['GET', 'POST'])
- def camera(tid):
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- if tid == 'CCargo_in':
- WS_URL = 'ws:///60.250.156.230:1111'
- camera_title = '清洗貨櫃內部'
- return render_template('camera.html', title='[畫面]' + camera_title, **locals())
- elif tid == 'CCargo_out':
- WS_URL = 'ws:///60.250.156.230:1111'
- camera_title = '清洗貨櫃外部'
- return render_template('camera.html', title='[畫面]' + camera_title, **locals())
- elif tid == 'FCargo_in':
- WS_URL = 'ws:///60.250.156.230:1111'
- camera_title = '發酵貨櫃內部'
- return render_template('camera.html', title='[畫面]' + camera_title, **locals())
- elif tid == 'FCargo_out':
- WS_URL = 'ws:///60.250.156.230:1111'
- camera_title = '發酵貨櫃外部'
- return render_template('camera.html', title='[畫面]' + camera_title, **locals())
- elif tid == 'DCargo_in':
- WS_URL = 'ws:///60.250.156.230:1111'
- camera_title = '乾燥貨櫃內部'
- return render_template('camera.html', title='[畫面]' + camera_title, **locals())
- elif tid == 'DCargo_out':
- WS_URL = 'ws:///60.250.156.230:1111'
- camera_title = '乾燥貨櫃外部'
- return render_template('camera.html', title='[畫面]' + camera_title, **locals())
- elif tid[:2] == 'DO':
- WS_URL_list = ['ws:///60.250.156.230:1111',
- 'ws:///60.250.156.230:2222'
- ]
- WS_URL = WS_URL_list[int(tid[2:])-1]
- camera_title = '乾燥出料儲豆槽'
- return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
- elif tid[:2] == 'DI':
- WS_URL_list = ['ws:///60.250.156.230:1111',
- 'ws:///60.250.156.230:2222'
- ]
- WS_URL = WS_URL_list[int(tid[2:])-1]
- camera_title = '乾燥入料儲豆槽'
- return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
- elif tid[:1] == 'D':
- WS_URL_list = ['ws:///60.250.156.230:8093', # D1 攝影機已安裝
- 'ws:///60.250.156.230:2222',
- 'ws:///60.250.156.230:3333',
- 'ws:///60.250.156.230:4444',
- 'ws:///60.250.156.230:5555',
- 'ws:///60.250.156.230:6666',
- 'ws:///60.250.156.230:7777',
- 'ws:///60.250.156.230:8888',
- 'ws:///60.250.156.230:9999',
- 'ws:///60.250.156.230:1010',
- 'ws:///60.250.156.230:1111',
- 'ws:///60.250.156.230:1212'
- ]
- WS_URL = WS_URL_list[int(tid[1:])-1]
- camera_title = '乾燥槽'
- return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
- elif tid[:2] == 'FO':
- WS_URL_list = ['ws:///60.250.156.230:1111',
- 'ws:///60.250.156.230:2222'
- ]
- WS_URL = WS_URL_list[int(tid[2:])-1]
- camera_title = '發酵出料儲豆槽'
- return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
- elif tid[:2] == 'FI':
- WS_URL_list = ['ws:///60.250.156.230:1111',
- 'ws:///60.250.156.230:2222'
- ]
- WS_URL = WS_URL_list[int(tid[2:])-1]
- camera_title = '發酵入料儲豆槽'
- return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
- elif tid[:1] == 'F':
- WS_URL_list = ['ws:///60.250.156.230:8089', # F1 攝影機已安裝
- 'ws:///60.250.156.230:2222',
- 'ws:///60.250.156.230:3333',
- 'ws:///60.250.156.230:4444',
- 'ws:///60.250.156.230:5555',
- 'ws:///60.250.156.230:6666',
- 'ws:///60.250.156.230:7777',
- 'ws:///60.250.156.230:8888',
- 'ws:///60.250.156.230:9999',
- 'ws:///60.250.156.230:1010',
- 'ws:///60.250.156.230:1111',
- 'ws:///60.250.156.230:1212'
- ]
- WS_URL = WS_URL_list[int(tid[1:])-1]
- camera_title = '發酵槽'
- return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
- elif tid[:2] == 'CO':
- WS_URL_list = ['ws:///60.250.156.230:1111',
- 'ws:///60.250.156.230:2222'
- ]
- WS_URL = WS_URL_list[int(tid[2:])-1]
- camera_title = '清洗浮選出料儲豆槽'
- return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
- elif tid[:1] == 'C':
- WS_URL_list = ['ws:///60.250.156.230:8088', # C1 攝影機已安裝
- 'ws:///60.250.156.230:2222',
- 'ws:///60.250.156.230:3333',
- 'ws:///60.250.156.230:4444'
- ]
- WS_URL = WS_URL_list[int(tid[1:])-1]
- camera_title = '清洗浮選槽'
- return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
- elif tid[:2] == 'SO':
- WS_URL_list = ['ws:///60.250.156.230:1111',
- 'ws:///60.250.156.230:2222'
- ]
- WS_URL = WS_URL_list[int(tid[2:])-1]
- camera_title = '色選機出料儲豆槽'
- return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
- elif tid[:1] == 'S':
- WS_URL_list = ['ws:///60.250.156.230:1111',
- 'ws:///60.250.156.230:2222'
- ]
- WS_URL = WS_URL_list[int(tid[1:])-1]
- camera_title = '色選機'
- return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
- elif tid[:2] == 'PO':
- WS_URL_list = ['ws:///60.250.156.230:1111',
- 'ws:///60.250.156.230:2222'
- ]
- WS_URL = WS_URL_list[int(tid[2:])-1]
- camera_title = '脫皮機出料儲豆槽'
- return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
- elif tid[:1] == 'P':
- WS_URL_list = ['ws:///60.250.156.230:1111',
- 'ws:///60.250.156.230:2222'
- ]
- WS_URL = WS_URL_list[int(tid[1:])-1]
- camera_title = '脫皮機'
- return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
- elif tid[:1] == 'R':
- WS_URL_list = ['ws:///60.250.156.230:1111'
- ]
- WS_URL = WS_URL_list[int(tid[1:])-1]
- camera_title = '中水桶'
- return render_template('camera.html', title='[畫面]' + camera_title + ' ' + tid, **locals())
- else:
- return render_template('sign_in.html')
- else:
- pass
- @main.route('/dry_SHT11_<dtid>', methods=['GET', 'POST'])
- def dry_SHT11(dtid):
- if request.method == 'GET':
- tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D' + dtid).order_by(text('datetime desc')).first()
- tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D' + dtid).order_by(text('datetime desc')).first()
- SHT11_Temp = tank_SHT11.SHT11_Temp
- SHT11_Humidity = tank_SHT11.SHT11_Humidity
- Soil_Temp = tank_Soil.soil_Temp
- return jsonify({"SHT11_Temp":SHT11_Temp,
- "SHT11_Humidity":SHT11_Humidity,
- "Soil_Temp":Soil_Temp
- })
- else:
- pass
- @main.route('/dry_UltraSonic_<dtid>', methods=['GET', 'POST'])
- def dry_UltraSonic(dtid):
- if request.method == 'GET':
- tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D' + dtid).order_by(text('datetime desc')).first()
- UltraSonic = tank_UltraSonic.UltraSonic
- return jsonify({"UltraSonic":UltraSonic
- })
- else:
- pass
- @main.route('/dry_input_UltraSonic_<dtid>', methods=['GET', 'POST'])
- def dry_input_UltraSonic(dtid):
- if request.method == 'GET':
- input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI' + dtid).order_by(text('datetime desc')).first()
- UltraSonic = input_UltraSonic.UltraSonic
- return jsonify({"UltraSonic":UltraSonic
- })
- else:
- pass
- @main.route('/dry_output_UltraSonic_<dtid>', methods=['GET', 'POST'])
- def dry_output_UltraSonic(dtid):
- if request.method == 'GET':
- output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO' + dtid).order_by(text('datetime desc')).first()
- UltraSonic = output_UltraSonic.UltraSonic
- return jsonify({"UltraSonic":UltraSonic
- })
- else:
- pass
- @main.route('/ferment_SHT11_<ftid>', methods=['GET', 'POST'])
- def ferment_SHT11(ftid):
- if request.method == 'GET':
- tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
- SHT11_Temp = tank_SHT11.SHT11_Temp
- return jsonify({"SHT11_Temp":SHT11_Temp
- })
- else:
- pass
- @main.route('/ferment_WaterLevel_<ftid>', methods=['GET', 'POST'])
- def ferment_WaterLevel(ftid):
- if request.method == 'GET':
- tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
- WaterLevel = tank_WaterLevel.WaterLevel
- return jsonify({"WaterLevel":WaterLevel
- })
- else:
- pass
-
- @main.route('/ferment_WaterIn_<ftid>', methods=['GET', 'POST'])
- def ferment_WaterIn(ftid):
- if request.method == 'GET':
- tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
- UltraSonic = (float(tank_UltraSonic.UltraSonic))
- # tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
- # PressureWaterLevel = '{:.2f}'.format((float(tank_PressureWaterLevel.PressureWaterLevel) -15 -90.278)/9.4214)
- tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
- WaterLevel = tank_WaterLevel.WaterLevel
- return jsonify({"UltraSonic":UltraSonic,
- "WaterLevel":WaterLevel
- })
- else:
- pass
- @main.route('/ferment_UltraSonic_<ftid>', methods=['GET', 'POST'])
- def ferment_UltraSonic(ftid):
- if request.method == 'GET':
- tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
- UltraSonic = (float(tank_UltraSonic.UltraSonic))
- return jsonify({"UltraSonic":UltraSonic
- })
- else:
- pass
- '''
- @main.route('/ferment_LiDAR_<ftid>', methods=['GET', 'POST'])
- def ferment_LiDAR(ftid):
- if request.method == 'GET':
- tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
- LiDAR = tank_LiDAR.LiDAR
- return jsonify({"LiDAR":LiDAR
- })
- else:
- pass
- '''
- @main.route('/ferment_input_UltraSonic_<ftid>', methods=['GET', 'POST'])
- def ferment_input_UltraSonic_(ftid):
- if request.method == 'GET':
- input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI' + ftid).order_by(text('datetime desc')).first()
- UltraSonic = input_UltraSonic.UltraSonic
- return jsonify({"UltraSonic":UltraSonic
- })
- else:
- pass
-
- @main.route('/ferment_output_UltraSonic_<ftid>', methods=['GET', 'POST'])
- def ferment_output_UltraSonic_(ftid):
- if request.method == 'GET':
- output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO' + ftid).order_by(text('datetime desc')).first()
- UltraSonic = output_UltraSonic.UltraSonic
- return jsonify({"UltraSonic":UltraSonic
- })
- else:
- pass
- @main.route('/ferment_watertesting_<tid>', methods=['GET', 'POST'])
- def ferment_watertesting(tid):
- if request.method == 'GET':
- tank_PH = ferment_tank_PH.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
- tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
- tank_DO = ferment_tank_DO.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
- tank_EC = ferment_tank_EC.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
- PH = tank_PH.PH
- ORP = tank_ORP.ORP
- DO = tank_DO.DO
- EC = tank_EC.EC
- return jsonify({"PH":PH,
- "ORP":ORP,
- "DO":DO,
- "EC":EC,
- })
- '''
- @main.route('/ferment_PressureWaterLevel_<ftid>', methods=['GET', 'POST'])
- def ferment_PressureWaterLevel(ftid):
- if request.method == 'GET':
- tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F' + ftid).order_by(text('datetime desc')).first()
- PressureWaterLevel = float(tank_PressureWaterLevel.PressureWaterLevel)
- #PressureWaterLevel = '{:.2f}'.format((float(tank_PressureWaterLevel.PressureWaterLevel) -15 -90.278)/9.4214)
- print("PressureWaterLevel_start: ", PressureWaterLevel)
- return jsonify({"PressureWaterLevel":PressureWaterLevel
- })
- # 此段刪除
- while int(PressureWaterLevel) < int(testing_water_height):
- tank_water_status = 'NO'
- time.sleep(3)
- # print(ferment_water_height(testing_water_height))
- # [目前桶內水位高度]發酵槽_感測器_壓力式水位計
- tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
- PressureWaterLevel = tank_PressureWaterLevel.PressureWaterLevel
- print("-- MySQL --")
- print("tank_PressureWaterLevel: ", tank_PressureWaterLevel)
- # tank_water_height()
- # print("PressureWaterLevel_while: ", PressureWaterLevel)
- ferment_water_height(testing_water_height)
- return jsonify({"testing_water_height":testing_water_height,
- "tank_water_status":tank_water_status
- })
- else:
- tank_water_status = 'OK'
- print("PressureWaterLevel_else: ", PressureWaterLevel)
- return jsonify({"testing_water_height":testing_water_height,
- "tank_water_status":tank_water_status
- })
- '''
- '''
- def tank_water_height():
- tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F1').order_by(text('datetime desc')).first()
- PressureWaterLevel = tank_PressureWaterLevel.PressureWaterLevel
- print("tank_water_height", PressureWaterLevel)
- return PressureWaterLevel
- '''
- @main.route('/loading/R<rtid>', methods=['GET', 'POST'])
- def R_loading(rtid):
- if request.method == 'GET':
- # 致動器_中水桶
- tank_actuator = reclaimed_tank_actuator.query.filter_by(tank_num='R'+rtid).order_by(text('datetime desc')).first()
- tank_solenoid_water_in = tank_actuator.solenoid_water_in
- tank_solenoid_reclaimed_out = tank_actuator.solenoid_reclaimed_out
- tank_solenoid_water_out = tank_actuator.solenoid_water_out
- tank_pump_reclaimed_out = tank_actuator.pump_reclaimed_out
- return jsonify({"tank_solenoid_water_in":tank_solenoid_water_in,
- "tank_solenoid_reclaimed_out":tank_solenoid_reclaimed_out,
- "tank_solenoid_water_out":tank_solenoid_water_out,
- "tank_pump_reclaimed_out":tank_pump_reclaimed_out
- })
- else:
- pass
- @main.route('/loading/SO<sotid>', methods=['GET', 'POST'])
- def SO_loading(sotid):
- if request.method == 'GET':
- # 致動器_脫皮機_ALL
- output_actuator = colorselect_output_actuator.query.filter_by(tank_num='SO'+sotid).order_by(text('datetime desc')).first()
- output_vacuum = output_actuator.vacuum
- return jsonify({"output_vacuum":output_vacuum
- })
- else:
- pass
- @main.route('/loading/S<stid>', methods=['GET', 'POST'])
- def S_loading(stid):
- if request.method == 'GET':
- # 致動器_色選機
- tank_actuator = colorselect_tank_actuator.query.filter_by(tank_num='S'+stid).order_by(text('datetime desc')).first()
- tank_vacuum = tank_actuator.vacuum
- tank_motor = tank_actuator.motor
- tank_nozzle = tank_actuator.nozzle
- # 致動器_超音波感測器colorselect_tank_UltraSonic
- tank_UltraSonic = colorselect_tank_UltraSonic.query.filter_by(tank_num='S'+stid).order_by(text('datetime desc')).first()
- UltraSonic = tank_UltraSonic.UltraSonic
- # 致動器_顏色感測器
- tank_color = colorselect_tank_color.query.filter_by(tank_num='S'+stid).order_by(text('datetime desc')).first()
- color = tank_color.color
-
- return jsonify({"tank_vacuum":tank_vacuum,
- "tank_motor":tank_motor,
- "tank_nozzle":tank_nozzle,
- "UltraSonic":UltraSonic,
- "color":color
- })
- else:
- pass
- @main.route('/loading/PO<potid>', methods=['GET', 'POST'])
- def PO_loading(potid):
- if request.method == 'GET':
- # 致動器_脫皮機_ALL
- output_actuator = peel_output_actuator.query.filter_by(tank_num='PO'+potid).order_by(text('datetime desc')).first()
- output_vacuum = output_actuator.vacuum
- return jsonify({"output_vacuum":output_vacuum
- })
- else:
- pass
- @main.route('/loading/P<ptid>', methods=['GET', 'POST'])
- def P_loading(ptid):
- if request.method == 'GET':
- # 致動器_脫皮機_ALL
- tank_actuator = peel_tank_actuator.query.filter_by(tank_num='P'+ptid).order_by(text('datetime desc')).first()
- tank_vacuum = tank_actuator.vacuum
- tank_motor = tank_actuator.motor
- return jsonify({"tank_vacuum":tank_vacuum,
- "tank_motor":tank_motor})
- else:
- pass
- @main.route('/loading/CO<cotid>', methods=['GET', 'POST'])
- def CO_loading(cotid):
- if request.method == 'GET':
- output_actuator = clean_output_actuator.query.filter_by(tank_num='CO'+cotid).order_by(text('datetime desc')).first()
- output_vacuum = output_actuator.vacuum
- return jsonify({"output_vacuum":output_vacuum
- })
- else:
- pass
- @main.route('/loading/C<ctid>', methods=['GET', 'POST'])
- def C_loading(ctid):
- if request.method == 'GET':
- # 致動器_浮選清洗_ALL
- tank_actuator = cleann_tank_actuator.query.filter_by(tank_num='C'+str(ctid)).order_by(text('datetime desc')).first()
- tank_vacuum = tank_actuator.vacuum
- tank_threewayvalve_input = tank_actuator.threewayvalve_input
- tank_motor = tank_actuator.motor
- tank_solenoid_reclaimed_in = tank_actuator.solenoid_reclaimed_in
- tank_solenoid_water_in = tank_actuator.solenoid_water_in
- tank_pump_water_in = tank_actuator.pump_water_in
- tank_solenoid_water_out = tank_actuator.solenoid_water_out
- tank_solenoid_reclaimed_out = tank_actuator.solenoid_reclaimed_out
- tank_solenoid_disinfect = tank_actuator.solenoid_disinfect
- tank_pump_disinfect = tank_actuator.pump_disinfect
- tank_diskvalve = tank_actuator.diskvalve
-
- # 感測器_浮選清洗_超音波感測器
- tank_UltraSonic = clean_tank_UltraSonic.query.filter_by(tank_num='C'+str(ctid)).order_by(text('datetime desc')).first()
- UltraSonic = tank_UltraSonic.UltraSonic
- tank_Encoder = clean_tank_Encoder.query.filter_by(tank_num='C'+str(ctid)).order_by(text('datetime desc')).first()
- Encoder = tank_Encoder.Encoder
- tank_Turbidity = clean_tank_Turbidity.query.filter_by(tank_num='C'+str(ctid)).order_by(text('datetime desc')).first()
- tankTurbidity = tank_Turbidity.tankTurbidity
- filter_Turbidity = clean_filter_Turbidity.query.filter_by(tank_num='C'+str(ctid)).order_by(text('datetime desc')).first()
- filterTurbidity = filter_Turbidity.filterTurbidity
- # tank_pump_waterInput = tank_actuator.pump_waterInput
- # tank_pump_waterL2L3 = tank_actuator.pump_waterL2L3
- # tank_pump_waterL4L5 = tank_actuator.pump_waterL4L5
- # tank_solenoid_waterL2L3 = tank_actuator.solenoid_waterL2L3
- # tank_solenoid_waterL4L5 = tank_actuator.solenoid_waterL4L5
- # tank_stepping_motor = tank_actuator.stepping_motor
- return jsonify({"UltraSonic":UltraSonic,
- "Encoder":Encoder,
- "tankTurbidity":tankTurbidity,
- "filterTurbidity":filterTurbidity,
- "tank_vacuum":tank_vacuum,
- "tank_threewayvalve_input":tank_threewayvalve_input,
- "tank_motor":tank_motor,
- "tank_solenoid_reclaimed_in":tank_solenoid_reclaimed_in,
- "tank_solenoid_water_in":tank_solenoid_water_in,
- "tank_pump_water_in":tank_pump_water_in,
- "tank_solenoid_water_out":tank_solenoid_water_out,
- "tank_solenoid_reclaimed_out":tank_solenoid_reclaimed_out,
- "tank_solenoid_disinfect":tank_solenoid_disinfect,
- "tank_pump_disinfect":tank_pump_disinfect,
- "tank_diskvalve":tank_diskvalve
- })
- else:
- pass
- @main.route('/loading/F<ftid>', methods=['GET', 'POST'])
- def F_loading(ftid):
- if request.method == 'GET':
- # 致動器_發酵槽_ALL
- tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- tank_vacuum = tank_actuator.vacuum
- tank_threewayvalve_input = tank_actuator.threewayvalve_input
- tank_diskvalve = tank_actuator.diskvalve
- solenoid_tank_pump = tank_actuator.solenoid_tank_pump
- tank_solenoid_disinfect = tank_actuator.solenoid_tank_disinfect
- outer_solenoid_water = tank_actuator.solenoid_outer_water
- tank_solenoid_water_in = tank_actuator.solenoid_tank_water_in
- tank_solenoid_water_out = tank_actuator.solenoid_tank_water_out
- tank_pump_sensor = tank_actuator.pump_sensor
- outer_threewayvalve_float = tank_actuator.threewayvalve_outer_float
- tank_motor = tank_actuator.motor
- tank_heater1 = tank_actuator.heater1
- tank_heater2 = tank_actuator.heater2
- tank_temp_enable = tank_actuator.temp_enable
- tank_temp = tank_actuator.temp
- # 感測器_發酵桶_SHT11
- tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- SHT11_Temp = float(tank_SHT11.SHT11_Temp)
- SHT11_Humidity = float(tank_SHT11.SHT11_Humidity)
- # 感測器_發酵桶_二氧化碳
- tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- CO2 = float(tank_CO2.CO2)
- # 感測器_發酵桶_酸鹼值
- tank_PH = ferment_tank_PH.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- tank_DO = ferment_tank_DO.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- tank_EC = ferment_tank_EC.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- PH = float(tank_PH.PH)
- ORP = float(tank_ORP.ORP)
- DO = float(tank_DO.DO)
- EC = float(tank_EC.EC)
- # 感測器_發酵桶_氣壓
- tank_PA = ferment_tank_PA.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- PA = float(tank_PA.PA)
- # 感測器_發酵桶_超音波感測器
- tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- UltraSonic= (float(tank_UltraSonic.UltraSonic))
- # 感測器_發酵桶_保溫夾層水位計
- tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- WaterLevel = tank_WaterLevel.WaterLevel
- # 感測器_發酵桶_咖啡生豆高度
- # tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- # LiDAR = tank_LiDAR.LiDAR
- # 感測器_發酵桶_水位高度
- # tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- # PressureWaterLevel = '{:.2f}'.format((float(tank_PressureWaterLevel.PressureWaterLevel) -15 -90.278)/9.4214)
- # 感測器_發酵桶_馬達編碼器
- tank_motorEncoder = ferment_tank_motorEncoder.query.filter_by(tank_num='F'+ftid).order_by(text('datetime desc')).first()
- motorEncoder = tank_motorEncoder.motorEncoder
- return jsonify({"SHT11_Temp": SHT11_Temp,
- "SHT11_Humidity":SHT11_Humidity,
- "CO2":CO2,
- "PH":PH,
- "ORP":ORP,
- "DO":DO,
- "EC":EC,
- "PA":PA,
- "WaterLevel":WaterLevel,
- "UltraSonic":UltraSonic,
- "motorEncoder":motorEncoder,
-
- "tank_vacuum":tank_vacuum,
- "tank_threewayvalve_input":tank_threewayvalve_input,
- "tank_diskvalve":tank_diskvalve,
- "solenoid_tank_pump":solenoid_tank_pump,
- "tank_solenoid_disinfect":tank_solenoid_disinfect,
- "outer_solenoid_water":outer_solenoid_water,
- "tank_solenoid_water_in":tank_solenoid_water_in,
- "tank_solenoid_water_out":tank_solenoid_water_out,
- "tank_pump_sensor":tank_pump_sensor,
- "outer_threewayvalve_float":outer_threewayvalve_float,
- "tank_motor":tank_motor,
- "tank_heater1":tank_heater1,
- "tank_heater2":tank_heater2,
- "tank_temp_enable":tank_temp_enable,
- "tank_temp":tank_temp
- })
- else:
- pass
-
- @main.route('/loading/FI<fitid>', methods=['GET', 'POST'])
- def FI_loading(fitid):
- if request.method == 'GET':
- input_actuator = ferment_input_actuator.query.filter_by(tank_num='F'+fitid).order_by(text('datetime desc')).first()
- input_vacuum = input_actuator.vacuum
- input_sensor = ferment_input_UltraSonic.query.filter_by(tank_num='F'+fitid).order_by(text('datetime desc')).first()
- # input_UltraSonic = float("{:.2f}".format(34.6 - float(input_sensor.UltraSonic)))
- input_UltraSonic = float(input_sensor.UltraSonic)
- return jsonify({"input_UltraSonic":input_UltraSonic,
- "input_vacuum":input_vacuum
- })
- else:
- pass
- @main.route('/loading/FO<fotid>', methods=['GET', 'POST'])
- def FO_loading(fotid):
- if request.method == 'GET':
- output_actuator = ferment_output_actuator.query.filter_by(tank_num='FO'+fotid).order_by(text('datetime desc')).first()
- output_vacuum = output_actuator.vacuum
- output_sensor = ferment_output_UltraSonic.query.filter_by(tank_num='FO'+fotid).order_by(text('datetime desc')).first()
- output_UltraSonic = output_sensor.UltraSonic
- tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+fotid).order_by(text('datetime desc')).first()
- LiDAR = tank_LiDAR.LiDAR
- return jsonify({"output_UltraSonic":output_UltraSonic,
- "output_vacuum":output_vacuum,
- "LiDAR":LiDAR
- })
- else:
- pass
- @main.route('/loading/DI<ditid>', methods=['GET', 'POST'])
- def DI_loading(ditid):
- if request.method == 'GET':
- input_actuator = dry_input_brake.query.filter_by(tank_num='DI'+ditid).order_by(text('datetime desc')).first()
- input_vacuum = input_actuator.vacuum
- input_sensor = dry_input_sensor.query.filter_by(tank_num='DI'+ditid).order_by(text('datetime desc')).first()
- input_UltraSonic = input_sensor.UltraSonic
- return jsonify({"input_UltraSonic":input_UltraSonic,
- "input_vacuum":input_vacuum
- })
- else:
- pass
- @main.route('/loading/DO<dotid>', methods=['GET', 'POST'])
- def DO_loading(dotid):
- if request.method == 'GET':
- output_actuator = dry_output_brake.query.filter_by(tank_num='DO'+dotid).order_by(text('datetime desc')).first()
- output_vacuum = output_actuator.vacuum
- output_sensor = dry_output_sensor.query.filter_by(tank_num='DO'+dotid).order_by(text('datetime desc')).first()
- output_UltraSonic = output_sensor.UltraSonic
- return jsonify({"output_vacuum":output_vacuum,
- "output_UltraSonic":output_UltraSonic
- })
- else:
- pass
- @main.route('/loading/D<dtid>', methods=['GET', 'POST'])
- def D_loading(dtid):
- if request.method == 'GET':
- # 感測器_乾燥桶_超音波感測器
- tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
- UltraSonic = tank_UltraSonic.UltraSonic
- # 感測器_乾燥桶_SHT11
- tonow = dt.now()
- # 感測器_乾燥桶_SHT11
- print("tonow: ", tonow)
- time_del = timedelta(minutes=-60)
- bias_date_time = tonow + time_del
- # print(dt.now() >= dt(2021,11,29,17,35,36))
- # bias_min = tonow.minute + 3
- tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(dtid))\
- .filter(dry_tank_SHT11.datetime >= bias_date_time)\
- .order_by(text('datetime desc')).first()
- 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'>
- print("hasattr tank_SHT11: ", hasattr(object, 'tank_SHT11'))
- print("hasattr tank_SHT11.SHT11_Temp: ", hasattr(object, 'tank_SHT11.SHT11_Temp'))
- try:
- SHT11_Temp = tank_SHT11.SHT11_Temp
- SHT11_Humidity = tank_SHT11.SHT11_Humidity
- except AttributeError:
- SHT11_Temp = " — "
- SHT11_Humidity = " — "
- # if not hasattr(object, 'tank_SHT11.SHT11_Temp'):
- # SHT11_Temp = " — "
- # SHT11_Humidity = " — "
- # else:
- # SHT11_Temp = tank_SHT11.SHT11_Temp
- # SHT11_Humidity = tank_SHT11.SHT11_Humidity
- # tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
- # SHT11_Temp = tank_SHT11.SHT11_Temp
- # SHT11_Humidity = tank_SHT11.SHT11_Humidity
- # 感測器_乾燥桶_土壤三合一
- tank_Soil = dry_tank_Soil.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
- soil_Temp = tank_Soil.soil_Temp
- soil_Humidity = tank_Soil.soil_Humidity
- soil_EC = tank_Soil.soil_EC
- # 感測器_乾燥桶_氣壓
- tank_PA = dry_tank_PA.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
- PA = tank_PA.PA
- # 致動器_乾燥桶_ALL
- tank_brake = dry_tank_brake.query.filter_by(tank_num="D"+dtid).order_by(text('datetime desc')).first()
- # tank_vacuum = 'ON' if i<100 else 2 if i>100 else 0
- tank_vacuum = tank_brake.vacuum
- tank_threewayvalve_input = tank_brake.threewayvalve_input
- tank_threewayvalve_bean = tank_brake.threewayvalve_bean
- tank_diskvalve = tank_brake.diskvalve
- tank_solenoid_disinfect = tank_brake.solenoid_disinfect
- tank_solenoid_water = tank_brake.solenoid_water
- tank_solenoid_outer_water = tank_brake.solenoid_outer_water
- tank_motor = tank_brake.motor
- tank_blower = tank_brake.blower
- tank_heater1 = tank_brake.heater1
- tank_heater2 = tank_brake.heater2
- tank_temp1_enable = tank_brake.temp1_enable
- tank_temp1 = tank_brake.temp1
- #return jsonify({"peeling": peeling_rpm})
- '''
- info = psutil.virtual_memory()
- print('記憶體使用: ', psutil.Process(os.getpid()).memory_info().rss)
- # print('總記憶體: ', info.total)
- print('記憶體占比: ', info.percent)
- print('cpu 個數: ', psutil.cpu_count())
- '''
- print("SHT11_Temp", SHT11_Temp)
- return jsonify({"UltraSonic":UltraSonic,
- "SHT11_Temp": SHT11_Temp,
- "SHT11_Humidity":SHT11_Humidity,
- "soil_Temp":soil_Temp,
- "soil_Humidity":soil_Humidity,
- "soil_EC":soil_EC,
- "PA":PA,
-
- "tank_vacuum":tank_vacuum,
- "tank_threewayvalve_input":tank_threewayvalve_input,
- "tank_threewayvalve_bean":tank_threewayvalve_bean,
- "tank_diskvalve":tank_diskvalve,
- "tank_solenoid_disinfect":tank_solenoid_disinfect,
- "tank_solenoid_water":tank_solenoid_water,
- "tank_solenoid_outer_water":tank_solenoid_outer_water,
- "tank_motor":tank_motor,
- "tank_blower":tank_blower,
- "tank_heater1":tank_heater1,
- "tank_heater2":tank_heater2,
- "tank_temp1_enable":tank_temp1_enable,
- "tank_temp1":tank_temp1
- })
- else:
- pass
- @main.route('/index_new')
- def index_new():
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html', **locals())
- elif status == 8:
- return render_template('signin_new.html', **locals())
- else:
- return render_template('oops.html', **locals())
-
- return render_template('index_new.html', title='Smart Coffee', **locals())
- @main.route('/user/<name>')
- def user(name):
- return render_template('hello.html', name=name)
- '''
- @main.route('/plot.png')
- def plot():
- # 重新整理會有問題
- # 圖的寬和高
- fig = plt.figure()
- # 在圖中新增子圖, 通常多個圖才會用到?
- axis = fig.add_subplot(1, 1, 1)
- # x、 軸資料
- xs = range(100)
- ys = [random.randint(1, 50) for x in xs]
- axis.plot(xs, ys)
- canvas = FigureCanvas(fig)
- output = io.BytesIO()
- canvas.print_png(output)
- response = make_response(output.getvalue())
- response.mimetype = 'image/png'
- return response
- '''
- @main.route('/chart_<tank>/<sensor_name>/<tid>', methods=['GET', 'POST'])
- def chart_D(tank, sensor_name, tid):
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
-
- if tank == 'DI':
- return render_template('sensor_chart_DI.html', title='[圖表]' + tank + tid + '乾燥入料儲豆槽', **locals())
- elif tank == 'DO':
- return render_template('sensor_chart_DO.html', title='[圖表]' + tank + tid + '乾燥出料儲豆槽', **locals())
- elif tank == 'FI':
- return render_template('sensor_chart_FI.html', title='[圖表]' + tank + tid + '發酵入料儲豆槽', **locals())
- elif tank == 'FO':
- return render_template('sensor_chart_FO.html', title='[圖表]' + tank + tid + '發酵出料儲豆槽', **locals())
- elif tank == 'F':
- return render_template('sensor_chart_F.html', title='[圖表]' + tank + tid + '發酵槽', **locals())
- else:
- return render_template('sensor_chart_D.html', title='[圖表]' + tank + tid + '乾燥槽', **locals())
- elif request.method == 'POST':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html', **locals())
- elif status == 8:
- return render_template('signin_new.html', **locals())
- else:
- return render_template('oops.html', **locals())
-
-
- starttime = request.values['sensor_starttime'] # 2021-07-19T09:00
- endtime = request.values['sensor_endtime'] # 2021-07-19T12:00
- sensor_name = request.values['sensors']
- print('sensor_name:', sensor_name)
- # 判斷資料索取區間 起<迄
- if starttime < endtime :
- # print('starttime endtime:', starttime, endtime)
- # print('TF:', starttime<endtime ) # 可以比較 起<迄
- # [html]2021-07-19T09:00 轉換成 [python]datetime.datetime(2021, 07, 19, 09, 00, 00)
- start_YY = starttime[:4] # '2021'
- start_MM = starttime[6:7] if starttime[5:7][:1] == '0' else starttime[5:7] # '07'
- start_DD = starttime[9:10] if starttime[8:10][:1] == '0' else starttime[8:10] # '19'
- start_hh = starttime[12:13] if starttime[11:13][:1] == '0' else starttime[11:13] # '09'
- start_mm = starttime[15:] if starttime[14:][:1] == '0' else starttime[14:] # '00'
- start_ss = 0
- end_YY = endtime[:4] # '2021'
- end_MM = endtime[6:7] if endtime[5:7][:1] == '0' else endtime[5:7] # '07'
- end_DD = endtime[9:10] if endtime[8:10][:1] == '0' else endtime[8:10] # '19'
- end_hh = endtime[12:13] if endtime[11:13][:1] == '0' else endtime[11:13] # '09'
- end_mm = endtime[15:] if endtime[14:][:1] == '0' else endtime[14:] # '00'
- end_ss = 0
- time_range = []
- temp_range = []
- # 拿掉會 Error, 要使用沒有 GUI 的 matplotlib
- plt.switch_backend('agg')
- plt.figure()
- if tank == 'DI':
- print('DI')
- if sensor_name == 'UltraSonic':
- for d in db.session.query(dry_input_sensor) \
- .filter_by(tank_num='DI' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_input_sensor.datetime) \
- .filter(dry_input_sensor.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(dry_input_sensor.datetime):
- # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
- time_range.append(str(d.datetime))
- temp_range.append(float(d.UltraSonic))
- print('time_range:', time_range)
- print('temp_range:', temp_range)
- return render_template('sensor_chart_DI.html', **locals())
- elif tank == 'DO':
- print('DO')
- if sensor_name == 'UltraSonic':
- for d in db.session.query(dry_output_sensor) \
- .filter_by(tank_num='DO' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_output_sensor.datetime) \
- .filter(dry_output_sensor.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(dry_output_sensor.datetime):
- # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
- time_range.append(str(d.datetime))
- temp_range.append(float(d.UltraSonic))
- print('time_range:', time_range)
- print('temp_range:', temp_range)
- return render_template('sensor_chart_DO.html', **locals())
- elif tank == 'D':
- print('D')
- if sensor_name == 'SHT11_Temp':
- for d in db.session.query(dry_tank_SHT11) \
- .filter_by(tank_num='D' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_SHT11.datetime) \
- .filter(dry_tank_SHT11.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(dry_tank_SHT11.datetime):
- # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
- time_range.append(str(d.datetime))
- temp_range.append(float(d.SHT11_Temp))
- # 畫出 x 軸基準線
- # plt.axhline(28.5, color= 'r')
-
- elif sensor_name == 'SHT11_Humidity':
- for d in db.session.query(dry_tank_SHT11) \
- .filter_by(tank_num='D' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_SHT11.datetime) \
- .filter(dry_tank_SHT11.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(dry_tank_SHT11.datetime):
- # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
- time_range.append(str(d.datetime))
- temp_range.append(float(d.SHT11_Humidity))
-
- elif sensor_name == 'UltraSonic':
- for d in db.session.query(dry_tank_UltraSonic) \
- .filter_by(tank_num='D' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_UltraSonic.datetime) \
- .filter(dry_tank_UltraSonic.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(dry_tank_UltraSonic.datetime):
- # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
- time_range.append(str(d.datetime))
- temp_range.append(float(d.UltraSonic))
-
- elif sensor_name == 'PA':
- for d in db.session.query(dry_tank_PA) \
- .filter_by(tank_num='D' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_PA.datetime) \
- .filter(dry_tank_PA.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(dry_tank_PA.datetime):
- # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
- time_range.append(str(d.datetime))
- temp_range.append(float(d.PA))
-
- elif sensor_name == 'soil_Temp':
- for d in db.session.query(dry_tank_Soil) \
- .filter_by(tank_num='D' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_Soil.datetime) \
- .filter(dry_tank_Soil.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(dry_tank_Soil.datetime):
- # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
- time_range.append(str(d.datetime))
- temp_range.append(float(d.soil_Temp))
- # 畫出 x 軸基準線
- plt.axhline(28.5, color= 'r')
- elif sensor_name == 'soil_Humidity':
- for d in db.session.query(dry_tank_Soil) \
- .filter_by(tank_num='D' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_Soil.datetime) \
- .filter(dry_tank_Soil.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(dry_tank_Soil.datetime):
- # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
- time_range.append(str(d.datetime))
- temp_range.append(float(d.soil_Humidity))
-
- elif sensor_name == 'soil_EC':
- for d in db.session.query(dry_tank_Soil) \
- .filter_by(tank_num='D' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_Soil.datetime) \
- .filter(dry_tank_Soil.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(dry_tank_Soil.datetime):
- # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
- time_range.append(str(d.datetime))
- temp_range.append(float(d.soil_EC))
- print('time_range:', time_range)
- print('temp_range:', temp_range)
- return render_template('sensor_chart_D.html', **locals())
- elif tank == 'FI':
- print('FI')
- if sensor_name == 'UltraSonic':
- for d in db.session.query(ferment_input_UltraSonic) \
- .filter_by(tank_num='FI' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_input_UltraSonic.datetime) \
- .filter(ferment_input_UltraSonic.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(ferment_input_UltraSonic.datetime):
- # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
- time_range.append(str(d.datetime))
- temp_range.append(float(d.UltraSonic))
- print('time_range:', time_range)
- print('temp_range:', temp_range)
- return render_template('sensor_chart_FI.html', **locals())
- elif tank == 'FO':
- print('FO')
- if sensor_name == 'UltraSonic':
- for d in db.session.query(ferment_output_UltraSonic) \
- .filter_by(tank_num='FO' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_output_UltraSonic.datetime) \
- .filter(ferment_output_UltraSonic.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(ferment_output_UltraSonic.datetime):
- # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
- time_range.append(str(d.datetime))
- temp_range.append(float(d.UltraSonic))
- print('time_range:', time_range)
- print('temp_range:', temp_range)
- return render_template('sensor_chart_FO.html', **locals())
- elif tank == 'F':
- print('F')
- if sensor_name == 'LiDAR':
- for d in db.session.query(ferment_tank_LiDAR) \
- .filter_by(tank_num='F' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_LiDAR.datetime) \
- .filter(ferment_tank_LiDAR.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(ferment_tank_LiDAR.datetime):
- time_range.append(str(d.datetime))
- temp_range.append(float(d.LiDAR))
- elif sensor_name == 'motorEncoder':
- print('sensor_name == motorEncoder')
- for d in db.session.query(ferment_tank_motorEncoder) \
- .filter_by(tank_num='F' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_motorEncoder.datetime) \
- .filter(ferment_tank_motorEncoder.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(ferment_tank_motorEncoder.datetime):
- time_range.append(str(d.datetime))
- temp_range.append(float(d.motorEncoder))
- print('time_range: ' + time_range)
- print('temp_range: ' + temp_range)
- elif sensor_name == 'PressureWaterLevel':
- for d in db.session.query(ferment_tank_PressureWaterLevel) \
- .filter_by(tank_num='F' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_PressureWaterLevel.datetime) \
- .filter(ferment_tank_PressureWaterLevel.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(ferment_tank_PressureWaterLevel.datetime):
- time_range.append(str(d.datetime))
- temp_range.append('{:.2f}'.format(float(d.PressureWaterLevel)))
- elif sensor_name == 'SHT11_Temp':
- for d in db.session.query(ferment_tank_SHT11) \
- .filter_by(tank_num='F' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_PressureWaterLevel.datetime) \
- .filter(ferment_tank_SHT11.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(ferment_tank_SHT11.datetime):
- time_range.append(str(d.datetime))
- temp_range.append(float(d.SHT11_Temp))
- elif sensor_name == 'SHT11_Humidity':
- for d in db.session.query(ferment_tank_SHT11) \
- .filter_by(tank_num='F' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_SHT11.datetime) \
- .filter(ferment_tank_SHT11.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(ferment_tank_SHT11.datetime):
- time_range.append(str(d.datetime))
- temp_range.append(float(d.SHT11_Humidity))
- elif sensor_name == 'CO2':
- for d in db.session.query(ferment_tank_CO2) \
- .filter_by(tank_num='F' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_CO2.datetime) \
- .filter(ferment_tank_CO2.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(ferment_tank_CO2.datetime):
- time_range.append(str(d.datetime))
- temp_range.append(float(d.CO2))
- elif sensor_name == 'PH':
- for d in db.session.query(ferment_tank_PH) \
- .filter_by(tank_num='F' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_PH.datetime) \
- .filter(ferment_tank_PH.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(ferment_tank_PH.datetime):
- time_range.append(str(d.datetime))
- temp_range.append(float(d.PH))
- elif sensor_name == 'ORP':
- for d in db.session.query(ferment_tank_ORP) \
- .filter_by(tank_num='F' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_ORP.datetime) \
- .filter(ferment_tank_ORP.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(ferment_tank_ORP.datetime):
- time_range.append(str(d.datetime))
- temp_range.append(float(d.ORP))
- elif sensor_name == 'DO':
- for d in db.session.query(ferment_tank_DO) \
- .filter_by(tank_num='F' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_DO.datetime) \
- .filter(ferment_tank_DO.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(ferment_tank_DO.datetime):
- time_range.append(str(d.datetime))
- temp_range.append(float(d.DO))
- elif sensor_name == 'EC':
- for d in db.session.query(ferment_tank_EC) \
- .filter_by(tank_num='F' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_EC.datetime) \
- .filter(ferment_tank_EC.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(ferment_tank_EC.datetime):
- time_range.append(str(d.datetime))
- temp_range.append(float(d.EC))
- elif sensor_name == 'PA':
- for d in db.session.query(ferment_tank_PA) \
- .filter_by(tank_num='F' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < ferment_tank_PA.datetime) \
- .filter(ferment_tank_PA.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(ferment_tank_PA.datetime):
- time_range.append(str(d.datetime))
- temp_range.append(float(d.PA))
-
- print('time_range:', time_range)
- print('temp_range:', temp_range)
- return render_template('sensor_chart_F.html', **locals())
-
- '''
- # 設定 x 軸資料、y 軸資料、折線顏色
- plt.plot(time_range, temp_range, 'bo')
- # x 軸標題 (中文無法顯示)
- # plt.xlabel('time')
- # plt.ylabel(sensor_name)
- # x 軸 label 和垂直顯示, rotation='vertical'
- plt.xticks(time_range, rotation='vertical' )
- # 設定圖表標題
- plt.title(sensor_name)
- # 調整圖片與周圍的間距
- plt.tight_layout()
- # plt.show()
- # 儲存圖片 應改為相對路徑
- plt.savefig('C:/Users/USER/Rita/Coffee/CoffeeProject/app/static/img/new_plot.png')
- '''
- # 判斷資料索取區間 起>迄
- else:
- return render_template('sensor_chart_D.html', **locals())
- '''
- @main.route('/chart_DI/<sensor_name>/<tid>', methods=['GET', 'POST'])
- def chart_DI(sensor_name, tid):
- if request.method == 'GET':
- return render_template('sensor_chart_DI.html', **locals())
- elif request.method == 'POST':
- starttime = request.values['sensor_starttime'] # 2021-07-19T09:00
- endtime = request.values['sensor_endtime'] # 2021-07-19T12:00
- sensor_name = request.values['sensors']
- print('sensor_name:', sensor_name)
- # 判斷資料索取區間 起<迄
- if starttime < endtime :
- start_YY = starttime[:4] # '2021'
- start_MM = starttime[6:7] if starttime[5:7][:1] == '0' else starttime[5:7] # '07'
- start_DD = starttime[9:10] if starttime[8:10][:1] == '0' else starttime[8:10] # '19'
- start_hh = starttime[12:13] if starttime[11:13][:1] == '0' else starttime[11:13] # '09'
- start_mm = starttime[15:] if starttime[14:][:1] == '0' else starttime[14:] # '00'
- start_ss = 0
- end_YY = endtime[:4] # '2021'
- end_MM = endtime[6:7] if endtime[5:7][:1] == '0' else endtime[5:7] # '07'
- end_DD = endtime[9:10] if endtime[8:10][:1] == '0' else endtime[8:10] # '19'
- end_hh = endtime[12:13] if endtime[11:13][:1] == '0' else endtime[11:13] # '09'
- end_mm = endtime[15:] if endtime[14:][:1] == '0' else endtime[14:] # '00'
- end_ss = 0
- time_range = []
- temp_range = []
- # 拿掉會 Error, 要使用沒有 GUI 的 matplotlib
- plt.switch_backend('agg')
- plt.figure()
- if sensor_name == 'UltraSonic':
- for d in db.session.query(dry_input_sensor) \
- .filter_by(tank_num='DI' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_UltraSonic.datetime) \
- .filter(dry_tank_UltraSonic.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(dry_tank_UltraSonic.datetime):
- # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
-
- time_range.append(str(d.datetime))
- temp_range.append(float(d.UltraSonic))
- # 畫出 x 軸基準線
- # plt.axhline(28.5, color= 'r')
-
- print('time_range:', time_range)
- print('temp_range:', temp_range)
-
- return render_template('sensor_chart_DI.html', **locals())
- # 判斷資料索取區間 起>迄
- else:
- return render_template('sensor_chart_DI.html', **locals())
- @main.route('/chart_DO/<sensor_name>/<tid>', methods=['GET', 'POST'])
- def chart_DO(sensor_name, tid):
- if request.method == 'GET':
- return render_template('sensor_chart_DO.html', **locals())
- elif request.method == 'POST':
- starttime = request.values['sensor_starttime'] # 2021-07-19T09:00
- endtime = request.values['sensor_endtime'] # 2021-07-19T12:00
- sensor_name = request.values['sensors']
- print('sensor_name:', sensor_name)
- # 判斷資料索取區間 起<迄
- if starttime < endtime :
- start_YY = starttime[:4] # '2021'
- start_MM = starttime[6:7] if starttime[5:7][:1] == '0' else starttime[5:7] # '07'
- start_DD = starttime[9:10] if starttime[8:10][:1] == '0' else starttime[8:10] # '19'
- start_hh = starttime[12:13] if starttime[11:13][:1] == '0' else starttime[11:13] # '09'
- start_mm = starttime[15:] if starttime[14:][:1] == '0' else starttime[14:] # '00'
- start_ss = 0
- end_YY = endtime[:4] # '2021'
- end_MM = endtime[6:7] if endtime[5:7][:1] == '0' else endtime[5:7] # '07'
- end_DD = endtime[9:10] if endtime[8:10][:1] == '0' else endtime[8:10] # '19'
- end_hh = endtime[12:13] if endtime[11:13][:1] == '0' else endtime[11:13] # '09'
- end_mm = endtime[15:] if endtime[14:][:1] == '0' else endtime[14:] # '00'
- end_ss = 0
- time_range = []
- temp_range = []
- # 拿掉會 Error, 要使用沒有 GUI 的 matplotlib
- plt.switch_backend('agg')
- plt.figure()
- if sensor_name == 'UltraSonic':
- for d in db.session.query(dry_input_sensor) \
- .filter_by(tank_num='DO' + tid) \
- .filter(dt(int(start_YY), int(start_MM), int(start_DD), int(start_hh), int(start_mm), int(start_ss)) < dry_tank_UltraSonic.datetime) \
- .filter(dry_tank_UltraSonic.datetime < dt(int(end_YY), int(end_MM), int(end_DD), int(end_hh), int(end_mm), int(end_ss))) \
- .order_by(dry_tank_UltraSonic.datetime):
- # print('d_test', f'{d.datetime} - {d.SHT11_Temp}')
-
- time_range.append(str(d.datetime))
- temp_range.append(float(d.UltraSonic))
- # 畫出 x 軸基準線
- # plt.axhline(28.5, color= 'r')
-
- print('time_range:', time_range)
- print('temp_range:', temp_range)
-
- return render_template('sensor_chart_DO.html', **locals())
- # 判斷資料索取區間 起>迄
- else:
- return render_template('sensor_chart_DO.html', **locals())
-
- '''
- # Rita 測試
- # 乾燥桶感測器/致動器測試
- # Rita 須加上 <tid> 區分桶號 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- @main.route('/dry_tank/1', methods=['GET'])
- def dry_tank():
- if request.method == 'GET':
-
- return render_template('dry_tank.html')
- @main.route('/clean', methods=['GET'])
- def clean():
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
- return render_template('clean.html', title='清洗貨櫃', **locals())
- @main.route('/ferment', methods=['GET'])
- def ferment():
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
- return render_template('ferment.html', title='發酵貨櫃', **locals())
- @main.route('/dry', methods=['GET'])
- def dry():
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
- return render_template('dry.html', title='乾燥貨櫃', **locals())
- @main.route('/reclaimedwater_tank/<tid>', methods=['GET', 'POST'])
- def reclaimedwater_tank(tid):
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
- # 致動器_中水桶
- tank_actuator = reclaimed_tank_actuator.query.filter_by(tank_num='R'+tid).order_by(text('datetime desc')).first()
- tank_solenoid_water_in = tank_actuator.solenoid_water_in
- tank_solenoid_reclaimed_out = tank_actuator.solenoid_reclaimed_out
- tank_solenoid_water_out = tank_actuator.solenoid_water_out
- tank_pump_reclaimed_out = tank_actuator.pump_reclaimed_out
-
- return render_template('reclaimedwater_tank.html', title='[操作] 中水桶操作介面', **locals())
- elif request.method == 'POST':
- pass
- @main.route('/colorselect_container_tank/<tid>', methods=['GET', 'POST'])
- def colorselect_container_tank(tid):
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
- # 致動器_色選機
- tank_actuator = colorselect_tank_actuator.query.filter_by(tank_num='S'+tid).order_by(text('datetime desc')).first()
- tank_vacuum = tank_actuator.vacuum
- tank_motor = tank_actuator.motor
- tank_nozzle = tank_actuator.nozzle
- # 致動器_超音波感測器colorselect_tank_UltraSonic
- tank_UltraSonic = colorselect_tank_UltraSonic.query.filter_by(tank_num='S'+tid).order_by(text('datetime desc')).first()
- # 致動器_顏色感測器
- tank_color = colorselect_tank_color.query.filter_by(tank_num='S'+tid).order_by(text('datetime desc')).first()
-
- return render_template('colorselect_container_tank.html', title='[操作] S' + tid + ' 色選機操作介面', **locals())
- elif request.method == 'POST':
- pass
-
- @main.route('/peel_container_tank/<tid>', methods=['GET', 'POST'])
- def peel_container_tank(tid):
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
- # 致動器_脫皮機_ALL
- # tank_num='P'+str(tid)
- tank_actuator = peel_tank_actuator.query.filter_by(tank_num='P'+str(tid)).order_by(text('datetime desc')).first()
- tank_vacuum = tank_actuator.vacuum
- tank_motor = tank_actuator.motor
- # 感測器_脫皮機出料儲豆槽_超音波高度
- tank_UltraSonic = peel_output_UltraSonic.query.filter_by(tank_num='P'+str(tid)).order_by(text('datetime desc')).first()
- # 感測器_脫皮機出料儲豆槽_馬達編碼器
- tank_motorEncoder = peel_output_motorEncoder.query.filter_by(tank_num='P'+str(tid)).order_by(text('datetime desc')).first()
-
- return render_template('peel_container_tank.html', title='[操作] P' + tid + ' 脫皮機操作介面', **locals())
- elif request.method == 'POST':
- pass
-
- @main.route('/peel_container/<tid>', methods=['GET', 'POST'])
- def peel_container(tid):
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
- # 致動器_入料儲豆槽_真空吸料機
- input_vacuum = peel_input_actuator.query.filter_by(tank_num='P'+str(tid)).order_by(text('datetime desc')).first()
- input_vacuum = input_vacuum.vacuum
- # 致動器_脫皮機_ALL
- tank_actuator = peel_tank_actuator.query.filter_by(tank_num='P'+str(tid)).order_by(text('datetime desc')).first()
- tank_vacuum = tank_actuator.vacuum
- tank_motor = tank_actuator.motor
-
- # 致動器_出料儲豆槽_真空吸料機
- output_vacuum = peel_output_actuator.query.filter_by(tank_num='P'+str(tid)).order_by(text('datetime desc')).first()
- output_vacuum = output_vacuum.vacuum
-
- return render_template('peel_container.html', title='脫皮機P' + tid + '總操作介面', **locals())
- elif request.method == 'POST':
- pass
- @main.route('/clean_container/<tid>', methods=['GET', 'POST'])
- def clean_container(tid):
- if request.method == 'GET':
-
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
- # 致動器_入料儲豆槽_真空吸料機
- input_vacuum = clean_input_actuator.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
- input_vacuum = 'ON' if (input_vacuum.vacuum == 1) else 'OFF'
- # 致動器_浮選清洗_ALL
- tank_actuator = clean_tank_actuator.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
- tank_vacuum = 'ON' if tank_actuator.vacuum == 1 else 'OFF'
- tank_pump_waterInput = 'ON' if tank_actuator.pump_waterInput == 1 else 'OFF'
- tank_pump_waterL2L3 = 'ON' if tank_actuator.pump_waterL2L3 == 1 else 'OFF'
- tank_pump_waterL4L5 = 'ON' if tank_actuator.pump_waterL4L5 == 1 else 'OFF'
- tank_solenoid_waterL2L3 = 'ON' if tank_actuator.solenoid_waterL2L3 == 1 else 'OFF'
- tank_solenoid_waterL4L5 = 'ON' if tank_actuator.solenoid_waterL4L5 == 1 else 'OFF'
- tank_stepping_motor = tank_actuator.stepping_motor
-
- # 致動器_出料儲豆槽_真空吸料機
- output_vacuum = clean_output_actuator.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
- output_vacuum = 'ON' if (output_vacuum.vacuum == 1) else 'OFF'
- # 感測器_浮選清洗_超音波感測器
- tank_UltraSonic = clean_tank_UltraSonic.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
-
-
- return render_template('clean_container.html', title='[操作] C' + tid + ' 清洗浮選槽操作介面', **locals())
- elif request.method == 'POST':
- pass
- @main.route('/clean_container_tank/<tid>', methods=['GET', 'POST'])
- def clean_container_tank(tid):
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
-
- # 致動器_浮選清洗_ALL
- tank_actuator = cleann_tank_actuator.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
- try:
- tank_vacuum = tank_actuator.vacuum
- except AttributeError:
- tank_vacuum = 'noValue'
- try:
- tank_threewayvalve_input = tank_actuator.threewayvalve_input
- except AttributeError:
- tank_threewayvalve_input = 'noValue'
- try:
- tank_motor = tank_actuator.motor
- except AttributeError:
- tank_motor = 'noValue'
- try:
- tank_solenoid_reclaimed_in = tank_actuator.solenoid_reclaimed_in
- except AttributeError:
- tank_solenoid_reclaimed_in = 'noValue'
- try:
- tank_solenoid_water_in = tank_actuator.solenoid_water_in
- except AttributeError:
- tank_solenoid_water_in = 'noValue'
- try:
- tank_pump_water_in = tank_actuator.pump_water_in
- except AttributeError:
- tank_pump_water_in = 'noValue'
- try:
- tank_solenoid_water_out = tank_actuator.solenoid_water_out
- except AttributeError:
- tank_solenoid_water_out = 'noValue'
- try:
- tank_solenoid_reclaimed_out = tank_actuator.solenoid_reclaimed_out
- except AttributeError:
- tank_solenoid_reclaimed_out = 'noValue'
- try:
- tank_solenoid_disinfect = tank_actuator.solenoid_disinfect
- except AttributeError:
- tank_solenoid_disinfect = 'noValue'
- try:
- tank_pump_disinfect = tank_actuator.pump_disinfect
- except AttributeError:
- tank_pump_disinfect = 'noValue'
- try:
- tank_diskvalve = tank_actuator.diskvalve
- except AttributeError:
- tank_diskvalve = 'noValue'
- # tank_pump_waterInput = 'ON' if tank_actuator.pump_waterInput == 1 else 'OFF'
- # tank_pump_waterL2L3 = 'ON' if tank_actuator.pump_waterL2L3 == 1 else 'OFF'
- # tank_pump_waterL4L5 = 'ON' if tank_actuator.pump_waterL4L5 == 1 else 'OFF'
- # tank_solenoid_waterL2L3 = 'ON' if tank_actuator.solenoid_waterL2L3 == 1 else 'OFF'
- # tank_solenoid_waterL4L5 = 'ON' if tank_actuator.solenoid_waterL4L5 == 1 else 'OFF'
- # tank_stepping_motor = tank_actuator.stepping_motor
-
- # 感測器_浮選清洗_超音波感測器
- tank_UltraSonic = clean_tank_UltraSonic.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
- try:
- UltraSonic = tank_UltraSonic.UltraSonic
- except AttributeError:
- UltraSonic = 'noValue'
- tank_Encoder = clean_tank_Encoder.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
- try:
- Encoder = tank_Encoder.Encoder
- except AttributeError:
- Encoder = 'noValue'
- tank_Turbidity = clean_tank_Turbidity.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
- try:
- tankTurbidity = tank_Turbidity.tankTurbidity
- except AttributeError:
- tankTurbidity = 'noValue'
- filter_Turbidity = clean_filter_Turbidity.query.filter_by(tank_num='C'+str(tid)).order_by(text('datetime desc')).first()
- try:
- filterTurbidity = filter_Turbidity.filterTurbidity
- except AttributeError:
- filterTurbidity = 'noValue'
- return render_template('clean_container_tank.html', title='[操作] C' + tid + ' 清洗浮選槽操作介面', **locals())
- elif request.method == 'POST':
- pass
- @main.route('/ferment_container/<tid>', methods=['GET', 'POST'])
- def ferment_container(tid):
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
- # 致動器_發酵槽_ALL
- tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- tank_vacuum = 'ON' if tank_actuator.vacuum == 1 else 'OFF'
- tank_threewayvalve_input = 'ON' if tank_actuator.threewayvalve_input == 1 else 'OFF'
- tank_diskvalve = 'ON' if tank_actuator.diskvalve == 1 else 'OFF'
- tank_solenoid_water_total = 'ON' if tank_actuator.solenoid_tank_water_total == 1 else 'OFF'
- tank_solenoid_disinfect = 'ON' if tank_actuator.solenoid_tank_disinfect == 1 else 'OFF'
- outer_solenoid_water = 'ON' if tank_actuator.solenoid_outer_water == 1 else 'OFF'
- tank_solenoid_water_in = 'ON' if tank_actuator.solenoid_tank_water_in == 1 else 'OFF'
- tank_pump_sensor = 'ON' if tank_actuator.pump_sensor == 1 else 'OFF'
- tank_threewayvalve_bean = 'ON' if tank_actuator.threewayvalve_bean == 1 else 'OFF'
- outer_threewayvalve_float = 'ON' if tank_actuator.threewayvalve_outer_float == 1 else 'OFF'
- tank_motor = tank_actuator.motor
- tank_heater1 = 'ON' if tank_actuator.heater1 == 1 else 'OFF'
- tank_heater2 = 'ON' if tank_actuator.heater2 == 1 else 'OFF'
- tank_temp_enable = 'ON' if tank_actuator.temp_enable == 1 else 'OFF'
- tank_temp = tank_actuator.temp
- # 感測器_發酵桶_SHT11
- tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- # 感測器_發酵桶_二氧化碳
- tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- # 感測器_發酵桶_酸鹼值
- tank_PH = ferment_tank_PH.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- tank_DO = ferment_tank_DO.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- tank_EC = ferment_tank_EC.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- # 感測器_發酵桶_氣壓
- tank_PA = ferment_tank_PA.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- # 感測器_發酵桶_超音波感測器
- tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- # 感測器_發酵桶_水位計
- tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- num_tank_WaterLevel = float(tank_WaterLevel.WaterLevel)
- print('tank_WaterLevel', tank_WaterLevel.WaterLevel)
- if tank_WaterLevel.WaterLevel == '1':
- WaterLevel = '滿'
- elif tank_WaterLevel.WaterLevel == '0':
- WaterLevel = '未達滿水高度'
- else:
- WaterLevel = 'ERROR'
- # 感測器_發酵桶_咖啡生豆高度
- tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- LiDAR = tank_LiDAR.LiDAR
- # 感測器_發酵桶_水位高度
- tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- PressureWaterLevel = '{:.2f}'.format((float(tank_PressureWaterLevel.PressureWaterLevel) -15 -90.278)/9.4214)
- if tid in ['1', '2', '3', '4', '5', '6']:
- # print("1")
- # 感測器_入料儲豆槽_超音波感測器
- input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI1').order_by(text('datetime desc')).first()
- # 致動器_入料儲豆槽_真空吸引機
- input_vacuum = ferment_input_actuator.query.filter_by(tank_num='FI1').order_by(text('datetime desc')).first()
- input_vacuum = input_vacuum.vacuum
- # 感測器_出料儲豆槽_超音波感測器
- output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO1').order_by(text('datetime desc')).first()
- # 致動器_出料儲豆槽_真空吸引機
- output_vacuum = ferment_output_actuator.query.filter_by(tank_num='FO1').order_by(text('datetime desc')).first()
- output_vacuum = output_vacuum.vacuum
- elif tid in ['7', '8', '9', '10', '11', '12']:
- # print("2")
- # 感測器_入料儲豆槽_超音波感測器
- input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI2').order_by(text('datetime desc')).first()
- # 致動器_入料儲豆槽_真空吸引機
- input_vacuum = ferment_input_actuator.query.filter_by(tank_num='FI2').order_by(text('datetime desc')).first()
- input_vacuum = input_vacuum.vacuum
- print("input_vacuum", input_vacuum)
- # 感測器_出料儲豆槽_超音波感測器
- output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO2').order_by(text('datetime desc')).first()
- # 致動器_出料儲豆槽_真空吸引機
- output_vacuum = ferment_output_actuator.query.filter_by(tank_num='FO2').order_by(text('datetime desc')).first()
- output_vacuum = output_vacuum.vacuum
- print("output_vacuum", output_vacuum)
-
- return render_template('ferment_container.html', title='發酵槽F' + tid + '總操作介面' , **locals())
- elif request.method == 'POST':
- pass
- @main.route('/ferment_container_tank/<tid>', methods=['GET', 'POST'])
- def ferment_container_tank(tid):
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
- # 致動器_發酵槽_ALL
-
- tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- tank_vacuum = 'ON' if tank_actuator.vacuum == 1 else 'OFF'
- tank_threewayvalve_input = 'ON' if tank_actuator.threewayvalve_input == 1 else 'OFF'
- tank_diskvalve = 'ON' if tank_actuator.diskvalve == 1 else 'OFF'
- solenoid_tank_pump = 'ON' if tank_actuator.solenoid_tank_pump == 1 else 'OFF'
- tank_solenoid_disinfect = 'ON' if tank_actuator.solenoid_tank_disinfect == 1 else 'OFF'
- outer_solenoid_water = 'ON' if tank_actuator.solenoid_outer_water == 1 else 'OFF'
- tank_solenoid_water_in = 'ON' if tank_actuator.solenoid_tank_water_in == 1 else 'OFF'
- tank_solenoid_water_out = 'ON' if tank_actuator.solenoid_tank_water_out == 1 else 'OFF'
- tank_pump_sensor = 'ON' if tank_actuator.pump_sensor == 1 else 'OFF'
- outer_threewayvalve_float = 'ON' if tank_actuator.threewayvalve_outer_float == 1 else 'OFF'
- tank_motor = tank_actuator.motor
- tank_heater1 = 'ON' if tank_actuator.heater1 == 1 else 'OFF'
- tank_heater2 = 'ON' if tank_actuator.heater2 == 1 else 'OFF'
- tank_temp_enable = 'ON' if tank_actuator.temp_enable == 1 else 'OFF'
- tank_temp = tank_actuator.temp
- # 感測器_發酵桶_SHT11
- tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- # 感測器_發酵桶_二氧化碳
- tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- # 感測器_發酵桶_酸鹼值
- tank_PH = ferment_tank_PH.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- tank_DO = ferment_tank_DO.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- tank_EC = ferment_tank_EC.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- # 感測器_發酵桶_氣壓
- tank_PA = ferment_tank_PA.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- # 感測器_發酵桶_超音波感測器
- tank_UltraSonic = ferment_tank_UltraSonic.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- # 感測器_發酵桶_水位計
- tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- num_tank_WaterLevel = float(tank_WaterLevel.WaterLevel)
- if tank_WaterLevel.WaterLevel == '1':
- WaterLevel = '滿'
- elif tank_WaterLevel.WaterLevel == '0':
- WaterLevel = '未達滿水高度'
- else:
- WaterLevel = 'ERROR'
- # 感測器_發酵桶_咖啡生豆高度
- #tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- #LiDAR = tank_LiDAR.LiDAR
- # 感測器_發酵桶_水位高度
- #tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- #PressureWaterLevel = '{:.2f}'.format((float(tank_PressureWaterLevel.PressureWaterLevel) -15 -90.278)/9.4214)
- # 感測器_發酵桶_馬達編碼器
- tank_motorEncoder = ferment_tank_motorEncoder.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
-
- return render_template('ferment_container_tank.html', title='[操作] F' + tid + ' 發酵槽操作介面', **locals())
- elif request.method == 'POST':
- pass
- @main.route('/ferment_container_input/<tid>', methods=['GET', 'POST'])
- def ferment_container_input(tid):
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
- # 感測器_入料儲豆槽_超音波感測器
- input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI' + tid).order_by(text('datetime desc')).first()
- # 致動器_入料儲豆槽_真空吸引機
- input_vacuum = ferment_input_actuator.query.filter_by(tank_num='FI' + tid).order_by(text('datetime desc')).first()
- input_vacuum = input_vacuum.vacuum
-
- return render_template('ferment_container_input.html', title='[操作] FI' + tid + ' 發酵入料儲豆槽操作介面', **locals())
- elif request.method == 'POST':
- pass
- @main.route('/ferment_container_output/<tid>', methods=['GET', 'POST'])
- def ferment_container_output(tid):
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
- # 感測器_出料儲豆槽_超音波感測器
- output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO' + tid).order_by(text('datetime desc')).first()
- # 致動器_出料儲豆槽_真空吸引機
- output_vacuum = ferment_output_actuator.query.filter_by(tank_num='FO' + tid).order_by(text('datetime desc')).first()
- output_vacuum = output_vacuum.vacuum
- tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- LiDAR = tank_LiDAR.LiDAR
-
- return render_template('ferment_container_output.html', title='[操作] FO' + tid + ' 發酵出料儲豆槽操作介面', **locals())
- elif request.method == 'POST':
- pass
- @main.route('/dry_container_schedule', methods=['GET', 'POST'])
- def dry_container_schedule():
- if request.method == 'GET':
- if 'id' in session and 'uname' in session:
- username = session['uname']
-
- # 感測器_入料儲豆槽_超音波感測器
- input_UltraSonic = dry_input_sensor.query.order_by(text('datetime desc')).first()
- # 感測器_乾燥桶_超音波感測器
- tank_UltraSonic = dry_tank_UltraSonic.query.order_by(text('datetime desc')).first()
-
- return render_template('dry_container_schedule.html', title='dry_container_schedule', **locals())
-
- elif request.method == 'POST':
- pass
- @main.route('/dry_block', methods=['GET', 'POST'])
- def dry_block():
- if request.method == 'GET':
- if 'id' in session and 'uname' in session:
- username = session['uname']
- DBW = dry_block_waiting.query.order_by(text('datetime desc')).first()
- pin_data = coffee1_0_pin.query.order_by(text('datetime desc')).first()
-
- return render_template('dry_block.html', title='積木設定_乾燥空桶等待', **locals())
-
- elif request.method == 'POST':
- pass
- @main.route('/dry_block_empty', methods=['GET', 'POST'])
- def dry_block_empty():
- if request.method == 'GET':
- if 'id' in session and 'uname' in session:
- username = session['uname']
-
- return render_template('dry_block_empty.html', title='積木設定空白_乾燥空桶等待', **locals())
-
- elif request.method == 'POST':
- pass
- # 0323 積木程式 格式調整
- @main.route('/dry_block_format', methods=['GET', 'POST'])
- def dry_block_format():
- if request.method == 'GET':
- info = request.args.to_dict()
- # print("info: ", info)
- # 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'}
- tank_num_data = info['tank_num'] # 桶槽編號:D1
- mainLength_data = int(info['mainLength'])+1 # 總條件數量
- addLength_data = int(info['addLength'])+1 # 子條件數量
- comLength_data = int(info['comLength'])+1 # 子物件數量
-
- cond_main_all_list = []
- for z in range(1,mainLength_data):
- # 初始
- cond_main_all_dict = {}
- cond_add_list = [] # 附加條件 List
- cond_com_list = [] # 物件動作 List
- # cond_main_dict_all = {}
- # cond_add_dict_all = {}
- # cond_com_dict_all = {}
-
- # print(z)
- # 總條件
- try:
- cond_main_all_dict['cond_main'] = info['cond_main' + str(z)]
- except(KeyError):
- pass
- # print("cond_main_dict: ", cond_main_dict)
- # 附加條件
- for x in range(1,addLength_data):
- try:
- cond_add_list.append(info['cond_add' + str(z) + '_' + str(x)])
- except(KeyError):
- pass
- # print("cond_add_list: ", cond_add_list)
- cond_main_all_dict['cond_add'] = cond_add_list
- # print("cond_main_dict: ", cond_main_dict)
- # 物件動作
- for y in range(1,comLength_data):
- try:
- cond_com_list.append(info['cond_com' + str(z) + '_' + str(y)])
- except(KeyError):
- pass
- # print("cond_com_list: ", cond_com_list)
- cond_main_all_dict['cond_com'] = cond_com_list
- # print("cond_main_dict: ", cond_main_dict)
- if cond_com_list != []:
- cond_main_all_list.append(cond_main_all_dict)
- # cond_main_all_list.append(cond_add_dict_all)
- # cond_main_all_list.append(cond_com_dict_all)
- print("cond_main_all_list: ", cond_main_all_list)
- # 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']}]
-
- dry_block_sehedule = {'command':'Dry_OTA', 'tank_num':tank_num_data, 'cond':cond_main_all_list}
- print('dry_block_sehedule:', dry_block_sehedule)
- # 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']}]}
- topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
- print('=========================================================')
- print("json.dumps(dry_block_sehedule):", json.dumps(dry_block_sehedule))
- # 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"]}]}
- print('=========================================================')
- # mqtt.publish(topic, json.dumps(dry_block_sehedule))
-
- return jsonify({"response":dry_block_sehedule})
- # 積木程式
- @main.route('/dry_block_set', methods=['GET', 'POST'])
- def dry_block_set():
- if request.method == 'GET':
- if 'id' in session and 'uname' in session:
- username = session['uname']
- info = request.args.to_dict()
- # print("info: ", info, type(info)) # dict
- # 傳回 總條件物件動作 數量
- condition = int(info['condition'])
- # 傳回 子條件 數量
- cond_add_child = int(info['cond_add_child'])
- # 傳回 子物件動作 數量
- act_add_child = int(info['act_add_child'])
- # 傳回 指令
- set_Schedule = eval(info['set_Schedule']) # 字串轉成字典
- # print("set_Schedule: ", set_Schedule, type(set_Schedule)) # dict
- cond_data = ''
- # mqtt_data("D1", "block_command_test", "condition=" + str(condition)) # 0321 TEST
- # ----- 0321 註解測試 -----
- # # 拆解條件 / 物件 / 動作
- # # # 條件物件取值
- # for z in range(1, condition+1, 1):
- # # 放要執行的判斷式
- # # # if / while
- # cond_data = ''
- # try:
- # z_num = 'cond_z' + str(z) + '_1'
- # # print("cond_z_value[z_num]: ", set_Schedule[z_num]) # if
- # cond_data += set_Schedule[z_num]
- # except KeyError:
- # pass
- # # # 桶槽號取值
- # try:
- # tank_num = 'cond_tank' + str(z) + '_1'
- # except KeyError:
- # pass
- # # # 子條件取值
- # for x in range(1, cond_add_child+1, 1):
- # # d
- # try:
- # x_num_d = 'cond_d' + str(z) + '_' + str(x)
- # # print("cond_d_value[x_num_d]: ", set_Schedule[x_num_d])
- # cond_data += ' ' + set_Schedule[x_num_d]
- # except KeyError:
- # pass
- # # a
- # x_num_a = 'cond_a' + str(z) + '_' + str(x)
- # try:
- # x_num_a = 'cond_a' + str(z) + '_' + str(x)
- # # print("cond_a_value[x_num_a]: ", set_Schedule[x_num_a])
- # cond_data += ' ' + set_Schedule[x_num_a]
- # if set_Schedule[x_num_a] == 'input_vacuum_status':
- # input_vacuum_status = dry_input_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().vacuum
- # print("input_vacuum_status: ", input_vacuum_status)
- # elif set_Schedule[x_num_a] == 'tank_vacuum_status':
- # tank_vacuum_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().vacuum
- # print("tank_vacuum_status: ", tank_vacuum_status)
- # elif set_Schedule[x_num_a] == 'tank_threewayvalve_input_status':
- # tank_threewayvalve_input_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().threewayvalve_input
- # print("tank_threewayvalve_input_status: ", tank_threewayvalve_input_status)
- # elif set_Schedule[x_num_a] == 'tank_motor_status':
- # tank_motor_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().motor
- # print("tank_motor_status: ", tank_motor_status)
- # elif set_Schedule[x_num_a] == 'tank_blower_status':
- # tank_blower_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().blower
- # print("tank_blower_status: ", tank_blower_status)
- # elif set_Schedule[x_num_a] == 'tank_heater1_status':
- # tank_heater1_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().heater1
- # print("tank_heater1_status: ", tank_heater1_status)
- # elif set_Schedule[x_num_a] == 'tank_heater2_status':
- # tank_heater2_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().heater2
- # print("tank_heater2_status: ", tank_heater2_status)
- # elif set_Schedule[x_num_a] == 'tank_diskvalve_status':
- # tank_diskvalve_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().diskvalve
- # print("tank_diskvalve_status: ", tank_diskvalve_status)
- # elif set_Schedule[x_num_a] == 'tank_solenoid_disinfect_status':
- # tank_solenoid_disinfect_status = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().solenoid_disinfect
- # print("tank_solenoid_disinfect_status: ", tank_solenoid_disinfect_status)
- # elif set_Schedule[x_num_a] == 'tank_solenoid_water_out_status':
- # 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
- # print("tank_solenoid_water_out_status: ", tank_solenoid_water_out_status)
- # elif set_Schedule[x_num_a] == 'outer_solenoid_water_status':
- # 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
- # print("outer_solenoid_water_status: ", outer_solenoid_water_status)
- # elif set_Schedule[x_num_a] == 'tank_temp_enable':
- # tank_temp_enable = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().temp1_enable
- # print("tank_temp_enable: ", tank_temp_enable)
- # elif set_Schedule[x_num_a] == 'tank_temp':
- # tank_temp = dry_tank_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().temp1
- # print("tank_temp: ", tank_temp)
- # elif set_Schedule[x_num_a] == 'output_vacuum':
- # output_vacuum = dry_output_brake.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().vacuum
- # print("output_vacuum: ", output_vacuum)
- # elif set_Schedule[x_num_a] == 'input_UltraSonic':
- # input_UltraSonic = float(dry_input_sensor.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().UltraSonic)
- # print("input_UltraSonic: ", input_UltraSonic)
- # elif set_Schedule[x_num_a] == 'tank_UltraSonic':
- # tank_UltraSonic = float(dry_tank_UltraSonic.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().UltraSonic)
- # print("tank_UltraSonic: ", tank_UltraSonic)
- # elif set_Schedule[x_num_a] == 'tank_SHT11_Temp':
- # tank_SHT11_Temp = float(dry_tank_SHT11.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().SHT11_Temp)
- # print("tank_SHT11_Temp: ", tank_SHT11_Temp)
- # elif set_Schedule[x_num_a] == 'tank_SHT11_Humidity':
- # tank_SHT11_Humidity = float(dry_tank_SHT11.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().SHT11_Humidity)
- # print("tank_SHT11_Humidity: ", tank_SHT11_Humidity)
- # elif set_Schedule[x_num_a] == 'tank_soil_Temp':
- # tank_soil_Temp = float(dry_tank_Soil.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().soil_Temp)
- # print("tank_soil_Temp: ", tank_soil_Temp)
- # elif set_Schedule[x_num_a] == 'tank_soil_Humidity':
- # tank_soil_Humidity = float(dry_tank_Soil.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().soil_Humidity)
- # print("tank_soil_Humidity: ", tank_soil_Temp)
- # elif set_Schedule[x_num_a] == 'tank_soil_EC':
- # tank_soil_EC = float(dry_tank_Soil.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().soil_EC)
- # print("tank_soil_EC: ", tank_soil_EC)
- # elif set_Schedule[x_num_a] == 'tank_PA':
- # tank_PA = float(dry_tank_PA.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().PA)
- # print("tank_PA: ", tank_PA)
- # elif set_Schedule[x_num_a] == 'output_UltraSonic':
- # output_UltraSonic = float(dry_output_sensor.query.filter_by(tank_num=set_Schedule[tank_num]).order_by(text('datetime desc')).first().UltraSonic)
- # print("output_UltraSonic: ", output_UltraSonic)
- # except KeyError:
- # pass
- # # b
- # try:
- # x_num_b = 'cond_b' + str(z) + '_' + str(x)
- # # print("cond_b_value[x_num_b]: ", set_Schedule[x_num_b])
- # cond_b_dict = {'morethan': ' >= ', 'lessthan': ' <= ', 'equal':' == '}
- # cond_data += cond_b_dict[set_Schedule[x_num_b]] # cond_b_dict['equal'] 會輸出 ' == '
- # except KeyError:
- # pass
- # # c
- # try:
- # x_num_c = 'cond_c' + str(z) + '_' + str(x)
- # # print("cond_c_value[x_num_c]: ", set_Schedule[x_num_c])
- # if set_Schedule[x_num_c] == 'on':
- # cond_data += '1'
- # elif set_Schedule[x_num_c] == 'off':
- # cond_data += '0'
- # else:
- # cond_data += set_Schedule[x_num_c]
- # except KeyError:
- # pass
- # if x == cond_add_child:
- # cond_data += ': '
- # # 子物件動作取值
- # for y in range(1, act_add_child+1, 1):
- # # do_obj
- # try:
- # y_num_obj = "do_obj" + str(z) + "_" + str(y)
- # # print("y_num_obj[y_num_obj]: ", set_Schedule[y_num_obj])
- # # cond_data += 'print(\'' + 'mqtt_data("D1", "' + str(set_Schedule[y_num_obj]) + '", '
- # if set_Schedule[y_num_obj] == 'time.sleep':
- # cond_data += '''
- # time.sleep('''
- # else:
- # cond_data += '''
- # mqtt_data('''
- # cond_data += '"' + set_Schedule[tank_num] + '", "' + str(set_Schedule[y_num_obj]) + '", '
- # except KeyError:
- # pass
- # try:
- # y_num_act = "do_act" + str(z) + "_" + str(y)
- # # print("y_num_act[y_num_act]: ", set_Schedule[y_num_act])
- # if set_Schedule[y_num_obj] == 'time.sleep':
- # cond_data += set_Schedule[y_num_act] + ')'
- # else:
- # cond_data += '"' + str(set_Schedule[y_num_act]) + '") '
- # cond_data += '''
- # time.sleep(0.5)'''
- # except KeyError:
- # pass
- # # TODO
- # # set_Schedule[z_num] → if / while
- # # set_Schedule[x_num_a] → actuator / sensor
- # # set_Schedule[x_num_b] → morethan / equal / lessthan
- # # set_Schedule[x_num_c] → 數值 / on / off
- # # set_Schedule[x_num_d] → or / and
- # # set_Schedule[y_num_obj] → actuator
- # # set_Schedule[y_num_act] → on / off / 對應數值
- # print("cond_data: ", cond_data)
- # if cond_data != ': ':
- # # exec(cond_data)
- # # 01/17 新增, 格式待修改
- # mqtt_data("D1", "command_test", "exec(" + cond_data + ")")
- return jsonify({"response":"OK"
- })
-
- elif request.method == 'POST':
- pass
- # 乾燥貨櫃_各致動器控制
- @main.route('/ctrl_DI_<actuator>/<tid>', methods=['GET', 'POST'])
- def ctrl_DI(actuator, tid):
- if request.method == 'GET':
- if actuator == 'Vacuum':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
- input_brake = dry_input_brake.query.filter_by(tank_num='DI'+str(tid)).order_by(text('datetime desc')).first()
- input_vacuum = input_brake.vacuum
- tank_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI'+str(tid)).order_by(text('datetime desc')).first()
- UltraSonic = tank_UltraSonic.UltraSonic
- return render_template('ctrl_DI_Vacuum.html', title='[操作]DI' + tid + '乾燥槽入料_真空吸料機', **locals())
- elif request.method == 'POST':
- pass
- @main.route('/ctrl_DO_<actuator>/<tid>', methods=['GET', 'POST'])
- def ctrl_DO(actuator, tid):
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
-
- if actuator == 'Vacuum':
- tank_brake = dry_output_brake.query.filter_by(tank_num='DO'+str(tid)).order_by(text('datetime desc')).first()
- tank_vacuum = tank_brake.vacuum
- tank_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO'+str(tid)).order_by(text('datetime desc')).first()
- UltraSonic = tank_UltraSonic.UltraSonic
- return render_template('ctrl_DO_Vacuum.html', title='[操作]DI' + tid + '乾燥槽出料_真空吸料機', **locals())
- elif request.method == 'POST':
- pass
-
- @main.route('/ctrl_D_<actuator>/<tid>', methods=['GET', 'POST'])
- def ctrl_D(actuator, tid):
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
- tank_brake = dry_tank_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- if actuator == 'Vacuum':
- tank_vacuum = tank_brake.vacuum
- tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- UltraSonic = tank_UltraSonic.UltraSonic
- return render_template('ctrl_D_Vacuum.html', title='[操作]D' + tid + '乾燥槽_真空吸料機', **locals())
- elif actuator == 'ThreeWayValveInput':
- tank_threewayvalve_input = tank_brake.threewayvalve_input
- return render_template('ctrl_D_ThreeWayValveInput.html', title='[操作]D' + tid + '乾燥槽_入料三通閥', **locals())
- elif actuator == 'ThreeWayValveBean':
- tank_threewayvalve_bean = tank_brake.threewayvalve_bean
- return render_template('ctrl_D_ThreeWayValveBean.html', title='[操作]D' + tid + '乾燥槽_測豆三通閥', **locals())
- elif actuator == 'DiskValve':
- tank_diskvalve = tank_brake.diskvalve
- return render_template('ctrl_D_DiskValve.html', title='[操作]D' + tid + '乾燥槽_蝴蝶閥', **locals())
- elif actuator == 'SolenoidDisinfect':
- tank_solenoid_disinfect = tank_brake.solenoid_disinfect
- return render_template('ctrl_D_SolenoidDisinfect.html', title='[操作]D' + tid + '乾燥槽_消毒電磁閥', **locals())
- elif actuator == 'SolenoidWater':
- tank_solenoid_water = tank_brake.solenoid_water
- return render_template('ctrl_D_SolenoidWater.html', title='[操作]D' + tid + '乾燥槽_排水電磁閥', **locals())
- elif actuator == 'Motor':
- tank_motor = tank_brake.motor
- return render_template('ctrl_D_Motor.html', title='[操作]D' + tid + '乾燥槽_馬達', **locals())
- elif actuator == 'Blower':
- tank_blower = tank_brake.blower
- tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- return render_template('ctrl_D_Blower.html', title='[操作]D' + tid + '乾燥槽_鼓風機', **locals())
- elif actuator == 'Heater1':
- tank_heater1 = tank_brake.heater1
- tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- return render_template('ctrl_D_Heater1.html', title='[操作]D' + tid + '乾燥槽_加熱器 1', **locals())
- elif actuator == 'Heater2':
- tank_heater2 = tank_brake.heater2
- tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- return render_template('ctrl_D_Heater2.html', title='[操作]D' + tid + '乾燥槽_加熱器 2', **locals())
- elif actuator == 'TempEnable':
- tank_temp1_enable = tank_brake.temp1_enable
- return render_template('ctrl_D_TempEnable.html', title='[操作]D' + tid + '乾燥槽_溫控開關', **locals())
- elif actuator == 'Temp':
- tank_temp1_enable = tank_brake.temp1_enable
- tank_temp1 = tank_brake.temp1
- tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- return render_template('ctrl_D_Temp.html', title='[操作]D' + tid + '乾燥槽_設定溫度', **locals())
- elif request.method == 'POST':
- pass
- # 發酵貨櫃_各致動器控制
- @main.route('/ctrl_FI_<actuator>/<tid>', methods=['GET', 'POST'])
- def ctrl_FI(actuator, tid):
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
- if actuator == 'Vacuum':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
- tank_actuator = ferment_input_actuator.query.filter_by(tank_num='FI'+str(tid)).order_by(text('datetime desc')).first()
- tank_vacuum = tank_actuator.vacuum
- tank_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num='FI'+str(tid)).order_by(text('datetime desc')).first()
- UltraSonic = tank_UltraSonic.UltraSonic
- return render_template('ctrl_FI_Vacuum.html', title='[操作]FI' + tid + '發酵入料儲豆槽_真空吸料機', **locals())
- elif request.method == 'POST':
- pass
- @main.route('/ctrl_FO_<actuator>/<tid>', methods=['GET', 'POST'])
- def ctrl_FO(actuator, tid):
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
- if actuator == 'Vacuum':
- tank_actuator = ferment_output_actuator.query.filter_by(tank_num='FO'+str(tid)).order_by(text('datetime desc')).first()
- tank_vacuum = tank_actuator.vacuum
- tank_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num='FO'+str(tid)).order_by(text('datetime desc')).first()
- UltraSonic = tank_UltraSonic.UltraSonic
- return render_template('ctrl_FO_Vacuum.html', title='[操作]FO' + tid + '發酵出料儲豆槽_真空吸料機', **locals())
- elif request.method == 'POST':
- pass
- @main.route('/ctrl_F_<actuator>/<tid>', methods=['GET', 'POST'])
- def ctrl_F(actuator, tid):
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
- tank_actuator = ferment_tank_actuator.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- if actuator == 'Vacuum':
- tank_vacuum = tank_actuator.vacuum
- tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num='F'+str(tid)).order_by(text('datetime desc')).first()
- LiDAR = tank_LiDAR.LiDAR
- return render_template('ctrl_F_Vacuum.html', title='[操作]F' + tid + '發酵槽_真空吸料機', **locals())
- elif actuator == 'ThreeWayValveInput':
- tank_threewayvalveinput = tank_actuator.threewayvalve_input
- return render_template('ctrl_F_ThreeWayValveInput.html', title='[操作]F' + tid + '發酵槽_入料三通閥', **locals())
- elif actuator == 'SolenoidWaterTotal':
- tank_solenoid_tank_water_total = tank_actuator.solenoid_tank_water_total
- return render_template('ctrl_F_SolenoidWaterTotal.html', title='[操作]F' + tid + '發酵槽_總進水電磁閥', **locals())
- elif actuator == 'SolenoidOuterWater':
- tank_solenoid_outer_water = tank_actuator.solenoid_outer_water
- tank_WaterLevel = ferment_tank_WaterLevel.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
- WaterLevel = tank_WaterLevel.WaterLevel
- return render_template('ctrl_F_SolenoidOuterWater.html', title='[操作]F' + tid + '發酵槽_保溫夾層進水電磁閥', **locals())
- elif actuator == 'SolenoidWaterIn':
- tank_solenoid_tank_water_in = tank_actuator.solenoid_tank_water_in
- tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
- PressureWaterLevel = tank_PressureWaterLevel.PressureWaterLevel
- return render_template('ctrl_F_SolenoidWaterIn.html', title='[操作]F' + tid + '發酵槽_桶內進水電磁閥', **locals())
- elif actuator == 'PumpSensor':
- tank_pump_sensor = tank_actuator.pump_sensor
- tank_PH = ferment_tank_PH.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
- tank_ORP = ferment_tank_ORP.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
- tank_DO = ferment_tank_DO.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
- tank_EC = ferment_tank_EC.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
- PH = tank_PH.PH
- ORP = tank_ORP.ORP
- DO = tank_DO.DO
- EC = tank_EC.EC
- return render_template('ctrl_F_PumpSensor.html', title='[操作]F' + tid + '發酵槽_感測器抽水雙核隔膜泵', **locals())
- elif actuator == 'ThreeWayValveBean':
- tank_threewayvalve_bean = tank_actuator.threewayvalve_bean
- return render_template('ctrl_F_ThreeWayValveBean.html', title='[操作]F' + tid + '發酵槽_感測模組下豆三通閥', **locals())
- elif actuator == 'ThreeWayValveFloat':
- tank_threewayvalve_outer_float = tank_actuator.threewayvalve_outer_float
- return render_template('ctrl_F_ThreeWayValveFloat.html', title='[操作]F' + tid + '發酵槽_外桶浮選三通閥', **locals())
- elif actuator == 'SolenoidDisinfect':
- tank_solenoid_tank_disinfect = tank_actuator.solenoid_tank_disinfect
- return render_template('ctrl_F_SolenoidDisinfect.html', title='[操作]F' + tid + '發酵槽_桶內消毒電磁閥', **locals())
- elif actuator == 'Motor':
- tank_motor = tank_actuator.motor
- return render_template('ctrl_F_Motor.html', title='[操作]F' + tid + '發酵槽_馬達', **locals())
- elif actuator == 'Heater1':
- tank_heater1 = tank_actuator.heater1
- tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
- return render_template('ctrl_F_Heater1.html', title='[操作]F' + tid + '發酵槽_加熱器 1', **locals())
- elif actuator == 'Heater2':
- tank_heater2 = tank_actuator.heater2
- tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
- return render_template('ctrl_F_Heater2.html', title='[操作]F' + tid + '發酵槽_加熱器 2', **locals())
- elif actuator == 'TempEnable':
- tank_temp_enable = tank_actuator.temp_enable
- return render_template('ctrl_F_TempEnable.html', title='[操作]F' + tid + '發酵槽_溫控開關', **locals())
- elif actuator == 'Temp':
- tank_temp = tank_actuator.temp
- tank_temp_enable = tank_actuator.temp_enable
- tank_SHT11 = ferment_tank_SHT11.query.filter_by(tank_num='F' + tid).order_by(text('datetime desc')).first()
- return render_template('ctrl_F_Temp.html', title='[操作]F' + tid + '發酵槽_溫度設定', **locals())
- elif actuator == 'DiskValve':
- tank_diskvalve = tank_actuator.diskvalve
- return render_template('ctrl_F_DiskValve.html', title='[操作]F' + tid + '發酵槽_蝴蝶閥', **locals())
- @main.route('/dry_Temp/<tid>/<Temp_Weights_SHT11>/<Temp_Weights_Soil>/<temp_data>', methods=['GET', 'POST'])
- def dry_Temp(tid, Temp_Weights_SHT11, Temp_Weights_Soil, temp_data):
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
- tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- SHT11_Temp = float(tank_SHT11.SHT11_Temp)
- SHT11_Humidity = tank_SHT11.SHT11_Humidity
- tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- Soil_Temp = float(tank_Soil.soil_Temp)
- Soil_Humidity = tank_Soil.soil_Humidity
- Temp_Weights_SHT11= float(Temp_Weights_SHT11)
- Temp_Weights_Soil = float(Temp_Weights_Soil)
- temp_data = float(temp_data)
- present_temp = math.ceil( (SHT11_Temp*Temp_Weights_SHT11 + Soil_Temp*Temp_Weights_Soil)/(Temp_Weights_SHT11+Temp_Weights_Soil) )
- # Math.round((present_SHT11_Temp*Temp_Weights_SHT11 + present_SOIL_Temp*Temp_Weights_Soil)/(Temp_Weights_SHT11+Temp_Weights_Soil)*100) / 100
- target_temp = math.ceil(temp_data)
- TempUp = {
- 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
- }
- if target_temp in TempUp and present_temp in TempUp:
- TempUpTime = ', 預計 ' + str(TempUp[target_temp] - TempUp[present_temp]) + ' 秒達到指定溫度'
- elif target_temp < 22 or present_temp < 22 :
- TempUpTime = '℃, 指定溫度過低, 持續升溫中'
- elif target_temp > 44 or present_temp > 44 :
- TempUpTime = '℃, 指定溫度過高, 持續升溫中'
-
- return jsonify({"SHT11_Temp":SHT11_Temp,
- "SHT11_Humidity":SHT11_Humidity,
- "Soil_Temp":Soil_Temp,
- "Soil_Humidity":Soil_Humidity,
- "present_temp":present_temp,
- "TempUpTime":TempUpTime
- })
- else:
- pass
- @main.route('/dry_container_tank/<tid>', methods=['GET', 'POST'])
- def dry_container_tank(tid):
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
- tonow = dt.now()
- print("tonow: ", tonow)
- time_del = timedelta(minutes=-60)
- bias_date_time = tonow + time_del
- # print(dt.now() >= dt(2021,11,29,17,35,36))
- # bias_min = tonow.minute + 3
- # 感測器_乾燥桶_SHT11
- tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid))\
- .filter(dry_tank_SHT11.datetime >= bias_date_time)\
- .order_by(text('datetime desc')).first()
- # 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'>
- if not hasattr(object, 'tank_SHT11'):
- tank_SHT11 = {"SHT11_Temp":" — ", "SHT11_Humidity":" — "}
- print(tank_SHT11["SHT11_Temp"])
- # 感測器_乾燥桶_土壤三合一
- tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- if not hasattr(object, 'tank_Soil'):
- tank_Soil = {"soil_Temp":" — ", "soil_Humidity":" — ", "soil_EC":" — "}
- # 感測器_乾燥桶_氣壓
- tank_PA = dry_tank_PA.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- if not hasattr(object, 'tank_PA'):
- tank_PA = {"PA":" — "}
- # 感測器_乾燥桶_超音波感測器
- tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- if not hasattr(object, 'tank_UltraSonic'):
- tank_UltraSonic = {"UltraSonic":" — "}
- # 致動器_乾燥桶_ALL
- tank_brake = dry_tank_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- tank_vacuum = tank_brake.vacuum
- tank_threewayvalve_input = tank_brake.threewayvalve_input
- tank_threewayvalve_bean = tank_brake.threewayvalve_bean
- tank_diskvalve = tank_brake.diskvalve
- tank_solenoid_disinfect = tank_brake.solenoid_disinfect
- tank_solenoid_water = tank_brake.solenoid_water
- tank_solenoid_outer_water = tank_brake.solenoid_outer_water
- tank_motor = tank_brake.motor
- tank_blower = tank_brake.blower
- tank_heater1 = tank_brake.heater1
- tank_heater2 = tank_brake.heater2
- tank_temp1_enable = tank_brake.temp1_enable
- tank_temp1 = tank_brake.temp1
- # Temp_weight = num_SHT11_temp * 0.5 + num_Soil_temp * 0.5
- return render_template('dry_container_tank.html', title='[操作] D' + tid + ' 乾燥槽操作介面', **locals())
- elif request.method == 'POST':
- pass
- @main.route('/dry_container_input/<tid>', methods=['GET', 'POST'])
- def dry_container_input(tid):
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
-
- input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI'+str(tid)).order_by(text('datetime desc')).first()
- input_vacuum = dry_input_brake.query.filter_by(tank_num='DI'+str(tid)).order_by(text('datetime desc')).first()
- input_vacuum = input_vacuum.vacuum
- return render_template('dry_container_input.html', title='[操作] DI' + tid + ' 乾燥入料儲豆槽操作介面', **locals())
- elif request.method == 'POST':
- pass
- @main.route('/dry_container_output/<tid>', methods=['GET', 'POST'])
- def dry_container_output(tid):
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
-
- output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO'+str(tid)).order_by(text('datetime desc')).first()
- output_vacuum = dry_output_brake.query.filter_by(tank_num='DO'+str(tid)).order_by(text('datetime desc')).first()
- output_vacuum = output_vacuum.vacuum
- return render_template('dry_container_output.html', title='[操作] DO' + tid + ' 乾燥出料儲豆槽操作介面', **locals())
- elif request.method == 'POST':
- pass
- # 原本的乾燥貨櫃控制, 備份用
- @main.route('/dry_container/<tid>', methods=['GET', 'POST'])
- def dry_container(tid):
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- username = session['uname']
- status = session['status']
- if status == 9:
- return render_template('signin_disable.html')
- elif status == 8:
- return render_template('signin_new.html')
- else:
- return render_template('oops.html')
- # Rita 參數 params 是用來取得參數的 locals=() 所有參數
- '''
- # 開啟本機 coffeetest 資料庫
- # mydb = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='g53743001', database='coffeetest', charset='utf8')
- mydb = pymysql.connect(host='52.69.200.169', port=3306, user='coffee',
- password='skyeye', database='Coffee', charset='utf8')
- mycursor = mydb.cursor()
- '''
- # 感測器_乾燥桶_SHT11
- tank_SHT11 = dry_tank_SHT11.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- num_SHT11_temp = float(tank_SHT11.SHT11_Temp)
- # 感測器_乾燥桶_土壤三合一
- tank_Soil = dry_tank_Soil.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- num_Soil_temp = float(tank_Soil.soil_Temp)
- # 感測器_乾燥桶_氣壓
- tank_PA = dry_tank_PA.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- # 感測器_乾燥桶_超音波感測器
- tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- # 感測器_出料儲豆槽_超音波感測器
- output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- # 致動器_乾燥桶_ALL
- tank_brake = dry_tank_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- tank_vacuum = tank_brake.vacuum
- tank_threewayvalve_input = tank_brake.threewayvalve_input
- tank_threewayvalve_bean = tank_brake.threewayvalve_bean
- tank_diskvalve = tank_brake.diskvalve
- tank_solenoid_disinfect = tank_brake.solenoid_disinfect
- tank_solenoid_water = tank_brake.solenoid_water
- tank_motor = tank_brake.motor
- tank_blower = tank_brake.blower
- tank_heater1 = tank_brake.heater1
- tank_heater2 = tank_brake.heater2
- tank_temp1_enable = tank_brake.temp1_enable
- tank_temp1 = tank_brake.temp1
- '''
- tank_vacuum = 'ON' if tank_brake.vacuum == 1 else 'OFF'
- tank_threewayvalve = 'ON' if tank_brake.threewayvalve == 1 else 'OFF'
- tank_diskvalve = 'ON' if tank_brake.diskvalve == 1 else 'OFF'
- tank_solenoid_disinfect = 'ON' if tank_brake.solenoid_disinfect == 1 else 'OFF'
- tank_solenoid_water = 'ON' if tank_brake.solenoid_water == 1 else 'OFF'
- tank_motor = tank_brake.motor
- tank_blower = 'ON' if tank_brake.blower == 1 else 'OFF'
- tank_heater1 = 'ON' if tank_brake.heater1 == 1 else 'OFF'
- tank_heater2 = 'ON' if tank_brake.heater2 == 1 else 'OFF'
- tank_temp1_enable = 'ON' if tank_brake.temp1_enable == 1 else 'OFF'
- tank_temp1 = tank_brake.temp1
- '''
- '''
- data = mycursor.execute(
- 'SELECT * FROM dry_tank_brake ORDER BY datetime DESC;')
- data = mycursor.fetchone()
- '''
- if tid in ['1', '2', '3', '4', '5', '6']:
- # print("1")
- # 感測器_入料儲豆槽_超音波感測器
- input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI1').order_by(text('datetime desc')).first()
- # 致動器_入料儲豆槽_真空吸引機
- input_vacuum = dry_input_brake.query.filter_by(tank_num='DI1').order_by(text('datetime desc')).first()
- input_vacuum = input_vacuum.vacuum
- # 感測器_出料儲豆槽_超音波感測器
- output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO1').order_by(text('datetime desc')).first()
- # 致動器_出料儲豆槽_真空吸引機
- output_vacuum = dry_output_brake.query.filter_by(tank_num='DO1').order_by(text('datetime desc')).first()
- output_vacuum = output_vacuum.vacuum
- elif tid in ['7', '8', '9', '10', '11', '12']:
- print("2")
- # 感測器_入料儲豆槽_超音波感測器
- input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='DI2').order_by(text('datetime desc')).first()
- # 致動器_入料儲豆槽_真空吸引機
- input_vacuum = dry_input_brake.query.filter_by(tank_num='DI2').order_by(text('datetime desc')).first()
- input_vacuum = input_vacuum.vacuum
- # 感測器_出料儲豆槽_超音波感測器
- output_UltraSonic = dry_output_sensor.query.filter_by(tank_num='DO2').order_by(text('datetime desc')).first()
- # 致動器_出料儲豆槽_真空吸引機
- output_vacuum = dry_output_brake.query.filter_by(tank_num='DO2').order_by(text('datetime desc')).first()
- output_vacuum = output_vacuum.vacuum
- '''
- # 感測器_入料儲豆槽_超音波感測器
- input_UltraSonic = dry_input_sensor.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- # 致動器_入料儲豆槽_真空吸引機
- input_vacuum = dry_input_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- # print("input_vacuum:", input_vacuum)
- input_vacuum = input_vacuum.vacuum
- #print('input_vacuum:', input_vacuum.vacuum)
- # 致動器_出料儲豆槽_真空吸引機
- output_vacuum = dry_output_brake.query.filter_by(tank_num='D'+str(tid)).order_by(text('datetime desc')).first()
- #print('output_vacuum.vacuum: ', output_vacuum.vacuum)
- output_vacuum = 'ON' if (output_vacuum.vacuum == 1) else 'OFF'
- #print('output_vacuum: ', output_vacuum)
- '''
- # 傳 MQTT 給阿超, 阿超讓硬體動作, 將資料儲存到資料庫
- input_data = set_dry_input.query.order_by(text('datetime desc')).first()
- schedule_input_height = input_data.input_height
- schedule_input_entertime = input_data.input_entertime
- schedule_input_exittime = input_data.input_exittime
- schedule_tank_height = input_data.tank_height
- return render_template('dry_container.html', title='dry_container', **locals())
- elif request.method == 'POST':
- # 表單輸入處
- print('/dry_input_setting POST')
- set = set_dry_input()
- set.input_height = request.form['schedule_input_height']
- set.input_entertime = request.form['schedule_input_entertime']
- set.input_exittime = request.form['schedule_input_exittime']
- set.tank_height = request.form['schedule_tank_height']
- #將數據保存進資料庫 - 註冊
- db.session.add(set)
- # 手動提交,目的是為了獲取提交後的user的id
- db.session.commit()
- # 當user成功插入進資料庫之後,程序會自動將所有信息取出來在賦值給user
- # 完成登入的操作
- # setting = Set_dry_input.query.order_by(text('datetime desc')).first()
- #session['id'] = set.userID
- #session['uname'] = set.username
- return redirect('/dry_container')
- # 登入頁面的訪問路徑
- @main.route('/login', methods=['GET', 'POST'])
- def login_views():
- if request.method == 'GET':
- if 'id' in session and 'uname' in session and 'status' in session:
- return redirect('/')
- else:
- return render_template('sign_in.html')
- else:
- # 接收前端傳過來的資料
- username = request.form['username']
- password = request.form['password']
- # 使用接收的用戶和密碼到資料庫中查詢
- user = User.query.filter_by(
- username=username, password=password).first()
- # 如果用戶存在,將信息保存置session並重定向回首頁,否則重定向回登入頁
- if user:
- resp = redirect('/')
- # 判斷是否有記住密碼
- if 'rem' in request.form:
- userID = str(user.userID)
- max_age = 60*60*24*365
- status = str(user.status)
- print('status: ', status)
- # Rita 以秒為單位, 一年
- # Rita 功能和 expires 很像,但此參數並非所有瀏覽器均支持,所以建議使用 expires 參數。
- # Rita expires:指定 Cookie 的有效日期, 當過了有效日期後就不會儲存在瀏覽器
- resp.set_cookie("username", username, max_age=max_age)
- resp.set_cookie("userID", userID, max_age=max_age)
- resp.set_cookie("status", status, max_age=max_age)
- session['uname'] = user.username
- session['id'] = user.userID
- session['status'] = user.status
- return resp
- else:
- errMsg = "Wrong login or password"
- return render_template('sign_in.html', errMsg=errMsg)
- # 登入重設密碼的頁面
- # Rita reset_pwd1 - Email
- # Rita reset_pwd2 - New password / Confirm password
- @main.route('/reset_password', methods=['POST', 'GET'])
- def reset_password_views():
- if request.method == 'GET':
- if 'mail' in session:
- del session['mail']
- return render_template('reset_pwd1.html')
- else:
- # POST
- # 如果有id在session裡,代表從reset_pwd2過來的 ? 對, reset_pwd2 POST (但也有其他可能)
- if "mail" in session:
- new_pwd = request.form['new_pwd']
- confirm_pwd = request.form['confirm_pwd']
- # 判斷密碼是否一致
- if new_pwd == confirm_pwd:
- mail = session['mail']
- user = User.query.filter_by(mail=mail).first()
- print("user: ", user)
- print("user.password_before: ", user.password)
- print("new_pwd: ", new_pwd)
- user.password = new_pwd
- print("user.password_after: ", user.password)
- db.session.add(user)
- db.session.commit()
- del session['mail']
- # 修改完後回登入頁
- return redirect('/login')
- else:
- # Rita errMsg 是指網頁上的 {{errMsg}} 位置
- errMsg = "Passwords does not match"
- return render_template('reset_pwd2.html', errMsg=errMsg)
- email = request.form['email']
- user = User.query.filter_by(mail=email).first()
- if user: # Rita 有找到對應 email
- session['mail'] = user.mail
- return render_template('reset_pwd2.html')
- else:
- errMsg = "Wrong email.Please try again"
- return render_template('reset_pwd1.html', errMsg=errMsg)
- # 註冊頁面的訪問路徑
- @main.route('/register', methods=['POST', "GET"])
- def register_views():
- if request.method == 'GET':
- return render_template('registration.html')
- else:
- # 獲取文本框的值並賦值給user實體對象
- user = User()
- user.firstname = request.form['firstname']
- user.lastname = request.form['lastname']
- user.mail = request.form['email']
- user.phone = request.form['phone']
- user.username = request.form['username']
- user.password = request.form['password']
- user.status = 8 # Rita app\models.py 設定 0:admin;1:new;9:disable [0906 更新] 0:admin;1:superuser;2:enduser;8:new;9:disable
- #將數據保存進資料庫 - 註冊
- db.session.add(user)
- # 手動提交,目的是為了獲取提交後的user的id
- db.session.commit()
- # 當user成功插入進資料庫之後,程序會自動將所有信息取出來在賦值給user
- # 完成登入的操作
- user = User.query.filter_by(username=user.username).first()
- session['status'] = user.status
- session['id'] = user.userID
- session['uname'] = user.username
- return redirect('/')
- # 驗證email訪問路徑
- @main.route('/check_email')
- def check_email_views():
- email = request.args['email']
- user = User.query.filter_by(mail=email).first()
- if user:
- # Rita email 錯誤時會顯示 Incorrect email address
- result = {"errMsg": " "}
- else:
- result = {"pass": " "}
- return json.dumps(result)
- # 驗證username訪問路徑
- @main.route('/check_username')
- def check_username_views():
- username = request.args['username']
- user = User.query.filter_by(username=username).first()
- if user:
- result = {"errMsg": " "}
- else:
- result = {"pass": " "}
- return json.dumps(result)
- # 咖啡貨櫃的訪問路徑
- @main.route('/cargo_list', methods=['GET', 'POST'])
- def cargo_list_views():
- username = session['uname']
- if request.method == 'GET':
- return render_template('cargo_list.html', params=locals())
- else:
- pass
- # 貨櫃1的訪問路徑
- @main.route('/cargo1', methods=['GET', 'POST'])
- def cargo1_views():
- username = session['uname']
- if request.method == 'GET':
- return render_template('cargo1.html', params=locals())
- else:
- pass
- # 貨櫃1排程的訪問路徑
- @main.route('/cargo1_schedule', methods=['GET', 'POST'])
- def cargo1_schedule_views():
- username = session['uname']
- if request.method == 'GET':
- # 將已儲存的排程資料傳給前端
- # 進豆閥
- try:
- bean = BeanValve.query.order_by(text('datetime desc')).first()
- datetime = bean.datetime
- beans = BeanValve.query.filter_by(
- datetime=datetime).all()
- except Exception as e:
- pass
- # 清洗機
- try:
- wash = WashMachine.query.order_by(text('datetime desc')).first()
- datetime = wash.datetime
- washes = WashMachine.query.filter_by(datetime=datetime).all()
- except Exception as e:
- pass
- # 輸送帶1
- try:
- belt1 = ConveyorBelt1.query.order_by(text('datetime desc')).first()
- datetime = belt1.datetime
- belts1 = ConveyorBelt1.query.filter_by(datetime=datetime).all()
- except Exception as e:
- pass
- # ///////////////////////////////////////////////////////////////////////////////////////////
- # 消毒機
- try:
- disinfect = Cargo1Disinfect.query.order_by(
- text('datetime desc')).first()
- datetime = disinfect.datetime
- disinfects = Cargo1Disinfect.query.filter_by(
- datetime=datetime).all()
- except Exception as e:
- pass
- # 色選機
- try:
- color = ColorMachine.query.order_by(text('datetime desc')).first()
- datetime = color.datetime
- colors = ColorMachine.query.filter_by(datetime=datetime).all()
- except Exception as e:
- pass
- # 輸送帶2
- try:
- belt2 = ConveyorBelt2.query.order_by(text('datetime desc')).first()
- datetime = belt2.datetime
- belts2 = ConveyorBelt2.query.filter_by(datetime=datetime).all()
- except Exception as e:
- pass
- # 去皮機
- try:
- peeling = PeelingMachine.query.order_by(
- text('datetime desc')).first()
- datetime = peeling.datetime
- peelings = PeelingMachine.query.filter_by(datetime=datetime).all()
- except Exception as e:
- pass
- # 輸送帶3
- try:
- belt3 = ConveyorBelt3.query.order_by(text('datetime desc')).first()
- datetime = belt3.datetime
- belts3 = ConveyorBelt3.query.filter_by(datetime=datetime).all()
- except Exception as e:
- pass
- return render_template('cargo1_schedule.html', params=locals())
- else:
- current_time = dt.now()
- # 循環從前端提交過來的資料
- for i in request.form:
- # 進豆閥
- if i[:10] == 'inletValve':
- if i[:19] == 'inletValve_duration':
- bean = BeanValve()
- bean.duration = request.form[i]
- elif i[:18] == 'inletValve_from_hr':
- iv_from_hr = request.form[i]
- elif i[:19] == 'inletValve_from_min':
- iv_from_min = request.form[i]
- bean.start = iv_from_hr + ":" + iv_from_min
- elif i[:16] == 'inletValve_to_hr':
- iv_to_hr = request.form[i]
- elif i[:17] == 'inletValve_to_min':
- iv_to_min = request.form[i]
- bean.end = iv_to_hr + ":" + iv_to_min
- bean.datetime = current_time
- db.session.add(bean)
- db.session.commit()
- # 清洗機
- elif i[:4] == 'wash':
- if i[:13] == 'wash_duration':
- wash = WashMachine()
- wash.duration = request.form[i]
- elif i[:12] == 'wash_from_hr':
- wash_from_hr = request.form[i]
- elif i[:13] == 'wash_from_min':
- wash_from_min = request.form[i]
- wash.start = wash_from_hr + ":" + wash_from_min
- elif i[:10] == 'wash_to_hr':
- wash_to_hr = request.form[i]
- elif i[:11] == 'wash_to_min':
- wash_to_min = request.form[i]
- wash.end = wash_to_hr + ":" + wash_to_min
- wash.datetime = current_time
- db.session.add(wash)
- db.session.commit()
- # 輸送帶1
- elif i[:5] == 'belt1':
- if i[:14] == 'belt1_duration':
- belt1 = ConveyorBelt1()
- belt1.duration = request.form[i]
- elif i[:13] == 'belt1_from_hr':
- belt1_from_hr = request.form[i]
- elif i[:14] == 'belt1_from_min':
- belt1_from_min = request.form[i]
- belt1.start = belt1_from_hr + ":" + belt1_from_min
- elif i[:11] == 'belt1_to_hr':
- belt1_to_hr = request.form[i]
- elif i[:12] == 'belt1_to_min':
- belt1_to_min = request.form[i]
- belt1.end = belt1_to_hr + ":" + belt1_to_min
- belt1.datetime = current_time
- db.session.add(belt1)
- db.session.commit()
- # 消毒
- elif i[:9] == 'disinfect':
- if i[:18] == 'disinfect_duration':
- disinfect = Cargo1Disinfect()
- disinfect.duration = request.form[i]
- elif i[:17] == 'disinfect_from_hr':
- di_from_hr = request.form[i]
- elif i[:18] == 'disinfect_from_min':
- di_from_min = request.form[i]
- disinfect.start = di_from_hr + ":" + di_from_min
- elif i[:15] == 'disinfect_to_hr':
- di_to_hr = request.form[i]
- elif i[:16] == 'disinfect_to_min':
- di_to_min = request.form[i]
- disinfect.end = di_to_hr + ":" + di_to_min
- disinfect.datetime = current_time
- db.session.add(disinfect)
- db.session.commit()
- # 色選機
- elif i[:5] == 'color':
- if i[:14] == 'color_duration':
- color = ColorMachine()
- color.duration = request.form[i]
- elif i[:13] == 'color_from_hr':
- color_from_hr = request.form[i]
- elif i[:14] == 'color_from_min':
- color_from_min = request.form[i]
- color.start = color_from_hr + ":" + color_from_min
- elif i[:11] == 'color_to_hr':
- color_to_hr = request.form[i]
- elif i[:12] == 'color_to_min':
- color_to_min = request.form[i]
- color.end = color_to_hr + ":" + color_to_min
- color.datetime = current_time
- db.session.add(color)
- db.session.commit()
- # 輸送帶2
- elif i[:5] == 'belt2':
- if i[:14] == 'belt2_duration':
- belt2 = ConveyorBelt2()
- belt2.duration = request.form[i]
- elif i[:13] == 'belt2_from_hr':
- belt2_from_hr = request.form[i]
- elif i[:14] == 'belt2_from_min':
- belt2_from_min = request.form[i]
- belt2.start = belt2_from_hr + ":" + belt2_from_min
- elif i[:11] == 'belt2_to_hr':
- belt2_to_hr = request.form[i]
- elif i[:12] == 'belt2_to_min':
- belt2_to_min = request.form[i]
- belt2.end = belt2_to_hr + ":" + belt2_to_min
- belt2.datetime = current_time
- db.session.add(belt2)
- db.session.commit()
- # 去皮機
- elif i[:6] == 'peeled':
- if i[:15] == 'peeled_duration':
- peeling = PeelingMachine()
- peeling.duration = request.form[i]
- elif i[:14] == 'peeled_from_hr':
- peeled_from_hr = request.form[i]
- elif i[:15] == 'peeled_from_min':
- peeled_from_min = request.form[i]
- peeling.start = peeled_from_hr + ":" + peeled_from_min
- elif i[:12] == 'peeled_to_hr':
- peeled_to_hr = request.form[i]
- elif i[:13] == 'peeled_to_min':
- peeled_to_min = request.form[i]
- peeling.end = peeled_to_hr + ":" + peeled_to_min
- peeling.datetime = current_time
- db.session.add(peeling)
- db.session.commit()
- # 輸送帶3
- elif i[:5] == 'belt3':
- if i[:14] == 'belt3_duration':
- belt3 = ConveyorBelt3()
- belt3.duration = request.form[i]
- elif i[:13] == 'belt3_from_hr':
- belt3_from_hr = request.form[i]
- elif i[:14] == 'belt3_from_min':
- belt3_from_min = request.form[i]
- belt3.start = belt3_from_hr + ":" + belt3_from_min
- elif i[:11] == 'belt3_to_hr':
- belt3_to_hr = request.form[i]
- elif i[:12] == 'belt3_to_min':
- belt3_to_min = request.form[i]
- belt3.end = belt3_to_hr + ":" + belt3_to_min
- belt3.datetime = current_time
- db.session.add(belt3)
- db.session.commit()
- return render_template('cargo1.html', params=locals())
- # 貨櫃2的訪問路徑
- @main.route('/cargo2', methods=['GET', 'POST'])
- def cargo2_views():
- username = session['uname']
- if request.method == 'GET':
- return render_template('cargo2.html', params=locals())
- else:
- pass
- # 貨櫃2排程的發酵槽訪問路徑
- @main.route('/cargo2_schedule_tanks', methods=['GET', 'POST'])
- def cargo2_schedule_tanks_views():
- username = session['uname']
- if request.method == 'GET':
- return render_template('cargo2_schedule_tanks.html', params=locals())
- else:
- pass
- # 貨櫃2排程發酵槽的清單訪問路徑
- @main.route('/cargo2_schedule/<tid>', methods=['GET', 'POST'])
- def cargo2_schedule_views(tid):
- username = session['uname']
- if request.method == 'GET':
- # 將已儲存的排程資料傳給前端
- # 打菌
- try:
- bacteria = Bacteria.query.filter_by(tank_num=int(
- tid)).order_by(text('datetime desc')).first()
- datetime = bacteria.datetime
- bacterias = Bacteria.query.filter_by(datetime=datetime).all()
- except Exception as e:
- pass
- # 消毒
- try:
- disinfect = Cargo2Disinfect.query.filter_by(
- tank_num=int(tid)).order_by(text('datetime desc')).first()
- datetime = disinfect.datetime
- disinfects = Cargo2Disinfect.query.filter_by(
- datetime=datetime).all()
- except Exception as e:
- pass
- # 加熱
- try:
- heating = Heating.query.filter_by(tank_num=int(
- tid)).order_by(text('datetime desc')).first()
- datetime = heating.datetime
- heatings = Heating.query.filter_by(datetime=datetime).all()
- except Exception as e:
- pass
- # 攪拌
- try:
- stir = Stir.query.filter_by(tank_num=int(tid)).order_by(
- text('datetime desc')).first()
- datetime = stir.datetime
- stirs = Stir.query.filter_by(datetime=datetime).all()
- except Exception as e:
- pass
- # 注水
- try:
- water = WaterInjection.query.filter_by(
- tank_num=int(tid)).order_by(text('datetime desc')).first()
- datetime = water.datetime
- waters = WaterInjection.query.filter_by(datetime=datetime).all()
- except Exception as e:
- pass
- # 開上閥
- try:
- top = TopValve.query.filter_by(tank_num=int(
- tid)).order_by(text('datetime desc')).first()
- datetime = top.datetime
- tops = TopValve.query.filter_by(datetime=datetime).all()
- except Exception as e:
- pass
- # 開下閥
- try:
- bottom = BottomValve.query.filter_by(tank_num=int(
- tid)).order_by(text('datetime desc')).first()
- datetime = bottom.datetime
- bottoms = BottomValve.query.filter_by(datetime=datetime).all()
- except Exception as e:
- pass
- # 溫度
- try:
- tem = Temperature.query.filter_by(tank_num=int(
- tid)).order_by(text('datetime desc')).first()
- datetime = tem.datetime
- tems = Temperature.query.filter_by(datetime=datetime).all()
- except Exception as e:
- pass
- return render_template('cargo2_schedule.html', params=locals())
- else:
- current_time = dt.now()
- # 循環從前端提交過來的資料
- for i in request.form:
- # 打菌
- if i[:8] == 'bacteria':
- if i[:17] == 'bacteria_duration':
- bacteria = Bacteria()
- bacteria.duration = request.form[i]
- elif i[:16] == 'bacteria_from_hr':
- bac_from_hr = request.form[i]
- elif i[:17] == 'bacteria_from_min':
- bac_from_min = request.form[i]
- bacteria.start = bac_from_hr + ":" + bac_from_min
- elif i[:14] == 'bacteria_to_hr':
- bac_to_hr = request.form[i]
- elif i[:15] == 'bacteria_to_min':
- bac_to_min = request.form[i]
- bacteria.end = bac_to_hr + ":" + bac_to_min
- bacteria.datetime = current_time
- bacteria.tank_num = int(tid)
- db.session.add(bacteria)
- db.session.commit()
- # 消毒
- elif i[:9] == 'disinfect':
- if i[:18] == 'disinfect_duration':
- disinfect = Cargo2Disinfect()
- disinfect.duration = request.form[i]
- elif i[:17] == 'disinfect_from_hr':
- di_from_hr = request.form[i]
- elif i[:18] == 'disinfect_from_min':
- di_from_min = request.form[i]
- disinfect.start = di_from_hr + ":" + di_from_min
- elif i[:15] == 'disinfect_to_hr':
- di_to_hr = request.form[i]
- elif i[:16] == 'disinfect_to_min':
- di_to_min = request.form[i]
- disinfect.end = di_to_hr + ":" + di_to_min
- disinfect.datetime = current_time
- disinfect.tank_num = int(tid)
- db.session.add(disinfect)
- db.session.commit()
- # 加熱
- elif i[:7] == 'heating':
- if i[:16] == 'heating_duration':
- heating = Heating()
- heating.duration = request.form[i]
- elif i[:15] == 'heating_from_hr':
- heat_from_hr = request.form[i]
- elif i[:16] == 'heating_from_min':
- heat_from_min = request.form[i]
- heating.start = heat_from_hr + ":" + heat_from_min
- elif i[:13] == 'heating_to_hr':
- heat_to_hr = request.form[i]
- elif i[:14] == 'heating_to_min':
- heat_to_min = request.form[i]
- heating.end = heat_to_hr + ":" + heat_to_min
- heating.datetime = current_time
- heating.tank_num = int(tid)
- db.session.add(heating)
- db.session.commit()
- # 攪拌
- elif i[:4] == 'stir':
- if i[:13] == 'stir_duration':
- stir = Stir()
- stir.duration = request.form[i]
- elif i[:12] == 'stir_from_hr':
- stir_from_hr = request.form[i]
- elif i[:13] == 'stir_from_min':
- stir_from_min = request.form[i]
- stir.start = stir_from_hr + ":" + stir_from_min
- elif i[:10] == 'stir_to_hr':
- stir_to_hr = request.form[i]
- elif i[:11] == 'stir_to_min':
- stir_to_min = request.form[i]
- stir.end = stir_to_hr + ":" + stir_to_min
- stir.datetime = current_time
- stir.tank_num = int(tid)
- db.session.add(stir)
- db.session.commit()
- # 注水
- elif i[:5] == 'water':
- if i[:14] == 'water_duration':
- water = WaterInjection()
- water.duration = request.form[i]
- elif i[:13] == 'water_from_hr':
- water_from_hr = request.form[i]
- elif i[:14] == 'water_from_min':
- water_from_min = request.form[i]
- water.start = water_from_hr + ":" + water_from_min
- elif i[:11] == 'water_to_hr':
- water_to_hr = request.form[i]
- elif i[:12] == 'water_to_min':
- water_to_min = request.form[i]
- water.end = water_to_hr + ":" + water_to_min
- water.datetime = current_time
- water.tank_num = int(tid)
- db.session.add(water)
- db.session.commit()
- # 開上閥
- elif i[:9] == 'highValve':
- if i[:18] == 'highValve_duration':
- top = TopValve()
- top.duration = request.form[i]
- elif i[:17] == 'highValve_from_hr':
- h_valve_from_hr = request.form[i]
- elif i[:18] == 'highValve_from_min':
- h_valve_from_min = request.form[i]
- top.start = h_valve_from_hr + ":" + h_valve_from_min
- elif i[:15] == 'highValve_to_hr':
- h_valve_to_hr = request.form[i]
- elif i[:16] == 'highValve_to_min':
- h_valve_to_min = request.form[i]
- top.end = h_valve_to_hr + ":" + h_valve_to_min
- top.datetime = current_time
- top.tank_num = int(tid)
- db.session.add(top)
- db.session.commit()
- # 開下閥
- elif i[:8] == 'lowValve':
- if i[:17] == 'lowValve_duration':
- bottom = BottomValve()
- bottom.duration = request.form[i]
- elif i[:16] == 'lowValve_from_hr':
- l_valve_from_hr = request.form[i]
- elif i[:17] == 'lowValve_from_min':
- l_valve_from_min = request.form[i]
- bottom.start = l_valve_from_hr + ":" + l_valve_from_min
- elif i[:14] == 'lowValve_to_hr':
- l_valve_to_hr = request.form[i]
- elif i[:15] == 'lowValve_to_min':
- l_valve_to_min = request.form[i]
- bottom.end = l_valve_to_hr + ":" + l_valve_to_min
- bottom.datetime = current_time
- bottom.tank_num = int(tid)
- db.session.add(bottom)
- db.session.commit()
- # 溫度
- elif i[:3] == 'tem':
- if i[:12] == 'tem_duration':
- tem = Temperature()
- tem.duration = request.form[i]
- elif i[:11] == 'tem_from_hr':
- tem_from_hr = request.form[i]
- elif i[:12] == 'tem_from_min':
- tem_from_min = request.form[i]
- tem.start = tem_from_hr + ":" + tem_from_min
- elif i[:9] == 'tem_to_hr':
- tem_to_hr = request.form[i]
- elif i[:10] == 'tem_to_min':
- tem_to_min = request.form[i]
- tem.end = tem_to_hr + ":" + tem_to_min
- tem.datetime = current_time
- tem.tank_num = int(tid)
- db.session.add(tem)
- db.session.commit()
- return render_template('cargo2.html', params=locals())
- # 貨櫃2感測器的發酵槽訪問路徑
- @main.route('/cargo2_sensor_tanks', methods=['GET', 'POST'])
- def cargo2_sensor_tanks_views():
- username = session['uname']
- if request.method == 'GET':
- return render_template('cargo2_sensor_tanks.html', params=locals())
- else:
- pass
- # 貨櫃2感測器發酵槽的清單訪問路徑
- @main.route('/cargo2_sensor/<tid>', methods=['GET', 'POST'])
- def s_tank_views(tid):
- # 判斷用戶是否已關閉瀏覽器或登出後,在訪問這個route,如果沒有session就回登入頁
- try:
- username = session['uname']
- except KeyError:
- return redirect('/')
- if request.method == 'GET':
- # Rita 網頁端 params.tank_tem.tem
- # Coffee/CoffeeProject/app/templates/cargo2_sensor.html
- tank_tem = TankTemSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
- tank_ph = TankPHSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
- tank_ec = TankECSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
- tank_sonic = TankSonicSensor.query.filter_by(tank_num=int(tid)).order_by(text('datetime desc')).first()
- return render_template('cargo2_sensor.html', params=locals())
- else:
- pass
- # 貨櫃2感測器發酵槽歷史數據的訪問路徑
- @main.route('/history_data', methods=['GET', 'POST'])
- def history_data_views():
- if request.method == 'GET':
- # json
- # tid:tid_D1
- # sensor_name:soil_Temp
- # avg:1
- # max:1
- # min:1
- # time-interval:month
- # date-start:2021-07-01
- # date-end:2021-07-28
- info = request.args.to_dict()
- evt = info['evt']
- avg = int(info['avg'])
- max = int(info['max'])
- min = int(info['min'])
- time_interval = info['time-interval']
- print(info)
- # Rita {'evt': '1-溫濕度', 'avg': '1', 'max': '0', 'min': '0', 'time-interval': 'month',
- # 'date-start': '2021-05-04', 'date-end': '2021-05-18'} {'all': [], 'avg': []}
- # print(info)
- # {'evt': '1-溫濕度', 'avg': '1', 'max': '0', 'min': '0', 'time-interval': 'hour', 'date-start': '2021-01-01', 'date-end': '2021-07-27'}
- # print(D)
- # {'all': [['2021-Feb-19_16:46:10', '24.4'], ['2021-Feb-19_16:46:20', '24.4'], ['2021-Feb-19_16:46:30', '24.4'], ['2021-Feb-19_16:46:41', '24.4'], ['2021-Feb-19_16:46:50', '24.4'], ['2021-Feb-19_16:47:00', '24.4'], ['2021-Feb-19_16:47:10', '24.4'], ['2021-Feb-19_16:47:20', '24.4'], ['2021-Feb-19_16:47:30', '24.4'], ['2021-Feb-19_16:47:40', '24.5'], ['2021-Feb-19_16:47:50', '24.5'], ['2021-Feb-19_16:48:00', '24.5'], ['2021-Feb-19_16:48:10', '24.5'], ['2021-Feb-19_16:48:20', '24.5'], ['2021-Feb-19_16:48:29', '24.5'], ['2021-Feb-19_16:48:39', '24.5'], ['2021-Feb-19_16:48:50', '24.5'], ['2021-Feb-19_16:49:00', '24.5'], ['2021-Feb-19_16:49:10', '24.5'], ['2021-Feb-19_16:49:19', '24.5'], ['2021-Feb-19_16:49:29', '24.5'], ['2021-Feb-19_16:49:39', '24.5'], ['2021-Feb-19_16:49:49', '24.5'], ['2021-Feb-19_16:49:59', '24.5'], ['2021-Feb-19_16:50:10', '24.5'], ['2021-Feb-19_16:50:19', '24.5'], ['2021-Feb-19_16:50:29', '24.5'], ['2021-Feb-19_16:50:39', '24.5'], ['2021-Feb-19_16:50:49', '24.5'], ['2021-Feb-19_16:50:59', '24.5'], ['2021-Feb-19_18:07:10', '25.3'], ['2021-Feb-19_18:07:20', '25.3'], ['2021-Feb-19_18:07:30', '25.3'], ['2021-Feb-19_18:07:40', '25.3'], ['2021-Feb-19_18:07:49', '25.3'], ['2021-Feb-19_18:07:59', '25.3'], ['2021-Feb-19_18:08:10', '25.3'], ['2021-Feb-19_18:08:20', '25.3'], ['2021-Feb-19_18:08:30', '25.2'], ['2021-Feb-19_18:08:39', '25.2'], ['2021-Feb-19_18:08:49', '25.2']],
- # 'avg': [['2021-02-19 16:00:00', '24.5'], ['2021-02-19 18:00:00', '25.3']]}
- # 192.168.50.65 - - [27/Jul/2021 11:57:23] "GET /history_data?evt=1-溫濕度&avg=1&max=0&min=0&time-interval=hour&date-start=2021-01-01&date-end=2021-07-27 HTTP/1.1" 200 -
- date_start = info['date-start']
- date_end_list = info['date-end'].split('-') # 先把 'date-end' 的 '2021-05-18' 拆成 ['2021', '05', '18']
- date_end_list[2] = str(int(date_end_list[2]) + 1) # 18 + 1 = 19 再轉成 str → '19'
- date_end = '-'.join(date_end_list) # '2021-05-19'
- tank_num = evt.split('-')[0] # 1
- sensor = evt.split('-')[1] # 溫濕度
- L = []
- D = {}
- maxData = []
- minData = []
- avgData = []
- def sensorData(data_name): # data_name = "tem"
- def dataResample(time_interval, how, data_name): # dataResample('month', how???, "tem") # 下方 "hour"
- interval = 0
- # 設置resample的第一個參數,要按照逐月、逐日或逐時
- if time_interval == 'month':
- interval = "M" # interval = "M"
- elif time_interval == 'day':
- interval = "D"
- elif time_interval == 'hour':
- interval = "H"
- if how == "max":
- # data = df.resample(interval, how={data_name:how})
- # 最新版的pandas
- data = df.resample(interval).max() # 取樣頻率 "H"
- # 刪除有 NaN 的列, any 任何一欄位為空則刪 (all 全部欄位為空值才刪)
- data = data.dropna(axis=0, how='any')
-
- if time_interval == ('hour' or 'day'):
- data.index = pd.to_datetime(
- data.index, format='%Y-%b-%d_%H:%M:%S') # 将数据类型转换为日期类型
- for a in range(0, len(data.index)):
- l = []
- # 如果是逐時,才顯示小時分秒
- if time_interval == 'hour':
- l.append(str(data.index[a]))
- else:
- l.append(str(data.index[a]).split(' ')[0])
- l.append(str(data[data_name][a]))
- maxData.append(l)
- D['max'] = maxData
- elif how == "mean":
- # data = df.resample(interval, how={data_name:how})
- # 最新版的pandas
- data = df.resample(interval).mean()
- # 刪除具有NaN的值
- data = data.dropna(axis=0, how='any')
- # 將平均數取自小數1位
- data = data.round({data_name: 1})
- for a in range(0, len(data.index)):
- l = []
- # 如果是逐時,才顯示小時分秒
- if time_interval == 'hour':
- l.append(str(data.index[a]))
- else:
- l.append(str(data.index[a]).split(' ')[0])
- l.append(str(data[data_name][a]))
- avgData.append(l)
- D['avg'] = avgData
- elif how == "min":
- # data = df.resample(interval, how={data_name:how})
- # 最新版的pandas
- data = df.resample(interval).min()
- # 刪除具有NaN的值
- data = data.dropna(axis=0, how='any')
- for a in range(0, len(data.index)):
- # print(data.index[a])
- l = []
- # 如果是逐時,才顯示小時分秒
- if time_interval == 'hour':
- l.append(str(data.index[a]))
- else:
- l.append(str(data.index[a]).split(' ')[0])
- l.append(str(data[data_name][a]))
- minData.append(l)
- D['min'] = minData
- df = pd.DataFrame(L, columns=["datetime", data_name]) # 指定欄標籤名稱 為 ["datetime", "tem"]
- df['datetime'] = pd.to_datetime(
- df['datetime'], format='%Y-%b-%d_%H:%M:%S') # 将数据类型转换为日期类型
- # print(df['datetime']) # 0 2021-02-19 16:46:10
- # 1 2021-02-19 16:46:20
- # 2 2021-02-19 16:46:30
- # 3 2021-02-19 16:46:41
- df[data_name] = df[data_name].astype(float)
- df = df.set_index('datetime') # 将datetime设置为index
- # print(df) # datetime tem
- # 2021-02-19 16:46:10 24.4
- # 2021-02-19 16:46:20 24.4
- if time_interval == 'month':
- if max:
- dataResample(time_interval, "max", data_name)
- if avg:
- dataResample(time_interval, "mean", data_name)
- if min:
- dataResample(time_interval, "min", data_name)
- elif time_interval == 'day':
- if max:
- dataResample(time_interval, "max", data_name)
- if avg:
- dataResample(time_interval, "mean", data_name)
- if min:
- dataResample(time_interval, "min", data_name)
- elif time_interval == 'hour':
- if max:
- dataResample(time_interval, "max", data_name)
- if avg:
- dataResample(time_interval, "mean", data_name)
- if min:
- dataResample(time_interval, "min", data_name)
- if sensor == '溫濕度':
- # tank_tem = TankTemSensor.query.filter_by(tank_num=int(tank_num)).order_by(text('datetime desc')).all()
- # [7/27 Benson] tank_tem = TankTemSensor.query.filter_by(tank_num=int(tank_num)).filter(TankTemSensor.datetime.between(date_start, date_end)).all()
- tank_tem = dry_tank_SHT11.query.filter(dry_tank_SHT11.datetime.between(date_start, date_end)).all()
- # .filter_by(tank_num="D"+tank_num)
- for tem in tank_tem:
- l = [] # l = []
- time = dt.strftime(tem.datetime, '%Y-%b-%d_%H:%M:%S') # time = '2021-Feb-19_16:46:10' 轉換時間格式
- # time = dt.strftime(tem.datetime, '%Y-%m-%d')
- l.append(time) # l = ['2021-Feb-19_16:46:10']
- #l.append(tem.tem) # l = ['2021-Feb-19_16:46:10', '24.4']
- l.append(tem.SHT11_Temp)
- L.append(l) # L = [['2021-Feb-19_16:46:10', '24.4']]
- # print(L)
- D['all'] = L # D = {'all': [['2021-Feb-19_16:46:10', '24.4']]} # all 所有符合數據
- sensorData("tem")
- elif sensor == '酸鹼值':
- tank_ph = TankPHSensor.query.filter_by(tank_num=int(tank_num)).filter(
- TankPHSensor.datetime.between(date_start, date_end)).all()
- for ph in tank_ph:
- l = []
- time = dt.strftime(ph.datetime, '%Y-%b-%d_%H:%M:%S')
- # time = dt.strftime(tem.datetime, '%Y-%m-%d')
- l.append(time)
- l.append(ph.ph)
- L.append(l)
- # print(L)
- D['all'] = L
- sensorData("ph")
- elif sensor == 'EC值':
- tank_ec = TankECSensor.query.filter_by(tank_num=int(tank_num)).filter(
- TankECSensor.datetime.between(date_start, date_end)).all()
- for ec in tank_ec:
- l = []
- time = dt.strftime(ec.datetime, '%Y-%b-%d_%H:%M:%S')
- # time = dt.strftime(tem.datetime, '%Y-%m-%d')
- l.append(time)
- l.append(ec.ec)
- L.append(l)
- # print(L)
- D['all'] = L
- sensorData("ec")
- elif sensor == '超音波':
- tank_sonic = TankSonicSensor.query.filter_by(tank_num=int(tank_num)).filter(
- TankSonicSensor.datetime.between(date_start, date_end)).all()
- for sonic in tank_sonic:
- l = []
- time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
- # time = dt.strftime(tem.datetime, '%Y-%m-%d')
- l.append(time)
- l.append(sonic.sonic)
- L.append(l)
- # print(L)
- D['all'] = L
- sensorData("sonic")
- print(D)
- return json.dumps(D)
- else:
- pass
- # Rita 改寫
- @main.route('/history_data_new', methods=['GET', 'POST'])
- def history_data_new_views():
- if request.method == 'GET':
- # json
- # tid:tid_D1
- # sensor_name:soil_Temp
- # avg:1
- # max:1
- # min:1
- # time-interval:month
- # date-start:2021-07-01
- # date-end:2021-07-28
- info = request.args.to_dict()
- # evt = info['evt']
- tid = info['tid']
- sensor_name = info['sensor_name']
- avg = int(info['avg'])
- max = int(info['max'])
- min = int(info['min'])
- time_interval = info['time-interval']
- print("info:", info)
- # Rita {'evt': '1-溫濕度', 'avg': '1', 'max': '0', 'min': '0', 'time-interval': 'month',
- # 'date-start': '2021-05-04', 'date-end': '2021-05-18'} {'all': [], 'avg': []}
- # print(info)
- # {'evt': '1-溫濕度', 'avg': '1', 'max': '0', 'min': '0', 'time-interval': 'hour', 'date-start': '2021-01-01', 'date-end': '2021-07-27'}
- # print(D)
- # {'all': [['2021-Feb-19_16:46:10', '24.4'], ['2021-Feb-19_16:46:20', '24.4'], ['2021-Feb-19_16:46:30', '24.4'], ['2021-Feb-19_16:46:41', '24.4'], ['2021-Feb-19_16:46:50', '24.4'], ['2021-Feb-19_16:47:00', '24.4'], ['2021-Feb-19_16:47:10', '24.4'], ['2021-Feb-19_16:47:20', '24.4'], ['2021-Feb-19_16:47:30', '24.4'], ['2021-Feb-19_16:47:40', '24.5'], ['2021-Feb-19_16:47:50', '24.5'], ['2021-Feb-19_16:48:00', '24.5'], ['2021-Feb-19_16:48:10', '24.5'], ['2021-Feb-19_16:48:20', '24.5'], ['2021-Feb-19_16:48:29', '24.5'], ['2021-Feb-19_16:48:39', '24.5'], ['2021-Feb-19_16:48:50', '24.5'], ['2021-Feb-19_16:49:00', '24.5'], ['2021-Feb-19_16:49:10', '24.5'], ['2021-Feb-19_16:49:19', '24.5'], ['2021-Feb-19_16:49:29', '24.5'], ['2021-Feb-19_16:49:39', '24.5'], ['2021-Feb-19_16:49:49', '24.5'], ['2021-Feb-19_16:49:59', '24.5'], ['2021-Feb-19_16:50:10', '24.5'], ['2021-Feb-19_16:50:19', '24.5'], ['2021-Feb-19_16:50:29', '24.5'], ['2021-Feb-19_16:50:39', '24.5'], ['2021-Feb-19_16:50:49', '24.5'], ['2021-Feb-19_16:50:59', '24.5'], ['2021-Feb-19_18:07:10', '25.3'], ['2021-Feb-19_18:07:20', '25.3'], ['2021-Feb-19_18:07:30', '25.3'], ['2021-Feb-19_18:07:40', '25.3'], ['2021-Feb-19_18:07:49', '25.3'], ['2021-Feb-19_18:07:59', '25.3'], ['2021-Feb-19_18:08:10', '25.3'], ['2021-Feb-19_18:08:20', '25.3'], ['2021-Feb-19_18:08:30', '25.2'], ['2021-Feb-19_18:08:39', '25.2'], ['2021-Feb-19_18:08:49', '25.2']],
- # 'avg': [['2021-02-19 16:00:00', '24.5'], ['2021-02-19 18:00:00', '25.3']]}
- # 192.168.50.65 - - [27/Jul/2021 11:57:23] "GET /history_data?evt=1-溫濕度&avg=1&max=0&min=0&time-interval=hour&date-start=2021-01-01&date-end=2021-07-27 HTTP/1.1" 200 -
- date_start = info['date-start']
- date_end_list = info['date-end'].split('-') # 先把 'date-end' 的 '2021-05-18' 拆成 ['2021', '05', '18']
- date_end_list[2] = str(int(date_end_list[2]) + 1) # 18 + 1 = 19 再轉成 str → '19'
- date_end = '-'.join(date_end_list) # '2021-05-19'
- # tank_num = evt.split('-')[0] # 1
- # sensor = evt.split('-')[1] # 溫濕度
- tank_num = tid # D1
- sensor = sensor_name # soil_Temp
- L = []
- D = {}
- maxData = []
- minData = []
- avgData = []
- def sensorData(data_name): # data_name = "tem"
- def dataResample(time_interval, how, data_name): # dataResample('month', how???, "tem") # 下方 "hour"
- interval = 0
- # 設置resample的第一個參數,要按照逐月、逐日或逐時
- if time_interval == 'month':
- interval = "M" # interval = "M"
- elif time_interval == 'day':
- interval = "D"
- elif time_interval == 'hour':
- interval = "H"
- if how == "max":
- # data = df.resample(interval, how={data_name:how})
- # 最新版的pandas
- data = df.resample(interval).max() # 取樣頻率 'H'
- # 刪除有 NaN 的列, any 任何一欄位為空則刪 (all 全部欄位為空值才刪)
- data = data.dropna(axis=0, how='any')
-
- if time_interval == ('hour' or 'day'):
- data.index = pd.to_datetime(
- data.index, format='%Y-%b-%d_%H:%M:%S') # 将数据类型转换为日期类型
- for a in range(0, len(data.index)):
- l = []
- # 如果是逐時,才顯示小時分秒
- if time_interval == 'hour':
- l.append(str(data.index[a]))
- else:
- l.append(str(data.index[a]).split(' ')[0])
- l.append(str(data[data_name][a]))
- maxData.append(l)
- D['max'] = maxData
- elif how == "mean":
- # data = df.resample(interval, how={data_name:how})
- # 最新版的pandas
- data = df.resample(interval).mean()
- # 刪除具有NaN的值
- data = data.dropna(axis=0, how='any')
- # 將平均數取自小數1位
- data = data.round({data_name: 1})
- for a in range(0, len(data.index)):
- l = []
- # 如果是逐時,才顯示小時分秒
- if time_interval == 'hour':
- l.append(str(data.index[a]))
- else:
- l.append(str(data.index[a]).split(' ')[0])
- l.append(str(data[data_name][a]))
- avgData.append(l)
- D['avg'] = avgData
- elif how == "min":
- # data = df.resample(interval, how={data_name:how})
- # 最新版的pandas
- data = df.resample(interval).min()
- # 刪除具有NaN的值
- data = data.dropna(axis=0, how='any')
- for a in range(0, len(data.index)):
- # print(data.index[a])
- l = []
- # 如果是逐時,才顯示小時分秒
- if time_interval == 'hour':
- l.append(str(data.index[a]))
- else:
- l.append(str(data.index[a]).split(' ')[0])
- l.append(str(data[data_name][a]))
- minData.append(l)
- D['min'] = minData
- df = pd.DataFrame(L, columns=["datetime", data_name]) # 指定欄標籤名稱 為 ["datetime", "tem"]
- df['datetime'] = pd.to_datetime(
- df['datetime'], format='%Y-%b-%d_%H:%M:%S') # 将数据类型转换为日期类型
- # print(df['datetime']) # 0 2021-02-19 16:46:10
- # 1 2021-02-19 16:46:20
- # 2 2021-02-19 16:46:30
- # 3 2021-02-19 16:46:41
- df[data_name] = df[data_name].astype(float)
- df = df.set_index('datetime') # 将datetime设置为index
- # print(df) # datetime tem
- # 2021-02-19 16:46:10 24.4
- # 2021-02-19 16:46:20 24.4
- if time_interval == 'month':
- if max:
- dataResample(time_interval, "max", data_name)
- if avg:
- dataResample(time_interval, "mean", data_name)
- if min:
- dataResample(time_interval, "min", data_name)
- elif time_interval == 'day':
- if max:
- dataResample(time_interval, "max", data_name)
- if avg:
- dataResample(time_interval, "mean", data_name)
- if min:
- dataResample(time_interval, "min", data_name)
- elif time_interval == 'hour':
- if max:
- dataResample(time_interval, "max", data_name)
- if avg:
- dataResample(time_interval, "mean", data_name)
- if min:
- dataResample(time_interval, "min", data_name)
- if tank_num[:2] == 'DI':
- # 乾燥入料儲豆槽
- if sensor == 'UltraSonic':
- tank_UltraSonic = dry_input_sensor.query.filter_by(tank_num=tank_num).filter(dry_input_sensor.datetime.between(date_start, date_end)).all()
- for sonic in tank_UltraSonic:
- l = []
- time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
- l.append(time)
- l.append(sonic.UltraSonic)
- L.append(l)
- D['all'] = L
- sensorData("UltraSonic")
- elif tank_num[:2] == 'DO':
- # 乾燥出料儲豆槽
- if sensor == 'UltraSonic':
- tank_UltraSonic = dry_output_sensor.query.filter_by(tank_num=tank_num).filter(dry_output_sensor.datetime.between(date_start, date_end)).all()
- for sonic in tank_UltraSonic:
- l = []
- time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
- l.append(time)
- l.append(sonic.UltraSonic)
- L.append(l)
- D['all'] = L
- sensorData("UltraSonic")
- elif tank_num[:1] == 'D':
- # 乾燥槽
- if sensor == 'SHT11_Temp':
- tank_tem = dry_tank_SHT11.query.filter_by(tank_num=tank_num).filter(dry_tank_SHT11.datetime.between(date_start, date_end)).all()
- for tem in tank_tem:
- l = [] # l = []
- time = dt.strftime(tem.datetime, '%Y-%b-%d_%H:%M:%S') # time = '2021-Feb-19_16:46:10' 轉換時間格式
- # time = dt.strftime(tem.datetime, '%Y-%m-%d')
- l.append(time) # l = ['2021-Feb-19_16:46:10']
- #l.append(tem.tem) # l = ['2021-Feb-19_16:46:10', '24.4']
- l.append(tem.SHT11_Temp)
- L.append(l) # L = [['2021-Feb-19_16:46:10', '24.4']]
- # print(L)
- D['all'] = L # D = {'all': [['2021-Feb-19_16:46:10', '24.4']]} # all 所有符合數據
- sensorData("SHT11_Temp")
- elif sensor == 'SHT11_Humidity':
- tank_hum = dry_tank_SHT11.query.filter_by(tank_num=tank_num).filter(dry_tank_SHT11.datetime.between(date_start, date_end)).all()
- for hum in tank_hum:
- l = []
- time = dt.strftime(hum.datetime, '%Y-%b-%d_%H:%M:%S')
- l.append(time)
- l.append(hum.SHT11_Humidity)
- L.append(l)
- D['all'] = L
- sensorData("SHT11_Humidity")
-
- elif sensor == 'UltraSonic':
- tank_UltraSonic = dry_tank_UltraSonic.query.filter_by(tank_num=tank_num).filter(dry_tank_UltraSonic.datetime.between(date_start, date_end)).all()
- for sonic in tank_UltraSonic:
- l = []
- time = dt.strftime(sonic.datetime, '%Y-%b-%d_%H:%M:%S')
- l.append(time)
- l.append(sonic.UltraSonic)
- L.append(l)
- D['all'] = L
- sensorData("UltraSonic")
- elif sensor == 'PA':
- tank_PA = dry_tank_PA.query.filter_by(tank_num=tank_num).filter(dry_tank_PA.datetime.between(date_start, date_end)).all()
- for pa in tank_PA:
- l = []
- time = dt.strftime(pa.datetime, '%Y-%b-%d_%H:%M:%S')
- l.append(time)
- l.append(pa.PA)
- L.append(l)
- D['all'] = L
- sensorData("PA")
-
- elif sensor == 'soil_Temp':
- tank_soiltemp = dry_tank_Soil.query.filter_by(tank_num=tank_num).filter(dry_tank_Soil.datetime.between(date_start, date_end)).all()
- for temp in tank_soiltemp:
- l = []
- time = dt.strftime(temp.datetime, '%Y-%b-%d_%H:%M:%S')
- l.append(time)
- l.append(temp.soil_Temp)
- L.append(l)
- D['all'] = L
- sensorData("soil_Temp")
- elif sensor == 'soil_Humidity':
- tank_soilHum = dry_tank_Soil.query.filter_by(tank_num=tank_num).filter(dry_tank_Soil.datetime.between(date_start, date_end)).all()
- for hum in tank_soilHum:
- l = []
- time = dt.strftime(hum.datetime, '%Y-%b-%d_%H:%M:%S')
- l.append(time)
- l.append(hum.soil_EC)
- L.append(l)
- D['all'] = L
- sensorData("soil_Humidity")
- elif sensor == 'soil_EC':
- tank_soilec = dry_tank_Soil.query.filter_by(tank_num=tank_num).filter(dry_tank_Soil.datetime.between(date_start, date_end)).all()
- for ec in tank_soilec:
- l = []
- time = dt.strftime(ec.datetime, '%Y-%b-%d_%H:%M:%S')
- # time = dt.strftime(tem.datetime, '%Y-%m-%d')
- l.append(time)
- l.append(ec.soil_EC)
- L.append(l)
- D['all'] = L
- sensorData("soil_EC")
- elif tank_num[:2] == 'FI':
- if sensor == 'UltraSonic':
- input_UltraSonic = ferment_input_UltraSonic.query.filter_by(tank_num=tank_num).filter(ferment_input_UltraSonic.datetime.between(date_start, date_end)).all()
- for UltraSonic in input_UltraSonic:
- l = []
- time = dt.strftime(UltraSonic.datetime, '%Y-%b-%d_%H:%M:%S')
- l.append(time)
- l.append(UltraSonic.UltraSonic)
- L.append(l)
- D['all'] = L
- sensorData("UltraSonic")
- elif tank_num[:2] == 'FO':
- if sensor == 'UltraSonic':
- output_UltraSonic = ferment_output_UltraSonic.query.filter_by(tank_num=tank_num).filter(ferment_output_UltraSonic.datetime.between(date_start, date_end)).all()
- for UltraSonic in output_UltraSonic:
- l = []
- time = dt.strftime(UltraSonic.datetime, '%Y-%b-%d_%H:%M:%S')
- l.append(time)
- l.append(UltraSonic.UltraSonic)
- L.append(l)
- D['all'] = L
- sensorData("UltraSonic")
- elif tank_num[:1] == 'F':
- if sensor == 'LiDAR':
- tank_LiDAR = ferment_tank_LiDAR.query.filter_by(tank_num = tank_num)\
- .filter(ferment_tank_LiDAR.datetime.between(date_start, date_end)).all()
- for LiDAR in tank_LiDAR:
- l = []
- time = dt.strftime(LiDAR.datetime, '%Y-%b-%d_%H:%M:%S')
- l.append(time)
- l.append(LiDAR.LiDAR)
- L.append(l)
- D['all'] = L
- sensorData("LiDAR")
- elif sensor == 'motorEncoder':
- tank_motorEncoder = ferment_tank_motorEncoder.query.filter_by(tank_num = tank_num)\
- .filter(ferment_tank_motorEncoder.datetime.between(date_start, date_end)).all()
- for motorEncoder in tank_motorEncoder:
- l = []
- time = dt.strftime(motorEncoder.datetime, '%Y-%b-%d_%H:%M:%S')
- l.append(time)
- l.append(motorEncoder.motorEncoder)
- L.append(l)
- D['all'] = L
- sensorData("motorEncoder")
- elif sensor == 'PressureWaterLevel':
- tank_PressureWaterLevel = ferment_tank_PressureWaterLevel.query.filter_by(tank_num = tank_num)\
- .filter(ferment_tank_PressureWaterLevel.datetime.between(date_start, date_end)).all()
- for PressureWaterLevel in tank_PressureWaterLevel:
- l = []
- time = dt.strftime(PressureWaterLevel.datetime, '%Y-%b-%d_%H:%M:%S')
- l.append(time)
- l.append(PressureWaterLevel.PressureWaterLevel)
- l.append('{:.2f}'.format(float(PressureWaterLevel.PressureWaterLevel)))
- L.append(l)
- D['all'] = L
- sensorData("PressureWaterLevel")
- elif sensor == 'SHT11_Temp':
- tank_Temp = ferment_tank_SHT11.query.filter_by(tank_num = tank_num)\
- .filter(ferment_tank_SHT11.datetime.between(date_start, date_end)).all()
- for Temp in tank_Temp:
- l = []
- time = dt.strftime(Temp.datetime, '%Y-%b-%d_%H:%M:%S')
- l.append(time)
- l.append(Temp.SHT11_Temp)
- L.append(l)
- D['all'] = L
- sensorData("SHT11_Temp")
- elif sensor == 'SHT11_Humidity':
- tank_Humidity = ferment_tank_SHT11.query.filter_by(tank_num = tank_num)\
- .filter(ferment_tank_SHT11.datetime.between(date_start, date_end)).all()
- for Humidity in tank_Humidity:
- l = []
- time = dt.strftime(Humidity.datetime, '%Y-%b-%d_%H:%M:%S')
- l.append(time)
- l.append(Humidity.SHT11_Humidity)
- L.append(l)
- D['all'] = L
- sensorData("SHT11_Humidity")
- elif sensor == 'CO2':
- tank_CO2 = ferment_tank_CO2.query.filter_by(tank_num = tank_num)\
- .filter(ferment_tank_CO2.datetime.between(date_start, date_end)).all()
- for CO2 in tank_CO2:
- l = []
- time = dt.strftime(CO2.datetime, '%Y-%b-%d_%H:%M:%S')
- l.append(time)
- l.append(CO2.CO2)
- L.append(l)
- D['all'] = L
- sensorData("CO2")
- elif sensor == 'PH':
- tank_PH = ferment_tank_PH.query.filter_by(tank_num = tank_num)\
- .filter(ferment_tank_PH.datetime.between(date_start, date_end)).all()
- for PH in tank_PH:
- l = []
- time = dt.strftime(PH.datetime, '%Y-%b-%d_%H:%M:%S')
- l.append(time)
- l.append(PH.PH)
- L.append(l)
- D['all'] = L
- sensorData("PH")
- elif sensor == 'ORP':
- tank_ORP = ferment_tank_ORP.query.filter_by(tank_num = tank_num)\
- .filter(ferment_tank_ORP.datetime.between(date_start, date_end)).all()
- for ORP in tank_ORP:
- l = []
- time = dt.strftime(ORP.datetime, '%Y-%b-%d_%H:%M:%S')
- l.append(time)
- l.append(ORP.ORP)
- L.append(l)
- D['all'] = L
- sensorData("ORP")
- elif sensor == 'DO':
- tank_DO = ferment_tank_DO.query.filter_by(tank_num = tank_num)\
- .filter(ferment_tank_DO.datetime.between(date_start, date_end)).all()
- for DO in tank_DO:
- l = []
- time = dt.strftime(DO.datetime, '%Y-%b-%d_%H:%M:%S')
- l.append(time)
- l.append(DO.DO)
- L.append(l)
- D['all'] = L
- sensorData("DO")
- elif sensor == 'EC':
- tank_EC = ferment_tank_EC.query.filter_by(tank_num = tank_num)\
- .filter(ferment_tank_EC.datetime.between(date_start, date_end)).all()
- for EC in tank_EC:
- l = []
- time = dt.strftime(EC.datetime, '%Y-%b-%d_%H:%M:%S')
- l.append(time)
- l.append(EC.EC)
- L.append(l)
- D['all'] = L
- sensorData("EC")
- elif sensor == 'PA':
- tank_PA = ferment_tank_PA.query.filter_by(tank_num = tank_num)\
- .filter(ferment_tank_PA.datetime.between(date_start, date_end)).all()
- for PA in tank_PA:
- l = []
- time = dt.strftime(PA.datetime, '%Y-%b-%d_%H:%M:%S')
- l.append(time)
- l.append(PA.PA)
- L.append(l)
- D['all'] = L
- sensorData("PA")
-
-
- print(D)
- return json.dumps(D)
- else:
- pass
- # 貨櫃2致動器的發酵槽訪問路徑
- @main.route('/cargo2_actuator_tanks', methods=['GET', 'POST'])
- def cargo2_actuator_tanks_views():
- username = session['uname']
- if request.method == 'GET':
- return render_template('cargo2_actuator_tanks.html', params=locals())
- else:
- pass
- # 貨櫃2致動器發酵槽的清單訪問路徑
- @main.route('/cargo2_actuator/<tid>', methods=['GET', 'POST'])
- def cargo2_actuator_views(tid):
- username = session['uname']
- if request.method == 'GET':
- return render_template('cargo2_actuator.html', params=locals())
- else:
- pass
- # 貨櫃3的訪問路徑
- @main.route('/cargo3', methods=['GET', 'POST'])
- def cargo3_views():
- username = session['uname']
- if request.method == 'GET':
- return render_template('cargo3.html', params=locals())
- else:
- pass
- # 貨櫃3排程的訪問路徑
- @main.route('/cargo3_schedule', methods=['GET', 'POST'])
- def cargo3_schedule_views():
- username = session['uname']
- if request.method == 'GET':
- # 將已儲存的排程資料傳給前端
- # 提升機
- try:
- hoist = Hoist.query.order_by(text('datetime desc')).first()
- datetime = hoist.datetime
- hoists = Hoist.query.filter_by(datetime=datetime).all()
- except Exception as e:
- pass
- # 烘乾機
- try:
- dryer = Dryer.query.order_by(text('datetime desc')).first()
- datetime = dryer.datetime
- dryers = Dryer.query.filter_by(datetime=datetime).all()
- except Exception as e:
- pass
- return render_template('cargo3_schedule.html', params=locals())
- else:
- # Rita: "POST /b_cargo3 HTTP/1.1" 404 -
- current_time = dt.now()
- # 循環從前端提交過來的資料
- for i in request.form:
- print('Rita test i :', i)
- # 堤升機
- if i[:5] == 'hoist':
- if i[:14] == 'hoist_duration':
- hoist = Hoist()
- hoist.duration = request.form[i]
- elif i[:13] == 'hoist_from_hr':
- ho_from_hr = request.form[i]
- elif i[:14] == 'hoist_from_min':
- ho_from_min = request.form[i]
- hoist.start = ho_from_hr + ":" + ho_from_min
- elif i[:11] == 'hoist_to_hr':
- ho_to_hr = request.form[i]
- elif i[:12] == 'hoist_to_min':
- ho_to_min = request.form[i]
- hoist.end = ho_to_hr + ":" + ho_to_min
- hoist.datetime = current_time
- db.session.add(hoist)
- db.session.commit()
- # 烘乾機
- elif i[:5] == 'dryer':
- if i[:14] == 'dryer_duration':
- dryer = Dryer()
- dryer.duration = request.form[i]
- elif i[:13] == 'dryer_from_hr':
- dry_from_hr = request.form[i]
- elif i[:14] == 'dryer_from_min':
- dry_from_min = request.form[i]
- dryer.start = dry_from_hr + ":" + dry_from_min
- elif i[:11] == 'dryer_to_hr':
- dry_to_hr = request.form[i]
- elif i[:12] == 'dryer_to_min':
- dry_to_min = request.form[i]
- dryer.end = dry_to_hr + ":" + dry_to_min
- dryer.datetime = current_time
- db.session.add(dryer)
- db.session.commit()
- return render_template('cargo3.html', params=locals())
- # 影像串流的訪問路徑
- @main.route('/video', methods=['GET', 'POST'])
- def video_views():
- username = session['uname']
- if request.method == 'GET':
- return render_template('video.html', params=locals())
- else:
- pass
- # 影像的訪問路徑
- @main.route('/learn', methods=['GET', 'POST'])
- def learn_views():
- username = session['uname']
- if request.method == 'GET':
- return render_template('learn.html', params=locals())
- else:
- pass
- # 獲取relay狀態路徑
- @main.route('/relay', methods=['GET', 'POST'])
- def relay_views():
- if request.method == 'GET':
- relay = Relay.query.order_by(text('datetime desc')).first()
- relay_status = relay.status
- return jsonify({"relay": relay_status})
- else:
- pass
- # 獲取脫皮機狀態路徑
- @main.route('/peel', methods=['GET', 'POST'])
- def peeling_views():
- if request.method == 'GET':
- peeling = PeelingMachineRPM.query.order_by(text('datetime desc')).first()
- peeling_rpm = peeling.rpm
- return jsonify({"peeling": peeling_rpm})
- else:
- pass
- # 退出的訪問路徑
- @main.route('/logout')
- def logout_views():
- if 'id' in session and 'uname' in session:
- del session['id']
- del session['uname']
- return redirect('/')
- @main.route("/udp_client", methods=['POST', 'GET'])
- def udp_views():
- # sl(0.5)
- global c_sock
- if request.method == 'GET':
- # def close():
- # global c_sock
- # sl(600)
- # c_sock.close()
- # c_sock = 0
- # print("c_sock is closing")
- max_length = 65000
- # max_length = 95000
- # lab1的IP
- host = "192.168.50.65"
- # lab2的IP
- # host = "192.168.51.160"
- port = 8000
- c_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- # t = threading.Thread(target=close)
- # t.daemon = True
- # t.start()
- print("test")
- # dict = request.args.to_dict()
- # nr = int(dict['nr'])
- # if nr == 1:
- # camara = 0
- # elif nr == 2:
- # camara = 'rtsp://admin:admin@192.168.50.182/av2_0'
- # elif nr == 3:
- # camara = 'rtsp://admin:abcd1234@192.168.51.101/av2_0'
- # 地下室小兵
- # cap = cv2.VideoCapture('rtsp://admin:abcd1234@192.168.51.48/av2_0')
- # 主機攝像頭
- # cap = cv2.VideoCapture(0)
- # 外面小兵
- # cap = cv2.VideoCapture('rtsp://admin:admin@192.168.50.182/av2_0')
- cap = cv2.VideoCapture('rtsp://192.168.50.182/av0_0')
- # cap = cv2.VideoCapture(0)
- # cap = cv2.VideoCapture(camara)
- ret, frame = cap.read()
- while ret:
- # compress frame
- frame = cv2.resize(frame, (550, 400), interpolation=cv2.INTER_AREA)
- retval, buffer = cv2.imencode(".jpg", frame)
- if retval:
- # convert to byte array
- buffer = buffer.tobytes()
- # get size of the frame
- buffer_size = len(buffer)
- num_of_packs = 1
- if buffer_size > max_length:
- num_of_packs = math.ceil(buffer_size / max_length)
- frame_info = {"packs": num_of_packs}
- # send the number of packs to be expected
- # print("Number of packs:", num_of_packs)
- c_sock.sendto(pickle.dumps(frame_info), (host, port))
- left = 0
- right = max_length
- for i in range(num_of_packs):
- # print("left:", left)
- # print("right:", right)
- # truncate data to send
- data = buffer[left:right]
- left = right
- right += max_length
- # send the frames accordingly
- c_sock.sendto(data, (host, port))
- ret, frame = cap.read()
- print("done")
- return "done"
- else:
- c_sock.shutdown(2)
- c_sock.close()
- c_sock = 0
- print("c_sock is closing")
- # 影像串流的路徑
- @main.route("/video_feed", methods=['POST', 'GET'])
- def video_feed_views():
- print("test2")
- global s_sock
- if request.method == 'GET':
- # 於10分鐘之後,自動關閉socket server
- # if s_sock == 0:
- # def socket_server_views():
- # global s_sock
- # print("test")
- # print(s_sock)
- # sl(600)
- # if s_sock != 0:
- # s_sock.close()
- # s_sock = 0
- # print('s_sock is closed')
- #
- # pool.submit(socket_server_views)
- host = "192.168.50.65"
- port = 8000
- max_length = 65540
- # max_length = 95540
- s_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- s_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- s_sock.bind((host, port))
- frame_info = None
- buffer = None
- frame = None
- encodedImage = None
- print("-> waiting for connection")
- # 影像生成器函數,將影像以jpg格式傳給前端
- def generate():
- while True:
- with lock:
- global s_sock, frame_info, buffer, frame, encodedImage
- if s_sock == 0:
- break
- data, address = s_sock.recvfrom(max_length)
- if len(data) < 100:
- frame_info = pickle.loads(data)
- if frame_info:
- nums_of_packs = frame_info["packs"]
- for i in range(nums_of_packs):
- if s_sock == 0:
- break
- data, address = s_sock.recvfrom(max_length)
- if i == 0:
- buffer = data
- else:
- buffer += data
- frame = np.frombuffer(buffer, dtype=np.uint8)
- frame = frame.reshape(frame.shape[0], 1)
- frame = cv2.imdecode(frame, cv2.IMREAD_UNCHANGED)
- # print(frame)
- # 如果frame為None就跳過
- if frame is None:
- continue
- frame = cv2.resize(
- frame, (640, 360), interpolation=cv2.INTER_AREA)
- # encode the frame in JPEG format
- (flag, encodedImage) = cv2.imencode(".jpg", frame)
- # ensure the frame was successfully encoded
- if not flag:
- continue
- # yield the output frame in the byte format
- yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' +
- bytearray(encodedImage) + b'\r\n')
- # return the response generated along with the specific media
- # type (mime type)
- return Response(generate(), mimetype="multipart/x-mixed-replace; boundary=frame")
- else:
- if s_sock != 0:
- s_sock.close()
- s_sock = 0
- print('s_sock is closed')
- return "s_sock is closed"
- print("test")
- return "s_sock is closed"
- D = {"input_vacuum_status": "0",
- "tank_vacuum_status": "0",
- "tank_threewayvalve_input_status": "0",
- "tank_threewayvalve_bean_status": "0",
- "tank_solenoid_disinfect_status": "0",
- "tank_pump_disinfect_status": "0",
- "outer_threewayvalve_float_status": "0",
- "tank_motor_status": 'none',
- "tank_pump_water_in_status": "0",
- "tank_pump_cleanwater_in_status": "0",
- "outer_solenoid_water_status": "0",
- "tank_solenoid_reclaimed_in_status": "0",
- "tank_solenoid_water_in_status": "0",
- "tank_solenoid_water_out_status": "0",
- "tank_solenoid_reclaimed_out_status": "0",
- "tank_pump_sensor_status": "0",
- "solenoid_tank_pump_status": "0",
- "tank_nozzle_status": "0",
- "tank_blower_status": "0",
- "tank_heater1_status": "0",
- "tank_heater2_status": "0",
- "temp1_enable": "0",
- "temp1": "0",
- "tank_diskvalve_status": "0",
- "output_vacuum_status": "0",
- "tank_temp_enable_status": "0",
- "tank_temp_status": "0",
- # "tank_pump_waterFloat_status": "0",
- # "tank_pump_waterL2_status": "0",
- # "tank_pump_waterL4_status": "0",
- # "tank_solenoid_waterL3_status": "0",
- # "tank_solenoid_waterL5_status": "0",
- # "tank_stepping_motor_status": 'none',
- }
- # pub_topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
- # sub_topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78/Log'
- # mqttObj = MQTT('aisky-client', 'aiskyc', '60.250.156.234', 1883, 60, sub_topic)
- mqttObj = MQTT()
- @main.route('/mqtt_block', methods=['POST'])
- def mqtt_block():
- import json
- dict = request.form.to_dict() # 將表單轉換成字典
- print('dict:', dict)
- # print('dict.keys():', dict.keys())
- # 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"]
- # }
- # ]
- # }
- # 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']"}
- json = json.dumps(dict)
- # 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"]}]}
- print('json:', json)
- # 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']}]}
- topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
- mqtt.publish(topic, json)
- return 'OK'
- # mqtt發布
- # @main.route('/mqtt/<tid>', methods=['POST'])
- @main.route('/mqtt/<tid>', methods=['POST'])
- def mqtt_views(tid):
- import json
- dict = request.form.to_dict() # 將表單轉換成字典
- json = json.dumps(dict)
- # print('dict:', dict) # dict: {'tank-number': '1', 'command': 'tank_vacuum_status', 'value': 'on'}
- # print('json:', json) # json: {"tank-number": "1", "command": "tank_vacuum_status", "value": "on"}
- topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
- # res = mqttObj.mqttPublish(pub_topic, json)
- # print(res)
- # sl(2)
- # print(mqttObj.res)
- #
- # print('test')
- mqtt.publish(topic, json)
- # 入料儲豆槽真空吸料機(ON吸料/OFF排氣)
- if dict['command'] == 'input_vacuum_status':
- time.sleep(1)
- # D[input_vacuum_status]: "0"
- print('D[input_vacuum_status]:', D['input_vacuum_status'])
- if D['input_vacuum_status'] == 'on':
- return 'on'
- elif D['input_vacuum_status'] == 'off':
- return 'off'
- else:
- return "input_vacuum_status signal was not received"
- # 真空吸料機
- elif dict['command'] == 'tank_vacuum_status':
- time.sleep(1)
- if D['tank_vacuum_status'] == 'on':
- return 'on'
- elif D['tank_vacuum_status'] == 'off':
- return 'off'
- else:
- return "tank_vacuum_status signal was not received"
- # 入料三通閥(ON吸料/OFF排氣)
- elif dict['command'] == 'tank_threewayvalve_input_status':
- time.sleep(1)
- if D['tank_threewayvalve_input_status'] == 'on':
- return 'on'
- elif D['tank_threewayvalve_input_status'] == 'off':
- return 'off'
- else:
- return "tank_threewayvalve_input_status signal was not received"
- # 測豆三通閥(ON吸料/OFF排氣)
- elif dict['command'] == 'tank_threewayvalve_bean_status':
- time.sleep(1)
- if D['tank_threewayvalve_bean_status'] == 'on':
- return 'on'
- elif D['tank_threewayvalve_bean_status'] == 'off':
- return 'off'
- else:
- return "tank_threewayvalve_bean_status signal was not received"
- # 消毒電磁閥(ON噴灑消毒/OFF關)
- elif dict['command'] == 'tank_solenoid_disinfect_status':
- time.sleep(1)
- if D['tank_solenoid_disinfect_status'] == 'on':
- return 'on'
- elif D['tank_solenoid_disinfect_status'] == 'off':
- return 'off'
- else:
- return "tank_solenoid_disinfect_status signal was not received"
- # 混合槽幫浦(ON抽水消毒/OFF關)
- elif dict['command'] == 'tank_pump_disinfect_status':
- time.sleep(1)
- if D['tank_pump_disinfect_status'] == 'on':
- return 'on'
- elif D['tank_pump_disinfect_status'] == 'off':
- return 'off'
- else:
- return "tank_pump_disinfect_status signal was not received"
-
- # 外桶浮選三通閥(ON開浮選出口/OFF關)
- elif dict['command'] == 'outer_threewayvalve_float_status':
- time.sleep(1)
- if D['outer_threewayvalve_float_status'] == 'on':
- return 'on'
- elif D['outer_threewayvalve_float_status'] == 'off':
- return 'off'
- else:
- return "outer_threewayvalve_float_status signal was not received"
- # 馬達(單位RPM)
- elif dict['command'] == 'tank_motor_status':
- print("D['tank_motor_status']", D['tank_motor_status'])
- time.sleep(1)
- if D['tank_motor_status'] == '0':
- return 'off'
- elif type(D['tank_motor_status']) == int:
- return 'on'
- else:
- return "tank_motor_status signal was not received"
- # 幫浦(清水入水)(ON開/OFF關)
- elif dict['command'] == 'tank_pump_water_in_status':
- time.sleep(1)
- if D['tank_pump_water_in_status'] == 'on':
- return 'on'
- elif D['tank_pump_water_in_status'] == 'off':
- return 'off'
- else:
- return "tank_pump_water_in_status signal was not received"
- # 幫浦(清洗槽入水)(ON開/OFF關)
- elif dict['command'] == 'tank_pump_cleanwater_in_status':
- time.sleep(1)
- if D['tank_pump_cleanwater_in_status'] == 'on':
- return 'on'
- elif D['tank_pump_cleanwater_in_status'] == 'off':
- return 'off'
- else:
- return "tank_pump_cleanwater_in_status signal was not received"
- # 桶外進水電磁閥(ON開/OFF關)
- elif dict['command'] == 'outer_solenoid_water_status':
- time.sleep(1)
- if D['outer_solenoid_water_status'] == 'on':
- return 'on'
- elif D['outer_solenoid_water_status'] == 'off':
- return 'off'
- else:
- return "outer_solenoid_water_status signal was not received"
- # 中水入水電磁閥(ON開/OFF關)
- elif dict['command'] == 'tank_solenoid_reclaimed_in_status':
- time.sleep(1)
- if D['tank_solenoid_reclaimed_in_status'] == 'on':
- return 'on'
- elif D['tank_solenoid_reclaimed_in_status'] == 'off':
- return 'off'
- else:
- return "tank_solenoid_reclaimed_in_status signal was not received"
- # 清水入水電磁閥(ON開/OFF關)
- elif dict['command'] == 'tank_solenoid_water_in_status':
- time.sleep(1)
- if D['tank_solenoid_water_in_status'] == 'on':
- return 'on'
- elif D['tank_solenoid_water_in_status'] == 'off':
- return 'off'
- else:
- return "tank_solenoid_water_in_status signal was not received"
- # 排水廢水電磁閥(ON開/OFF關)
- elif dict['command'] == 'tank_solenoid_water_out_status':
- time.sleep(1)
- if D['tank_solenoid_water_out_status'] == 'on':
- return 'on'
- elif D['tank_solenoid_water_out_status'] == 'off':
- return 'off'
- else:
- return "tank_solenoid_water_out_status signal was not received"
- # 排水中水電磁閥(ON開/OFF關)
- elif dict['command'] == 'tank_solenoid_reclaimed_out_status':
- time.sleep(1)
- if D['tank_solenoid_reclaimed_out_status'] == 'on':
- return 'on'
- elif D['tank_solenoid_reclaimed_out_status'] == 'off':
- return 'off'
- else:
- return "tank_solenoid_reclaimed_out_status signal was not received"
- # 雙核隔膜泵(ON開/OFF關)
- elif dict['command'] == 'tank_pump_sensor_status':
- time.sleep(1)
- if D['tank_pump_sensor_status'] == 'on':
- return 'on'
- elif D['tank_pump_sensor_status'] == 'off':
- return 'off'
- else:
- return "tank_pump_sensor_status signal was not received"
- # 逆洗 pump 電磁閥(ON開/OFF關)
- elif dict['command'] == 'solenoid_tank_pump_status':
- time.sleep(1)
- if D['solenoid_tank_pump_status'] == 'on':
- return 'on'
- elif D['solenoid_tank_pump_status'] == 'off':
- return 'off'
- else:
- return "solenoid_tank_pump_status signal was not received"
- # 噴嘴(ON開/OFF關)
- elif dict['command'] == 'tank_nozzle_status':
- time.sleep(1)
- if D['tank_nozzle_status'] == 'on':
- return 'on'
- elif D['tank_nozzle_status'] == 'off':
- return 'off'
- else:
- return "tank_nozzle_status signal was not received"
- # 鼓風機(ON開/OFF關)
- elif dict['command'] == 'tank_blower_status':
- time.sleep(1)
- if D['tank_blower_status'] == 'on':
- return 'on'
- elif D['tank_blower_status'] == 'off':
- return 'off'
- else:
- return "tank_blower_status signal was not received"
- # 加熱棒 1(ON開/OFF關)
- elif dict['command'] == 'tank_heater1_status':
- time.sleep(1)
- if D['tank_heater1_status'] == 'on':
- return 'on'
- elif D['tank_heater1_status'] == 'off':
- return 'off'
- else:
- return "tank_heater1_status signal was not received"
- # 加熱棒 2(ON開/OFF關)
- elif dict['command'] == 'tank_heater2_status':
- time.sleep(1)
- if D['tank_heater2_status'] == 'on':
- return 'on'
- elif D['tank_heater2_status'] == 'off':
- return 'off'
- else:
- return "tank_heater2_status signal was not received"
- # 溫度控制(ON開/OFF關)
- elif dict['command'] == 'temp1_enable':
- time.sleep(1)
- if D['temp1_enable'] == 'on':
- return 'on'
- elif D['temp1_enable'] == 'off':
- return 'off'
- else:
- return "temp1_enable_status signal was not received"
- # 設定溫度
- elif dict['command'] == 'temp1':
- time.sleep(1)
- if D['temp1'] == '0':
- return 'off'
- elif type(D['temp1']) == float:
- return 'on'
- else:
- return "temp1 signal was not received"
-
- # 發酵槽 溫控開關
- elif dict['command'] == 'tank_temp_enable':
- time.sleep(1)
- if D['tank_temp_enable'] == 'on':
- return 'on'
- elif D['tank_temp_enable'] == 'off':
- return 'off'
- else:
- return "tank_temp_enable signal was not received"
- # 發酵槽 設定溫度
- elif dict['command'] == 'tank_temp':
- time.sleep(1)
- if D['tank_temp'] == '0':
- return 'off'
- elif type(D['tank_temp']) == float:
- return 'on'
- else:
- return "tank_temp signal was not received"
- # 蝴蝶閥(ON開/OFF關)
- elif dict['command'] == 'tank_diskvalve_status':
- time.sleep(1)
- if D['tank_diskvalve_status'] == 'on':
- return 'on'
- elif D['tank_diskvalve_status'] == 'off':
- return 'off'
- else:
- return "tank_diskvalve_status signal was not received"
- # 出料儲豆槽真空吸料機(ON吸料/OFF排氣)
- elif dict['command'] == 'output_vacuum_status':
- time.sleep(1)
- if D['output_vacuum_status'] == 'on':
- return 'on'
- elif D['output_vacuum_status'] == 'off':
- return 'off'
- else:
- return "output_vacuum_status signal was not received"
- else:
- return "MQTT command NOT FOUND"
- # return "publish done" # 1201 test
-
- # --- 12/10 ------------------------------------------ start
- @main.route('/mqtt_data/<tid>_<command>_<value>', methods=['POST'])
- def mqtt_data(tank_num, command, value):
- import json
- data = { "tank_num": str(tank_num), "command": str(command), "value": str(value) }
- json = json.dumps(data)
- # print('json:', json) # json: {"tank-number": "1", tank_vacuum_status", "value": "on"}
- print('json:', json)
- topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
- mqtt.publish(topic, json)
- # --- 12/10 ------------------------------------------ finish
- # --- 10/19 ------------------------------------------ start
- # mqtt發布
- # @main.route('/mqtt/<tid>', methods=['POST'])
- @main.route('/mqtt_f/<tid>', methods=['POST'])
- def mqtt_f(data):
- import json
- dict = request.form.to_dict()
- json = json.dumps(data)
- # print('dict:', dict) # dict: {'tank-number': '1', 'command': 'tank_vacuum_status', 'value': 'on'}
- # print('json:', json) # json: {"tank-number": "1", tank_vacuum_status", "value": "on"}
- print('json:', json)
- topic = 'AISKY/Coffee/MK-G/b8:27:eb:7e:24:78'
- # res = mqttObj.mqttPublish(pub_topic, json)
- # print(res)
- # sl(2)
- # print(mqttObj.res)
- #
- # print('test')
- mqtt.publish(topic, json)
- # 入料儲豆槽真空吸料機(ON吸料/OFF排氣)
- if dict['command'] == 'input_vacuum_status':
- time.sleep(1)
- # D[input_vacuum_status]: "0"
- print('D[input_vacuum_status]:', D['input_vacuum_status'])
- if D['input_vacuum_status'] == 'on':
- return 'on'
- elif D['input_vacuum_status'] == 'off':
- return 'off'
- else:
- return "input_vacuum_status signal was not received"
- # 真空吸料機
- elif dict['command'] == 'tank_vacuum_status':
- time.sleep(1)
- if D['tank_vacuum_status'] == 'on':
- return 'on'
- elif D['tank_vacuum_status'] == 'off':
- return 'off'
- else:
- return "tank_vacuum_status signal was not received"
- # 入料三通閥(ON吸料/OFF排氣)
- elif dict['command'] == 'tank_threewayvalve_input_status':
- time.sleep(1)
- if D['tank_threewayvalve_input_status'] == 'on':
- return 'on'
- elif D['tank_threewayvalve_input_status'] == 'off':
- return 'off'
- else:
- return "tank_threewayvalve_input_status signal was not received"
- # 測豆三通閥(ON吸料/OFF排氣)
- elif dict['command'] == 'tank_threewayvalve_bean_status':
- time.sleep(1)
- if D['tank_threewayvalve_bean_status'] == 'on':
- return 'on'
- elif D['tank_threewayvalve_bean_status'] == 'off':
- return 'off'
- else:
- return "tank_threewayvalve_bean_status signal was not received"
- # 消毒電磁閥(ON噴灑消毒/OFF關)
- elif dict['command'] == 'tank_solenoid_disinfect_status':
- time.sleep(1)
- if D['tank_solenoid_disinfect_status'] == 'on':
- return 'on'
- elif D['tank_solenoid_disinfect_status'] == 'off':
- return 'off'
- else:
- return "tank_solenoid_disinfect_status signal was not received"
- # 混合槽幫浦(ON抽水消毒/OFF關)
- elif dict['command'] == 'tank_pump_disinfect_status':
- time.sleep(1)
- if D['tank_pump_disinfect_status'] == 'on':
- return 'on'
- elif D['tank_pump_disinfect_status'] == 'off':
- return 'off'
- else:
- return "tank_pump_disinfect_status signal was not received"
-
- # 外桶浮選三通閥(ON開浮選出口/OFF關)
- elif dict['command'] == 'outer_threewayvalve_float_status':
- time.sleep(1)
- if D['outer_threewayvalve_float_status'] == 'on':
- return 'on'
- elif D['outer_threewayvalve_float_status'] == 'off':
- return 'off'
- else:
- return "outer_threewayvalve_float_status signal was not received"
- # 馬達(單位RPM)
- elif dict['command'] == 'tank_motor_status':
- print("D['tank_motor_status']", D['tank_motor_status'])
- time.sleep(1)
- if D['tank_motor_status'] == '0':
- return 'off'
- elif type(D['tank_motor_status']) == int:
- return 'on'
- else:
- return "tank_motor_status signal was not received"
- # 幫浦(清水入水)(ON開/OFF關)
- elif dict['command'] == 'tank_pump_water_in_status':
- time.sleep(1)
- if D['tank_pump_water_in_status'] == 'on':
- return 'on'
- elif D['tank_pump_water_in_status'] == 'off':
- return 'off'
- else:
- return "tank_pump_water_in_status signal was not received"
- # 幫浦(清洗槽入水)(ON開/OFF關)
- elif dict['command'] == 'tank_pump_cleanwater_in_status':
- time.sleep(1)
- if D['tank_pump_cleanwater_in_status'] == 'on':
- return 'on'
- elif D['tank_pump_cleanwater_in_status'] == 'off':
- return 'off'
- else:
- return "tank_pump_cleanwater_in_status signal was not received"
- # 桶外進水電磁閥(ON開/OFF關)
- elif dict['command'] == 'outer_solenoid_water_status':
- time.sleep(1)
- if D['outer_solenoid_water_status'] == 'on':
- return 'on'
- elif D['outer_solenoid_water_status'] == 'off':
- return 'off'
- else:
- return "outer_solenoid_water_status signal was not received"
- # 中水入水電磁閥(ON開/OFF關)
- elif dict['command'] == 'tank_solenoid_reclaimed_in_status':
- time.sleep(1)
- if D['tank_solenoid_reclaimed_in_status'] == 'on':
- return 'on'
- elif D['tank_solenoid_reclaimed_in_status'] == 'off':
- return 'off'
- else:
- return "tank_solenoid_reclaimed_in_status signal was not received"
- # 清水入水電磁閥(ON開/OFF關)
- elif dict['command'] == 'tank_solenoid_water_in_status':
- time.sleep(1)
- if D['tank_solenoid_water_in_status'] == 'on':
- return 'on'
- elif D['tank_solenoid_water_in_status'] == 'off':
- return 'off'
- else:
- return "tank_solenoid_water_in_status signal was not received"
- # 排水廢水電磁閥(ON開/OFF關)
- elif dict['command'] == 'tank_solenoid_water_out_status':
- time.sleep(1)
- if D['tank_solenoid_water_out_status'] == 'on':
- return 'on'
- elif D['tank_solenoid_water_out_status'] == 'off':
- return 'off'
- else:
- return "tank_solenoid_water_out_status signal was not received"
- # 排水中水電磁閥(ON開/OFF關)
- elif dict['command'] == 'tank_solenoid_reclaimed_out_status':
- time.sleep(1)
- if D['tank_solenoid_reclaimed_out_status'] == 'on':
- return 'on'
- elif D['tank_solenoid_reclaimed_out_status'] == 'off':
- return 'off'
- else:
- return "tank_solenoid_reclaimed_out_status signal was not received"
- # 雙核隔膜泵(ON開/OFF關)
- elif dict['command'] == 'tank_pump_sensor_status':
- time.sleep(1)
- if D['tank_pump_sensor_status'] == 'on':
- return 'on'
- elif D['tank_pump_sensor_status'] == 'off':
- return 'off'
- else:
- return "tank_pump_sensor_status signal was not received"
- # 逆洗 pump 電磁閥(ON開/OFF關)
- elif dict['command'] == 'solenoid_tank_pump_status':
- time.sleep(1)
- if D['solenoid_tank_pump_status'] == 'on':
- return 'on'
- elif D['solenoid_tank_pump_status'] == 'off':
- return 'off'
- else:
- return "solenoid_tank_pump_status signal was not received"
- # 噴嘴(ON開/OFF關)
- elif dict['command'] == 'tank_nozzle_status':
- time.sleep(1)
- if D['tank_nozzle_status'] == 'on':
- return 'on'
- elif D['tank_nozzle_status'] == 'off':
- return 'off'
- else:
- return "tank_nozzle_status signal was not received"
- # 鼓風機(ON開/OFF關)
- elif dict['command'] == 'tank_blower_status':
- time.sleep(1)
- if D['tank_blower_status'] == 'on':
- return 'on'
- elif D['tank_blower_status'] == 'off':
- return 'off'
- else:
- return "tank_blower_status signal was not received"
- # 加熱棒 1(ON開/OFF關)
- elif dict['command'] == 'tank_heater1_status':
- time.sleep(1)
- if D['tank_heater1_status'] == 'on':
- return 'on'
- elif D['tank_heater1_status'] == 'off':
- return 'off'
- else:
- return "tank_heater1_status signal was not received"
- # 加熱棒 2(ON開/OFF關)
- elif dict['command'] == 'tank_heater2_status':
- time.sleep(1)
- if D['tank_heater2_status'] == 'on':
- return 'on'
- elif D['tank_heater2_status'] == 'off':
- return 'off'
- else:
- return "tank_heater2_status signal was not received"
- # 溫度控制(ON開/OFF關)
- elif dict['command'] == 'temp1_enable':
- time.sleep(1)
- if D['temp1_enable'] == 'on':
- return 'on'
- elif D['temp1_enable'] == 'off':
- return 'off'
- else:
- return "temp1_enable_status signal was not received"
- # 設定溫度
- elif dict['command'] == 'temp1':
- time.sleep(1)
- if D['temp1'] == '0':
- return 'off'
- elif type(D['temp1']) == float:
- return 'on'
- else:
- return "temp1 signal was not received"
-
- # 發酵槽 溫控開關
- elif dict['command'] == 'tank_temp_enable':
- time.sleep(1)
- if D['tank_temp_enable'] == 'on':
- return 'on'
- elif D['tank_temp_enable'] == 'off':
- return 'off'
- else:
- return "tank_temp_enable signal was not received"
- # 發酵槽 設定溫度
- elif dict['command'] == 'tank_temp':
- time.sleep(1)
- if D['tank_temp'] == '0':
- return 'off'
- elif type(D['tank_temp']) == float:
- return 'on'
- else:
- return "tank_temp signal was not received"
- # 蝴蝶閥(ON開/OFF關)
- elif dict['command'] == 'tank_diskvalve_status':
- time.sleep(1)
- if D['tank_diskvalve_status'] == 'on':
- return 'on'
- elif D['tank_diskvalve_status'] == 'off':
- return 'off'
- else:
- return "tank_diskvalve_status signal was not received"
- # 出料儲豆槽真空吸料機(ON吸料/OFF排氣)
- elif dict['command'] == 'output_vacuum_status':
- time.sleep(1)
- if D['output_vacuum_status'] == 'on':
- return 'on'
- elif D['output_vacuum_status'] == 'off':
- return 'off'
- else:
- return "output_vacuum_status signal was not received"
- else:
- return "MQTT command NOT FOUND"
- # ---10/19 ------------------------------------------- end
- board_prog = {
- "D1": "0",
- "D2": "0",
- "D3": "0",
- "D4": "0",
- "D5": "0",
- "D6": "0",
- "D7": "0",
- "D8": "0",
- "D9": "0",
- "D10": "0",
- "D11": "0",
- "D12": "0",
- }
- # 處理mqtt訂閱的信息
- # 收到訊息後我們可以用 on_message(),來讀取收到的內容:
- @mqtt.on_message()
- def handle_mqtt_message(client, userdata, message):
- # topic = message.topic # 收到的主題 Rita 原本就沒有此行, 增加說明用
- payload = message.payload.decode() # 收到的內容
- payload = json.loads(payload)
- # print("-------msg-------")
- # print('name :', p['name'])
- # print('email :', p['email'])
- print('payload:', payload)
-
- # success / upload error / no reply
- # {'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'}
- if payload['command'] == 'Code_upload':
- board_prog[payload['tank_number']] = payload['response']
- # res = "on_message" + payload['response']
- # return res
- # 入料儲豆槽真空吸料機(ON吸料/OFF排氣)
- if payload['command'] == 'input_vacuum_status':
- if payload['response'] == 'on':
- D['input_vacuum_status'] = 'on'
- else:
- D['input_vacuum_status'] = 'off'
- # 真空吸料機(ON吸料/OFF排氣)
- elif payload['command'] == 'tank_vacuum_status':
- if payload['response'] == 'on':
- D['tank_vacuum_status'] = 'on'
- else:
- D['tank_vacuum_status'] = 'off'
- # 入料三通閥(ON吸料/OFF排氣)
- elif payload['command'] == 'tank_threewayvalve_input_status':
- if payload['response'] == 'on':
- D['tank_threewayvalve_input_status'] = 'on'
- else:
- D['tank_threewayvalve_input_status'] = 'off'
- # 測豆三通閥(ON測豆/OFF排氣)
- elif payload['command'] == 'tank_threewayvalve_bean_status':
- if payload['response'] == 'on':
- D['tank_threewayvalve_bean_status'] = 'on'
- else:
- D['tank_threewayvalve_bean_status'] = 'off'
- # 消毒電磁閥(ON噴灑消毒/OFF關)
- elif payload['command'] == 'tank_solenoid_disinfect_status':
- if payload['response'] == 'on':
- D['tank_solenoid_disinfect_status'] = 'on'
- else:
- D['tank_solenoid_disinfect_status'] = 'off'
- # 混合槽幫浦(ON消毒槽抽水/OFF關)
- elif payload['command'] == 'tank_pump_disinfect_status':
- if payload['response'] == 'on':
- D['tank_pump_disinfect_status'] = 'on'
- else:
- D['tank_pump_disinfect_status'] = 'off'
- # 外桶浮選三通閥(ON浮選落豆/OFF桶內真空)
- elif payload['command'] == 'outer_threewayvalve_float_status':
- if payload['response'] == 'on':
- D['outer_threewayvalve_float_status'] = 'on'
- else:
- D['outer_threewayvalve_float_status'] = 'off'
- # 馬達(單位RPM)
- elif payload['command'] == 'tank_motor_status':
- if payload['response'] == 'off' or payload['response'] == '0':
- D['tank_motor_status'] = '0'
- else:
- D['tank_motor_status'] = payload['response']
- # 幫浦(清水入水)(ON開/OFF關)
- elif payload['command'] == 'tank_pump_water_in_status':
- if payload['response'] == 'on':
- D['tank_pump_water_in_status'] = 'on'
- else:
- D['tank_pump_water_in_status'] = 'off'
- # 幫浦(清洗槽入水)(ON開/OFF關)
- elif payload['command'] == 'tank_pump_cleanwater_in_status':
- if payload['response'] == 'on':
- D['tank_pump_cleanwater_in_status'] = 'on'
- else:
- D['tank_pump_cleanwater_in_status'] = 'off'
- # 桶外進水電磁閥(ON開/OFF關)
- elif payload['command'] == 'outer_solenoid_water_status':
- if payload['response'] == 'on':
- D['outer_solenoid_water_status'] = 'on'
- else:
- D['outer_solenoid_water_status'] = 'off'
- # 中水入水電磁閥(ON開/OFF關)
- elif payload['command'] == 'tank_solenoid_reclaimed_in_status':
- if payload['response'] == 'on':
- D['tank_solenoid_reclaimed_in_status'] = 'on'
- else:
- D['tank_solenoid_reclaimed_in_status'] = 'off'
- # 清水入水電磁閥(ON開/OFF關)
- elif payload['command'] == 'tank_solenoid_water_in_status':
- if payload['response'] == 'on':
- D['tank_solenoid_water_in_status'] = 'on'
- else:
- D['tank_solenoid_water_in_status'] = 'off'
- # 排水廢水電磁閥(ON開/OFF關)
- elif payload['command'] == 'tank_solenoid_water_out_status':
- if payload['response'] == 'on':
- D['tank_solenoid_water_out_status'] = 'on'
- else:
- D['tank_solenoid_water_out_status'] = 'off'
- # 排水中水電磁閥(ON開/OFF關)
- elif payload['command'] == 'tank_solenoid_reclaimed_out_status':
- if payload['response'] == 'on':
- D['tank_solenoid_reclaimed_out_status'] = 'on'
- else:
- D['tank_solenoid_reclaimed_out_status'] = 'off'
- # 雙核隔膜泵(ON開/OFF關)
- elif payload['command'] == 'tank_pump_sensor_status':
- if payload['response'] == 'on':
- D['tank_pump_sensor_status'] = 'on'
- else:
- D['tank_pump_sensor_status'] = 'off'
- # 逆洗 pump 電磁閥(ON開/OFF關)
- elif payload['command'] == 'solenoid_tank_pump_status':
- if payload['response'] == 'on':
- D['solenoid_tank_pump_status'] = 'on'
- else:
- D['solenoid_tank_pump_status'] = 'off'
- # 噴嘴(ON開/OFF關)
- elif payload['command'] == 'tank_nozzle_status':
- if payload['response'] == 'on':
- D['tank_nozzle_status'] = 'on'
- else:
- D['tank_nozzle_status'] = 'off'
- # 鼓風機(ON開/OFF關)
- elif payload['command'] == 'tank_blower_status':
- if payload['response'] == 'on':
- D['tank_blower_status'] = 'on'
- else:
- D['tank_blower_status'] = 'off'
- # 加熱棒 1(ON開/OFF關)
- elif payload['command'] == 'tank_heater1_status':
- if payload['response'] == 'on':
- D['tank_heater1_status'] = 'on'
- else:
- D['tank_heater1_status'] = 'off'
- # 加熱棒 2(ON開/OFF關)
- elif payload['command'] == 'tank_heater2_status':
- if payload['response'] == 'on':
- D['tank_heater2_status'] = 'on'
- else:
- D['tank_heater2_status'] = 'off'
-
- # 發酵槽 溫控開關
- elif payload['command'] == 'tank_temp_enable':
- if payload['response'] == 'on':
- D['tank_temp_enable'] = 'on'
- else:
- D['tank_temp_enable'] = 'off'
- # 發酵槽 設定溫度
- elif payload['command'] == 'tank_temp':
- if payload['response'] == 'off':
- D['tank_temp'] = '0'
- else:
- D['tank_temp'] = payload['response']
- # 蝴蝶閥(ON開/OFF關)
- elif payload['command'] == 'tank_diskvalve_status':
- if payload['response'] == 'on':
- D['tank_diskvalve_status'] = 'on'
- else:
- D['tank_diskvalve_status'] = 'off'
-
- # 出料儲豆槽真空吸料機(ON吸料/OFF排氣)
- elif payload['command'] == 'output_vacuum_status':
- if payload['response'] == 'on':
- D['output_vacuum_status'] = 'on'
- else:
- D['output_vacuum_status'] = 'off'
- else:
- return "MQTT command NOT FOUND"
|