aisky-mqttd 26 KB

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