aisky-mqttd 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. #!/usr/bin/env python3.5
  2. import paho.mqtt.client as mqtt
  3. import time
  4. import sys
  5. import http.client, urllib
  6. import json
  7. import threading
  8. import os
  9. import shutil
  10. import uuid
  11. import hashlib
  12. import serial
  13. import array
  14. import base64
  15. import urllib.request
  16. import datetime
  17. import requests
  18. import logging
  19. """ Device Information - the information about this device
  20. These device information is used for the MQTT topic. This program will subscribe and publish to
  21. the MQTT topic.
  22. MQTT topic to subscribe to: AISKY/<project_name>/<model_name>/<device_id>
  23. MQTT topic to publish to : AISKY/<project_name>/<model_name>/<device_id>/Log
  24. """
  25. # @var project_name The project name comes from the u-boot environment variable 'project'.
  26. # @var model_name The model name comes from the u-boot environment variable 'model'.
  27. # @var device_id The device id comes from the mac address of eth0.
  28. project_name = os.popen('cat /etc/aisky.conf | grep project').readline().split('=')[1].strip()
  29. model_name = os.popen('cat /etc/aisky.conf | grep model').readline().split('=')[1].strip()
  30. device_id = open('/sys/class/net/eth0/address').readline().strip()
  31. """ NOTE: Remember to setup the u-boot environment variables before executing this program. The
  32. commands to setup the u-boot environment variables are as follows.
  33. Setup the 'project' variable: The following command sets the 'project' variable to AppleFarm.
  34. root@mylinkit:~# fw_setenv project AppleFarm
  35. Setup the 'model' variable: The following command sets the 'model' variable to MK-G.
  36. root@mylinkit:~# fw_setenv model MK-G
  37. Then, the following command can be used to display the u-boot environment variables.
  38. root@mylinkit:~# fw_printenv
  39. """
  40. """ MQTT Server
  41. If you don't have your own MQTT server, you can use the public MQTT server 'iot.eclipse.org'. But
  42. with the public MQTT server, you can only publish and subscribe without a user name and password.
  43. Sometimes the public MQTT server is unstable.
  44. """
  45. # @var mqtt_server The URL or IP address of the MQTT server to connect to.
  46. # @var mqtt_port The port of the MQTT server to connect to.
  47. # @var mqtt_alive Maximum period in seconds allowed between communications with the broker. If
  48. # no other messages are being exchanged, this controls the rate at which the
  49. # client will send ping messages to the broker.
  50. mqtt_server = "60.250.156.234"
  51. mqtt_port = 1883
  52. mqtt_alive = 60
  53. # camera API command
  54. camera_ircut_high = 'http://169.254.185.181/cgi-bin/camerasetting_cgi?action=set&channel=0&user=admin&pwd=abcd1234&TRCutLevel=high'
  55. camera_ircut_low = 'http://169.254.185.181/cgi-bin/camerasetting_cgi?action=set&channel=0&user=admin&pwd=abcd1234&TRCutLevel=low'
  56. camera_image = 'http://169.254.185.181/cgi-bin/images_cgi?channel=0&user=admin&pwd=abcd1234'
  57. camera_zoomin = "http://169.254.185.181/cgi-bin/ptz_cgi?action=ZoomAdd&user=admin&pwd=abcd1234"
  58. camera_zoomout = "http://169.254.185.181/cgi-bin/ptz_cgi?action=ZoomSub&user=admin&pwd=abcd1234"
  59. #php path
  60. picture_path = 'http://60.250.156.234/cust/c1.php'
  61. reboot_path ="http://www.aisky.com.tw/field/status.php"
  62. #log
  63. # @var mqtt_sub_topic The MQTT topic to subscribe to.
  64. # @var mqtt_pub_topic The MQTT topic to publish to.
  65. mqtt_sub_topic = "AISKY/" + project_name + "/" + model_name + "/" + device_id
  66. mqtt_pub_topic = mqtt_sub_topic + "/Log"
  67. ##nr
  68. nr = "GTW009002014"
  69. ##angle
  70. Tilt_old = 0
  71. Pan_old = 0
  72. Zoom_old = 0
  73. ## Calculate the SHA256 checksum of the file.
  74. # @param file [in] The file path for which you want to calculate the checksum.
  75. def get_sha256sum(file):
  76. with open(file, "rb") as f:
  77. bytes = f.read()
  78. return hashlib.sha256(bytes).hexdigest()
  79. ## Send logs to the server.
  80. # @param command [in] The command received from the server.
  81. # @param response [in] The response message to the command.
  82. def server_log(command, rqnn):
  83. localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  84. # message to be sent in JSON format
  85. payload = {
  86. # let server know which device the message came from
  87. 'device_id': device_id,
  88. # let server know when the message was sent from the device
  89. 'localtime': localtime,
  90. 'node_id': nr,
  91. 'command': command,
  92. 'rqnn': rqnn
  93. }
  94. jsonobj = json.dumps(payload, sort_keys=True, indent=4)
  95. mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)
  96. print('Sent:')
  97. print(jsonobj)
  98. def call_log(command,msg,rqnn):
  99. localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  100. # message to be sent in JSON format
  101. payload = {
  102. 'device_id': device_id,
  103. 'localtime': localtime,
  104. 'node_id': nr,
  105. 'command': command,
  106. 'position':msg['position'],
  107. 'time':msg['time'],
  108. 'rqnn': rqnn
  109. }
  110. jsonobj = json.dumps(payload, sort_keys=True, indent=4)
  111. mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)
  112. print('Sent:')
  113. print(jsonobj)
  114. def parameter_log(command,msg,rqnn):
  115. localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  116. # message to be sent in JSON format
  117. payload = {
  118. 'device_id': device_id,
  119. 'localtime': localtime,
  120. 'node_id': nr,
  121. 'command': command,
  122. 'position': msg['position'],
  123. 'time': msg['time'],
  124. 'Pan': msg['orPan'],
  125. 'Tilt': msg['orTilt'],
  126. 'Zoom': msg['orZoom'],
  127. 'rqnn': rqnn,
  128. }
  129. jsonobj = json.dumps(payload, sort_keys=True, indent=4)
  130. mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)
  131. print('Sent:')
  132. print(jsonobj)
  133. def preview_photo_log(command,msg,rqnn):
  134. localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  135. # message to be sent in JSON format
  136. payload = {
  137. 'device_id': device_id,
  138. 'localtime': localtime,
  139. 'node_id': nr,
  140. 'command': command,
  141. 'position':msg['position'],
  142. 'rqnn': rqnn
  143. }
  144. jsonobj = json.dumps(payload, sort_keys=True, indent=4)
  145. mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)
  146. print('Sent:')
  147. print(jsonobj)
  148. def ndvi_log(command,msg,size1,size2,rqnn):
  149. localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  150. # message to be sent in JSON format
  151. payload = {
  152. # let server know which device the message came from
  153. 'device_id': device_id,
  154. # let server know when the message was sent from the device
  155. 'localtime': localtime,
  156. 'node_id': nr,
  157. 'command': command,
  158. 'position':msg['position'],
  159. 'time':msg['time'],
  160. 'filename':msg['filename'],
  161. 'a': size1,
  162. 'b': size2,
  163. 'rqnn': rqnn,
  164. }
  165. jsonobj = json.dumps(payload, sort_keys=True, indent=4)
  166. mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)
  167. print('Sent:')
  168. print(jsonobj)
  169. def tilt_log(command,msg,rqnn):
  170. localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  171. # message to be sent in JSON format
  172. payload = {
  173. 'device_id': device_id,
  174. 'localtime': localtime,
  175. 'node_id': nr,
  176. 'command': command,
  177. 'tilt':msg['Tilt'],
  178. 'rqnn': rqnn
  179. }
  180. jsonobj = json.dumps(payload, sort_keys=True, indent=4)
  181. mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)
  182. print('Sent:')
  183. print(jsonobj)
  184. def pan_log(command,msg,rqnn):
  185. localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  186. # message to be sent in JSON format
  187. payload = {
  188. 'device_id': device_id,
  189. 'localtime': localtime,
  190. 'node_id': nr,
  191. 'command': command,
  192. 'pan':msg['Pan'],
  193. 'rqnn': rqnn
  194. }
  195. jsonobj = json.dumps(payload, sort_keys=True, indent=4)
  196. mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)
  197. print('Sent:')
  198. print(jsonobj)
  199. def zoom_log(command,msg,rqnn):
  200. localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  201. # message to be sent in JSON format
  202. payload = {
  203. 'device_id': device_id,
  204. 'localtime': localtime,
  205. 'node_id': nr,
  206. 'command': command,
  207. 'zoom':msg['Zoom'],
  208. 'rqnn': rqnn
  209. }
  210. jsonobj = json.dumps(payload, sort_keys=True, indent=4)
  211. mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)
  212. print('Sent:')
  213. print(jsonobj)
  214. def get_ip_address(ifname):
  215. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  216. try:
  217. return socket.inet_ntoa(fcntl.ioctl(
  218. s.fileno(),
  219. 0x8915, # SIOCGIFADDR
  220. struct.pack('256s', ifname[:15])
  221. )[20:24])
  222. except:
  223. return ""
  224. ## Reset this device.
  225. def system_reboot():
  226. server_log('a035', '1')
  227. time.sleep(5)
  228. os.system('sudo reboot')
  229. time.sleep(10)
  230. def system_update_code():
  231. os.system('sudo su')
  232. os.system('rm -rf /home/pi/KDAIS')
  233. os.system('git clone -b KDAIS14 --single-branch http://60.250.156.230:3000/fatwolf/KDAIS.git /home/pi/KDAIS')
  234. time.sleep(3)
  235. os.system('cp /home/pi/KDAIS/aisky-mqttd /usr/sbin/')
  236. time.sleep(1)
  237. os.system('cp /home/pi/KDAIS/udp_client.py /home/pi/')
  238. time.sleep(1)
  239. os.system('sudo chmod 777 /usr/sbin/aisky-mqttd')
  240. os.system('sudo chmod 777 /home/pi/udp_client.py')
  241. time.sleep(2)
  242. server_log('a033', '1')
  243. os.system('sudo reboot')
  244. time.sleep(10)
  245. def monitor():
  246. os.system('sudo su')
  247. os.system('rm -rf /home/pi/KDAIS')
  248. os.system('git clone -b KDAIS14 --single-branch http://60.250.156.230:3000/fatwolf/KDAIS.git /home/pi/KDAIS')
  249. time.sleep(3)
  250. os.system('pip3 install psutil')
  251. time.sleep(3)
  252. os.system('pip3 install gpiozero')
  253. time.sleep(3)
  254. os.system('cp /home/pi/KDAIS/proc-wdtd.conf /etc/')
  255. os.system('cp /home/pi/KDAIS/get_cpuusage.py /home/pi/')
  256. time.sleep(1)
  257. os.system('sudo chmod 777 /home/pi/get_cpuusage.py')
  258. time.sleep(2)
  259. server_log('a057', '1')
  260. os.system('sudo reboot')
  261. time.sleep(10)
  262. def stream0(msg):
  263. os.system('sudo su')
  264. os.system('cd /home/pi')
  265. os.system("ps aux | grep /home/pi/udp_client.py | awk '{print $2}' | xargs kill -9")
  266. time.sleep(2)
  267. os.system('sudo nohup python3.5 /home/pi/udp_client.py>/home/pi/nohup.out 2>&1 &')
  268. server_log('a053', '1')
  269. def stream1(msg):
  270. os.system('sudo su')
  271. os.system("ps aux | grep /home/pi/udp_client.py | awk '{print $2}' | xargs kill -9")
  272. time.sleep(2)
  273. server_log('a054', '1')
  274. def timecheck(msg):
  275. x = datetime.datetime.now()
  276. x.year
  277. x.month
  278. x.day
  279. x.hour
  280. x.minute
  281. x.second
  282. print(x.year,x.month,x.day,x.hour,x.minute,x.second)
  283. req = requests.get('http://169.254.185.181/cgi-bin/date_cgi?action=set&user=admin&pwd=abcd1234&year=%d&month=%d&day=%d&hour=%d&minute=%d&second=%d&timezone=31'%(x.year,x.month,x.day,x.hour,x.minute,x.second))
  284. server_log('a055', 'timecheck')
  285. ## Receive the system action to this device .
  286. def call(msg):
  287. print("call ok")
  288. call_log('a000',msg, '1')
  289. def parameter_setting(msg):
  290. print(msg['Pan'])
  291. print(msg['Tilt'])
  292. print(msg['Zoom'])
  293. print(msg['position'])
  294. pan(msg)
  295. tilt(msg)
  296. zoom(msg)
  297. time.sleep(2)
  298. print("NDVI 1 angle ok")
  299. parameter_log('a050',msg,'1')
  300. def take_preview_photo(msg):
  301. im = datetime.datetime.now().strftime('/home/pi/immediate/PV.jpg')
  302. save_photo = datetime.datetime.now().strftime(im)
  303. fileName = datetime.datetime.now().strftime(save_photo)
  304. req = requests.get(camera_image)
  305. file = open(fileName, 'wb')
  306. for chunk in req.iter_content(100000):
  307. file.write(chunk)
  308. file.close()
  309. dress = '/home/pi/immediate/'
  310. for root, dirs, files in os.walk(dress):
  311. print('files: {}'.format(len(files)))
  312. if len(files) >= 1:
  313. files.sort()
  314. for f in files:
  315. with open(os.path.join(root, f), "rb") as imageFile:
  316. str = base64.b64encode(imageFile.read())
  317. url = picture_path
  318. nr = '14'
  319. values = {'data': str, 'name': f,'nr':nr}
  320. data = urllib.parse.urlencode(values)
  321. data = data.encode('utf-8')
  322. req = urllib.request.Request(url, data)
  323. req.add_header('User-Agent', 'Magic Browser')
  324. resp = urllib.request.urlopen(req)
  325. respData = resp.read()
  326. #print(respData)
  327. #os.remove(os.path.join(root, f))
  328. print("ok")
  329. preview_photo_log('a018',msg,'1')
  330. print("take_preview_photo ok")
  331. def preview_photo(msg):
  332. print("ok")
  333. req = requests.get(camera_ircut_low)
  334. fileName = datetime.datetime.now().strftime("/home/pi/p"+msg['position']+"/"+msg['position']+".tif")
  335. req = requests.get(camera_image)
  336. file = open(fileName, 'wb')
  337. for chunk in req.iter_content(100000):
  338. file.write(chunk)
  339. file.close()
  340. dress = '/home/pi/p'+msg['position']+'/'
  341. for root, dirs, files in os.walk(dress):
  342. print('files: {}'.format(len(files)))
  343. if len(files) >= 1:
  344. files.sort()
  345. for f in files:
  346. with open(os.path.join(root, f), "rb") as imageFile:
  347. str = base64.b64encode(imageFile.read())
  348. url = picture_path
  349. nr ='14'
  350. values = {'p': str, 'p_name':msg['position'],'nr':nr}
  351. p22_1 = urllib.parse.urlencode(values)
  352. p22_1 = p22_1.encode('utf-8')
  353. req = urllib.request.Request(url, p22_1)
  354. req.add_header('User-Agent', 'Magic Browser')
  355. resp = urllib.request.urlopen(req)
  356. respData = resp.read()
  357. print(os.path.join(root, f))
  358. #print(respdata)
  359. os.remove(os.path.join(root, f))
  360. print("ok")
  361. preview_photo_log('a018',msg,'1')
  362. print("preview_photo ok")
  363. def tilt(msg):
  364. Tilt(int(msg['Tilt']))
  365. tilt_log('a014',msg,'1')
  366. def pan(msg):
  367. if(0<=int(msg['Pan'])<30):
  368. Pan((int(msg['Pan'])+330))
  369. if(int(msg['Pan'])==30):
  370. Pan(359)
  371. if(30<int(msg['Pan'])<=355):
  372. Pan((int(msg['Pan'])-30))
  373. pan_log('a012',msg,'1')
  374. def zoom(msg):
  375. Zoom(int(msg['Zoom']))
  376. zoom_log('a016',msg,'1')
  377. def zoom0(msg):
  378. Tilt(0)
  379. Pan(330)
  380. Zoom(-5)
  381. server_log('a052','1')
  382. ## device action.
  383. def Pan(pan):
  384. if 0<pan<=359:
  385. a = pan
  386. a1 = a * 100
  387. print (a1)
  388. k = '{0:x}'.format(a1)
  389. h = k.zfill(4)
  390. print(h)
  391. p3 = (h[0:2])
  392. ##print(p3)
  393. p4 = (h[2:])
  394. ##print(p4)
  395. str_10 = int(p3, 16)
  396. str_10_2 = int(p4, 16)
  397. sum_10 = (str_10 + str_10_2 + 76)
  398. str_16 = hex(sum_10)
  399. ##print(str_16)
  400. sum = (str_16[-2:])
  401. str_10_sum = int(sum, 16)
  402. SERIAL_PORT = '/dev/ttyS0'
  403. ser = serial.Serial(SERIAL_PORT, baudrate=9600, timeout=10)
  404. Pan = [0xFF, 0x01, 0x00,0x4B, str_10, str_10_2, str_10_sum]
  405. print(Pan)
  406. ser.write(array.array('B', Pan).tostring())
  407. print('left')
  408. elif a == 0:
  409. SERIAL_PORT = '/dev/ttyS0'
  410. ser = serial.Serial(SERIAL_PORT, baudrate=9600, timeout=10)
  411. Pan = [0xFF, 0x01, 0x00, 0x4B, 0x00, 0x00, 0x4C]
  412. ser.write(array.array('B', Pan).tostring())
  413. print('leftzore')
  414. def Tilt(tilt):
  415. a = tilt
  416. def up():
  417. q = int(360)
  418. a1 = (q - a) * 100
  419. print(a1)
  420. k = '{0:x}'.format(a1)
  421. h = k.zfill(4)
  422. print(h)
  423. p3 = (h[0:2])
  424. ##print(p3)
  425. p4 = (h[2:])
  426. ##print(p4)
  427. str_10 = int(p3, 16)
  428. str_10_2 = int(p4, 16)
  429. sum_10 = (str_10 + str_10_2 + 78)
  430. str_16 = hex(sum_10)
  431. ##print(str_16)
  432. sum = (str_16[-2:])
  433. str_10_sum = int(sum, 16)
  434. SERIAL_PORT = '/dev/ttyS0'
  435. ser = serial.Serial(SERIAL_PORT, baudrate=9600, timeout=5)
  436. Pan = [0xFF, 0x01, 0x00, 0x4D, str_10, str_10_2, str_10_sum]
  437. print(Pan)
  438. ser.write(array.array('B', Pan).tostring())
  439. print('up')
  440. def down():
  441. k = abs(a)
  442. a1 = k * 100
  443. print (a1)
  444. k = '{0:x}'.format(a1)
  445. h = k.zfill(4)
  446. print(h)
  447. p3 = (h[0:2])
  448. ##print(p3)
  449. p4 = (h[2:])
  450. ##print(p4)
  451. str_10 = int(p3, 16)
  452. str_10_2 = int(p4, 16)
  453. sum_10 = (str_10 + str_10_2 + 78)
  454. str_16 = hex(sum_10)
  455. ##print(str_16)
  456. sum = (str_16[-2:])
  457. str_10_sum = int(sum, 16)
  458. SERIAL_PORT = '/dev/ttyS0'
  459. ser = serial.Serial(SERIAL_PORT, baudrate=9600, timeout=5)
  460. Pan = [0xFF, 0x01, 0x00, 0x4D, str_10, str_10_2, str_10_sum]
  461. print(Pan)
  462. ser.write(array.array('B', Pan).tostring())
  463. print('down')
  464. if 0 <= a <= 90:
  465. up()
  466. elif 0 > a >= -25:
  467. down()
  468. def Zoom(zoom):
  469. def Zoom1():
  470. headers = {'Content-Type': 'text/xml'}
  471. data = '<?xml version="1.0" encoding="utf-8"?><request><ptzcmd><protocol>0</protocol><cmd>0</cmd><addr>1</addr></</request>'
  472. url = camera_zoomin
  473. r = requests.post(url, headers=headers, data=data)
  474. print (r.content)
  475. def Zoom_1():
  476. headers = {'Content-Type': 'text/xml'}
  477. data = '<?xml version="1.0" encoding="utf-8"?><request><ptzcmd><protocol>0</protocol><cmd>0</cmd><addr>1</addr></</request>'
  478. url = camera_zoomout
  479. r = requests.post(url, headers=headers, data=data)
  480. print (r.content)
  481. print ('you')
  482. a = zoom
  483. print(a)
  484. if (a == 0):
  485. print("NO")
  486. elif (a>0):
  487. for i in range(a):
  488. time.sleep(1)
  489. for j in range(10):
  490. Zoom1()
  491. else:
  492. a=-1*a
  493. for i in range(a):
  494. time.sleep(1)
  495. for j in range(10):
  496. Zoom_1()
  497. def manual_ndvi(msg):
  498. req = requests.get(camera_ircut_high)
  499. time.sleep(2)
  500. fileName = datetime.datetime.now().strftime("/home/pi/ir_image1/"+msg['filename']+"a.tif")
  501. req = requests.get(camera_image)
  502. file = open(fileName, 'wb')
  503. for chunk in req.iter_content(100000):
  504. file.write(chunk)
  505. file.close()
  506. path1 = '/home/pi/ir_image1/'+msg['filename']+'a.tif'
  507. size1 = os.path.getsize(path1)
  508. print(size1)
  509. req = requests.get(camera_ircut_low)
  510. time.sleep(2)
  511. fileName = datetime.datetime.now().strftime("/home/pi/n_image1/"+msg['filename']+"b.tif")
  512. req = requests.get(camera_image)
  513. file = open(fileName, 'wb')
  514. for chunk in req.iter_content(100000):
  515. file.write(chunk)
  516. file.close()
  517. path2 = '/home/pi/n_image1/'+msg['filename']+'b.tif'
  518. size2 = os.path.getsize(path2)
  519. print(size2)
  520. def main_n():
  521. dress = '/home/pi/ir_image1/'
  522. for root, dirs, files in os.walk(dress):
  523. print('files: {}'.format(len(files)))
  524. if len(files) >= 1:
  525. files.sort()
  526. for f in files:
  527. with open(os.path.join(root, f), "rb") as imageFile:
  528. str = base64.b64encode(imageFile.read())
  529. url = picture_path
  530. nr = '14'
  531. values = {'data_ira': str, 'name_ira': f, 'nr': nr}
  532. data = urllib.parse.urlencode(values)
  533. data = data.encode('utf-8')
  534. req = urllib.request.Request(url, data)
  535. req.add_header('User-Agent', 'Magic Browser')
  536. resp = urllib.request.urlopen(req)
  537. respData = resp.read()
  538. print(os.path.join(root, f))
  539. # print(respData)
  540. os.remove(os.path.join(root, f))
  541. print("ok")
  542. def main_ir():
  543. dress = '/home/pi/n_image1/'
  544. for root, dirs, files in os.walk(dress):
  545. print('files: {}'.format(len(files)))
  546. if len(files) >= 1:
  547. files.sort()
  548. for f in files:
  549. with open(os.path.join(root, f), "rb") as imageFile:
  550. str = base64.b64encode(imageFile.read())
  551. url = picture_path
  552. nr = '14'
  553. values = {'c_na': str, 'name_na': f, 'nr': nr}
  554. c = urllib.parse.urlencode(values)
  555. c = c.encode('utf-8')
  556. req = urllib.request.Request(url, c)
  557. req.add_header('User-Agent', 'Magic Browser')
  558. resp = urllib.request.urlopen(req)
  559. respData = resp.read()
  560. print(os.path.join(root, f))
  561. #print(respData)
  562. os.remove(os.path.join(root, f))
  563. print("ok")
  564. main_n()
  565. main_ir()
  566. print("NDVI ok")
  567. ndvi_log('a051',msg,size1,size2,'1')
  568. def ndvi(msg):
  569. req = requests.get(camera_ircut_high)
  570. time.sleep(2)
  571. fileName = datetime.datetime.now().strftime("/home/pi/a"+msg['position']+"/"+msg['filename']+"a"+msg['position']+".tif")
  572. req = requests.get(camera_image)
  573. file = open(fileName, 'wb')
  574. for chunk in req.iter_content(100000):
  575. file.write(chunk)
  576. file.close()
  577. path1 = '/home/pi/a'+msg['position']+'/'+msg['filename']+'a'+msg['position']+'.tif'
  578. size1 = os.path.getsize(path1)
  579. print(size1)
  580. req = requests.get(camera_ircut_low)
  581. time.sleep(2)
  582. fileName = datetime.datetime.now().strftime("/home/pi/b"+msg['position']+"/"+msg['filename']+"b"+msg['position']+".tif")
  583. req = requests.get(camera_image)
  584. file = open(fileName, 'wb')
  585. for chunk in req.iter_content(100000):
  586. file.write(chunk)
  587. file.close()
  588. path2 = '/home/pi/b'+msg['position']+'/'+msg['filename']+'b'+msg['position']+'.tif'
  589. size2 = os.path.getsize(path2)
  590. print(size2)
  591. def main_n():
  592. dress = '/home/pi/a'+msg['position']+'/'
  593. for root, dirs, files in os.walk(dress):
  594. print('files: {}'.format(len(files)))
  595. if len(files) >= 1:
  596. files.sort()
  597. for f in files:
  598. with open(os.path.join(root, f), "rb") as imageFile:
  599. str = base64.b64encode(imageFile.read())
  600. url = picture_path
  601. nr = '14'
  602. values = {'data_ira': str, 'name_ira': f, 'nr': nr}
  603. data = urllib.parse.urlencode(values)
  604. data = data.encode('utf-8')
  605. req = urllib.request.Request(url, data)
  606. req.add_header('User-Agent', 'Magic Browser')
  607. resp = urllib.request.urlopen(req)
  608. respData = resp.read()
  609. print(os.path.join(root, f))
  610. #print(respData)
  611. os.remove(os.path.join(root, f))
  612. print("ok")
  613. def main_ir():
  614. dress = '/home/pi/b'+msg['position']+'/'
  615. for root, dirs, files in os.walk(dress):
  616. print('files: {}'.format(len(files)))
  617. if len(files) >= 1:
  618. files.sort()
  619. for f in files:
  620. with open(os.path.join(root, f), "rb") as imageFile:
  621. str = base64.b64encode(imageFile.read())
  622. url = picture_path
  623. nr = '14'
  624. values = {'c_na': str, 'name_na': f, 'nr': nr}
  625. c = urllib.parse.urlencode(values)
  626. c = c.encode('utf-8')
  627. req = urllib.request.Request(url, c)
  628. req.add_header('User-Agent', 'Magic Browser')
  629. resp = urllib.request.urlopen(req)
  630. respData = resp.read()
  631. print(os.path.join(root, f))
  632. #print(respData)
  633. os.remove(os.path.join(root, f))
  634. print("ok")
  635. # --------------------------------------------------------------------------------------
  636. main_n()
  637. main_ir()
  638. print("NDVI ok")
  639. ndvi_log('a051',msg,size1,size2,'1')
  640. ## The callback function for connecting.
  641. # @param client [in] The client instance for this callback.
  642. # @param userdata [in] The private user data as set in Client() or user_data_set().
  643. # @param flags [in] Response flags sent by the broker.
  644. # @param rc [in] The connection result.
  645. def on_connect(client, userdata, flags, rc):
  646. # subscribe MQTT topic on connection
  647. client.subscribe(mqtt_sub_topic, qos=2)
  648. server_log('a035', '1')
  649. logging.info('system running')
  650. data = {'nr': nr, 'status': 'reboot'}
  651. data = urllib.parse.urlencode(data)
  652. data = data.encode('utf-8')
  653. req = urllib.request.Request(reboot_path, data)
  654. req.add_header('User-Agent', 'Magic Browser')
  655. resp = urllib.request.urlopen(req)
  656. respData = resp.read()
  657. print("reboot check ok")
  658. ## The callback function for processing messages from the server.
  659. # @param client [in] The client instance for this callback.
  660. # @param userdata [in] The private user data as set in Client() or user_data_set().
  661. # @param msg [in] An instance of MQTT message.
  662. def on_message(client, userdata, msg):
  663. # print(msg.payload)
  664. msg.payload = msg.payload.decode('utf-8')
  665. jsonmsg = json.loads(msg.payload)
  666. #print(jsonmsg)
  667. print('Received:')
  668. print(json.dumps(jsonmsg, sort_keys=True, indent=4, separators=(',', ':')))
  669. # processing the command from the server
  670. if (jsonmsg['command'] == 'a035'):
  671. system_reboot()
  672. elif (jsonmsg['command'] == 'a033'):
  673. system_update_code()
  674. elif (jsonmsg['command'] == 'vpn_connect'):
  675. vpn_connect()
  676. elif (jsonmsg['command'] == 'vpn_disconnect'):
  677. vpn_disconnect()
  678. elif (jsonmsg['command'] == 'a055'):
  679. timecheck(jsonmsg)
  680. elif (jsonmsg['command'] == 'a057'):
  681. monitor()
  682. elif (jsonmsg['node_id'] == "GTW009002014"):
  683. if (jsonmsg['command'] == 'a000'):
  684. call(jsonmsg)
  685. elif (jsonmsg['command'] == 'a050'):
  686. parameter_setting(jsonmsg)
  687. elif (jsonmsg['command'] == 'a051'):
  688. if (jsonmsg['position'] == '0'):
  689. manual_ndvi(jsonmsg)
  690. else:
  691. ndvi(jsonmsg)
  692. elif (jsonmsg['command'] == 'a014'):
  693. tilt(jsonmsg)
  694. elif (jsonmsg['command'] == 'a012'):
  695. pan(jsonmsg)
  696. elif (jsonmsg['command'] == 'a016'):
  697. zoom(jsonmsg)
  698. elif (jsonmsg['command'] == 'a052'):
  699. zoom0(jsonmsg)
  700. elif (jsonmsg['command'] == 'a053'):
  701. stream0(jsonmsg)
  702. elif (jsonmsg['command'] == 'a054'):
  703. stream1(jsonmsg)
  704. elif (jsonmsg['command'] == 'a018'):
  705. if (jsonmsg['position'] == '0'):
  706. take_preview_photo(jsonmsg)
  707. else:
  708. preview_photo(jsonmsg)
  709. else:
  710. server_log(jsonmsg['command'], 'ERROR: Unknown command')
  711. ## A thread used to subscribe to and wait for messages from the server.
  712. def thread_job():
  713. # create a MQTT client with a user name and password to subscribe to the messages
  714. mqtt_thread_client = mqtt.Client()
  715. mqtt_thread_client.on_connect = on_connect
  716. mqtt_thread_client.on_message = on_message
  717. mqtt_thread_client.username_pw_set(username='aisky-client', password='aiskyc')
  718. mqtt_thread_client.connect(mqtt_server, mqtt_port, mqtt_alive)
  719. mqtt_thread_client.loop_forever()
  720. # create a MQTT client with a user name and password to publish messages
  721. mqtt_client = mqtt.Client()
  722. mqtt_client.username_pw_set(username='aisky-client', password='aiskyc')
  723. mqtt_client.connect(mqtt_server, mqtt_port, mqtt_alive)
  724. # create a thread to subscribe to and wait for messages from the server
  725. mqtt_subscribe_thread = threading.Thread(target=thread_job)
  726. mqtt_subscribe_thread.start()
  727. mqtt_client.loop_forever()