aisky-mqttd 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 RPi.GPIO as GPIO
  20. """ Device Information - the information about this device
  21. These device information is used for the MQTT topic. This program will subscribe and publish to
  22. the MQTT topic.
  23. MQTT topic to subscribe to: AISKY/<project_name>/<model_name>/<device_id>
  24. MQTT topic to publish to : AISKY/<project_name>/<model_name>/<device_id>/Log
  25. """
  26. # @var project_name The project name comes from the u-boot environment variable 'project'.
  27. # @var model_name The model name comes from the u-boot environment variable 'model'.
  28. # @var device_id The device id comes from the mac address of eth0.
  29. project_name = os.popen('cat /etc/aisky.conf | grep project').readline().split('=')[1].strip()
  30. model_name = os.popen('cat /etc/aisky.conf | grep model').readline().split('=')[1].strip()
  31. device_id = open('/sys/class/net/eth0/address').readline().strip()
  32. """ NOTE: Remember to setup the u-boot environment variables before executing this program. The
  33. commands to setup the u-boot environment variables are as follows.
  34. Setup the 'project' variable: The following command sets the 'project' variable to AppleFarm.
  35. root@mylinkit:~# fw_setenv project AppleFarm
  36. Setup the 'model' variable: The following command sets the 'model' variable to MK-G.
  37. root@mylinkit:~# fw_setenv model MK-G
  38. Then, the following command can be used to display the u-boot environment variables.
  39. root@mylinkit:~# fw_printenv
  40. """
  41. """ MQTT Server
  42. If you don't have your own MQTT server, you can use the public MQTT server 'iot.eclipse.org'. But
  43. with the public MQTT server, you can only publish and subscribe without a user name and password.
  44. Sometimes the public MQTT server is unstable.
  45. """
  46. # @var mqtt_server The URL or IP address of the MQTT server to connect to.
  47. # @var mqtt_port The port of the MQTT server to connect to.
  48. # @var mqtt_alive Maximum period in seconds allowed between communications with the broker. If
  49. # no other messages are being exchanged, this controls the rate at which the
  50. # client will send ping messages to the broker.
  51. mqtt_server = "60.250.156.234"
  52. mqtt_port = 1883
  53. mqtt_alive = 60
  54. # camera API command
  55. #php path
  56. #reboot_path ="http://www.aisky.com.tw/field/status.php"
  57. #log
  58. # @var mqtt_sub_topic The MQTT topic to subscribe to.
  59. # @var mqtt_pub_topic The MQTT topic to publish to.
  60. mqtt_sub_topic = "AISKY/" + project_name + "/" + model_name + "/" + device_id
  61. mqtt_pub_topic = mqtt_sub_topic + "/Log"
  62. ##nr
  63. nr = "AGV_CAR"
  64. ##gpio
  65. GPIO.setmode(GPIO.BOARD)
  66. GPIO.setwarnings(False)
  67. GPIO.setup(11, GPIO.OUT, initial=GPIO.LOW)
  68. GPIO.setup(12, GPIO.OUT, initial=GPIO.LOW)
  69. GPIO.setup(13, GPIO.OUT, initial=GPIO.LOW)
  70. GPIO.setup(15, GPIO.OUT, initial=GPIO.LOW)
  71. GPIO.setup(16, GPIO.OUT, initial=GPIO.LOW)
  72. ##sonic
  73. trigger_pin = 22
  74. echo_pin = 24
  75. GPIO.setup(trigger_pin, GPIO.OUT, initial=GPIO.LOW)
  76. GPIO.setup(echo_pin, GPIO.IN,pull_up_down = GPIO.PUD_DOWN)
  77. ##water_level
  78. water_level_pin1 =18
  79. signal_read_pin1 =19
  80. water_level_pin2 =21
  81. signal_read_pin2 =23
  82. GPIO.setup(water_level_pin1, GPIO.OUT, initial=GPIO.HIGH)
  83. GPIO.setup(signal_read_pin1, GPIO.IN,pull_up_down = GPIO.PUD_DOWN)
  84. GPIO.setup(water_level_pin2, GPIO.OUT, initial=GPIO.HIGH)
  85. GPIO.setup(signal_read_pin2, GPIO.IN,pull_up_down = GPIO.PUD_DOWN)
  86. ## Calculate the SHA256 checksum of the file.
  87. # @param file [in] The file path for which you want to calculate the checksum.
  88. def get_sha256sum(file):
  89. with open(file, "rb") as f:
  90. bytes = f.read()
  91. return hashlib.sha256(bytes).hexdigest()
  92. ## Send logs to the server.
  93. # @param command [in] The command received from the server.
  94. # @param response [in] The response message to the command.
  95. def server_log(command, rqnn):
  96. localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  97. # message to be sent in JSON format
  98. payload = {
  99. # let server know which device the message came from
  100. 'device_id': device_id,
  101. # let server know when the message was sent from the device
  102. 'localtime': localtime,
  103. 'node_id': nr,
  104. 'command': command,
  105. 'rqnn': rqnn
  106. }
  107. jsonobj = json.dumps(payload, sort_keys=True, indent=4)
  108. mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)
  109. print('Sent:')
  110. print(jsonobj)
  111. def get_ip_address(ifname):
  112. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  113. try:
  114. return socket.inet_ntoa(fcntl.ioctl(
  115. s.fileno(),
  116. 0x8915, # SIOCGIFADDR
  117. struct.pack('256s', ifname[:15])
  118. )[20:24])
  119. except:
  120. return ""
  121. ## Reset this device.
  122. def system_reboot():
  123. server_log('a035', '1')
  124. time.sleep(5)
  125. os.system('sudo reboot')
  126. time.sleep(10)
  127. def system_update_code():
  128. os.system('sudo su')
  129. os.system('rm -rf /home/pi/AGVCAR')
  130. os.system('git clone -b AGVCAR --single-branch http://60.250.156.230:3000/allen/AGV.git /home/pi/AGVCAR')
  131. time.sleep(3)
  132. os.system('cp /home/pi/AGVCAR/aisky-mqttd /usr/sbin/')
  133. time.sleep(1)
  134. os.system('cp /home/pi/AGVCAR/udp_client.py /home/pi/')
  135. time.sleep(1)
  136. os.system('sudo chmod 777 /usr/sbin/aisky-mqttd')
  137. os.system('sudo chmod 777 /home/pi/udp_client.py')
  138. time.sleep(5)
  139. server_log('a033', '1')
  140. os.system('sudo reboot')
  141. time.sleep(10)
  142. ## Receive the system action to this device .
  143. def fan(msg):
  144. if (msg['value'] == 'on'):
  145. GPIO.output(11, GPIO.HIGH)
  146. server_log(' fan', "on")
  147. elif (msg['value'] == 'off'):
  148. GPIO.output(11, GPIO.LOW)
  149. server_log(' fan', "off")
  150. else:
  151. server_log(' fan', "NULL")
  152. def water_bump(msg):
  153. if (msg['value'] == 'on'):
  154. GPIO.output(12, GPIO.HIGH)
  155. server_log('water_bump', "on")
  156. elif (msg['value'] == 'off'):
  157. GPIO.output(12, GPIO.LOW)
  158. server_log('water_bump', "off")
  159. else:
  160. server_log(' water_bump', "NULL")
  161. def red_light(msg):
  162. if (msg['value'] == 'on'):
  163. GPIO.output(13, GPIO.HIGH)
  164. server_log(' red_light', "on")
  165. elif (msg['value'] == 'off'):
  166. GPIO.output(13, GPIO.LOW)
  167. server_log(' red_light', "off")
  168. else:
  169. server_log(' red_light', "NULL")
  170. def yellow_light(msg):
  171. if (msg['value'] == 'on'):
  172. GPIO.output(15, GPIO.HIGH)
  173. server_log(' yellow_light', "on")
  174. elif (msg['value'] == 'off'):
  175. GPIO.output(15, GPIO.LOW)
  176. server_log(' yellow_light', "off")
  177. else:
  178. server_log(' yellow_light', "NULL")
  179. def green_light(msg):
  180. if (msg['value'] == 'on'):
  181. GPIO.output(16, GPIO.HIGH)
  182. server_log(' green_light', "on")
  183. elif (msg['value'] == 'off'):
  184. GPIO.output(16, GPIO.LOW)
  185. server_log(' green_light', "off")
  186. else:
  187. server_log('green_light', "NULL")
  188. def send_trigger_pulse():
  189. GPIO.output(trigger_pin, True)
  190. time.sleep(0.001)
  191. GPIO.output(trigger_pin, False)
  192. def wait_for_echo(value, timeout):
  193. count = timeout
  194. while GPIO.input(echo_pin) != value and count > 0:
  195. count = count - 1
  196. def sonic():
  197. send_trigger_pulse()
  198. wait_for_echo(True, 5000)
  199. start = time.time()
  200. wait_for_echo(False, 5000)
  201. finish = time.time()
  202. pulse_len = finish - start
  203. distance_cm = pulse_len * 340 *100 /2
  204. distance_in = distance_cm / 2.5
  205. print(distance_cm)
  206. server_log('sonic',distance_cm)
  207. def water_level():
  208. level_1=GPIO.input(signal_read_pin1)
  209. level_2=GPIO.input(signal_read_pin2)
  210. print(level_1)
  211. print(level_2)
  212. if(level_1 == False):
  213. if(level_2 == False):
  214. server_log('water_level', "top")
  215. elif(level_2 == False):
  216. server_log('water_level', "error")
  217. elif(level_1 == True):
  218. if(level_2 == False):
  219. server_log('water_level', "center")
  220. elif(level_2 == True):
  221. server_log('water_level', "bottom")
  222. def video2(msg):
  223. if(msg['value']=="on"):
  224. os.system('sudo su')
  225. os.system('cd /hmoe/pi')
  226. os.system('sudo nohup python3.5 /home/pi/udp_client.py>/home/pi/nohup.out 2>&1 &')
  227. time.sleep(2)
  228. server_log('video2', 'on')
  229. elif (msg['value'] == 'off'):
  230. os.system('sudo su')
  231. os.system("ps aux | grep /home/pi/udp_client.py | awk '{print $2}' | xargs kill -9")
  232. time.sleep(2)
  233. server_log('video2', "off")
  234. else:
  235. server_log('video2', "error")
  236. ## The callback function for connecting.
  237. # @param client [in] The client instance for this callback.
  238. # @param userdata [in] The private user data as set in Client() or user_data_set().
  239. # @param flags [in] Response flags sent by the broker.
  240. # @param rc [in] The connection result.
  241. def on_connect(client, userdata, flags, rc):
  242. # subscribe MQTT topic on connection
  243. client.subscribe(mqtt_sub_topic, qos=2)
  244. server_log('a035', '1')
  245. #logging.info('system running')
  246. #data = {'nr': nr, 'status': 'reboot'}
  247. #data = urllib.parse.urlencode(data)
  248. #data = data.encode('utf-8')
  249. #req = urllib.request.Request(reboot_path, data)
  250. #req.add_header('User-Agent', 'Magic Browser')
  251. #resp = urllib.request.urlopen(req)
  252. #respData = resp.read()
  253. print("reboot check ok")
  254. ## The callback function for processing messages from the server.
  255. # @param client [in] The client instance for this callback.
  256. # @param userdata [in] The private user data as set in Client() or user_data_set().
  257. # @param msg [in] An instance of MQTT message.
  258. def on_message(client, userdata, msg):
  259. # print(msg.payload)
  260. msg.payload = msg.payload.decode('utf-8')
  261. jsonmsg = json.loads(msg.payload)
  262. #print(jsonmsg)
  263. print('Received:')
  264. print(json.dumps(jsonmsg, sort_keys=True, indent=4, separators=(',', ':')))
  265. # processing the command from the server
  266. if (jsonmsg['command'] == 'a035'):
  267. system_reboot()
  268. elif (jsonmsg['command'] == 'a033'):
  269. system_update_code()
  270. elif (jsonmsg['command'] == 'vpn_connect'):
  271. vpn_connect()
  272. elif (jsonmsg['command'] == 'vpn_disconnect'):
  273. vpn_disconnect()
  274. elif (jsonmsg['command'] == 'fan'):
  275. fan(jsonmsg)
  276. elif (jsonmsg['command'] == 'water_bump'):
  277. water_bump(jsonmsg)
  278. elif (jsonmsg['command'] == 'red_light'):
  279. red_light(jsonmsg)
  280. elif (jsonmsg['command'] == 'yellow_light'):
  281. yellow_light(jsonmsg)
  282. elif (jsonmsg['command'] == 'green_light'):
  283. green_light(jsonmsg)
  284. elif (jsonmsg['command'] == 'sonic'):
  285. sonic()
  286. elif (jsonmsg['command'] == 'water_level'):
  287. water_level()
  288. elif (jsonmsg['command'] == 'video2'):
  289. video2(jsonmsg)
  290. else:
  291. server_log(jsonmsg['command'], 'ERROR: Unknown command')
  292. ## A thread used to subscribe to and wait for messages from the server.
  293. def thread_job():
  294. # create a MQTT client with a user name and password to subscribe to the messages
  295. mqtt_thread_client = mqtt.Client()
  296. mqtt_thread_client.on_connect = on_connect
  297. mqtt_thread_client.on_message = on_message
  298. mqtt_thread_client.username_pw_set(username='aisky-client', password='aiskyc')
  299. mqtt_thread_client.connect(mqtt_server, mqtt_port, mqtt_alive)
  300. mqtt_thread_client.loop_forever()
  301. # create a MQTT client with a user name and password to publish messages
  302. mqtt_client = mqtt.Client()
  303. mqtt_client.username_pw_set(username='aisky-client', password='aiskyc')
  304. mqtt_client.connect(mqtt_server, mqtt_port, mqtt_alive)
  305. # create a thread to subscribe to and wait for messages from the server
  306. mqtt_subscribe_thread = threading.Thread(target=thread_job)
  307. mqtt_subscribe_thread.start()
  308. mqtt_client.loop_forever()