coffee3.020220805.py 122 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import paho.mqtt.client as mqtt
  4. import time
  5. import sys
  6. import urllib
  7. import json
  8. import threading
  9. import os
  10. import shutil
  11. import uuid
  12. import hashlib
  13. import serial
  14. import array
  15. import numpy
  16. import base64
  17. import datetime
  18. import requests
  19. import numpy as np
  20. import pymysql.cursors
  21. import sqlite3
  22. import subprocess
  23. """ Device Information - the information about this device
  24. These device information is used for the MQTT topic. This program will subscribe and publish to
  25. the MQTT topic.
  26. MQTT topic to subscribe to: AISKY/<project_name>/<model_name>/<device_id>
  27. MQTT topic to publish to : AISKY/<project_name>/<model_name>/<device_id>/Log
  28. """
  29. # @var project_name The project name comes from the u-boot environment variable 'project'.
  30. # @var model_name The model name comes from the u-boot environment variable 'model'.
  31. # @var device_id The device id comes from the mac address of eth0.
  32. project_name = "Coffee"
  33. model_name = "MK-G"
  34. #device_id = open('/sys/class/net/eth0/address').readline().strip()
  35. device_id = "b8:27:eb:7e:24:78"
  36. """ NOTE: Remember to setup the u-boot environment variables before executing this program. The
  37. commands to setup the u-boot environment variables are as follows.
  38. Setup the 'project' variable: The following command sets the 'project' variable to AppleFarm.
  39. root@mylinkit:~# fw_setenv project AppleFarm
  40. Setup the 'model' variable: The following command sets the 'model' variable to MK-G.
  41. root@mylinkit:~# fw_setenv model MK-G
  42. Then, the following command can be used to display the u-boot environment variables.
  43. root@mylinkit:~# fw_printenv
  44. """
  45. """ MQTT Server
  46. If you don't have your own MQTT server, you can use the public MQTT server 'iot.eclipse.org'. But
  47. with the public MQTT server, you can only publish and subscribe without a user name and password.
  48. Sometimes the public MQTT server is unstable.
  49. """
  50. # @var mqtt_server The URL or IP address of the MQTT server to connect to.
  51. # @var mqtt_port The port of the MQTT server to connect to.
  52. # @var mqtt_alive Maximum period in seconds allowed between communications with the broker. If
  53. # no other messages are being exchanged, this controls the rate at which the
  54. # client will send ping messages to the broker.
  55. mqtt_server = "60.250.156.234"
  56. mqtt_port = 1883
  57. mqtt_alive = 60
  58. # @var mqtt_sub_topic The MQTT topic to subscribe to.
  59. # @var mqtt_pub_topic The MQTT topic to publish to.
  60. mqtt_sub_topic = "AISKY/" + project_name + "/" + model_name + "/" + device_id
  61. mqtt_pub_topic = mqtt_sub_topic + "/Log"
  62. validation = 0
  63. number = 1
  64. r_humidity = 0
  65. r_air_temp = 0
  66. r_ph = 0
  67. r_TDS1 = 0
  68. r_CO2 = 0
  69. r_sonic = 0
  70. r_atmospheric = 0
  71. i=0
  72. j=0
  73. count=0
  74. vacuum_value=0
  75. threewayvalve_value=0
  76. diskvalve_value=0
  77. solenoid_disinfect_value=0
  78. solenoid_water_value=0
  79. motor_value=0
  80. blower_value=0
  81. heater1_value=0
  82. heater2_value=0
  83. vacuum_value1=0
  84. vacuum_value2=0
  85. input_vacuum_value1=0
  86. input_vacuum_value2=0
  87. air_temp1_value=0
  88. air_temp1_enable_value=0
  89. arr=[]
  90. x=0
  91. #乾燥槽狀態
  92. dryer_motor_value=[0,0,0,0,0,0,0,0,0,0,0,0]
  93. dryer_diskvalve_value=[0,0,0,0,0,0,0,0,0,0,0,0]
  94. dryer_temp_value=[0,0,0,0,0,0,0,0,0,0,0,0]
  95. dryer_temp_enable_value=[0,0,0,0,0,0,0,0,0,0,0,0]
  96. dryer_blower_value=[0,0,0,0,0,0,0,0,0,0,0,0]
  97. dryer_heater1_value=[0,0,0,0,0,0,0,0,0,0,0,0]
  98. dryer_heater2_value=[0,0,0,0,0,0,0,0,0,0,0,0]
  99. dryer_solenoid_disinfect=[0,0,0,0,0,0,0,0,0,0,0,0]
  100. dryer_solenoid_water_value=[0,0,0,0,0,0,0,0,0,0,0,0]
  101. dryer_vacuum_value=[0,0,0,0,0,0,0,0,0,0,0,0]
  102. #發酵槽狀態
  103. ferment_temp=[0,0,0,0,0,0,0,0,0,0,0,0]
  104. ferment_temp_enable=[0,0,0,0,0,0,0,0,0,0,0,0]
  105. ferment_motor_value=[0,0,0,0,0,0,0,0,0,0,0,0]
  106. ferment_diskvalve_value=[0,0,0,0,0,0,0,0,0,0,0,0]
  107. ferment_solenoid_disinfect=[0,0,0,0,0,0,0,0,0,0,0,0]
  108. ferment_pump_sensor=[0,0,0,0,0,0,0,0,0,0,0,0]
  109. ferment_solenoid_tank_pump=[0,0,0,0,0,0,0,0,0,0,0,0]
  110. ferment_solenoid_water_in=[0,0,0,0,0,0,0,0,0,0,0,0]
  111. ferment_outer_solenoid_water=[0,0,0,0,0,0,0,0,0,0,0,0]
  112. ferment_tank_solenoid_water_out=[0,0,0,0,0,0,0,0,0,0,0,0]
  113. ferment_outer_threewayvalve_float=[0,0,0,0,0,0,0,0,0,0,0,0]
  114. #清洗槽狀態
  115. clean_stepping_motor_value=[0,0,0,0,0,0,0,0,0,0,0,0]
  116. clean_pump_waterL2L3_value=[0,0,0,0,0,0,0,0,0,0,0,0]
  117. clean_pump_waterL4L5_value=[0,0,0,0,0,0,0,0,0,0,0,0]
  118. clean_pump_waterInput_value=[0,0,0,0,0,0,0,0,0,0,0,0]
  119. clean_solenoid_waterL3_value=[0,0,0,0,0,0,0,0,0,0,0,0]
  120. clean_solenoid_waterL5_value=[0,0,0,0,0,0,0,0,0,0,0,0]
  121. clean_vacuum_value=[0,0,0,0,0,0,0,0,0,0,0,0]
  122. #脫皮機狀態
  123. peel_motor_value=[0,0,0,0,0,0,0,0,0,0,0,0]
  124. peel_vacuum_value=[0,0,0,0,0,0,0,0,0,0,0,0]
  125. #path = "http://13.113.114.87/20200312/tofitolab.php"
  126. ## Calculate the SHA256 checksum of the file.
  127. # @param file [in] The file path for which you want to calculate the checksum.
  128. def get_sha256sum(file):
  129. with open(file, "rb") as f:
  130. bytes = f.read()
  131. return hashlib.sha256(bytes).hexdigest()
  132. ## Send logs to the server.
  133. # @param command [in] The command received from the server.
  134. # @param response [in] The response message to the command.
  135. #串口設定
  136. def used_com1port():
  137. global ser
  138. #UART串口設定
  139. ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
  140. #ZIGBEE串口設定
  141. #ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
  142. def used_com2port():
  143. global ser
  144. #UART串口設定
  145. #ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
  146. #ZIGBEE串口設定
  147. #ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
  148. def used_com3port():
  149. global ser
  150. #UART串口設定
  151. ser = serial.Serial('/dev/ttyUSB2', 115200, timeout=1)
  152. #ZIGBEE串口設定
  153. #ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
  154. def used_com4port():
  155. global ser
  156. #UART串口設定
  157. #ser = serial.Serial('/dev/ttyUSB1', 115200, timeout=1)
  158. #ZIGBEE串口設定
  159. #ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
  160. #MQTT回覆
  161. def server_log(command,number,response):
  162. localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  163. # message to be sent in JSON format
  164. payload = {
  165. # let server know which device the message came from
  166. 'device_id': device_id,
  167. # let server know when the message was sent from the device
  168. 'localtime': localtime,
  169. 'tank_number':number,
  170. 'command': command,
  171. 'response': response
  172. }
  173. jsonobj = json.dumps(payload, sort_keys=True, indent=4)
  174. mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)
  175. print('Sent:')
  176. print(jsonobj)
  177. def sql_local_upload(command):
  178. conn = sqlite3.connect('/home/pi/coffee.db')
  179. c = conn.cursor()
  180. c.execute("UPDATE coffee set command = '%s' where sn=1"\
  181. %(command))
  182. conn.commit()
  183. conn.close()
  184. def sql_local_pin_configuration_upload(msg):
  185. conn = sqlite3.connect('/home/pi/coffee.db')
  186. c = conn.cursor()
  187. c.execute("UPDATE pin_configuration set M4 = '%s' ,M10 = '%s', M16 = '%s', M5 = '%s',M2 = '%s',M17 = '%s',M7 = '%s',M3 = '%s',M18 = '%s',M6 = '%s',M9 = '%s',M14 = '%s',M15 = '%s',M13 = '%s',M12 = '%s',M11 = '%s',M8 = '%s',M1 = '%s',M19 = '%s',zigbee = '%s',wifi = '%s',ethernet = '%s',SD = '%s',relay1 = '%s',relay2 = '%s',relay3 = '%s',relay4 = '%s',relay5 = '%s',relay6 = '%s',relay7 = '%s',relay8 = '%s',relay9 = '%s',relay10 = '%s',relay11 = '%s',relay12 = '%s',relay13 = '%s',relay14 = '%s',relay15 = '%s',relay16 = '%s',relay17 = '%s',relay18 = '%s',relay19 = '%s',relay20 = '%s' where sn=1"\
  188. %(msg['M4'] , msg['M10'] ,msg['M16'] , msg['M5'], msg['M2'], msg['M17'], msg['M7'], msg['M3'], msg['M18'], msg['M6'], msg['M9'], msg['M14'], msg['M15'], msg['M13'], msg['M12'], msg['M11'], msg['M8'], msg['M1'], msg['M19'], msg['zigbee'], msg['wifi'], msg['ethernet'], msg['SD'], msg['relay1'], msg['relay2'], msg['relay3'], msg['relay4'], msg['relay5'], msg['relay6'], msg['relay7'], msg['relay8'], msg['relay9'], msg['relay10'], msg['relay11'], msg['relay12'], msg['relay13'], msg['relay14'], msg['relay15'], msg['relay16'], msg['relay17'], msg['relay18'], msg['relay19'], msg['relay20']))
  189. conn.commit()
  190. conn.close()
  191. def sql_local_pin_configuration(msg):
  192. localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  193. for i in range (len(msg['pin'])):
  194. conn = sqlite3.connect('/home/pi/coffee.db')
  195. c = conn.cursor()
  196. c.execute("INSERT INTO pin (time,pin_nr,pin_position,pin_type) \
  197. VALUES ('%s','%s','%s','%s')"
  198. %(localtime,msg['pin'][i]['pin_nr'],msg['pin'][i]['pin_position'], msg['pin'][i]['pin_type']))
  199. conn.commit()
  200. conn.close()
  201. print("end")
  202. server_log(msg['command'],"D1","ok")
  203. def sql_local_add_cond_code_upload(msg):
  204. for i in range (len(msg['cond'])):
  205. for j in range (len(msg['cond'][i]['cond_add'])):
  206. add=msg['cond'][i]['cond_add'][j].split(" ")
  207. conn = sqlite3.connect('/home/pi/coffee.db')
  208. c = conn.cursor()
  209. c.execute("INSERT INTO add_cond_code (time,cont,cond_d1_2,cond_a1_2,cond_b1_2,cond_c1_2) \
  210. VALUES ('%s','%d','%s','%s', '%s', '%s')"
  211. %(localtime,i+1,add[0],add[1], add[2],add[3]))
  212. conn.commit()
  213. conn.close()
  214. print("end")
  215. server_log('cond_add_code_upload',msg['cond_tank1_1'],"ok")
  216. def sql_local_act_code_upload(msg):
  217. for i in range (len(msg['cond'])):
  218. for j in range (len(msg['cond'][i]['cond_com'])):
  219. com=msg['cond'][i]['cond_com'][j].split(" ")
  220. conn = sqlite3.connect('/home/pi/coffee.db')
  221. c = conn.cursor()
  222. c.execute("INSERT INTO act_code (time,cont,do_obj1_1,act) \
  223. VALUES ('%s','%d','%s','%s')"
  224. %(localtime,i+1,com[0],com[1]))
  225. conn.commit()
  226. conn.close()
  227. print("end")
  228. server_log('act_code_upload',msg['cond_tank1_1'],"ok")
  229. def sql_local_code_upload(msg):
  230. print(msg['cond'])
  231. print(msg['cond'][0]['cond_main'])
  232. print(msg['cond'][0]['cond_add'])
  233. print(len(msg['cond'][0]['cond_add']))
  234. print(msg['cond'][0]['cond_com'][0])
  235. print(len(msg['cond'][0]['cond_com']))
  236. localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  237. for i in range (len(msg['cond'])):
  238. m=msg['cond'][i]['cond_main'].split(" ")
  239. print(m[0])
  240. print(m[1])
  241. if(m[0]=="else" and m[1]=="if"):
  242. print("ok")
  243. m[0]=m[0]+" "+m[1]
  244. m[1]=m[2]
  245. m[2]=m[3]
  246. m[3]=m[4]
  247. m[4]=m[5]
  248. conn = sqlite3.connect('/home/pi/coffee.db')
  249. c = conn.cursor()
  250. c.execute("INSERT INTO cond_code (time,cont,cond_tank1_1,cond_z1_1,cond_a1_1,cond_b1_1,cond_c1_1) \
  251. VALUES ('%s','%d','%s','%s', '%s', '%s', '%s')"
  252. %(localtime,i+1,m[1],m[0],m[2], m[3], m[4]))
  253. conn.commit()
  254. conn.close()
  255. for i in range (len(msg['cond'])):
  256. for j in range (len(msg['cond'][i]['cond_add'])):
  257. add=msg['cond'][i]['cond_add'][j].split(" ")
  258. conn = sqlite3.connect('/home/pi/coffee.db')
  259. c = conn.cursor()
  260. c.execute("INSERT INTO add_cond_code (time,cont,cond_d1_2,cond_a1_2,cond_b1_2,cond_c1_2) \
  261. VALUES ('%s','%d','%s','%s', '%s', '%s')"
  262. %(localtime,i+1,add[0],add[1], add[2],add[3]))
  263. conn.commit()
  264. conn.close()
  265. for i in range (len(msg['cond'])):
  266. for j in range (len(msg['cond'][i]['cond_com'])):
  267. com=msg['cond'][i]['cond_com'][j].split(" ")
  268. conn = sqlite3.connect('/home/pi/coffee.db')
  269. c = conn.cursor()
  270. c.execute("INSERT INTO act_code (time,cont,do_obj1_1,act) \
  271. VALUES ('%s','%d','%s','%s')"
  272. %(localtime,i+1,com[0],com[1]))
  273. conn.commit()
  274. conn.close()
  275. print("end")
  276. server_log(msg['command'],"D1","ok")
  277. def sql_upload(command,value):
  278. global vacuum_value
  279. global threewayvalve_value
  280. global diskvalve_value
  281. global solenoid_disinfect_value
  282. global solenoid_water_value
  283. global motor_value
  284. global blower_value
  285. global heater1_value
  286. global heater2_value
  287. global air_temp1_value
  288. global air_temp1_enable_value
  289. datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  290. print (datetime)
  291. conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye', database='Coffee',
  292. charset='utf8')
  293. a = conn.cursor()
  294. if (command == 'temp1'):
  295. temp1_value = value
  296. elif (command == 'temp1_enable'):
  297. temp1_enable_value = value
  298. elif (command == 'tank_motor_status'):
  299. motor_value = value
  300. elif (command == 'tank_diskvalve_status'):
  301. diskvalve_value = value
  302. elif (command == 'tank_blower_status'):
  303. blower_value = value
  304. elif (command == 'tank_heater1_status'):
  305. heater1_value = value
  306. elif (command == 'tank_heater2_status'):
  307. heater2_value = value
  308. elif (command == 'tank_threewayvalve_status'):
  309. threewayvalve_value = value
  310. elif (command == 'tank_solenoid_disinfect_status'):
  311. solenoid_disinfect_value = value
  312. elif (command == 'outer_solenoid_water_status'):
  313. solenoid_water_value = value
  314. elif (command == 'outer_threewayvalve_float_status'):
  315. vacuum_value = value
  316. print(
  317. datetime, vacuum_value, threewayvalve_value, diskvalve_value, solenoid_disinfect_value, solenoid_water_value,
  318. motor_value, blower_value, heater1_value, heater2_value,air_temp1_enable_value,air_temp1_value)
  319. sqlStuff = "INSERT INTO dry_tank_brake (datetime,vacuum,threewayvalve,diskvalve,solenoid_disinfect,solenoid_water,motor,blower,heater1,heater2,temp1_enable,temp1) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
  320. data = [(datetime, vacuum_value, threewayvalve_value, diskvalve_value, solenoid_disinfect_value,
  321. solenoid_water_value, motor_value, blower_value, heater1_value, heater2_value,air_temp1_enable_value,air_temp1_value)]
  322. a.executemany(sqlStuff, data)
  323. conn.commit()
  324. #發酵槽資料表
  325. def ferment_sql_upload(command,tank_num,number,value):
  326. global ferment_temp
  327. global ferment_temp_enable
  328. global ferment_motor_value
  329. global ferment_diskvalve_value
  330. global ferment_solenoid_disinfect
  331. global ferment_pump_sensor
  332. global ferment_solenoid_tank_pump
  333. global ferment_solenoid_water_in
  334. global ferment_outer_solenoid_water
  335. global ferment_tank_solenoid_water_out
  336. global ferment_outer_threewayvalve_float
  337. datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  338. print (datetime)
  339. conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye', database='Coffee',
  340. charset='utf8')
  341. a = conn.cursor()
  342. if (command == 'tank_temp'):
  343. ferment_temp[number-1] = value
  344. if (command == 'tank_temp_enable'):
  345. ferment_temp_enable[number-1] = value
  346. if (command == 'tank_motor_status'):
  347. ferment_motor_value[number-1] = value
  348. elif (command == 'tank_diskvalve_status'):
  349. ferment_diskvalve_value[number-1] = value
  350. elif (command == 'tank_solenoid_disinfect_status'):
  351. ferment_solenoid_disinfect[number-1] = value
  352. elif (command == 'tank_pump_sensor_status'):
  353. ferment_pump_sensor[number-1] = value
  354. elif (command == 'solenoid_tank_pump_status'):
  355. ferment_solenoid_tank_pump[number-1] = value
  356. elif (command == 'tank_solenoid_water_in_status'):
  357. ferment_solenoid_water_in[number-1] = value
  358. elif (command == 'outer_solenoid_water_status'):
  359. ferment_outer_solenoid_water[number-1] = value
  360. elif (command == 'outer_threewayvalve_float_status'):
  361. ferment_outer_threewayvalve_float[number-1] = value
  362. elif (command == 'tank_solenoid_water_out_status'):
  363. ferment_tank_solenoid_water_out[number-1] = value
  364. sqlStuff = "INSERT INTO ferment_tank_actuator (datetime,tank_num,vacuum,threewayvalve_input,diskvalve,solenoid_tank_pump,solenoid_tank_disinfect,solenoid_outer_water,solenoid_tank_water_in,solenoid_tank_water_out,pump_sensor,threewayvalve_outer_float,motor,heater1,heater2,temp_enable,temp) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
  365. data = [(datetime,tank_num,0,0,ferment_diskvalve_value[number-1],ferment_solenoid_tank_pump[number-1],ferment_solenoid_disinfect[number-1],ferment_outer_solenoid_water[number-1],ferment_solenoid_water_in[number-1],ferment_tank_solenoid_water_out[number-1],ferment_pump_sensor[number-1],ferment_outer_threewayvalve_float[number-1],ferment_motor_value[number-1],0,0,ferment_temp_enable[number-1],ferment_temp[number-1])]
  366. a.executemany(sqlStuff, data)
  367. conn.commit()
  368. #乾燥槽資料表
  369. def dryer_sql_upload(command,tank_num,number,value):
  370. global dryer_temp_value
  371. global dryer_temp_enable_value
  372. global dryer_motor_value
  373. global dryer_diskvalve_value
  374. global dryer_blower_value
  375. global dryer_heater1_value
  376. global dryer_heater2_value
  377. global dryer_solenoid_disinfect
  378. global dryer_solenoid_water_value
  379. global dryer_vacuum_value
  380. datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  381. print (datetime)
  382. conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye', database='Coffee',
  383. charset='utf8')
  384. a = conn.cursor()
  385. if (command == 'tank_temp'):
  386. dryer_temp_value[number-1] = value
  387. elif (command == 'tank_temp_enable'):
  388. dryer_temp_enable_value[number-1] = value
  389. elif (command == 'tank_motor_status'):
  390. dryer_motor_value[number-1] = value
  391. elif (command == 'tank_diskvalve_status'):
  392. dryer_diskvalve_value[number-1] = value
  393. elif (command == 'tank_blower_status'):
  394. dryer_blower_value[number-1] = value
  395. elif (command == 'tank_heater1_status'):
  396. dryer_heater1_value[number-1] = value
  397. elif (command == 'tank_heater2_status'):
  398. dryer_heater2_value[number-1] = value
  399. elif (command == 'tank_solenoid_disinfect_status'):
  400. dryer_solenoid_disinfect[number-1] = value
  401. elif (command == 'tank_solenoid_water_status'):
  402. dryer_solenoid_water_value[number-1] = value
  403. elif (command == 'tank_vacuum_status'):
  404. dryer_vacuum_value[number-1] = value
  405. print(datetime,tank_num,dryer_motor_value[number-1],dryer_diskvalve_value[number-1])
  406. sqlStuff = "INSERT INTO dry_tank_brake (datetime,tank_num,vacuum,threewayvalve,diskvalve,solenoid_disinfect,solenoid_water,motor,blower,heater1,heater2,temp1_enable,temp1) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
  407. data = [(datetime,tank_num,dryer_vacuum_value[number-1],0,dryer_diskvalve_value[number-1],dryer_solenoid_disinfect[number-1],dryer_solenoid_water_value[number-1],dryer_motor_value[number-1],dryer_blower_value[number-1],dryer_heater1_value[number-1],dryer_heater2_value[number-1],dryer_temp_enable_value[number-1],dryer_temp_value[number-1])]
  408. a.executemany(sqlStuff, data)
  409. conn.commit()
  410. #清洗槽資料表
  411. def clean_sql_upload(command,tank_num,number,value):
  412. global clean_stepping_motor_value
  413. global clean_pump_waterL2L3_value
  414. global clean_pump_waterL4L5_value
  415. global clean_pump_waterInput_value
  416. global clean_solenoid_waterL3_value
  417. global clean_solenoid_waterL5_value
  418. global clean_vacuum_value
  419. datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  420. print (datetime)
  421. conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye', database='Coffee',
  422. charset='utf8')
  423. a = conn.cursor()
  424. if (command == 'step_motor_status'):
  425. clean_stepping_motor_value[number-1] = value
  426. elif (command == 'tank_pump_waterL4L5_status'):
  427. clean_pump_waterL4L5_value[number-1] = value
  428. elif (command == 'tank_pump_waterInput_status'):
  429. clean_pump_waterInput_value[number-1] = value
  430. elif (command == 'tank_pump_waterL2L3_status'):
  431. clean_pump_waterL2L3_value[number-1] = value
  432. elif (command == 'tank_solenoid_waterL2L3_status'):
  433. clean_solenoid_waterL3_value[number-1] = value
  434. elif (command == 'tank_solenoid_waterL4L5_status'):
  435. clean_solenoid_waterL5_value[number-1] = value
  436. elif (command == 'tank_vacuum_status'):
  437. clean_vacuum_value[number-1] = value
  438. sqlStuff = "INSERT INTO clean_tank_actuator (datetime,tank_num,vacuum,pump_waterInput,pump_waterL2L3,pump_waterL4L5,solenoid_waterL2L3,solenoid_waterL4L5,stepping_motor) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"
  439. data = [(datetime,tank_num,clean_vacuum_value[number-1],clean_pump_waterInput_value[number-1],clean_pump_waterL2L3_value[number-1],clean_pump_waterL4L5_value[number-1],clean_solenoid_waterL3_value[number-1],clean_solenoid_waterL5_value[number-1],clean_stepping_motor_value[number-1])]
  440. a.executemany(sqlStuff, data)
  441. conn.commit()
  442. #脫皮機資料表
  443. def peel_sql_upload(command,tank_num,number,value):
  444. global peel_motor_value
  445. global peel_vacuum_value
  446. datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  447. print (datetime)
  448. conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye', database='Coffee',
  449. charset='utf8')
  450. a = conn.cursor()
  451. if (command == 'tank_motor_status'):
  452. peel_motor_value[number-1] = value
  453. elif (command == 'tank_vacuum_status'):
  454. peel_vacuum_value[number-1] = value
  455. sqlStuff = "INSERT INTO peel_tank_actuator (datetime,tank_num,vacuum,motor) VALUES (%s,%s,%s,%s)"
  456. data = [(datetime,tank_num,peel_vacuum_value[number-1],peel_motor_value[number-1])]
  457. a.executemany(sqlStuff, data)
  458. conn.commit()
  459. #乾燥槽入料儲豆槽資料表
  460. def sql_dry_input_brake(command,number,value):
  461. global vacuum_value1
  462. datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  463. print (datetime)
  464. conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye',database='Coffee', charset='utf8')
  465. a = conn.cursor()
  466. vacuum_value1 = int(value)
  467. sqlStuff = "INSERT INTO dry_input_brake (datetime,vacuum) VALUES (%s,%s)"
  468. data = [(datetime,vacuum_value1)]
  469. a.executemany(sqlStuff, data)
  470. conn.commit()
  471. #乾燥槽出料儲豆槽資料表
  472. def sql_dry_output_brake(command,number,value):
  473. global vacuum_value2
  474. datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  475. print (datetime)
  476. conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye',database='Coffee', charset='utf8')
  477. a = conn.cursor()
  478. vacuum_value2 = int(value)
  479. sqlStuff = "INSERT INTO dry_output_brake (datetime,vacuum) VALUES (%s,%s)"
  480. data = [(datetime,vacuum_value2)]
  481. a.executemany(sqlStuff, data)
  482. conn.commit()
  483. #發酵槽入料儲豆槽資料表
  484. def sql_ferment_input_brake(command,tank_num,number,value):
  485. global input_vacuum_value1
  486. datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  487. print (datetime)
  488. conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye',database='Coffee', charset='utf8')
  489. a = conn.cursor()
  490. vacuum_value1 = int(value)
  491. sqlStuff = "INSERT INTO ferment_input_actuator (datetime,tank_num,vacuum) VALUES (%s,%s,%s)"
  492. data = [(datetime,tank_num,vacuum_value1)]
  493. a.executemany(sqlStuff, data)
  494. conn.commit()
  495. #發酵槽出料儲豆槽資料表
  496. def sql_ferment_output_brake(command,tank_num,number,value):
  497. global input_vacuum_value2
  498. datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  499. print (datetime)
  500. conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye',database='Coffee', charset='utf8')
  501. a = conn.cursor()
  502. vacuum_value2 = int(value)
  503. sqlStuff = "INSERT INTO ferment_output_actuator (datetime,tank_num,vacuum) VALUES (%s,%s,%s)"
  504. data = [(datetime,tank_num,vacuum_value2)]
  505. a.executemany(sqlStuff, data)
  506. conn.commit()
  507. #桶槽編號轉換
  508. def typecomtonum(command):
  509. global type_num
  510. tank_type=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
  511. type_number=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]
  512. for c in range(26):
  513. if (tank_type[c]==command):
  514. print(type_number[c])
  515. type_num=type_number[c]
  516. ## Reset this device.
  517. def system_reboot():
  518. server_log('reboot', 'Restarting system')
  519. time.sleep(5)
  520. os.system('reboot -f')
  521. time.sleep(10)
  522. ## Reset this device to factory default.
  523. def factory_reset():
  524. server_log('factory_reset', 'Resetting to factory default')
  525. time.sleep(5)
  526. os.system('firstboot -y')
  527. os.system('reboot -f')
  528. time.sleep(10)
  529. ## Report the system information about this device to the server.
  530. def system_info():
  531. # get firmware version from the file
  532. fw_version = open('/etc/fw_version').readline().strip()
  533. localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  534. # message to be sent in JSON format
  535. payload = {
  536. 'device_id': device_id,
  537. 'localtime': localtime,
  538. 'command': 'system_info',
  539. 'project': project_name,
  540. 'model': model_name,
  541. 'fw_version': fw_version,
  542. 'mqtt_sub_topic': mqtt_sub_topic,
  543. 'mqtt_pub_topic': mqtt_pub_topic
  544. }
  545. jsonobj = json.dumps(payload, sort_keys=True, indent=4)
  546. mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)
  547. print('Sent:')
  548. print(jsonobj)
  549. ## Update system firmware.
  550. # @param msg [in] The message from the server in JSON format.
  551. def system_update(msg):
  552. if (msg['filetype'] == 'img'):
  553. # create a directory to store the firmware image
  554. dirname = '/tmp/' + str(uuid.uuid1()) + '/'
  555. filepath = dirname + 'update.img'
  556. os.makedirs(dirname)
  557. # start to download the firmware image
  558. server_log('system_update', 'Downloading system firmware')
  559. urllib.urlretrieve(msg['url'], filepath)
  560. # check the SHA256 checksum of the firmware image
  561. if (msg['sha256sum'] == get_sha256sum(filepath)):
  562. server_log('system_update', 'Updating system firmware')
  563. # start to upgrade the system firmware
  564. os.system('sysupgrade -n ' + filepath)
  565. else:
  566. server_log('system_update', 'ERROR: SHA256 checksum is wrong')
  567. shutil.rmtree(dirname, ignore_errors=True)
  568. #馬達轉速設定
  569. def stir(msg):
  570. if(msg['tank_num']=="D1"):
  571. rpm=int(msg['value'])
  572. if(rpm<0):
  573. direction=1
  574. rpm=-rpm
  575. else:
  576. direction=0
  577. pwm=int(round((1.8088*rpm)+11))
  578. if(rpm==0):
  579. pwm=0
  580. if(pwm>99):
  581. pwm=99
  582. used_com3port()
  583. print("ok")
  584. typecomtonum(msg['tank_num'][0:1])
  585. print(int(msg['tank_num'][1:]))
  586. #commandarray = [0xFF,0xF1,0x02,0x01,0x01,direction,rpm,0x0D]
  587. commandarray = [0xFF,pwm,direction,0x00,0x00,0x00,0x0D]
  588. print(commandarray)
  589. ser.write(array.array('B', commandarray).tostring())
  590. #sql_upload(msg['command'],int(msg['value']))
  591. if(msg['tank_num']=="P1"):
  592. peel_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),int(msg['value']))
  593. elif(msg['tank_num']=="F1"):
  594. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),int(msg['value']))
  595. elif(msg['tank_num']=="D1"):
  596. dryer_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),int(msg['value']))
  597. if(direction==1):
  598. rpm=-rpm
  599. server_log('tank_motor_status',msg['tank_num'],rpm)
  600. #入料儲豆槽真空吸引機
  601. def input_vacuum(msg):
  602. typecomtonum(msg['tank_num'][0:1])
  603. if (msg['value'] == 'on'):
  604. used_com2port()
  605. commandarray = [0xFF,0xF1,0x01,0x02,0x01,0x02,0x00,0x0D]
  606. #commandarray = [0xFF,0x01,0x02,0x03,0x01,0x00,0x0D]
  607. print(commandarray)
  608. ser.write(array.array('B', commandarray).tostring())
  609. #sql_dry_output_brake(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  610. sql_ferment_input_brake(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  611. server_log('input_vacuum_status',msg['tank_num'], "on")
  612. elif(msg['value'] == 'off'):
  613. used_com2port()
  614. commandarray = [0xFF,0xF1,0x01,0x02,0x01,0x02,0x01,0x0D]
  615. #commandarray = [0xFF,0x01,0x02,0x03,0x01,0x01,0x0D]
  616. print(commandarray)
  617. ser.write(array.array('B', commandarray).tostring())
  618. #sql_dry_output_brake(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  619. sql_ferment_input_brake(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  620. server_log('input_vacuum_status',msg['tank_num'], "off")
  621. #真空吸料機設定
  622. def vacuum(msg):
  623. if(msg['tank_num']=="D1"):
  624. typecomtonum(msg['tank_num'][0:1])
  625. if (msg['value'] == 'on'):
  626. used_com2port()
  627. #commandarray = [0xFF,0xF1,0x01,0x02,0x01,0x01,0x00,0x0D]
  628. #print(commandarray)
  629. #ser.write(array.array('B', commandarray).tostring())
  630. #time.sleep(0.2)
  631. #commandarray = [0xFF,0xF1,0x02,0x02,0x01,0x02,0x01,0x0D]
  632. commandarray = [0xF1,0x01,0x02,0x03,0x02,0x00,0x0D]
  633. print(commandarray)
  634. ser.write(array.array('B', commandarray).tostring())
  635. if(msg['tank_num']=="P1"):
  636. peel_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  637. elif(msg['tank_num']=="F1"):
  638. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  639. elif(msg['tank_num']=="D1"):
  640. dryer_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  641. elif(msg['tank_num']=="C1"):
  642. clean_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  643. server_log('tank_vacuum_status',msg['tank_num'],"on")
  644. elif(msg['value'] == 'off'):
  645. used_com2port()
  646. #commandarray = [0xFF,0xF1,0x01,0x02,0x01,0x01,0x01,0x0D]
  647. #print(commandarray)
  648. #ser.write(array.array('B', commandarray).tostring())
  649. #time.sleep(0.2)
  650. #commandarray = [0xFF,0xF1,0x02,0x02,0x01,0x02,0x00,0x0D]
  651. commandarray = [0xF1,0x01,0x02,0x03,0x02,0x01,0x0D]
  652. print(commandarray)
  653. ser.write(array.array('B', commandarray).tostring())
  654. if(msg['tank_num']=="P1"):
  655. peel_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  656. elif(msg['tank_num']=="F1"):
  657. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  658. elif(msg['tank_num']=="D1"):
  659. dryer_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  660. elif(msg['tank_num']=="C1"):
  661. clean_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  662. server_log('tank_vacuum_status',msg['tank_num'],"off")
  663. #出料儲豆槽真空吸引機
  664. def output_vacuum(msg):
  665. typecomtonum(msg['tank_num'][0:1])
  666. if (msg['value'] == 'on'):
  667. used_com2port()
  668. commandarray = [0xFF,0xF1,0x01,0x02,0x01,0x03,0x00,0x0D]
  669. #commandarray = [0xFF,0x01,0x02,0x03,0x03,0x00,0x0D]
  670. print(commandarray)
  671. ser.write(array.array('B', commandarray).tostring())
  672. #sql_dry_output_brake(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  673. sql_ferment_output_brake(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  674. server_log('output_vacuum_status',msg['tank_num'], "on")
  675. elif(msg['value'] == 'off'):
  676. used_com2port()
  677. commandarray = [0xFF,0xF1,0x01,0x02,0x01,0x03,0x01,0x0D]
  678. #commandarray = [0xFF,0x01,0x02,0x03,0x03,0x01,0x0D]
  679. print(commandarray)
  680. ser.write(array.array('B', commandarray).tostring())
  681. #sql_dry_output_brake(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  682. sql_ferment_output_brake(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  683. server_log('output_vacuum_status',msg['tank_num'], "off")
  684. #吸料機三通閥設定
  685. def threewayvalve_input(msg):
  686. typecomtonum(msg['tank_num'][0:1])
  687. if (msg['value'] == 'on'):
  688. #used_com4port()
  689. commandarray = [0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0D]
  690. print(commandarray)
  691. #ser.write(array.array('B', commandarray).tostring())
  692. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  693. server_log('tank_threewayvalve_status',msg['tank_num'],"on")
  694. elif (msg['value'] == 'off'):
  695. #used_com4port()
  696. commandarray = [0xFF, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0D]
  697. print(commandarray)
  698. #ser.write(array.array('B', commandarray).tostring())
  699. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  700. server_log('tank_threewayvalve_status',msg['tank_num'],"off")
  701. #蝴蝶閥設定
  702. def diskvalve(msg):
  703. if(msg['tank_num']=="D1"):
  704. typecomtonum(msg['tank_num'][0:1])
  705. if (msg['value'] == 'on'):
  706. used_com2port()
  707. #commandarray = [0xFF,0x02,0x00,0x00,0x01,0x00,0x0D]
  708. commandarray = [0xF1,0x01,0x02,0x03,0x03,0x00,0x0D]
  709. print(commandarray)
  710. ser.write(array.array('B', commandarray).tostring())
  711. #sql_upload(msg['command'],1)
  712. if(msg['tank_num']=="F1"):
  713. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  714. elif(msg['tank_num']=="D1"):
  715. dryer_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  716. server_log('tank_diskvalve_status',msg['tank_num'], "on")
  717. elif(msg['value'] == 'off'):
  718. used_com2port()
  719. #commandarray = [0xFF,0x02,0x00,0x00,0x01,0x01,0x0D]
  720. commandarray = [0xF1,0x01,0x02,0x03,0x03,0x01,0x0D]
  721. print(commandarray)
  722. ser.write(array.array('B', commandarray).tostring())
  723. #sql_upload(msg['command'],0)
  724. if(msg['tank_num']=="F1"):
  725. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  726. elif(msg['tank_num']=="D1"):
  727. dryer_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  728. server_log('tank_diskvalve_status',msg['tank_num'], "off")
  729. #消毒閥設定
  730. def disinfect(msg):
  731. typecomtonum(msg['tank_num'][0:1])
  732. if (msg['value'] == 'on'):
  733. used_com2port()
  734. commandarray = [0xFF, 0x02, 0x00, 0x00, 0x03, 0x00, 0x0D]
  735. print(commandarray)
  736. ser.write(array.array('B', commandarray).tostring())
  737. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  738. server_log('tank_solenoid_disinfect_status',msg['tank_num'], "on")
  739. elif (msg['value'] == 'off'):
  740. used_com2port()
  741. commandarray = [0xFF, 0x02, 0x00, 0x00, 0x03, 0x01, 0x0D]
  742. print(commandarray)
  743. ser.write(array.array('B', commandarray).tostring())
  744. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  745. server_log('tank_solenoid_disinfect_status',msg['tank_num'], "off")
  746. #加熱管1設定
  747. def heater1(msg):
  748. if(msg['tank_num']=="D1"):
  749. typecomtonum(msg['tank_num'][0:1])
  750. if (msg['value'] == 'on'):
  751. used_com1port()
  752. commandarray = [0xF1,0x02,0x02,0x03,0x01,0x00,0x0D]
  753. print(commandarray)
  754. ser.write(array.array('B', commandarray).tostring())
  755. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  756. server_log('tank_heater1_status',msg['tank_num'], "on")
  757. elif(msg['value'] == 'off'):
  758. used_com1port()
  759. commandarray = [0xF1,0x02,0x02,0x03,0x01,0x01,0x0D]
  760. print(commandarray)
  761. ser.write(array.array('B', commandarray).tostring())
  762. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  763. server_log('tank_heater1_status',msg['tank_num'], "off")
  764. #加熱管2設定
  765. def heater2(msg):
  766. if(msg['tank_num']=="D1"):
  767. typecomtonum(msg['tank_num'][0:1])
  768. if (msg['value'] == 'on'):
  769. used_com1port()
  770. commandarray = [0xF1,0x01,0x02,0x03,0x02,0x00,0x0D]
  771. print(commandarray)
  772. ser.write(array.array('B', commandarray).tostring())
  773. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  774. server_log('tank_heater2_status',msg['tank_num'], "on")
  775. elif(msg['value'] == 'off'):
  776. used_com1port()
  777. commandarray = [0xF1,0x01,0x02,0x03,0x02,0x01,0x0D]
  778. print(commandarray)
  779. ser.write(array.array('B', commandarray).tostring())
  780. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  781. server_log('tank_heater2_status',msg['tank_num'], "off")
  782. #控制溫度設定
  783. def air_temp(msg):
  784. typecomtonum(msg['tank_num'][0:1])
  785. temp1=int(float(msg['value'])//10)
  786. temp2=int(((float(msg['value'])%10)*10)//10)
  787. temp3=int(((float(msg['value'])%10)*10)%10)
  788. used_com1port()
  789. commandarray = [0xFF,temp1,temp2, temp3,0x01,0x01,0x0D]
  790. print(commandarray)
  791. ser.write(array.array('B', commandarray).tostring())
  792. dryer_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),float(msg['value']))
  793. server_log(msg['command'],msg['tank_num'], msg['value'])
  794. #控制溫度持續時間設定
  795. def temp_time(msg):
  796. typecomtonum(msg['tank_num'][0:1])
  797. #used_com3port()
  798. if msg['day']=='':
  799. msg['day']=0
  800. if msg['hr']=='':
  801. msg['hr']=0
  802. if msg['min']=='':
  803. msg['min']=0
  804. commandarray = [0xF4,int(msg['day']),int(msg['hr']),int(msg['min']),0x01,0x01,0x0D]
  805. print(commandarray)
  806. #ser.write(array.array('B', commandarray).tostring())
  807. sql_upload(msg['command'],int(msg['value']))
  808. server_log(msg['command'],msg['tank_num'], msg['value'])
  809. #溫度控制功能啟用與否
  810. def air_temp_enable(msg):
  811. typecomtonum(msg['tank_num'][0:1])
  812. if (msg['value'] == 'on'):
  813. used_com1port()
  814. commandarray = [0xF2,0x01,0x03, 0x03, 0x01, 0x01, 0x0D]
  815. print(commandarray)
  816. ser.write(array.array('B', commandarray).tostring())
  817. dryer_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  818. server_log(msg['command'],msg['tank_num'], "on")
  819. elif(msg['value'] == 'off'):
  820. used_com1port()
  821. commandarray = [0xF3,0x03,0x03, 0x03, 0x01, 0x01, 0x0D]
  822. print(commandarray)
  823. ser.write(array.array('B', commandarray).tostring())
  824. dryer_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  825. server_log(msg['command'],msg['tank_num'], "off")
  826. #雙核水泵設定
  827. def pump(msg,con):
  828. typecomtonum(msg['tank_num'][0:1])
  829. if (msg['value'] == 'on'):
  830. used_com1port()
  831. commandarray = [0xFF,0x01,0x02,0x03,0x03,0x00,0x0D]
  832. print(commandarray)
  833. ser.write(array.array('B', commandarray).tostring())
  834. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  835. server_log('tank_pump_sensor_status',msg['tank_num'], "on")
  836. elif(msg['value'] == 'off'):
  837. used_com1port()
  838. commandarray = [0xFF,0x01,0x02,0x03,0x03,0x01,0x0D]
  839. print(commandarray)
  840. ser.write(array.array('B', commandarray).tostring())
  841. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  842. server_log('tank_pump_sensor_status',msg['tank_num'], "off")
  843. #發酵槽廢水排水閥
  844. def water_out(msg):
  845. typecomtonum(msg['tank_num'][0:1])
  846. if (msg['value'] == 'on'):
  847. used_com1port()
  848. commandarray = [0xFF,0x02,0x02,0x03,0x01,0x00,0x0D]
  849. print(commandarray)
  850. ser.write(array.array('B', commandarray).tostring())
  851. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  852. server_log(msg['command'],msg['tank_num'], "on")
  853. elif(msg['value'] == 'off'):
  854. used_com1port()
  855. commandarray = [0xFF,0x02,0x02,0x03,0x01,0x01,0x0D]
  856. print(commandarray)
  857. ser.write(array.array('B', commandarray).tostring())
  858. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  859. server_log(msg['command'],msg['tank_num'], "off")
  860. #內桶進水電磁閥
  861. def water_in(msg):
  862. typecomtonum(msg['tank_num'][0:1])
  863. if (msg['value'] == 'on'):
  864. used_com1port()
  865. commandarray = [0xFF,0x01,0x02,0x03,0x01,0x00,0x0D]
  866. print(commandarray)
  867. ser.write(array.array('B', commandarray).tostring())
  868. #sql_upload(msg['command'],1)
  869. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  870. server_log('tank_solenoid_water_in_status',msg['tank_num'], "on")
  871. elif(msg['value'] == 'off'):
  872. used_com1port()
  873. commandarray = [0xFF,0x01,0x02,0x03,0x01,0x01,0x0D]
  874. print(commandarray)
  875. ser.write(array.array('B', commandarray).tostring())
  876. #sql_upload(msg['command'],0)
  877. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  878. server_log('tank_solenoid_water_in_status',msg['tank_num'], "off")
  879. #外桶進水電磁閥
  880. def water(msg):
  881. typecomtonum(msg['tank_num'][0:1])
  882. if (msg['value'] == 'on'):
  883. used_com1port()
  884. commandarray = [0xFF,0x01,0x02,0x03,0x02,0x00,0x0D]
  885. print(commandarray)
  886. ser.write(array.array('B', commandarray).tostring())
  887. #sql_upload(msg['command'],1)
  888. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  889. server_log('tank_solenoid_water_status',msg['tank_num'], "on")
  890. elif(msg['value'] == 'off'):
  891. used_com1port()
  892. commandarray = [0xFF,0x01,0x02,0x03,0x02,0x01,0x0D]
  893. print(commandarray)
  894. ser.write(array.array('B', commandarray).tostring())
  895. #sql_upload(msg['command'],0)
  896. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  897. server_log('tank_solenoid_water_status',msg['tank_num'], "off")
  898. #逆洗閥
  899. def solenoid_tank_pump(msg):
  900. typecomtonum(msg['tank_num'][0:1])
  901. if (msg['value'] == 'on'):
  902. used_com2port()
  903. commandarray = [0xFF, 0x02, 0x01, 0x00, 0x02, 0x00, 0x0D]
  904. print(commandarray)
  905. ser.write(array.array('B', commandarray).tostring())
  906. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  907. server_log(msg['command'],msg['tank_num'],"on")
  908. elif (msg['value'] == 'off'):
  909. used_com2port()
  910. commandarray = [0xFF, 0x02, 0x00, 0x00, 0x02, 0x01, 0x0D]
  911. print(commandarray)
  912. ser.write(array.array('B', commandarray).tostring())
  913. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  914. server_log(msg['command'],msg['tank_num'],"off")
  915. #浮選三通閥
  916. def threewayvalve_float(msg):
  917. typecomtonum(msg['tank_num'][0:1])
  918. if (msg['value'] == 'on'):
  919. #ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
  920. commandarray = [0xFF, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0D]
  921. print(commandarray)
  922. #ser.write(array.array('B', commandarray).tostring())
  923. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  924. server_log('outer_threewayvalve_float_status',msg['tank_num'],"on")
  925. elif (msg['value'] == 'off'):
  926. #ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
  927. commandarray = [0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0D]
  928. print(commandarray)
  929. #ser.write(array.array('B', commandarray).tostring())
  930. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  931. server_log('outer_threewayvalve_float_status',msg['tank_num'],"off")
  932. #加壓幫浦
  933. def pump1(msg,con):
  934. typecomtonum(msg['tank_num'][0:1])
  935. if (msg['value'] == 'on'):
  936. #ser = serial.Serial('/dev/ttyUSB3', 115200, timeout=1)
  937. commandarray = [0xF1,0x01,0x02,0x03,con,0x00,0x0D]
  938. print(commandarray)
  939. #ser.write(array.array('B', commandarray).tostring())
  940. clean_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  941. server_log(msg['command'],msg['tank_num'], "on")
  942. elif(msg['value'] == 'off'):
  943. #ser = serial.Serial('/dev/ttyUSB3', 115200, timeout=1)
  944. commandarray = [0xF1,0x01,0x02,0x03,con,0x01,0x0D]
  945. print(commandarray)
  946. #ser.write(array.array('B', commandarray).tostring())
  947. clean_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  948. server_log(msg['command'],msg['tank_num'], "off")
  949. #乾燥槽排水閥
  950. def drain(msg):
  951. if (msg['value'] == 'on'):
  952. #ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
  953. commandarray = [0xF1,0x01,0x02,0x03,0x02,0x00,0x0D]
  954. print(commandarray)
  955. #ser.write(array.array('B', commandarray).tostring())
  956. server_log('tank_solenoid_water_status',msg['tank_num'], "on")
  957. elif(msg['value'] == 'off'):
  958. #ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
  959. commandarray = [0xF1,0x01,0x02,0x03,0x02,0x01,0x0D]
  960. print(commandarray)
  961. #ser.write(array.array('B', commandarray).tostring())
  962. server_log('tank_solenoid_water_status',msg['tank_num'], "off")
  963. #鼓風機
  964. def blower(msg):
  965. if(msg['tank_num']=="D1"):
  966. if (msg['value'] == 'on'):
  967. used_com1port()
  968. commandarray = [0xF1,0x01,0x02,0x03,0x03,0x00,0x0D]
  969. print(commandarray)
  970. ser.write(array.array('B', commandarray).tostring())
  971. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  972. server_log('tank_blower_status',msg['tank_num'], "on")
  973. elif(msg['value'] == 'off'):
  974. used_com1port()
  975. commandarray = [0xF1,0x01,0x02,0x03,0x03,0x01,0x0D]
  976. print(commandarray)
  977. ser.write(array.array('B', commandarray).tostring())
  978. ferment_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  979. server_log('tank_blower_status',msg['tank_num'], "off")
  980. def valve5(msg):
  981. if (msg['value'] == 'on'):
  982. #ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
  983. commandarray = [0xFF,0xF1,0x01,0x03,0x01,0x02,0x00,0x0D]
  984. print(commandarray)
  985. #ser.write(array.array('B', commandarray).tostring())
  986. clean_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  987. server_log(msg['command'],msg['tank_num'], "on")
  988. elif(msg['value'] == 'off'):
  989. #ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
  990. commandarray = [0xFF,0xF1,0x01,0x03,0x01,0x02,0x01,0x0D]
  991. print(commandarray)
  992. #ser.write(array.array('B', commandarray).tostring())
  993. clean_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  994. server_log(msg['command'],msg['tank_num'], "off")
  995. def valve6(msg):
  996. if (msg['value'] == 'on'):
  997. #ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
  998. commandarray = [0xFF,0xF1,0x01,0x03,0x01,0x01,0x00,0x0D]
  999. print(commandarray)
  1000. #ser.write(array.array('B', commandarray).tostring())
  1001. clean_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),1)
  1002. server_log(msg['command'],msg['tank_num'], "on")
  1003. elif(msg['value'] == 'off'):
  1004. #ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
  1005. commandarray = [0xFF,0xF1,0x01,0x03,0x01,0x01,0x01,0x0D]
  1006. print(commandarray)
  1007. #ser.write(array.array('B', commandarray).tostring())
  1008. clean_sql_upload(msg['command'],msg['tank_num'],int(msg['tank_num'][1:]),0)
  1009. server_log(msg['command'],msg['tank_num'], "off")
  1010. def otatest(msg):
  1011. ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
  1012. ser.flushOutput()
  1013. commandarray = [0xFF,0x03,0x00,0x00, 0x00, 0x00, 0x0D]
  1014. print(commandarray)
  1015. ser.write(array.array('B', commandarray).tostring())
  1016. print('Send OK')
  1017. server_log('otatest',msg['tank_num'],'success')
  1018. def otastart(msg):
  1019. ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=0.1)
  1020. ser.flushOutput()
  1021. arr=[]
  1022. i=0
  1023. global j
  1024. j=0
  1025. file = '/home/pi/ISP/newtest.hex'
  1026. with open(file, "rb") as f:
  1027. for line in f.readlines():
  1028. if (line[1:2])==b'1':
  1029. j=j+1
  1030. j1=int(j/100)
  1031. j2=j%100
  1032. #print(j)
  1033. commandarray = [0xFF,0x01,j1,j2, 0x00, 0x00, 0x0D]
  1034. #print(commandarray)
  1035. ser.write(array.array('B', commandarray).tostring())
  1036. try:
  1037. e=0
  1038. rcv = ser.read(1)
  1039. print (hex(ord(rcv)))
  1040. if (hex(ord(rcv)) == "0x79"):
  1041. file = '/home/pi/ISP/newtest.hex'
  1042. with open(file, "rb") as f:
  1043. for line in f.readlines():
  1044. i=i+1
  1045. if(i>1 and i<j+2 and e==0):
  1046. num1 =int(line[9:11],16)
  1047. num2 =int(line[11:13],16)
  1048. num3 =int(line[13:15],16)
  1049. num4 =int(line[15:17],16)
  1050. num5 =int(line[17:19],16)
  1051. num6 =int(line[19:21],16)
  1052. num7 =int(line[21:23],16)
  1053. num8 =int(line[23:25],16)
  1054. num9 =int(line[25:27],16)
  1055. num10 =int(line[27:29],16)
  1056. num11=int(line[29:31],16)
  1057. num12=int(line[31:33],16)
  1058. num13 =int(line[33:35],16)
  1059. num14 =int(line[35:37],16)
  1060. num15 =int(line[37:39],16)
  1061. num16 =int(line[39:-4],16)
  1062. checksum=0x0F^num4^num3^num2^num1^num8^num7^num6^num5^num12^num11^num10^num9^num16^num15^num14^num13
  1063. arr= [num4]+[num3]+[num2]+[num1]+[num8]+[num7]+[num6]+[num5]+[num12]+[num11]+[num10]+[num9]+[num16]+[num15]+[num14]+[num13]+[checksum]
  1064. #print(arr)
  1065. #print(checksum)
  1066. #time.sleep(0.1)
  1067. ser.write(array.array('B', arr).tostring())
  1068. ser.flushOutput()
  1069. try:
  1070. rcv = ser.readline()
  1071. rcv1 = ser.readline()
  1072. rcv2 = ser.readline()
  1073. rcv3 = ser.readline()
  1074. rcv4 = ser.readline()
  1075. rcv5 = ser.readline()
  1076. if(str(checksum)==rcv4[:-2]):
  1077. e=0
  1078. print("success")
  1079. else:
  1080. if(rcv5=="error"):
  1081. print("error")
  1082. arr= [num4]+[num3]+[num2]+[num1]+[num8]+[num7]+[num6]+[num5]+[num12]+[num11]+[num10]+[num9]+[num16]+[num15]+[num14]+[num13]+[checksum]
  1083. ser.write(array.array('B', arr).tostring())
  1084. rcv = ser.readline()
  1085. rcv1 = ser.readline()
  1086. rcv2 = ser.readline()
  1087. rcv3 = ser.readline()
  1088. rcv4 = ser.readline()
  1089. rcv5 = ser.readline()
  1090. if(str(checksum)==rcv4[:-2]):
  1091. e=0
  1092. print("success")
  1093. else:
  1094. e=1
  1095. print("error again")
  1096. except:
  1097. server_log('OTA',msg['tank_num'], 'no reply')
  1098. else:
  1099. e=1
  1100. if(e==0):
  1101. server_log('ota',msg['tank_num'], 'success')
  1102. else:
  1103. server_log('OTA',msg['tank_num'], 'upload error')
  1104. except:
  1105. server_log('OTA',msg['tank_num'], 'no reply')
  1106. def ota(msg):
  1107. os.system('sudo su')
  1108. os.system('rm -rf /home/pi/OTA')
  1109. os.system('git clone '+msg['url']+' /home/pi/OTA')
  1110. ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=0.1)
  1111. ser.flushOutput()
  1112. arr=[]
  1113. i=0
  1114. global j
  1115. j=0
  1116. file = '/home/pi/OTA/OTASTM32F4.hex'
  1117. with open(file, "rb") as f:
  1118. for line in f.readlines():
  1119. print(line[1:2])
  1120. if (line[1:2])==b'1':
  1121. j=j+1
  1122. j1=int(j/100)
  1123. j2=j%100
  1124. print(j*4)
  1125. commandarray = [0xFF,0x01,j1,j2, 0x00, 0x00, 0x0D]
  1126. print(commandarray)
  1127. ser.write(array.array('B', commandarray).tostring())
  1128. try:
  1129. e=0
  1130. rcv = ser.read(1)
  1131. print (hex(ord(rcv)))
  1132. if (hex(ord(rcv)) == "0x79"):
  1133. file = '/home/pi/OTA/OTASTM32F4.hex'
  1134. with open(file, "rb") as f:
  1135. for line in f.readlines():
  1136. i=i+1
  1137. if(i>1 and i<j+2 and e==0):
  1138. num1 =int(line[9:11],16)
  1139. num2 =int(line[11:13],16)
  1140. num3 =int(line[13:15],16)
  1141. num4 =int(line[15:17],16)
  1142. num5 =int(line[17:19],16)
  1143. num6 =int(line[19:21],16)
  1144. num7 =int(line[21:23],16)
  1145. num8 =int(line[23:25],16)
  1146. num9 =int(line[25:27],16)
  1147. num10 =int(line[27:29],16)
  1148. num11=int(line[29:31],16)
  1149. num12=int(line[31:33],16)
  1150. num13 =int(line[33:35],16)
  1151. num14 =int(line[35:37],16)
  1152. num15 =int(line[37:39],16)
  1153. num16 =int(line[39:-4],16)
  1154. checksum=0x0F^num4^num3^num2^num1^num8^num7^num6^num5^num12^num11^num10^num9^num16^num15^num14^num13
  1155. arr= [num4]+[num3]+[num2]+[num1]+[num8]+[num7]+[num6]+[num5]+[num12]+[num11]+[num10]+[num9]+[num16]+[num15]+[num14]+[num13]+[checksum]
  1156. #print(arr)
  1157. #print(checksum)
  1158. #time.sleep(0.1)
  1159. ser.write(array.array('B', arr).tostring())
  1160. ser.flushOutput()
  1161. try:
  1162. rcv = ser.readline()
  1163. rcv1 = ser.readline()
  1164. rcv2 = ser.readline()
  1165. rcv3 = ser.readline()
  1166. rcv4 = ser.readline()
  1167. rcv5 = ser.readline()
  1168. if(str(checksum)==rcv4[:-2]):
  1169. e=0
  1170. else:
  1171. if(rcv5=="error"):
  1172. arr= [num4]+[num3]+[num2]+[num1]+[num8]+[num7]+[num6]+[num5]+[num12]+[num11]+[num10]+[num9]+[num16]+[num15]+[num14]+[num13]+[checksum]
  1173. ser.write(array.array('B', arr).tostring())
  1174. rcv = ser.readline()
  1175. rcv1 = ser.readline()
  1176. rcv2 = ser.readline()
  1177. rcv3 = ser.readline()
  1178. rcv4 = ser.readline()
  1179. rcv5 = ser.readline()
  1180. if(str(checksum)==rcv4[:-2]):
  1181. e=0
  1182. else:
  1183. e=1
  1184. except:
  1185. server_log('OTA',msg['tank_num'], 'no reply')
  1186. else:
  1187. e=1
  1188. if(e==0):
  1189. server_log('ota', msg['tank_num'],'success')
  1190. else:
  1191. server_log('OTA',msg['tank_num'], 'upload error')
  1192. except:
  1193. server_log('OTA',msg['tank_num'], 'no reply')
  1194. def ICP(msg):
  1195. ser.flushOutput()
  1196. arr=[]
  1197. i=0
  1198. global j
  1199. file = '/home/pi/OTA/OTA.hex'
  1200. with open(file, "rb") as f:
  1201. for line in f.readlines():
  1202. i=i+1
  1203. if(i>1 and i<j+2):
  1204. num1 =int(line[9:11],16)
  1205. num2 =int(line[11:13],16)
  1206. num3 =int(line[13:15],16)
  1207. num4 =int(line[15:17],16)
  1208. num5 =int(line[17:19],16)
  1209. num6 =int(line[19:21],16)
  1210. num7 =int(line[21:23],16)
  1211. num8 =int(line[23:25],16)
  1212. num9 =int(line[25:27],16)
  1213. num10 =int(line[27:29],16)
  1214. num11=int(line[29:31],16)
  1215. num12=int(line[31:33],16)
  1216. num13 =int(line[33:35],16)
  1217. num14 =int(line[35:37],16)
  1218. num15 =int(line[37:39],16)
  1219. num16 =int(line[39:-4],16)
  1220. arr+= [num4]+[num3]+[num2]+[num1]+[num8]+[num7]+[num6]+[num5]+[num12]+[num11]+[num10]+[num9]+[num16]+[num15]+[num14]+[num13]
  1221. print(arr)
  1222. ser.write(array.array('B', arr).tostring())
  1223. print('Send OK')
  1224. server_log('icp',msg['tank_num'], '1')
  1225. def clear(msg):
  1226. ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=0.1)
  1227. ser.flushOutput()
  1228. commandarray = [0x7F]
  1229. ser.write(array.array('B', commandarray).tostring())
  1230. ser.flushOutput()
  1231. try:
  1232. rcv = ser.read(1)
  1233. print(hex(ord(rcv)))
  1234. if (hex(ord(rcv)) =="0x79"):
  1235. commandarray = [0x02,0xFD]
  1236. ser.write(array.array('B', commandarray).tostring())
  1237. try:
  1238. rcv1 = ser.read(1)
  1239. rcv2 = ser.read(1)
  1240. rcv3 = ser.read(1)
  1241. rcv4 = ser.read(1)
  1242. rcv5 = ser.read(1)
  1243. print (hex(ord(rcv4)))
  1244. if (hex(ord(rcv4)) =="0x17"):
  1245. commandarray = [0x44,0xBB]
  1246. ser.write(array.array('B', commandarray).tostring())
  1247. ser.flushOutput()
  1248. try:
  1249. rcv = ser.read(1)
  1250. print (hex(ord(rcv)))
  1251. checksum=[]
  1252. commandarray = [0x00,0xFE]
  1253. sum=0
  1254. if (hex(ord(rcv)) =="0x79"):
  1255. for x in range (510):
  1256. addr1=x/255
  1257. addr2=x%255
  1258. commandarray += [int(addr1),int(addr2)]
  1259. sum=sum^x
  1260. checksum=[int(sum/255),int(sum%255)]
  1261. commandarray += checksum
  1262. ser.write(array.array('B', commandarray).tostring())
  1263. try:
  1264. rcv = ser.read(1)
  1265. print (hex(ord(rcv)))
  1266. if (hex(ord(rcv)) =="0x79"):
  1267. server_log('clear',msg['tank_num'], 'success')
  1268. else:
  1269. server_log('clear',msg['tank_num'], 'upload failed')
  1270. except:
  1271. server_log('clear',msg['tank_num'], 'upload failed')
  1272. else:
  1273. server_log('clear',msg['tank_num'], 'erase memory error')
  1274. except:
  1275. server_log('clear',msg['tank_num'], 'erase memory error')
  1276. elif(hex(ord(rcv4)) =="0x13"):
  1277. commandarray = [0x44,0xBB]
  1278. ser.write(array.array('B', commandarray).tostring())
  1279. ser.flushOutput()
  1280. try:
  1281. rcv = ser.read(1)
  1282. print (hex(ord(rcv)))
  1283. if (hex(ord(rcv)) =="0x79"):
  1284. commandarray = [0xFF,0xFF,0x00]
  1285. ser.write(array.array('B', commandarray).tostring())
  1286. ser.flushOutput()
  1287. try:
  1288. time.sleep(20)
  1289. rcv = ser.read(1)
  1290. print (hex(ord(rcv)))
  1291. if (hex(ord(rcv)) =="0x79"):
  1292. server_log('clear',msg['tank_num'], 'success')
  1293. else:
  1294. server_log('clear',msg['tank_num'], 'upload failed')
  1295. except:
  1296. server_log('clear',msg['tank_num'], 'upload failed')
  1297. else:
  1298. server_log('clear',msg['tank_num'], 'erase memory failed')
  1299. except:
  1300. server_log('clear',msg['tank_num'], 'erase memory failed')
  1301. else:
  1302. server_log('clear', msg['tank_num'],'recognition failed')
  1303. except:
  1304. server_log('clear', msg['tank_num'],'recognition failed')
  1305. else:
  1306. server_log('clear',msg['tank_num'], 'no ready')
  1307. except:
  1308. server_log('clear',msg['tank_num'], 'no ready')
  1309. def ISP(msg):
  1310. ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=0.1)
  1311. ser.flushOutput()
  1312. commandarray = [0x7F]
  1313. ser.write(array.array('B', commandarray).tostring())
  1314. ser.flushOutput()
  1315. try:
  1316. rcv = ser.read(1)
  1317. print(hex(ord(rcv)))
  1318. if (hex(ord(rcv)) =="0x79"):
  1319. commandarray = [0x02,0xFD]
  1320. ser.write(array.array('B', commandarray).tostring())
  1321. try:
  1322. rcv1 = ser.read(1)
  1323. rcv2 = ser.read(1)
  1324. rcv3 = ser.read(1)
  1325. rcv4 = ser.read(1)
  1326. rcv5 = ser.read(1)
  1327. print (hex(ord(rcv4)))
  1328. if (hex(ord(rcv4)) =="0x17"):
  1329. commandarray = [0x44,0xBB]
  1330. ser.write(array.array('B', commandarray).tostring())
  1331. ser.flushOutput()
  1332. try:
  1333. rcv = ser.read(1)
  1334. print (hex(ord(rcv)))
  1335. checksum=[]
  1336. commandarray = [0x00,0xFE]
  1337. sum=0
  1338. if (hex(ord(rcv)) =="0x79"):
  1339. for x in range (510):
  1340. addr1=x/255
  1341. addr2=x%255
  1342. commandarray += [int(addr1),int(addr2)]
  1343. sum=sum^x
  1344. checksum=[int(sum/255),int(sum%255)]
  1345. commandarray += checksum
  1346. ser.write(array.array('B', commandarray).tostring())
  1347. try:
  1348. rcv = ser.read(1)
  1349. print (hex(ord(rcv)))
  1350. if (hex(ord(rcv)) =="0x79"):
  1351. server_log('clear',msg['tank_num'], 'success')
  1352. except:
  1353. server_log('clear',msg['tank_num'], 'upload failed')
  1354. except:
  1355. server_log('clear',msg['tank_num'], 'erase memory error')
  1356. elif(hex(ord(rcv4)) =="0x13"):
  1357. commandarray = [0x44,0xBB]
  1358. ser.write(array.array('B', commandarray).tostring())
  1359. ser.flushOutput()
  1360. try:
  1361. rcv = ser.read(1)
  1362. print (hex(ord(rcv)))
  1363. if (hex(ord(rcv)) =="0x79"):
  1364. commandarray = [0xFF,0xFF,0x00]
  1365. ser.write(array.array('B', commandarray).tostring())
  1366. ser.flushOutput()
  1367. try:
  1368. time.sleep(20)
  1369. rcv = ser.read(1)
  1370. print (hex(ord(rcv)))
  1371. if (hex(ord(rcv)) =="0x79"):
  1372. s=1
  1373. except:
  1374. server_log('clear',msg['tank_num'], 'upload failed')
  1375. except:
  1376. server_log('clear',msg['tank_num'], 'erase memory failed')
  1377. except:
  1378. server_log('clear',msg['tank_num'], 'recognition failed')
  1379. except:
  1380. server_log('clear',msg['tank_num'], 'no ready')
  1381. if (s==1):
  1382. s=0
  1383. ser.flushOutput()
  1384. arr=[]
  1385. j=0
  1386. i=0
  1387. file = '/home/pi/ISP/OTA.hex'
  1388. with open(file, "rb") as f:
  1389. for line in f.readlines():
  1390. if (line[1:2])==b'1':
  1391. j=j+1
  1392. print(j)
  1393. file = '/home/pi/ISP/OTA.hex'
  1394. with open(file, "rb") as f:
  1395. for line in f.readlines():
  1396. i=i+1
  1397. if(i>1 and i<j+2):
  1398. addr1=int(line[3:5],16)
  1399. addr2=int(line[5:7],16)
  1400. num1 =int(line[9:11],16)
  1401. num2 =int(line[11:13],16)
  1402. num3 =int(line[13:15],16)
  1403. num4 =int(line[15:17],16)
  1404. num5 =int(line[17:19],16)
  1405. num6 =int(line[19:21],16)
  1406. num7 =int(line[21:23],16)
  1407. num8 =int(line[23:25],16)
  1408. num9 =int(line[25:27],16)
  1409. num10 =int(line[27:29],16)
  1410. num11=int(line[29:31],16)
  1411. num12=int(line[31:33],16)
  1412. num13 =int(line[33:35],16)
  1413. num14 =int(line[35:37],16)
  1414. num15 =int(line[37:39],16)
  1415. num16 =int(line[39:-4],16)
  1416. commandarray = [0x31,0xCE]
  1417. #print(commandarray)
  1418. ser.write(array.array('B', commandarray).tostring())
  1419. try:
  1420. rcv = ser.read(1)
  1421. #print (hex(ord(rcv)))
  1422. if (hex(ord(rcv)) =="0x79"):
  1423. commandarray = [0x08,0x00,addr1,addr2,(0x08^0x00^addr1^addr2)]
  1424. ser.write(array.array('B', commandarray).tostring())
  1425. try:
  1426. rcv = ser.read(1)
  1427. #print (hex(ord(rcv)))
  1428. if (hex(ord(rcv)) =="0x79"):
  1429. checksum=0x0F^num1^num2^num3^num4^num5^num6^num7^num8^num9^num10^num11^num12^num13^num14^num15^num16
  1430. commandarray = [0x0F]+[num1]+[num2]+[num3]+[num4]+[num5]+[num6]+[num7]+[num8]+[num9]+[num10]+[num11]+[num12]+[num13]+[num14]+[num15]+[num16]+[checksum]
  1431. #print(commandarray)
  1432. ser.write(array.array('B', commandarray).tostring())
  1433. try:
  1434. rcv = ser.read(1)
  1435. #print (hex(ord(rcv)))
  1436. if (hex(ord(rcv)) !="0x79"):
  1437. con=1
  1438. server_log('isp',msg['tank_num'], 'upload error')
  1439. else:
  1440. con=0
  1441. except:
  1442. server_log('isp',msg['tank_num'], 'upload error')
  1443. except:
  1444. server_log('isp',msg['tank_num'], 'addr error')
  1445. except:
  1446. server_log('isp',msg['tank_num'], 'write memory failed')
  1447. if (con==0):
  1448. server_log('isp',msg['tank_num'], 'success')
  1449. def sht11(msg):
  1450. ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
  1451. commandarray = [0xFF,0xF1,0x01,0x01,0x03,0x00,0x00,0x0D]
  1452. print(commandarray)
  1453. ser.write(array.array('B', commandarray).tostring())
  1454. temp=0
  1455. humidity=0
  1456. tank=0
  1457. ser.flushOutput()
  1458. time.sleep(1)
  1459. if ser.inWaiting():
  1460. x = ser.readline()
  1461. if (hex(ord(x[0])) == "0xff" and hex(ord(x[10])) == "0xd"):
  1462. if int(ord(x[2])) == 2:
  1463. tank="D1"
  1464. if int(ord(x[3])) == 1:
  1465. print (-1*(int(ord(x[4]))+ (0.1 * int(ord(x[5])))))
  1466. temp=-1 * (int(ord(x[4])) + (0.1 * int(ord(x[5]))))
  1467. print (int(ord(x[6]))+(0.1 * int(ord(x[7]))))
  1468. humidity=int(ord(x[6])) + (0.1 * int(ord(x[7])))
  1469. if int(ord(x[3])) == 0:
  1470. print(int(ord(x[4])) + 0.1 * int(ord(x[5])))
  1471. temp=int(ord(x[4])) + 0.1 * int(ord(x[5]))
  1472. print (int(ord(x[6])) + 0.1 * int(ord(x[7])))
  1473. humidity=int(ord(x[6])) + 0.1 * int(ord(x[7]))
  1474. print(tank)
  1475. datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  1476. conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye',
  1477. database='Coffee', charset='utf8')
  1478. a = conn.cursor()
  1479. sqlStuff = "INSERT INTO dry_tank_SHT11 (datetime,tank_num,SHT11_Temp,SHT11_Humidity) VALUES (%s,%s,%s,%s)"
  1480. data = [(datetime,tank,temp,humidity)]
  1481. a.executemany(sqlStuff, data)
  1482. conn.commit()
  1483. server_log(msg['command'],msg['tank_num'], temp)
  1484. def sht12(msg):
  1485. ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
  1486. commandarray = [0xFF,0xF1,0x02,0x01,0x03,0x00,0x00,0x0D]
  1487. print(commandarray)
  1488. ser.write(array.array('B', commandarray).tostring())
  1489. temp=0
  1490. humidity=0
  1491. tank=0
  1492. ser.flushOutput()
  1493. time.sleep(1)
  1494. if ser.inWaiting():
  1495. x = ser.readline()
  1496. if (hex(ord(x[0])) == "0xff" and hex(ord(x[10])) == "0xd"):
  1497. if int(ord(x[2])) == 3:
  1498. tank="D2"
  1499. if int(ord(x[3])) == 1:
  1500. print (-1*(int(ord(x[4]))+ (0.1 * int(ord(x[5])))))
  1501. temp=-1 * (int(ord(x[4])) + (0.1 * int(ord(x[5]))))
  1502. print (int(ord(x[6]))+(0.1 * int(ord(x[7]))))
  1503. humidity=int(ord(x[6])) + (0.1 * int(ord(x[7])))
  1504. if int(ord(x[3])) == 0:
  1505. print(int(ord(x[4])) + 0.1 * int(ord(x[5])))
  1506. temp=int(ord(x[4])) + 0.1 * int(ord(x[5]))
  1507. print (int(ord(x[6])) + 0.1 * int(ord(x[7])))
  1508. humidity=int(ord(x[6])) + 0.1 * int(ord(x[7]))
  1509. print(tank)
  1510. datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  1511. conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye',
  1512. database='Coffee', charset='utf8')
  1513. a = conn.cursor()
  1514. sqlStuff = "INSERT INTO dry_tank_SHT11 (datetime,tank_num,SHT11_Temp,SHT11_Humidity) VALUES (%s,%s,%s,%s)"
  1515. data = [(datetime,tank,temp,humidity)]
  1516. a.executemany(sqlStuff, data)
  1517. conn.commit()
  1518. server_log(msg['command'],msg['tank_num'], temp)
  1519. def sonic(msg):
  1520. ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
  1521. commandarray = [0xFF,0xF1,0x02,0x01,0x03,0x00,0x00,0x0D]
  1522. print(commandarray)
  1523. ser.write(array.array('B', commandarray).tostring())
  1524. temp=0
  1525. humidity=0
  1526. tank=0
  1527. ser.flushOutput()
  1528. time.sleep(1)
  1529. if ser.inWaiting():
  1530. x = ser.readline()
  1531. if (hex(ord(x[0])) == "0xff" and hex(ord(x[10])) == "0xd"):
  1532. if int(ord(x[2])) == 1:
  1533. tank="F1"
  1534. if int(ord(x[3])) == 1:
  1535. print (-1*(int(ord(x[4]))+ (0.1 * int(ord(x[5])))))
  1536. temp=-1 * (int(ord(x[4])) + (0.1 * int(ord(x[5]))))
  1537. print (int(ord(x[6]))+(0.1 * int(ord(x[7]))))
  1538. humidity=int(ord(x[6])) + (0.1 * int(ord(x[7])))
  1539. if int(ord(x[3])) == 0:
  1540. print(int(ord(x[4])) + 0.1 * int(ord(x[5])))
  1541. temp=int(ord(x[4])) + 0.1 * int(ord(x[5]))
  1542. print (int(ord(x[6])) + 0.1 * int(ord(x[7])))
  1543. humidity=int(ord(x[6])) + 0.1 * int(ord(x[7]))
  1544. print(tank)
  1545. datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  1546. conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffee', passwd='skyeye',
  1547. database='Coffee', charset='utf8')
  1548. a = conn.cursor()
  1549. sqlStuff = "INSERT INTO ferment_tank_SHT11 (datetime,tank_num,SHT11_Temp,SHT11_Humidity) VALUES (%s,%s,%s,%s)"
  1550. data = [(datetime,tank,temp,humidity)]
  1551. a.executemany(sqlStuff, data)
  1552. conn.commit()
  1553. server_log(msg['command'],msg['tank_num'], temp)
  1554. def ferment(msg):
  1555. os.system('sudo su')
  1556. os.system('cd /home/pi')
  1557. os.system("ps aux | grep /home/pi/coffee5.0.py | awk '{print $2}' | xargs kill -9")
  1558. os.system('sudo nohup python /home/pi/coffee5.0.py>/home/pi/nohup.out 2>&1 &')
  1559. server_log('ferment','ferment_all', 'open')
  1560. def ferment_close(msg):
  1561. os.system('sudo su')
  1562. os.system('cd /home/pi')
  1563. os.system("ps aux | grep /home/pi/coffee5.0.py | awk '{print $2}' | xargs kill -9")
  1564. server_log('ferment','ferment_all', 'close')
  1565. def valve(msg):
  1566. #ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
  1567. #commandarray = [0xFF,0xF1,0x01,0x02,int(msg['value']),0x02,0x00,0x0D]
  1568. #print(commandarray)
  1569. #ser.write(array.array('B', commandarray).tostring())
  1570. conn = sqlite3.connect('home/pi/coffee.db')
  1571. c = conn.cursor()
  1572. c.execute("UPDATE coffee set command = '%s',open_time = '%s',close_time = '%s',tank_num = '%s',temp = '%s',rpm = '%s',water_high_level = '%s',water_low_level = '%s',coffee_level = '%s',ferment_date = '%s',ferment_hr = '%s',ferment_min = '%s',ferment_sec = '%s',sensor_time = '%s',disinfect_time = '%s' where sn=1"\
  1573. %(msg['command'],msg['open_time'],msg['close_time'],msg['tank_num'],msg['temp'],msg['rpm'],msg['water_high_level'],msg['water_low_level'],msg['coffee_level'],msg['ferment_date'],msg['ferment_hr'],msg['ferment_min'],msg['ferment_sec'],msg['sensor_time'],msg['disinfect_time']))
  1574. conn.commit()
  1575. conn.close()
  1576. os.system('sudo su')
  1577. os.system('cd /home/pi')
  1578. os.system("ps aux | grep /home/pi/coffee5.02022_0103.py | awk '{print $2}' | xargs kill -9")
  1579. os.system('sudo nohup python /home/pi/coffee5.02022_0103.py>/home/pi/nohup.out 2>&1 &')
  1580. server_log(msg['command'],'F1', 'success')
  1581. def ferment_input(msg):
  1582. if int(msg['Ferment_Input_1'])==1 :
  1583. ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
  1584. commandarray = [0xFF,0xF1,0x02,0x02, 0x01, 0x02,0x00, 0x0D]
  1585. print(commandarray)
  1586. ser.write(array.array('B', commandarray).tostring())
  1587. else:
  1588. ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)
  1589. commandarray = [0xFF,0xF1,0x02,0x02, 0x01, 0x02,0x01, 0x0D]
  1590. print(commandarray)
  1591. ser.write(array.array('B', commandarray).tostring())
  1592. server_log('Ferment_Input','ferment_input_1', 'success')
  1593. def ferment_upload(msg):
  1594. os.system('sudo su')
  1595. os.system('rm -rf /home/pi/ferment_ota')
  1596. os.system('rm -rf /home/pi/coffee.db')
  1597. os.system('sudo python /home/pi/coffee8.0.py')
  1598. os.system(msg['upload_url']+' /home/pi/ferment_ota')
  1599. time.sleep(3)
  1600. os.system('cp /home/pi/ferment_ota/coffee3.0.py /home/pi/')
  1601. time.sleep(1)
  1602. os.system('sudo chmod 777 /home/pi/coffee3.0.py')
  1603. time.sleep(2)
  1604. server_log(msg['command'],msg['tank_num'], 'success')
  1605. os.system('sudo reboot')
  1606. def ferment_input_bean(msg):
  1607. sql_local_upload(msg['command'])
  1608. os.system('sudo su')
  1609. os.system('cd /home/pi')
  1610. os.system("ps aux | grep /home/pi/coffee5.02022_0103.py | awk '{print $2}' | xargs kill -9")
  1611. os.system('sudo nohup python /home/pi/coffee5.02022_0103.py>/home/pi/nohup.out 2>&1 &')
  1612. server_log(msg['command'],'F1', 'success')
  1613. def ferment_add_outer_water(msg):
  1614. sql_local_upload(msg['command'])
  1615. os.system('sudo su')
  1616. os.system('cd /home/pi')
  1617. os.system("ps aux | grep /home/pi/coffee5.02022_0103.py | awk '{print $2}' | xargs kill -9")
  1618. os.system('sudo nohup python /home/pi/coffee5.02022_0103.py>/home/pi/nohup.out 2>&1 &')
  1619. server_log(msg['command'],'F1', 'success')
  1620. def ferment_add_inner_water(msg):
  1621. sql_local_upload(msg['command'])
  1622. os.system('sudo su')
  1623. os.system('cd /home/pi')
  1624. os.system("ps aux | grep /home/pi/coffee5.02022_0103.py | awk '{print $2}' | xargs kill -9")
  1625. os.system('sudo nohup python /home/pi/coffee5.02022_0103.py>/home/pi/nohup.out 2>&1 &')
  1626. server_log(msg['command'],'F1', 'success')
  1627. def ferment_heat(msg):
  1628. sql_local_upload(msg['command'])
  1629. os.system('sudo su')
  1630. os.system('cd /home/pi')
  1631. os.system("ps aux | grep /home/pi/coffee5.02022_0103.py | awk '{print $2}' | xargs kill -9")
  1632. os.system('sudo nohup python /home/pi/coffee5.02022_0103.py>/home/pi/nohup.out 2>&1 &')
  1633. server_log(msg['command'],'F1', 'success')
  1634. def ferment_drain_inner_water(msg):
  1635. sql_local_upload(msg['command'])
  1636. os.system('sudo su')
  1637. os.system('cd /home/pi')
  1638. os.system("ps aux | grep /home/pi/coffee5.02022_0103.py | awk '{print $2}' | xargs kill -9")
  1639. os.system('sudo nohup python /home/pi/coffee5.02022_0103.py>/home/pi/nohup.out 2>&1 &')
  1640. server_log(msg['command'],'F1', 'success')
  1641. def ferment_out_bean(msg):
  1642. sql_local_upload(msg['command'])
  1643. os.system('sudo su')
  1644. os.system('cd /home/pi')
  1645. os.system("ps aux | grep /home/pi/coffee5.02022_0103.py | awk '{print $2}' | xargs kill -9")
  1646. os.system('sudo nohup python /home/pi/coffee5.02022_0103.py>/home/pi/nohup.out 2>&1 &')
  1647. server_log(msg['command'],'F1', 'success')
  1648. def ferment_disinfect(msg):
  1649. sql_local_upload(msg['command'])
  1650. os.system('sudo su')
  1651. os.system('cd /home/pi')
  1652. os.system("ps aux | grep /home/pi/coffee5.02022_0103.py | awk '{print $2}' | xargs kill -9")
  1653. os.system('sudo nohup python /home/pi/coffee5.02022_0103.py>/home/pi/nohup.out 2>&1 &')
  1654. server_log(msg['command'],'F1', 'success')
  1655. def ferment_ota(msg):
  1656. sql_local_upload(msg['command'])
  1657. os.system('sudo su')
  1658. os.system('cd /home/pi')
  1659. #os.system("ps aux | grep /home/pi/coffee5.02022_0103.py | awk '{print $2}' | xargs kill -9")
  1660. #os.system('sudo nohup python /home/pi/coffee5.02022_0103.py>/home/pi/nohup.out 2>&1 &')
  1661. server_log(msg['command'],'F1', 'success')
  1662. def ferment_pin_configuration(msg):
  1663. os.system('sudo su')
  1664. os.system('cd /home/pi')
  1665. os.system("python /home/pi/CTO20220419.py")
  1666. os.system('cd /home/pi/newtest2;make')
  1667. os.system('cp /home/pi/newtest2/newtest.hex /home/pi/OTA')
  1668. n = subprocess.call(["git", "add","newtest.hex"],cwd="/home/pi/OTA/")
  1669. if (n==0):
  1670. n = subprocess.call(["git", "commit","-m","OTA"],cwd="/home/pi/OTA/")
  1671. if(n==0):
  1672. n = subprocess.call(["git", "push"],cwd="/home/pi/OTA/")
  1673. if(n==0):
  1674. server_log(msg['command'],'F1',"success")
  1675. elif(n==1):
  1676. server_log(msg['command'],'F1',"no change")
  1677. else:
  1678. server_log('git push','F1',"error")
  1679. elif(n==1):
  1680. server_log('git commit','F1',"no change")
  1681. else:
  1682. server_log('git commit','F1',"error")
  1683. elif(n==1):
  1684. server_log('git add','F1',"no change")
  1685. else:
  1686. server_log('git add','F1',"error")
  1687. def OTA_UPLOAD(msg):
  1688. m=msg['url']
  1689. m=m.replace("\\r\\n", "\r\n")
  1690. file = '/home/pi/CTO/SDIO.hex'
  1691. f = open(file, 'w')
  1692. f.write(m)
  1693. ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=0.2)
  1694. ser.flushOutput()
  1695. arr=[]
  1696. i=0
  1697. global j
  1698. j=0
  1699. file = '/home/pi/CTO/SDIO.hex'
  1700. with open(file, "rb") as f:
  1701. for line in f.readlines():
  1702. if (line[8:9])==b'0':
  1703. j=j+1
  1704. j1=int(line[3:5],16)
  1705. j2=int(line[5:7],16)
  1706. #print(j1)
  1707. #print(j2)
  1708. commandarray = [0xFF,0x01,j1,j2, 0x00, 0x00, 0x0D]
  1709. #print(commandarray)
  1710. ser.write(array.array('B', commandarray).tostring())
  1711. try:
  1712. e=0
  1713. rcv = ser.read(1)
  1714. print (hex(ord(rcv)))
  1715. if (hex(ord(rcv)) == "0x79"):
  1716. file = '/home/pi/CTO/SDIO.hex'
  1717. with open(file, "rb") as f:
  1718. for line in f.readlines():
  1719. i=i+1
  1720. #print(i)
  1721. if(i>1 and i<j+2 and e==0 and line[8:9]=='0'):
  1722. #print(i)
  1723. checksum=0x0F
  1724. arr=[int(line[1:3],16)]
  1725. arr+=[int(line[3:5],16)]
  1726. arr+=[int(line[5:7],16)]
  1727. for x in range (0,int(line[1:3],16)):
  1728. checksum^=int(line[9+(2*x):11+(2*x)],16)
  1729. arr+=[int(line[9+(2*x):11+(2*x)],16)]
  1730. arr+=[checksum]
  1731. for x in range (0,(16-int(line[1:3],16))):
  1732. arr+=[0]
  1733. print(arr)
  1734. ser.write(array.array('B', arr).tostring())
  1735. ser.flushOutput()
  1736. try:
  1737. rcv = ser.readline()
  1738. if(rcv=="success"):
  1739. e=0
  1740. print("success")
  1741. arr=[]
  1742. elif(rcv=="error"):
  1743. for z in range (10):
  1744. print("error")
  1745. ser.write(array.array('B', arr).tostring())
  1746. rcv = ser.readline()
  1747. if(rcv=="success"):
  1748. e=0
  1749. print("success")
  1750. arr=[]
  1751. break
  1752. else:
  1753. e=1
  1754. print("upload error")
  1755. else:
  1756. for z in range (10):
  1757. print("error")
  1758. ser.write(array.array('B', arr).tostring())
  1759. rcv = ser.readline()
  1760. if(rcv=="success"):
  1761. e=0
  1762. print("success")
  1763. arr=[]
  1764. break
  1765. else:
  1766. e=1
  1767. print("upload error")
  1768. except:
  1769. server_log(msg['command'],msg['tank_num'], 'no reply')
  1770. else:
  1771. e=1
  1772. if(e==0):
  1773. server_log(msg['command'],msg['tank_num'], 'success')
  1774. else:
  1775. server_log(msg['command'],msg['tank_num'], 'upload error')
  1776. except:
  1777. server_log(msg['command'],msg['tank_num'], 'no reply')
  1778. def OTA_hex(msg):
  1779. print("ok")
  1780. file = '/home/pi/newtest/SDIO.hex'
  1781. f = open(file, 'r')
  1782. ota_hex=f.read()
  1783. print(f.read())
  1784. server_log('OTA',msg['tank_num'],ota_hex)
  1785. def OTA_hex_save(msg):
  1786. print(msg['url'])
  1787. m=msg['url']
  1788. m=m.replace("\\r\\n", "\r\n")
  1789. print(m)
  1790. file = '/home/pi/newtest/SDIO.hex'
  1791. f = open(file, 'w')
  1792. f.write(m)
  1793. server_log('OTA',msg['tank_num'],"ok")
  1794. def creat_hex(msg):
  1795. f=open("/home/pi/newtest/test.c", mode='w')
  1796. f.write("/* USER CODE BEGIN Header */\n"
  1797. +"/**\n"
  1798. +" ******************************************************************************\n"
  1799. +" * @file : main.c\n"
  1800. +" * @brief : Main program body\n"
  1801. +" * @attention\n"
  1802. +" *\n"
  1803. +" * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics.\n"
  1804. +" * All rights reserved.</center></h2>\n"
  1805. +" *\n"
  1806. +" * This software component is licensed by ST under BSD 3-Clause license,\n"
  1807. +" * the License; You may not use this file except in compliance with the\n"
  1808. +" * License. You may obtain a copy of the License at:\n"
  1809. +" * www.st.com/SLA0044\n"
  1810. +" *\n"
  1811. +" ******************************************************************************\n"
  1812. +" */\n"
  1813. +"/* USER CODE END Header */\n"
  1814. +"\n"
  1815. +"/* Includes ------------------------------------------------------------------*/\n")
  1816. #添加標題檔
  1817. header=('#include"main.h"\n'
  1818. +'#include "adc.h"\n'
  1819. +'#include "usart.h"\n'
  1820. +'#include "gpio.h"\n'
  1821. +'#include "stdio.h"\n')
  1822. f.write(header)
  1823. #變數宣告說明
  1824. f.write("\n"
  1825. +"/* Private variables ---------------------------------------------------------*/\n")
  1826. #連接資料庫
  1827. #conn = sqlite3.connect('/home/pi/coffee.db')
  1828. conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffeemanage', passwd='skyeye', database='CoffeeManage',
  1829. charset='utf8')
  1830. c = conn.cursor()
  1831. print ("connect success")
  1832. #搜尋最新腳位配置時間
  1833. c.execute("SELECT *from coffee1_0_pin ORDER BY datetime ASC")
  1834. results=c.fetchall()
  1835. for row in results:
  1836. time = row[1]
  1837. #腳位配置加入
  1838. c.execute("SELECT *from coffee1_0_pin where datetime='%s'"\
  1839. %(time))
  1840. results=c.fetchall()
  1841. for row in results:
  1842. for i in range (19):
  1843. row[i+26]
  1844. for i in range (19):
  1845. PH("M"+str(i+1),row[i+26])
  1846. f.write(pin_variables)
  1847. DO("M"+str(i+1),row[i+26])
  1848. f.write(pin_variables)
  1849. WATERLEVEL("M"+str(i+1),row[i+26])
  1850. f.write(pin_variables)
  1851. ORP("M"+str(i+1),row[i+26])
  1852. #ESMUS07(pin_position,pin_type)
  1853. #SEN0189(pin_position,pin_type)
  1854. #SOIL(pin_position,pin_type)
  1855. #SERVO(pin_position,pin_type)
  1856. #MOTOR(pin_position,pin_type)
  1857. #SHT11(pin_position,pin_type)
  1858. #BMP280(pin_position,pin_type)
  1859. f.write(pin_variables)
  1860. #變數宣告
  1861. #f.write(pin_variables)
  1862. #副函式宣告
  1863. f.write("/* USER CODE BEGIN PV */\n"
  1864. +"typedef void (*pFunction)(void);\n"
  1865. +"/* USER CODE END PV */\n"
  1866. +"/* Private function prototypes -----------------------------------------------*/\n"
  1867. +"void SystemClock_Config(void);\n"
  1868. +"/* USER CODE BEGIN PFP */\n"
  1869. +"/* USER CODE END PFP */\n"
  1870. +"/* Private user code ---------------------------------------------------------*/\n"
  1871. +"/* USER CODE BEGIN 0 */\n"
  1872. +"/* USER CODE END 0 */\n"
  1873. +"/**\n"
  1874. +"* @brief The application entry point.\n"
  1875. +"* @retval int\n"
  1876. +"*/\n")
  1877. #主程式撰寫
  1878. #main宣告
  1879. f.write("int main(void)\n"
  1880. +"{\n")
  1881. #致能週邊
  1882. enable=(" HAL_Init();\n"
  1883. +" SystemClock_Config();\n"
  1884. +" MX_GPIO_Init();\n"
  1885. +" MX_USART2_UART_Init();\n"
  1886. +" MX_UART4_Init();\n"
  1887. +" MX_USART1_UART_Init();\n"
  1888. +" MX_ADC1_Init();\n")
  1889. f.write(enable)
  1890. code=(" while (1)\n"
  1891. +" {\n")
  1892. f.write(code)
  1893. #連接資料庫
  1894. conn = pymysql.connect(host="52.69.200.169", port=3306, user='coffeemanage', passwd='skyeye', database='CoffeeManage',
  1895. charset='utf8')
  1896. #conn = sqlite3.connect('/home/pi/coffee.db')
  1897. c = conn.cursor()
  1898. print ("connect success")
  1899. #搜尋最新腳位配置時間
  1900. c.execute("SELECT *from coffee1_0_pin ORDER BY datetime ASC")
  1901. results = c.fetchall()
  1902. for row in results:
  1903. time = row[1]
  1904. #腳位配置加入
  1905. c.execute("SELECT *from coffee1_0_pin where datetime='%s'"\
  1906. %(time))
  1907. results = c.fetchall()
  1908. for row in results:
  1909. for i in range (19):
  1910. row[i+26]
  1911. for i in range (19):
  1912. PH("M"+str(i+1),row[i+26])
  1913. f.write(pin_code)
  1914. DO("M"+str(i+1),row[i+26])
  1915. f.write(pin_code)
  1916. WATERLEVEL("M"+str(i+1),row[i+26])
  1917. f.write(pin_code)
  1918. ORP("M"+str(i+1),row[i+26])
  1919. #ESMUS07(pin_position,pin_type)
  1920. #SEN0189(pin_position,pin_type)
  1921. #SOIL(pin_position,pin_type)
  1922. #SERVO(pin_position,pin_type)
  1923. #MOTOR(pin_position,pin_type)
  1924. #SHT11(pin_position,pin_type)
  1925. #BMP280(pin_position,pin_type)
  1926. f.write(pin_code)
  1927. for i in range (len(msg['cond'])):
  1928. m=msg['cond'][i]['cond_main'].split(" ")
  1929. if(m[0]=="else" and m[1]=="if"):
  1930. m[0]=m[0]+" "+m[1]
  1931. m[1]=m[2]
  1932. m[2]=m[3]
  1933. m[3]=m[4]
  1934. m[4]=m[5]
  1935. m=""+m[0]+"("+m[2]+m[3]+m[4]
  1936. f.write(" "+m)
  1937. if(m[0]==" "):
  1938. m=""
  1939. else:
  1940. for j in range (len(msg['cond'][i]['cond_add'])):
  1941. if(j==len(msg['cond'][i]['cond_add'])-1):
  1942. if(msg['cond'][i]['cond_add'][j]==" "):
  1943. add=")\n"
  1944. else:
  1945. add=" "+str(msg['cond'][i]['cond_add'][j])+")\n"
  1946. f.write(add)
  1947. else:
  1948. if(msg['cond'][i]['cond_add'][j]==" "):
  1949. add=""
  1950. else:
  1951. add=" "+str(msg['cond'][i]['cond_add'][j])
  1952. f.write(add)
  1953. f.write(" {\n")
  1954. for j in range (len(msg['cond'][i]['cond_com'])):
  1955. if(j==len(msg['cond'][i]['cond_com'])-1):
  1956. if(msg['cond'][i]['cond_com'][j]==" "):
  1957. com="\n}\n"
  1958. else:
  1959. com=msg['cond'][i]['cond_com'][j].split(" ")
  1960. com=" "+GPIO(com[0],com[1])+"\n }\n"
  1961. f.write(com)
  1962. else:
  1963. if(msg['cond'][i]['cond_com'][j]==" "):
  1964. com=""
  1965. else:
  1966. com=msg['cond'][i]['cond_com'][j].split(" ")
  1967. com=" "+GPIO(com[0],com[1])+"\n"
  1968. f.write(com)
  1969. f.write(" }\n")
  1970. f.write("}\n")
  1971. #系統時鐘宣告
  1972. time=("void SystemClock_Config(void)\n"
  1973. +"{\n"
  1974. +" RCC_OscInitTypeDef RCC_OscInitStruct = {0};\n"
  1975. +" RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};\n"
  1976. +" __HAL_RCC_PWR_CLK_ENABLE();\n"
  1977. +" __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);\n"
  1978. +" RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;\n"
  1979. +" RCC_OscInitStruct.HSIState = RCC_HSI_ON;\n"
  1980. +" RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;\n"
  1981. +" RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;\n"
  1982. +" RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;\n"
  1983. +" RCC_OscInitStruct.PLL.PLLM = 8;\n"
  1984. +" RCC_OscInitStruct.PLL.PLLN = 72;\n"
  1985. +" RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;\n"
  1986. +" RCC_OscInitStruct.PLL.PLLQ = 3;\n"
  1987. +" RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;\n"
  1988. +" if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)\n"
  1989. +" {\n"
  1990. +" Error_Handler();\n"
  1991. +" }\n"
  1992. +" RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK\n"
  1993. +" |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;\n"
  1994. +" RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;\n"
  1995. +" RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;\n"
  1996. +" RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;\n"
  1997. +" RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;\n"
  1998. +" if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)\n"
  1999. +" {\n"
  2000. +" Error_Handler();\n"
  2001. +" }\n"
  2002. +"}\n")
  2003. f.write(time)
  2004. f.write("void Error_Handler(void)\n{\n}\n")
  2005. f.close()
  2006. f=open("/home/pi/newtest/test.c", mode='r')
  2007. words=f.read()
  2008. print(words)
  2009. f.close()
  2010. server_log(msg['command'],"D1","ok")
  2011. def GPIO(relay,status):
  2012. if relay=="relay1":
  2013. if status=="on":
  2014. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_13, GPIO_PIN_RESET);\n"
  2015. elif status=="off":
  2016. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_13, GPIO_PIN_SET);\n"
  2017. else:
  2018. act=""
  2019. elif relay=="relay2":
  2020. if status=="on":
  2021. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_12, GPIO_PIN_RESET);\n"
  2022. elif status=="off":
  2023. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_12, GPIO_PIN_SET);\n"
  2024. else:
  2025. act=""
  2026. elif relay=="relay3":
  2027. if status=="on":
  2028. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_11, GPIO_PIN_RESET);\n"
  2029. elif status=="off":
  2030. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_11, GPIO_PIN_SET);\n"
  2031. else:
  2032. act=""
  2033. elif relay=="relay4":
  2034. if status=="on":
  2035. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_10, GPIO_PIN_RESET);\n"
  2036. elif status=="off":
  2037. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_10, GPIO_PIN_SET);\n"
  2038. else:
  2039. act=""
  2040. elif relay=="relay5":
  2041. if status=="on":
  2042. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_9, GPIO_PIN_RESET);\n"
  2043. elif status=="off":
  2044. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_9, GPIO_PIN_SET);\n"
  2045. else:
  2046. act=""
  2047. elif relay=="relay6":
  2048. if status=="on":
  2049. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_8, GPIO_PIN_RESET);\n"
  2050. elif status=="off":
  2051. act=" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_8, GPIO_PIN_SET);\n"
  2052. else:
  2053. act=""
  2054. elif relay=="relay7":
  2055. if status=="on":
  2056. act=" HAL_GPIO_WritePin(GPIOC,GPIO_PIN_9, GPIO_PIN_RESET);\n"
  2057. elif status=="off":
  2058. act=" HAL_GPIO_WritePin(GPIOC,GPIO_PIN_9, GPIO_PIN_SET);\n"
  2059. else:
  2060. act=""
  2061. elif relay=="relay8":
  2062. if status=="on":
  2063. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_15, GPIO_PIN_RESET);\n"
  2064. elif status=="off":
  2065. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_15, GPIO_PIN_SET);\n"
  2066. else:
  2067. act=""
  2068. elif relay=="relay9":
  2069. if status=="on":
  2070. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_14, GPIO_PIN_RESET);\n"
  2071. elif status=="off":
  2072. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_14, GPIO_PIN_SET);\n"
  2073. else:
  2074. act=""
  2075. elif relay=="relay10":
  2076. if status=="on":
  2077. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_13, GPIO_PIN_RESET);\n"
  2078. elif status=="off":
  2079. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_13, GPIO_PIN_SET);\n"
  2080. else:
  2081. act=""
  2082. elif relay=="relay11":
  2083. if status=="on":
  2084. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_12, GPIO_PIN_RESET);\n"
  2085. elif status=="off":
  2086. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_12, GPIO_PIN_SET);\n"
  2087. else:
  2088. act=""
  2089. elif relay=="relay12":
  2090. if status=="on":
  2091. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_11, GPIO_PIN_RESET);\n"
  2092. elif status=="off":
  2093. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_11, GPIO_PIN_SET);\n"
  2094. else:
  2095. act=""
  2096. elif relay=="relay13":
  2097. if status=="on":
  2098. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_10, GPIO_PIN_RESET);\n"
  2099. elif status=="off":
  2100. act=" HAL_GPIO_WritePin(GPIOD,GPIO_PIN_10, GPIO_PIN_SET);\n"
  2101. else:
  2102. act=""
  2103. elif relay=="relay14":
  2104. if status=="on":
  2105. act=" HAL_GPIO_WritePin(GPIOB,GPIO_PIN_15, GPIO_PIN_RESET);\n"
  2106. elif status=="off":
  2107. act=" HAL_GPIO_WritePin(GPIOB,GPIO_PIN_15, GPIO_PIN_SET);\n"
  2108. else:
  2109. act=""
  2110. elif relay=="relay15":
  2111. if status=="on":
  2112. act=" HAL_GPIO_WritePin(GPIOB,GPIO_PIN_14, GPIO_PIN_RESET);\n"
  2113. elif status=="off":
  2114. act=" HAL_GPIO_WritePin(GPIOB,GPIO_PIN_14, GPIO_PIN_SET);\n"
  2115. else:
  2116. act=""
  2117. elif relay=="relay16":
  2118. if status=="on":
  2119. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_15, GPIO_PIN_RESET);\n"
  2120. elif status=="off":
  2121. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_15, GPIO_PIN_SET);\n"
  2122. else:
  2123. act=""
  2124. elif relay=="relay17":
  2125. if status=="on":
  2126. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_14, GPIO_PIN_RESET);\n"
  2127. elif status=="off":
  2128. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_14, GPIO_PIN_SET);\n"
  2129. else:
  2130. act=""
  2131. elif relay=="relay18":
  2132. if status=="on":
  2133. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_13, GPIO_PIN_RESET);\n"
  2134. elif status=="off":
  2135. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_13, GPIO_PIN_SET);\n"
  2136. else:
  2137. act=""
  2138. elif relay=="relay19":
  2139. if status=="on":
  2140. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_12, GPIO_PIN_RESET);\n"
  2141. elif status=="off":
  2142. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_12, GPIO_PIN_SET);\n"
  2143. else:
  2144. act=""
  2145. elif relay=="relay20":
  2146. if status=="on":
  2147. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_11, GPIO_PIN_RESET);\n"
  2148. elif status=="off":
  2149. act=" HAL_GPIO_WritePin(GPIOE,GPIO_PIN_11, GPIO_PIN_SET);\n"
  2150. else:
  2151. act=""
  2152. elif relay=="timesleep":
  2153. if status=="5":
  2154. act=" HAL_Delay(500);\n"
  2155. elif status=="10":
  2156. act=" HAL_Delay(1000);\n"
  2157. else:
  2158. act=""
  2159. elif relay=="tank_motor_status":
  2160. if status=="5":
  2161. act=" PWM(500);\n"
  2162. elif status=="10":
  2163. act=" PWM(1000);\n"
  2164. else:
  2165. act=""
  2166. else:
  2167. act=""
  2168. return act
  2169. def PH(pin_position,pin_type):
  2170. global pin_variables,pin_code
  2171. if pin_type =="PH":
  2172. print("PH ok")
  2173. pin_variables=("uint16_t "+pin_position+"AD_Value = 0;\n"
  2174. +"float "+pin_position+"voltage_V =0;\n"
  2175. +"float pH_mid = 1.500;\n"
  2176. +"float pH_low = 2.030;\n"
  2177. +"float pH_high =0.975;\n"
  2178. +"float "+pin_position+"_"+pin_type+"=0;\n")
  2179. pin_code=(" HAL_ADC_Start(&hadc1);\n"
  2180. +" HAL_ADC_PollForConversion(&hadc1, 50);\n"
  2181. +" if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
  2182. +" {\n"
  2183. +" AD_Value = HAL_ADC_GetValue(&hadc1);\n"
  2184. +' printf("voltage : %1.3fV\\n",(AD_Value*3.3f/4096));\n'
  2185. +" voltage_V = AD_Value*3.3f/4096;\n"
  2186. +" if (voltage_V > pH_mid)\n"
  2187. +" {\n"
  2188. +" "+pin_position+"_"+pin_type+" = 7.0 - 3.0 / (pH_low - pH_mid) * (voltage_V - pH_mid);\n"
  2189. +" }\n"
  2190. +" else\n"
  2191. +" {\n"
  2192. +" "+pin_position+"_"+pin_type+" = 7.0 - 3.0 / (pH_mid - pH_high) * (voltage_V - pH_mid);\n"
  2193. +" }\n"
  2194. +' printf("'+pin_position+"_"+pin_type+': %1.1f\\n",'+pin_position+"_"+pin_type+');\n'
  2195. +" }\n"
  2196. +" HAL_Delay(10000);\n")
  2197. else:
  2198. pin_variables=""
  2199. pin_code=""
  2200. def DO(pin_position,pin_type):
  2201. global pin_variables,pin_code
  2202. if pin_type =="DO":
  2203. print("DO ok")
  2204. pin_variables=("uint16_t "+pin_position+"AD_Value = 0;\n"
  2205. +"float "+pin_position+"voltage_V =0;\n"
  2206. +"float DO_offset =0.44;\n"
  2207. +"float "+pin_position+"_"+pin_type+" =0;\n")
  2208. pin_code=(" HAL_ADC_Start(&hadc1);\n"
  2209. +" HAL_ADC_PollForConversion(&hadc1, 50);\n"
  2210. +" if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
  2211. +" {\n"
  2212. +" AD_Value = HAL_ADC_GetValue(&hadc1);\n"
  2213. +' printf("voltage : %1.3fV\\n",(AD_Value*3.3f/4096));\n'
  2214. +" voltage_V = AD_Value*3.3f/4096;\n"
  2215. +" "+pin_position+"_"+pin_type+"= (((AD_Value*3.3f/4096)*100)/DO_offset);\n"
  2216. +' printf("'+pin_position+"_"+pin_type+' : %1.1f\\n",'+pin_position+"_"+pin_type+');\n'
  2217. +" }\n"
  2218. +" HAL_Delay(10000);\n")
  2219. else:
  2220. pin_variables=""
  2221. pin_code=""
  2222. def WATERLEVEL(pin_position,pin_type):
  2223. global pin_variables,pin_code
  2224. if pin_type =="WATERLEVEL":
  2225. print("WATERLEVEL ok")
  2226. pin_variables=("uint16_t "+pin_position+"AD_Value = 0;\n"
  2227. +"float "+pin_position+"voltage_V =0;\n"
  2228. +"float "+pin_position+"_"+pin_type+" =0;\n")
  2229. pin_code=(" HAL_ADC_Start(&hadc1);\n"
  2230. +" HAL_ADC_PollForConversion(&hadc1, 50);\n"
  2231. +" if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
  2232. +" {\n"
  2233. +" AD_Value = HAL_ADC_GetValue(&hadc1);\n"
  2234. +" voltage_V = AD_Value*3.3f/4096;\n"
  2235. +" "+pin_position+"_"+pin_type+"= (((AD_Value*3.3f/4096)*10));\n"
  2236. +' printf("'+pin_position+"_"+pin_type+' : %1.1f\\n",'+pin_position+"_"+pin_type+');\n'
  2237. +" }\n"
  2238. +" HAL_Delay(10000);\n")
  2239. else:
  2240. pin_variables=""
  2241. pin_code=""
  2242. def ORP(pin_position,pin_type):
  2243. global pin_variables,pin_code
  2244. if pin_type =="ORP":
  2245. print("ORP ok")
  2246. pin_variables=("uint16_t "+pin_position+"AD_Value = 0;\n"
  2247. +"float "+pin_position+"voltage_V =0;\n"
  2248. +"float ORP_offset =0;\n"
  2249. +"float "+pin_position+"_"+pin_type+" =0;\n")
  2250. pin_code=(" HAL_ADC_Start(&hadc1);\n"
  2251. +" HAL_ADC_PollForConversion(&hadc1, 50);\n"
  2252. +" if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
  2253. +" {\n"
  2254. +" AD_Value = HAL_ADC_GetValue(&hadc1);\n"
  2255. +" voltage_V = AD_Value*3.3f/4096;\n"
  2256. +" "+pin_position+"_"+pin_type+"= (((AD_Value*3.3f/4096)-(1.5+ORP_offset)));\n"
  2257. +' printf("'+pin_position+"_"+pin_type+' : %1.3f\\n",'+pin_position+"_"+pin_type+');\n'
  2258. +" }\n"
  2259. +" HAL_Delay(10000);\n")
  2260. else:
  2261. pin_variables=""
  2262. pin_code=""
  2263. def ESMUS07(pin_position,pin_type):
  2264. global pin_variables,pin_code
  2265. if pin_type =="ESMUS07":
  2266. print("ESMUS07 ok")
  2267. pin_variables=("uint16_t "+pin_position+"AD_Value = 0;\n"
  2268. +"float "+pin_position+"voltage_V =0;\n"
  2269. +"float "+pin_position+"_"+pin_type+" =0;\n")
  2270. pin_code=(" HAL_ADC_Start(&hadc1);\n"
  2271. +" HAL_ADC_PollForConversion(&hadc1, 50);\n"
  2272. +" if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
  2273. +" {\n"
  2274. +" AD_Value = HAL_ADC_GetValue(&hadc1);\n"
  2275. +" voltage_V = AD_Value*5.3f/4096;\n"
  2276. +" if (voltage_V==0)\n"
  2277. +" {\n"
  2278. +' printf("'+pin_position+"_"+pin_type+':100\\n");\n'
  2279. +" }\n"
  2280. +" else\n"
  2281. +" {\n"
  2282. +" "+pin_position+"_"+pin_type+ " = (voltage_V*180)+100;\n"
  2283. +' printf("'+pin_position+"_"+pin_type+' : %1.1f\\n",'+pin_position+"_"+pin_type+');\n'
  2284. +" }\n"
  2285. +" }\n"
  2286. +" HAL_Delay(10000);\n")
  2287. else:
  2288. pin_variables=""
  2289. pin_code=""
  2290. def SEN0189(pin_position,pin_type):
  2291. global pin_variables,pin_code
  2292. if pin_type =="SEN0189":
  2293. print("SEN0189 ok")
  2294. pin_variables=("uint16_t "+pin_position+"AD_Value = 0;\n"
  2295. +"float "+pin_position+"voltage_V =0;\n"
  2296. +"float "+pin_position+"_"+pin_type+" =0;\n")
  2297. pin_code=(" HAL_ADC_Start(&hadc1);\n"
  2298. +" HAL_ADC_PollForConversion(&hadc1, 50);\n"
  2299. +" if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))\n"
  2300. +" {\n"
  2301. +" AD_Value = HAL_ADC_GetValue(&hadc1);\n"
  2302. +" voltage_V = AD_Value*5.0f/4096;\n"
  2303. +" if (voltage_V>4.2)\n"
  2304. +" {\n"
  2305. +' printf("'+pin_position+"_"+pin_type+': 0\\n");\n'
  2306. +" }\n"
  2307. +" else if (voltage_V<2.5)\n"
  2308. +" {\n"
  2309. +' printf("'+pin_position+"_"+pin_type+' : 3000\\n");\n'
  2310. +" }\n"
  2311. +" else\n"
  2312. +" {\n"
  2313. +" "+pin_position+"_"+pin_type+"=(-1120.4*voltage_V*voltage_V)+(5742.3*voltage_V)-4352.9;\n"
  2314. +' printf("'+pin_position+"_"+pin_type+' : %1.1f\\n",'+pin_position+"_"+pin_type+');\n'
  2315. +" }\n"
  2316. +" }\n"
  2317. +" HAL_Delay(10000);\n")
  2318. print(pin_variables)
  2319. print(pin_code)
  2320. else:
  2321. pin_variables=""
  2322. pin_code=""
  2323. def SERVO(pin_position,pin_type):
  2324. global pin_variables,pin_code
  2325. if pin_type =="Servo":
  2326. print("Servo ok")
  2327. pin_code=(" HAL_UART_Receive_IT(&huart1, (uint8_t *)checkfeedback,sizeof(checkfeedback));\n")
  2328. pin_add_code=(" void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)\n"
  2329. +"{\n"
  2330. +" if(checkfeedback[0]==0xff && checkfeedback[6]==0x0D)\n"
  2331. +" {\n"
  2332. +" direction=checkfeedback[1];\n"
  2333. +" if(direction==0)\n"
  2334. +" {\n"
  2335. +" HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_RESET);\n"
  2336. +" HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, GPIO_PIN_SET);\n"
  2337. +" user_pwm_setvalue(50);\n"
  2338. +" }\n"
  2339. +" else if(direction==1)\n"
  2340. +" {\n"
  2341. +" HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_RESET);\n"
  2342. +" HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, GPIO_PIN_RESET);\n"
  2343. +" user_pwm_setvalue(50);\n"
  2344. +" }\n"
  2345. +" else\n"
  2346. +" {\n"
  2347. +" HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_SET);\n"
  2348. +" HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, GPIO_PIN_RESET);\n"
  2349. +" user_pwm_setvalue(0);\n"
  2350. +" }\n"
  2351. +" }\n"
  2352. +"}\n")
  2353. print(pin_code)
  2354. print(pin_add_code)
  2355. else:
  2356. pin_variables=""
  2357. pin_code=""
  2358. def MOTOR(pin_position,pin_type):
  2359. global pin_variables,pin_code
  2360. if pin_type =="Servo":
  2361. print("Servo ok")
  2362. pin_code=(" HAL_UART_Receive_IT(&huart1, (uint8_t *)checkfeedback,sizeof(checkfeedback));\n"
  2363. +" HAL_Delay(100);\n"
  2364. +" if(direction==0)\n"
  2365. +" {\n"
  2366. +" user_pwm_setvalue2(0);\n"
  2367. +" user_pwm_setvalue(pwm_value);\n"
  2368. +" }\n"
  2369. +" else\n"
  2370. +" {\n"
  2371. +" user_pwm_setvalue2(pwm_value);\n"
  2372. +" user_pwm_setvalue(0);\n"
  2373. +" }\n")
  2374. pin_add_code=(" void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)\n"
  2375. +"{\n"
  2376. +" if(checkfeedback[0]==0xff && checkfeedback[6]==0x0D)\n"
  2377. +" {\n"
  2378. +" pwm_value=checkfeedback[1];\n"
  2379. +" direction=checkfeedback[2];\n"
  2380. +' printf("%d",pwm_value);\n'
  2381. +" }\n"
  2382. +"}\n")
  2383. print(pin_code)
  2384. print(pin_add_code)
  2385. else:
  2386. pin_variables=""
  2387. pin_code=""
  2388. def SOIL(pin_position,pin_type):
  2389. global pin_variables,pin_code
  2390. if pin_type =="Soil":
  2391. print("SOIL ok")
  2392. pin_code=(" HAL_UART_Transmit(&huart2, (uint8_t *)soil,sizeof(soil),50);\n"
  2393. +" HAL_UART_Receive_IT(&huart2, (uint8_t *)data,sizeof(data));\n")
  2394. pin_add_code=(" void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart);\n"
  2395. +"{\n"
  2396. +" if(huart->Instance == USART2);\n"
  2397. +" {\n"
  2398. +" if(data[0]==0x01 && data[1]==0x03)\n"
  2399. +" {\n"
  2400. +" rh = (data[3] << 8) + data[4];\n"
  2401. +" temp = (data[5] << 8) + data[6];\n"
  2402. +" ec = (data[7] << 8) + data[8];\n"
  2403. +' printf("%4d\\n",rh);\n'
  2404. +' printf("%4d\\n",temp);\n'
  2405. +' printf("%4d\\n",ec);\n'
  2406. +" }\n"
  2407. +" }\n"
  2408. +"}\n")
  2409. print(pin_variables)
  2410. print(pin_code)
  2411. print(pin_add_code)
  2412. def SHT11(pin_position,pin_type):
  2413. global pin_variables,pin_code
  2414. if pin_type =="SHT11":
  2415. print("SHT11 ok")
  2416. pin_variables=("uint16_t i,val,value_H,value_L,Cvalue,Hvalue;\n"
  2417. +"int error;\n"
  2418. +"float C1=-2.0468;\n"
  2419. +"float C2=0.0367;\n"
  2420. +"float C3=-0.0000015955;\n"
  2421. +"float RH_Lin;\n"
  2422. +"float RH_Ture;\n"
  2423. +"float d1=-39.6;\n"
  2424. +"float d2=0.01;\n"
  2425. +"float T1=0.01;\n"
  2426. +"float T2=0.00008;\n"
  2427. +"float temp_C=0;\n"
  2428. +"int temp;\n"
  2429. +"int RH;\n")
  2430. pin_code=(" Cvalue=0;\n"
  2431. +" Hvalue=0;\n"
  2432. +" value_H=0;\n"
  2433. +" value_L=0;\n"
  2434. +" SHT10_TransStart();\n"
  2435. +" SHT10_WriteByte();\n"
  2436. +" MX_GPIO_Input();\n"
  2437. +" HAL_Delay(250);\n"
  2438. +" if(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_4)==0)\n"
  2439. +" {\n"
  2440. +" SHT10_ReadByte();\n"
  2441. +" value_H=val;\n"
  2442. +" SHT10_ReadByte();\n"
  2443. +" value_L=val;\n"
  2444. +" Cvalue = (value_H<< 8 | value_L)\n"
  2445. +" }\n"
  2446. +" SHT10_TransStart();\n"
  2447. +" SHT10_WriteByte2();\n"
  2448. +" MX_GPIO_Input();\n"
  2449. +" HAL_Delay(250);\n"
  2450. +" if(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_4)==0)\n"
  2451. +" {\n"
  2452. +" SHT10_ReadByte();\n"
  2453. +" value_H=val;\n"
  2454. +" SHT10_ReadByte();\n"
  2455. +" value_L=val;\n"
  2456. +" Hvalue = (value_H<< 8 | value_L)\n"
  2457. +" }\n"
  2458. +" SHT10_Calculate();\n"
  2459. +" HAL_Delay(10000);\n")
  2460. pin_add_code=(" void SHT10_TransStart(void)\n"
  2461. +"{\n"
  2462. +" MX_GPIO_Init();\n"
  2463. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_SET);\n"
  2464. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);\n"
  2465. +" HAL_Delay(10);\n"
  2466. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);\n"
  2467. +" HAL_Delay(10);\n"
  2468. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_RESET);\n"
  2469. +" HAL_Delay(10);\n"
  2470. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);\n"
  2471. +" HAL_Delay(10);\n"
  2472. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);\n"
  2473. +" HAL_Delay(10);\n"
  2474. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_SET);\n"
  2475. +" HAL_Delay(10);\n"
  2476. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);\n"
  2477. +" HAL_Delay(10);\n"
  2478. +"}\n"
  2479. +" void SHT10_WriteByte(void)\n"
  2480. +"{\n"
  2481. +" MX_GPIO_Init();\n"
  2482. +" for (i=0x80;i>0;i/=2)\n"
  2483. +" {\n"
  2484. +" if(i & 0x03)\n"
  2485. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_SET);\n"
  2486. +" else\n"
  2487. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_RESET);\n"
  2488. +" HAL_Delay(10);\n"
  2489. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);\n"
  2490. +" HAL_Delay(10);\n"
  2491. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);\n"
  2492. +" HAL_Delay(10);\n"
  2493. +" }\n"
  2494. +" MX_GPIO_Input();\n"
  2495. +" HAL_Delay(10);\n"
  2496. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);\n"
  2497. +" HAL_Delay(10);\n"
  2498. +" error=HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_4);\n"
  2499. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);\n"
  2500. +" HAL_Delay(10);\n"
  2501. +"}\n"
  2502. +" void SHT10_WriteByte2(void)\n"
  2503. +"{\n"
  2504. +" MX_GPIO_Init();\n"
  2505. +" for (i=0x80;i>0;i/=2)\n"
  2506. +" {\n"
  2507. +" if(i & 0x05)\n"
  2508. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_SET);\n"
  2509. +" else\n"
  2510. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_RESET);\n"
  2511. +" HAL_Delay(10);\n"
  2512. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);\n"
  2513. +" HAL_Delay(10);\n"
  2514. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);\n"
  2515. +" HAL_Delay(10);\n"
  2516. +" }\n"
  2517. +" MX_GPIO_Input();\n"
  2518. +" HAL_Delay(10);\n"
  2519. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);\n"
  2520. +" HAL_Delay(10);\n"
  2521. +" error=HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_4);\n"
  2522. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);\n"
  2523. +" HAL_Delay(10);\n"
  2524. +"}\n"
  2525. +" void SHT10_ReadByte(void)\n"
  2526. +"{\n"
  2527. +" val=0;\n"
  2528. +" MX_GPIO_Input();\n"
  2529. +" for (i=0x80;i>0;i/=2)\n"
  2530. +" {\n"
  2531. +" HAL_Delay(10);\n"
  2532. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);\n"
  2533. +" HAL_Delay(10);\n"
  2534. +" if(HAL_GPIO_ReadPin(GPIOA,GPIO_Pin_4))\n"
  2535. +" val=( val | i );\n"
  2536. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);\n"
  2537. +" }\n"
  2538. +" MX_GPIO_Init();\n"
  2539. +" if(1)\n"
  2540. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_RESET);\n"
  2541. +" else\n"
  2542. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_SET);\n"
  2543. +" HAL_Delay(10);\n"
  2544. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_SET);\n"
  2545. +" HAL_Delay(10);\n"
  2546. +" HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,GPIO_PIN_RESET);\n"
  2547. +" HAL_Delay(10);\n"
  2548. +"}\n"
  2549. +" void SHT10_Calculate(void)\n"
  2550. +"{\n"
  2551. +" temp_C=d1+d2*Cvalue;\n"
  2552. +" RH_Lin = C1+C2*Hvalue+C3*Hvalue*Hvalue;\n"
  2553. +" RH_Ture= (temp_C-25)*(T1+T2*Hvalue)+RH_Lin;\n"
  2554. +" if(RH_Ture>100)\n"
  2555. +" RH_Ture= 100;\n"
  2556. +" if(RH_Ture<0.1)\n"
  2557. +" RH_Ture=0.1;\n"
  2558. +" if(temp_C<0)\n"
  2559. +" {\n"
  2560. +" cmd[1]=1;\n"
  2561. +" cmd[2]=-1*temp_C;\n"
  2562. +" temp=(-10*temp_C);\n"
  2563. +" cmd[3]=temp%10;\n"
  2564. +" cmd[4]=RH_Ture;\n"
  2565. +" RH=RH_Ture*10;\n"
  2566. +" cmd[5]=RH%10;\n"
  2567. +" }\n"
  2568. +" else\n"
  2569. +" {\n"
  2570. +" cmd[1]=0;\n"
  2571. +" cmd[2]=temp_C;\n"
  2572. +" temp=(10*temp_C);\n"
  2573. +" cmd[3]=temp%10;\n"
  2574. +" cmd[4]=RH_Ture;\n"
  2575. +" RH=RH_Ture*10;\n"
  2576. +" cmd[5]=RH%10;\n"
  2577. +" }\n"
  2578. +"}\n")
  2579. print(pin_variables)
  2580. print(pin_code)
  2581. print(pin_add_code)
  2582. def BMP280(pin_position,pin_type):
  2583. global pin_variables,pin_code
  2584. if pin_type =="BMP280":
  2585. print("BMP280 ok")
  2586. pin_variables=("HAL_StatusTypeDef Status;\n"
  2587. +"#define ADDR_AT24C04_WRITE_FIRST_16_PAGES 0xEC;\n"
  2588. +"#define ADDR_AT24C04_WRITE_FIRST_16_PAGES 0xEC;\n"
  2589. +"#define ADDR_AT24C04_READ 0xED;\n"
  2590. +"#define AT24C04_PAGE_SIZE 16;\n"
  2591. +"#define AT24C04_TIMEOUT 0xED;\n"
  2592. +"#define BUFFER_SIZE 1;\n"
  2593. +"uint16_t dig_T1;\n"
  2594. +"uint16_t dig_T2;\n"
  2595. +"uint16_t dig_T3;\n"
  2596. +"uint16_t dig_P1;\n"
  2597. +"uint16_t dig_P2;\n"
  2598. +"uint16_t dig_P3;\n"
  2599. +"uint16_t dig_P4;\n"
  2600. +"uint16_t dig_P5;\n"
  2601. +"uint16_t dig_P6;\n"
  2602. +"uint16_t dig_P7;\n"
  2603. +"uint16_t dig_P8;\n"
  2604. +"uint16_t dig_P9;\n"
  2605. +"uint32_t adc_P=0;\n"
  2606. +"uint32_t adc_T=0;\n"
  2607. +"uint8_t WriteBuffer[BUFFER_SIZE]={0xb6};\n"
  2608. +"uint8_t WriteBuffer1[BUFFER_SIZE]={0xff};\n"
  2609. +"uint8_t WriteBuffer2[BUFFER_SIZE]={0x00};\n"
  2610. +"uint8_t ReadBuffer[BUFFER_SIZE];\n"
  2611. +"int RH;\n")
  2612. pin_code=(" Cvalue=0;\n"
  2613. +" Hvalue=0;\n"
  2614. +" value_H=0;\n"
  2615. +" value_L=0;\n"
  2616. +" SHT10_TransStart();\n"
  2617. +" SHT10_WriteByte();\n"
  2618. +" MX_GPIO_Input();\n"
  2619. +" HAL_Delay(250);\n"
  2620. +" if(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_4)==0)\n"
  2621. +" {\n"
  2622. +" SHT10_ReadByte();\n"
  2623. +" value_H=val;\n"
  2624. +" SHT10_ReadByte();\n"
  2625. +" value_L=val;\n"
  2626. +" Cvalue = (value_H<< 8 | value_L)\n"
  2627. +" }\n"
  2628. +" SHT10_TransStart();\n"
  2629. +" SHT10_WriteByte2();\n"
  2630. +" MX_GPIO_Input();\n"
  2631. +" HAL_Delay(250);\n"
  2632. +" if(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_4)==0)\n"
  2633. +" {\n"
  2634. +" SHT10_ReadByte();\n"
  2635. +" value_H=val;\n"
  2636. +" SHT10_ReadByte();\n"
  2637. +" value_L=val;\n"
  2638. +" Hvalue = (value_H<< 8 | value_L)\n"
  2639. +" }\n"
  2640. +" SHT10_Calculate();\n"
  2641. +" HAL_Delay(10000);\n")
  2642. ## The callback function for connecting.
  2643. # @param client [in] The client instance for this callback.
  2644. # @param userdata [in] The private user data as set in Client() or user_data_set().
  2645. # @param flags [in] Response flags sent by the broker.
  2646. # @param rc [in] The connection result.
  2647. def on_connect(client, userdata, flags, rc):
  2648. # subscribe MQTT topic on connection
  2649. client.subscribe(mqtt_sub_topic, qos=2)
  2650. server_log('reboot | factory_reset','','Boot completed')
  2651. ## The callback function for processing messages from the server.
  2652. # @param client [in] The client instance for this callback.
  2653. # @param userdata [in] The private user data as set in Client() or user_data_set().
  2654. # @param msg [in] An instance of MQTT message.
  2655. def on_message(client, userdata, msg):
  2656. msg.payload = msg.payload.decode('utf-8')
  2657. jsonmsg = json.loads(msg.payload)
  2658. print('Received:')
  2659. print(json.dumps(jsonmsg, sort_keys=True, indent=4, separators=(',', ':')))
  2660. # processing the command from the server
  2661. if (jsonmsg['command'] == 'reboot'):
  2662. system_reboot()
  2663. elif (jsonmsg['command'] == 'factory_reset'):
  2664. factory_reset()
  2665. elif (jsonmsg['command'] == 'system_info'):
  2666. system_info()
  2667. elif (jsonmsg['command'] == 'a061'):
  2668. download(jsonmsg)
  2669. elif (jsonmsg['command'] == 'a060'):
  2670. ota(jsonmsg)
  2671. elif (jsonmsg['command'] == 'a058'):
  2672. otastart(jsonmsg)
  2673. elif (jsonmsg['command'] == 'a059'):
  2674. #download(jsonmsg)
  2675. otatest(jsonmsg)
  2676. elif (jsonmsg['command'] == 'a062'):
  2677. ICP(jsonmsg)
  2678. elif (jsonmsg['command'] == 'a063'):
  2679. ISP(jsonmsg)
  2680. elif (jsonmsg['command'] == 'a064'):
  2681. clear(jsonmsg)
  2682. elif (jsonmsg['command'] == 'tank_solenoid_waterL2L3_status'):
  2683. valve5(jsonmsg)
  2684. elif (jsonmsg['command'] == 'tank_solenoid_waterL4L5_status'):
  2685. valve6(jsonmsg)
  2686. elif (jsonmsg['command'] == 'tank_pump_waterL4L5_status'):
  2687. count=1
  2688. pump1(jsonmsg,count)
  2689. elif (jsonmsg['command'] == 'tank_pump_waterInput_status'):
  2690. count=3
  2691. pump1(jsonmsg,count)
  2692. elif (jsonmsg['command'] == 'tank_pump_waterL2L3_status'):
  2693. count=2
  2694. pump1(jsonmsg,count)
  2695. elif (jsonmsg['command'] == 'system_update'):
  2696. system_update(jsonmsg)
  2697. elif (jsonmsg['command'] == 'tank_vacuum_status'):
  2698. vacuum(jsonmsg)
  2699. elif (jsonmsg['command'] == 'tank_threewayvalve_input_status'):
  2700. threewayvalve_input(jsonmsg)
  2701. elif (jsonmsg['command'] == 'tank_diskvalve_status'):
  2702. diskvalve(jsonmsg)
  2703. elif (jsonmsg['command'] == 'tank_solenoid_disinfect_status'):
  2704. disinfect(jsonmsg)
  2705. elif (jsonmsg['command'] == 'tank_motor_status'):
  2706. stir(jsonmsg)
  2707. elif (jsonmsg['command'] == 'tank_heater1_status'):
  2708. heater1(jsonmsg)
  2709. elif (jsonmsg['command'] == 'tank_heater2_status'):
  2710. heater2(jsonmsg)
  2711. elif (jsonmsg['command'] == 'tank_temp'):
  2712. air_temp(jsonmsg)
  2713. elif (jsonmsg['command'] == 'temptime'):
  2714. temp_time(jsonmsg)
  2715. elif (jsonmsg['command'] == 'tank_temp_enable'):
  2716. air_temp_enable(jsonmsg)
  2717. elif (jsonmsg['command'] == 'input_vacuum_status'):
  2718. input_vacuum(jsonmsg)
  2719. elif (jsonmsg['command'] == 'output_vacuum_status'):
  2720. output_vacuum(jsonmsg)
  2721. elif (jsonmsg['command'] == 'tank_pump_sensor_status'):
  2722. count=0
  2723. pump(jsonmsg,count)
  2724. elif (jsonmsg['command'] == 'solenoid_tank_pump_status'):
  2725. solenoid_tank_pump(jsonmsg)
  2726. elif (jsonmsg['command'] == 'tank_solenoid_water_in_status'):
  2727. water_in(jsonmsg)
  2728. elif (jsonmsg['command'] == 'outer_solenoid_water_status'):
  2729. water(jsonmsg)
  2730. elif (jsonmsg['command'] == 'outer_threewayvalve_float_status'):
  2731. threewayvalve_float(jsonmsg)
  2732. elif (jsonmsg['command'] == 'tank_solenoid_water_out_status'):
  2733. water_out(jsonmsg)
  2734. elif (jsonmsg['command'] == 'tank_solenoid_water_status'):
  2735. drain(jsonmsg)
  2736. elif (jsonmsg['command'] == 'tank_blower_status'):
  2737. blower(jsonmsg)
  2738. elif (jsonmsg['command'] == 'SHT11'):
  2739. sht11(jsonmsg)
  2740. elif (jsonmsg['command'] == 'SHT12'):
  2741. sht12(jsonmsg)
  2742. elif (jsonmsg['command'] == 'sonic'):
  2743. sonic(jsonmsg)
  2744. elif (jsonmsg['command'] == 'ferment'):
  2745. ferment(jsonmsg)
  2746. elif (jsonmsg['command'] == 'ferment_close'):
  2747. ferment_close(jsonmsg)
  2748. elif (jsonmsg['command'] == 'Ferment_schedule'):
  2749. valve(jsonmsg)
  2750. elif (jsonmsg['command'] == 'Ferment_Input'):
  2751. ferment_input(jsonmsg)
  2752. elif (jsonmsg['command'] == 'Ferment_Upload'):
  2753. ferment_upload(jsonmsg)
  2754. elif (jsonmsg['command'] == 'Ferment_input_bean'):
  2755. ferment_input_bean(jsonmsg)
  2756. elif (jsonmsg['command'] == 'Ferment_add_outer_water'):
  2757. ferment_add_outer_water(jsonmsg)
  2758. elif (jsonmsg['command'] == 'Ferment_add_inner_water'):
  2759. ferment_add_inner_water(jsonmsg)
  2760. elif (jsonmsg['command'] == 'Ferment_heat'):
  2761. ferment_heat(jsonmsg)
  2762. elif (jsonmsg['command'] == 'Ferment_drain_inner_water'):
  2763. ferment_drain_inner_water(jsonmsg)
  2764. elif (jsonmsg['command'] == 'Ferment_out_bean'):
  2765. ferment_out_bean(jsonmsg)
  2766. elif (jsonmsg['command'] == 'Ferment_disinfect'):
  2767. ferment_disinfect(jsonmsg)
  2768. elif (jsonmsg['command'] == 'Ferment_restart'):
  2769. ferment(jsonmsg)
  2770. elif (jsonmsg['command'] == 'Condition_setting'):
  2771. #sql_local_pin_configuration(jsonmsg)
  2772. sql_local_code_upload(jsonmsg)
  2773. ferment_pin_configuration(jsonmsg)
  2774. #elif (jsonmsg['command'] == 'Dry_OTA'):
  2775. #creat_hex(jsonmsg)
  2776. #elif (jsonmsg['command'] == 'Pin_assignment'):
  2777. #sql_local_pin_configuration(jsonmsg)
  2778. elif (jsonmsg['command'] == 'Code_upload'):
  2779. OTA_UPLOAD(jsonmsg)
  2780. #OTA_hex(jsonmsg)
  2781. #OTA_hex_save(jsonmsg)
  2782. #else:
  2783. #server_log(jsonmsg['command'],jsonmsg['tank_num'],'ERROR: Unknown command')
  2784. ## A thread used to subscribe to and wait for messages from the server.
  2785. def thread_job():
  2786. # create a MQTT client with a user name and password to subscribe to the messages
  2787. mqtt_thread_client = mqtt.Client()
  2788. mqtt_thread_client.on_connect = on_connect
  2789. mqtt_thread_client.on_message = on_message
  2790. mqtt_thread_client.username_pw_set(username='aisky-client', password='aiskyc')
  2791. mqtt_thread_client.connect(mqtt_server, mqtt_port, mqtt_alive)
  2792. mqtt_thread_client.loop_forever()
  2793. # create a MQTT client with a user name and password to publish messages
  2794. mqtt_client = mqtt.Client()
  2795. mqtt_client.username_pw_set(username='aisky-client', password='aiskyc')
  2796. mqtt_client.connect(mqtt_server, mqtt_port, mqtt_alive)
  2797. # create a thread to subscribe to and wait for messages from the server
  2798. mqtt_subscribe_thread = threading.Thread(target=thread_job)
  2799. mqtt_subscribe_thread.start()
  2800. mqtt_client.loop_forever()