aisky-mqttd 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  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 = "GTW009002016"
  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 KDAIS16 --single-branch http://60.250.156.230:3000/fatwolf/KDAIS.git /home/pi/KDAIS')
  238. time.sleep(3)
  239. os.system('cp /home/pi/KDAIS/aisky-mqttd /usr/sbin/')
  240. time.sleep(1)
  241. os.system('cp /home/pi/KDAIS/udp_client.py /home/pi/')
  242. time.sleep(1)
  243. os.system('sudo chmod 777 /usr/sbin/aisky-mqttd')
  244. os.system('sudo chmod 777 /home/pi/udp_client.py')
  245. time.sleep(2)
  246. server_log('a033', '1')
  247. os.system('sudo reboot')
  248. time.sleep(10)
  249. def monitor():
  250. os.system('sudo su')
  251. os.system('rm -rf /home/pi/KDAIS')
  252. os.system('git clone -b KDAIS16 --single-branch http://60.250.156.230:3000/fatwolf/KDAIS.git /home/pi/KDAIS')
  253. time.sleep(3)
  254. os.system('pip3 install psutil')
  255. time.sleep(3)
  256. os.system('pip3 install gpiozero')
  257. time.sleep(3)
  258. os.system('cp /home/pi/KDAIS/proc-wdtd.conf /etc/')
  259. os.system('cp /home/pi/KDAIS/get_cpuusage.py /home/pi/')
  260. time.sleep(1)
  261. os.system('sudo chmod 777 /home/pi/get_cpuusage.py')
  262. time.sleep(2)
  263. server_log('a057', '1')
  264. os.system('sudo reboot')
  265. time.sleep(10)
  266. def stream0(msg):
  267. os.system('sudo su')
  268. os.system('cd /home/pi')
  269. os.system("ps aux | grep /home/pi/udp_client.py | awk '{print $2}' | xargs kill -9")
  270. time.sleep(2)
  271. os.system('sudo nohup python3.5 /home/pi/udp_client.py>/home/pi/nohup.out 2>&1 &')
  272. server_log('a053', '1')
  273. def stream1(msg):
  274. os.system('sudo su')
  275. os.system("ps aux | grep /home/pi/udp_client.py | awk '{print $2}' | xargs kill -9")
  276. time.sleep(2)
  277. server_log('a054', '1')
  278. def timecheck(msg):
  279. x = datetime.datetime.now()
  280. x.year
  281. x.month
  282. x.day
  283. x.hour
  284. x.minute
  285. x.second
  286. print(x.year,x.month,x.day,x.hour,x.minute,x.second)
  287. 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))
  288. server_log('a055', 'timecheck')
  289. ## Receive the system action to this device .
  290. def call(msg):
  291. print("call ok")
  292. call_log('a000',msg, '1')
  293. def parameter_setting(msg):
  294. print(msg['Pan'])
  295. print(msg['Tilt'])
  296. print(msg['Zoom'])
  297. print(msg['position'])
  298. pan(msg)
  299. tilt(msg)
  300. zoom(msg)
  301. time.sleep(2)
  302. print("NDVI 1 angle ok")
  303. parameter_log('a050',msg,'1')
  304. def take_preview_photo(msg):
  305. im = datetime.datetime.now().strftime('/home/pi/immediate/PV.jpg')
  306. save_photo = datetime.datetime.now().strftime(im)
  307. fileName = datetime.datetime.now().strftime(save_photo)
  308. req = requests.get(camera_image)
  309. file = open(fileName, 'wb')
  310. for chunk in req.iter_content(100000):
  311. file.write(chunk)
  312. file.close()
  313. dress = '/home/pi/immediate/'
  314. for root, dirs, files in os.walk(dress):
  315. print('files: {}'.format(len(files)))
  316. if len(files) >= 1:
  317. files.sort()
  318. for f in files:
  319. with open(os.path.join(root, f), "rb") as imageFile:
  320. str = base64.b64encode(imageFile.read())
  321. url = picture_path
  322. nr = '16'
  323. values = {'data': str, 'name': f,'nr':nr}
  324. data = urllib.parse.urlencode(values)
  325. data = data.encode('utf-8')
  326. req = urllib.request.Request(url, data)
  327. req.add_header('User-Agent', 'Magic Browser')
  328. resp = urllib.request.urlopen(req)
  329. respData = resp.read()
  330. #print(respData)
  331. #os.remove(os.path.join(root, f))
  332. print("ok")
  333. preview_photo_log('a018',msg,'1')
  334. print("take_preview_photo ok")
  335. def preview_photo(msg):
  336. print("ok")
  337. req = requests.get(camera_ircut_low)
  338. fileName = datetime.datetime.now().strftime("/home/pi/p"+msg['position']+"/"+msg['position']+".tif")
  339. req = requests.get(camera_image)
  340. file = open(fileName, 'wb')
  341. for chunk in req.iter_content(100000):
  342. file.write(chunk)
  343. file.close()
  344. dress = '/home/pi/p'+msg['position']+'/'
  345. for root, dirs, files in os.walk(dress):
  346. print('files: {}'.format(len(files)))
  347. if len(files) >= 1:
  348. files.sort()
  349. for f in files:
  350. with open(os.path.join(root, f), "rb") as imageFile:
  351. str = base64.b64encode(imageFile.read())
  352. url = picture_path
  353. nr = '16'
  354. values = {'p': str, 'p_name':msg['position'],'nr':nr}
  355. p22_1 = urllib.parse.urlencode(values)
  356. p22_1 = p22_1.encode('utf-8')
  357. req = urllib.request.Request(url, p22_1)
  358. req.add_header('User-Agent', 'Magic Browser')
  359. resp = urllib.request.urlopen(req)
  360. respData = resp.read()
  361. print(os.path.join(root, f))
  362. #print(respdata)
  363. os.remove(os.path.join(root, f))
  364. print("ok")
  365. preview_photo_log('a018',msg,'1')
  366. print("preview_photo ok")
  367. def tilt(msg):
  368. Tilt(int(msg['Tilt']))
  369. tilt_log('a014',msg,'1')
  370. def pan(msg):
  371. if(0<=int(msg['Pan'])<30):
  372. Pan((int(msg['Pan'])+330))
  373. if(int(msg['Pan'])==30):
  374. Pan(359)
  375. if(30<int(msg['Pan'])<=355):
  376. Pan((int(msg['Pan'])-30))
  377. pan_log('a012',msg,'1')
  378. def zoom(msg):
  379. Zoom(int(msg['Zoom']))
  380. zoom_log('a016',msg,'1')
  381. def zoom0(msg):
  382. Tilt(0)
  383. Pan(330)
  384. Zoom(-5)
  385. server_log('a052','1')
  386. ## device action.
  387. def Pan(pan):
  388. if 0<pan<=359:
  389. a = pan
  390. a1 = 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 + 76)
  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=10)
  408. Pan = [0xFF, 0x01, 0x00,0x4B, str_10, str_10_2, str_10_sum]
  409. print(Pan)
  410. ser.write(array.array('B', Pan).tostring())
  411. print('left')
  412. elif a == 0:
  413. SERIAL_PORT = '/dev/ttyS0'
  414. ser = serial.Serial(SERIAL_PORT, baudrate=9600, timeout=10)
  415. Pan = [0xFF, 0x01, 0x00, 0x4B, 0x00, 0x00, 0x4C]
  416. ser.write(array.array('B', Pan).tostring())
  417. print('leftzore')
  418. def Tilt(tilt):
  419. a = tilt
  420. def up():
  421. q = int(360)
  422. a1 = (q - a) * 100
  423. print(a1)
  424. k = '{0:x}'.format(a1)
  425. h = k.zfill(4)
  426. print(h)
  427. p3 = (h[0:2])
  428. ##print(p3)
  429. p4 = (h[2:])
  430. ##print(p4)
  431. str_10 = int(p3, 16)
  432. str_10_2 = int(p4, 16)
  433. sum_10 = (str_10 + str_10_2 + 78)
  434. str_16 = hex(sum_10)
  435. ##print(str_16)
  436. sum = (str_16[-2:])
  437. str_10_sum = int(sum, 16)
  438. SERIAL_PORT = '/dev/ttyS0'
  439. ser = serial.Serial(SERIAL_PORT, baudrate=9600, timeout=5)
  440. Pan = [0xFF, 0x01, 0x00, 0x4D, str_10, str_10_2, str_10_sum]
  441. print(Pan)
  442. ser.write(array.array('B', Pan).tostring())
  443. print('up')
  444. def down():
  445. k = abs(a)
  446. a1 = k * 100
  447. print (a1)
  448. k = '{0:x}'.format(a1)
  449. h = k.zfill(4)
  450. print(h)
  451. p3 = (h[0:2])
  452. ##print(p3)
  453. p4 = (h[2:])
  454. ##print(p4)
  455. str_10 = int(p3, 16)
  456. str_10_2 = int(p4, 16)
  457. sum_10 = (str_10 + str_10_2 + 78)
  458. str_16 = hex(sum_10)
  459. ##print(str_16)
  460. sum = (str_16[-2:])
  461. str_10_sum = int(sum, 16)
  462. SERIAL_PORT = '/dev/ttyS0'
  463. ser = serial.Serial(SERIAL_PORT, baudrate=9600, timeout=5)
  464. Pan = [0xFF, 0x01, 0x00, 0x4D, str_10, str_10_2, str_10_sum]
  465. print(Pan)
  466. ser.write(array.array('B', Pan).tostring())
  467. print('down')
  468. if 0 <= a <= 90:
  469. up()
  470. elif 0 > a >= -25:
  471. down()
  472. def Zoom(zoom):
  473. def Zoom1():
  474. headers = {'Content-Type': 'text/xml'}
  475. data = '<?xml version="1.0" encoding="utf-8"?><request><ptzcmd><protocol>0</protocol><cmd>0</cmd><addr>1</addr></</request>'
  476. url = camera_zoomin
  477. r = requests.post(url, headers=headers, data=data)
  478. print (r.content)
  479. def Zoom_1():
  480. headers = {'Content-Type': 'text/xml'}
  481. data = '<?xml version="1.0" encoding="utf-8"?><request><ptzcmd><protocol>0</protocol><cmd>0</cmd><addr>1</addr></</request>'
  482. url = camera_zoomout
  483. r = requests.post(url, headers=headers, data=data)
  484. print (r.content)
  485. print ('you')
  486. a = zoom
  487. print(a)
  488. if (a == 0):
  489. print("NO")
  490. elif (a>0):
  491. for i in range(a):
  492. time.sleep(1)
  493. for j in range(10):
  494. Zoom1()
  495. else:
  496. a=-1*a
  497. for i in range(a):
  498. time.sleep(1)
  499. for j in range(10):
  500. Zoom_1()
  501. def manual_ndvi(msg):
  502. req = requests.get(camera_ircut_high)
  503. time.sleep(2)
  504. fileName = datetime.datetime.now().strftime("/home/pi/ir_image1/"+msg['filename']+"a.tif")
  505. req = requests.get(camera_image)
  506. file = open(fileName, 'wb')
  507. for chunk in req.iter_content(100000):
  508. file.write(chunk)
  509. file.close()
  510. path1 = '/home/pi/ir_image1/'+msg['filename']+'a.tif'
  511. size1 = os.path.getsize(path1)
  512. print(size1)
  513. req = requests.get(camera_ircut_low)
  514. time.sleep(2)
  515. fileName = datetime.datetime.now().strftime("/home/pi/n_image1/"+msg['filename']+"b.tif")
  516. req = requests.get(camera_image)
  517. file = open(fileName, 'wb')
  518. for chunk in req.iter_content(100000):
  519. file.write(chunk)
  520. file.close()
  521. path2 = '/home/pi/n_image1/'+msg['filename']+'b.tif'
  522. size2 = os.path.getsize(path2)
  523. print(size2)
  524. def main_n():
  525. dress = '/home/pi/ir_image1/'
  526. for root, dirs, files in os.walk(dress):
  527. print('files: {}'.format(len(files)))
  528. if len(files) >= 1:
  529. files.sort()
  530. for f in files:
  531. with open(os.path.join(root, f), "rb") as imageFile:
  532. str = base64.b64encode(imageFile.read())
  533. url = picture_path
  534. nr = '16'
  535. values = {'data_ira': str, 'name_ira': f, 'nr': nr}
  536. data = urllib.parse.urlencode(values)
  537. data = data.encode('utf-8')
  538. req = urllib.request.Request(url, data)
  539. req.add_header('User-Agent', 'Magic Browser')
  540. resp = urllib.request.urlopen(req)
  541. respData = resp.read()
  542. print(os.path.join(root, f))
  543. # print(respData)
  544. os.remove(os.path.join(root, f))
  545. print("ok")
  546. def main_ir():
  547. dress = '/home/pi/n_image1/'
  548. for root, dirs, files in os.walk(dress):
  549. print('files: {}'.format(len(files)))
  550. if len(files) >= 1:
  551. files.sort()
  552. for f in files:
  553. with open(os.path.join(root, f), "rb") as imageFile:
  554. str = base64.b64encode(imageFile.read())
  555. url = picture_path
  556. nr = '16'
  557. values = {'c_na': str, 'name_na': f, 'nr': nr}
  558. c = urllib.parse.urlencode(values)
  559. c = c.encode('utf-8')
  560. req = urllib.request.Request(url, c)
  561. req.add_header('User-Agent', 'Magic Browser')
  562. resp = urllib.request.urlopen(req)
  563. respData = resp.read()
  564. print(os.path.join(root, f))
  565. #print(respData)
  566. os.remove(os.path.join(root, f))
  567. print("ok")
  568. main_n()
  569. main_ir()
  570. print("NDVI ok")
  571. ndvi_log('a051',msg,size1,size2,'1')
  572. def ndvi(msg):
  573. req = requests.get(camera_ircut_high)
  574. time.sleep(2)
  575. fileName = datetime.datetime.now().strftime("/home/pi/a"+msg['position']+"/"+msg['filename']+"a"+msg['position']+".tif")
  576. req = requests.get(camera_image)
  577. file = open(fileName, 'wb')
  578. for chunk in req.iter_content(100000):
  579. file.write(chunk)
  580. file.close()
  581. path1 = '/home/pi/a'+msg['position']+'/'+msg['filename']+'a'+msg['position']+'.tif'
  582. size1 = os.path.getsize(path1)
  583. print(size1)
  584. req = requests.get(camera_ircut_low)
  585. time.sleep(2)
  586. fileName = datetime.datetime.now().strftime("/home/pi/b"+msg['position']+"/"+msg['filename']+"b"+msg['position']+".tif")
  587. req = requests.get(camera_image)
  588. file = open(fileName, 'wb')
  589. for chunk in req.iter_content(100000):
  590. file.write(chunk)
  591. file.close()
  592. path2 = '/home/pi/b'+msg['position']+'/'+msg['filename']+'b'+msg['position']+'.tif'
  593. size2 = os.path.getsize(path2)
  594. print(size2)
  595. def main_n():
  596. dress = '/home/pi/a'+msg['position']+'/'
  597. for root, dirs, files in os.walk(dress):
  598. print('files: {}'.format(len(files)))
  599. if len(files) >= 1:
  600. files.sort()
  601. for f in files:
  602. with open(os.path.join(root, f), "rb") as imageFile:
  603. str = base64.b64encode(imageFile.read())
  604. url = picture_path
  605. nr = '16'
  606. values = {'data_ira': str, 'name_ira': f, 'nr': nr}
  607. data = urllib.parse.urlencode(values)
  608. data = data.encode('utf-8')
  609. req = urllib.request.Request(url, data)
  610. req.add_header('User-Agent', 'Magic Browser')
  611. resp = urllib.request.urlopen(req)
  612. respData = resp.read()
  613. print(os.path.join(root, f))
  614. #print(respData)
  615. os.remove(os.path.join(root, f))
  616. print("ok")
  617. def main_ir():
  618. dress = '/home/pi/b'+msg['position']+'/'
  619. for root, dirs, files in os.walk(dress):
  620. print('files: {}'.format(len(files)))
  621. if len(files) >= 1:
  622. files.sort()
  623. for f in files:
  624. with open(os.path.join(root, f), "rb") as imageFile:
  625. str = base64.b64encode(imageFile.read())
  626. url = picture_path
  627. nr = '16'
  628. values = {'c_na': str, 'name_na': f, 'nr': nr}
  629. c = urllib.parse.urlencode(values)
  630. c = c.encode('utf-8')
  631. req = urllib.request.Request(url, c)
  632. req.add_header('User-Agent', 'Magic Browser')
  633. resp = urllib.request.urlopen(req)
  634. respData = resp.read()
  635. print(os.path.join(root, f))
  636. #print(respData)
  637. os.remove(os.path.join(root, f))
  638. print("ok")
  639. # --------------------------------------------------------------------------------------
  640. main_n()
  641. main_ir()
  642. print("NDVI ok")
  643. ndvi_log('a051',msg,size1,size2,'1')
  644. ## The callback function for connecting.
  645. # @param client [in] The client instance for this callback.
  646. # @param userdata [in] The private user data as set in Client() or user_data_set().
  647. # @param flags [in] Response flags sent by the broker.
  648. # @param rc [in] The connection result.
  649. def on_connect(client, userdata, flags, rc):
  650. # subscribe MQTT topic on connection
  651. client.subscribe(mqtt_sub_topic, qos=2)
  652. server_log('a035', '1')
  653. logging.info('system running')
  654. data = {'nr': nr, 'status': 'reboot'}
  655. data = urllib.parse.urlencode(data)
  656. data = data.encode('utf-8')
  657. req = urllib.request.Request(reboot_path, data)
  658. req.add_header('User-Agent', 'Magic Browser')
  659. resp = urllib.request.urlopen(req)
  660. respData = resp.read()
  661. print("reboot check ok")
  662. ## The callback function for processing messages from the server.
  663. # @param client [in] The client instance for this callback.
  664. # @param userdata [in] The private user data as set in Client() or user_data_set().
  665. # @param msg [in] An instance of MQTT message.
  666. def on_message(client, userdata, msg):
  667. # print(msg.payload)
  668. msg.payload = msg.payload.decode('utf-8')
  669. jsonmsg = json.loads(msg.payload)
  670. #print(jsonmsg)
  671. print('Received:')
  672. print(json.dumps(jsonmsg, sort_keys=True, indent=4, separators=(',', ':')))
  673. # processing the command from the server
  674. if (jsonmsg['command'] == 'a035'):
  675. system_reboot()
  676. elif (jsonmsg['command'] == 'a033'):
  677. system_update_code()
  678. elif (jsonmsg['command'] == 'vpn_connect'):
  679. vpn_connect()
  680. elif (jsonmsg['command'] == 'vpn_disconnect'):
  681. vpn_disconnect()
  682. elif (jsonmsg['command'] == 'a055'):
  683. timecheck(jsonmsg)
  684. elif (jsonmsg['command'] == 'a057'):
  685. monitor()
  686. elif (jsonmsg['node_id'] == "GTW009002016"):
  687. if (jsonmsg['command'] == 'a000'):
  688. call(jsonmsg)
  689. elif (jsonmsg['command'] == 'a050'):
  690. parameter_setting(jsonmsg)
  691. elif (jsonmsg['command'] == 'a051'):
  692. if (jsonmsg['position'] == '0'):
  693. manual_ndvi(jsonmsg)
  694. else:
  695. ndvi(jsonmsg)
  696. elif (jsonmsg['command'] == 'a014'):
  697. tilt(jsonmsg)
  698. elif (jsonmsg['command'] == 'a012'):
  699. pan(jsonmsg)
  700. elif (jsonmsg['command'] == 'a016'):
  701. zoom(jsonmsg)
  702. elif (jsonmsg['command'] == 'a052'):
  703. zoom0(jsonmsg)
  704. elif (jsonmsg['command'] == 'a053'):
  705. stream0(jsonmsg)
  706. elif (jsonmsg['command'] == 'a054'):
  707. stream1(jsonmsg)
  708. elif (jsonmsg['command'] == 'a018'):
  709. if (jsonmsg['position'] == '0'):
  710. take_preview_photo(jsonmsg)
  711. else:
  712. preview_photo(jsonmsg)
  713. else:
  714. server_log(jsonmsg['command'], 'ERROR: Unknown command')
  715. ## A thread used to subscribe to and wait for messages from the server.
  716. def thread_job():
  717. # create a MQTT client with a user name and password to subscribe to the messages
  718. mqtt_thread_client = mqtt.Client()
  719. mqtt_thread_client.on_connect = on_connect
  720. mqtt_thread_client.on_message = on_message
  721. mqtt_thread_client.username_pw_set(username='aisky-client', password='aiskyc')
  722. mqtt_thread_client.connect(mqtt_server, mqtt_port, mqtt_alive)
  723. mqtt_thread_client.loop_forever()
  724. # create a MQTT client with a user name and password to publish messages
  725. mqtt_client = mqtt.Client()
  726. mqtt_client.username_pw_set(username='aisky-client', password='aiskyc')
  727. mqtt_client.connect(mqtt_server, mqtt_port, mqtt_alive)
  728. # create a thread to subscribe to and wait for messages from the server
  729. mqtt_subscribe_thread = threading.Thread(target=thread_job)
  730. mqtt_subscribe_thread.start()
  731. mqtt_client.loop_forever()