aisky-mqttd 26 KB

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