aisky-mqttd 27 KB

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