aisky-mqttd 26 KB

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