aisky-mqttd 26 KB

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