aisky-mqttd 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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_TOP_CAR"
  64. ## Calculate the SHA256 checksum of the file.
  65. # @param file [in] The file path for which you want to calculate the checksum.
  66. def get_sha256sum(file):
  67. with open(file, "rb") as f:
  68. bytes = f.read()
  69. return hashlib.sha256(bytes).hexdigest()
  70. ## Send logs to the server.
  71. # @param command [in] The command received from the server.
  72. # @param response [in] The response message to the command.
  73. def server_log(command, rqnn):
  74. localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
  75. # message to be sent in JSON format
  76. payload = {
  77. # let server know which device the message came from
  78. 'device_id': device_id,
  79. # let server know when the message was sent from the device
  80. 'localtime': localtime,
  81. 'node_id': nr,
  82. 'command': command,
  83. 'rqnn': rqnn
  84. }
  85. jsonobj = json.dumps(payload, sort_keys=True, indent=4)
  86. mqtt_client.publish(mqtt_pub_topic, jsonobj, qos=2)
  87. print('Sent:')
  88. print(jsonobj)
  89. def get_ip_address(ifname):
  90. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  91. try:
  92. return socket.inet_ntoa(fcntl.ioctl(
  93. s.fileno(),
  94. 0x8915, # SIOCGIFADDR
  95. struct.pack('256s', ifname[:15])
  96. )[20:24])
  97. except:
  98. return ""
  99. ## Reset this device.
  100. def system_reboot():
  101. server_log('a035', '1')
  102. time.sleep(5)
  103. os.system('sudo reboot')
  104. time.sleep(10)
  105. def system_update_code():
  106. os.system('sudo su')
  107. os.system('rm -rf /home/pi/AGVCAR')
  108. os.system('git clone -b AGV_TOP_CAR --single-branch http://60.250.156.230:3000/allen/AGV.git /home/pi/AGVCAR')
  109. time.sleep(3)
  110. os.system('cp /home/pi/AGV_TOP_CAR/aisky-mqttd /usr/sbin/')
  111. time.sleep(1)
  112. os.system('cp /home/pi/AGV_TOP_CAR/udp_client.py /home/pi/')
  113. time.sleep(1)
  114. os.system('sudo chmod 777 /usr/sbin/aisky-mqttd')
  115. os.system('sudo chmod 777 /home/pi/udp_client.py')
  116. time.sleep(5)
  117. server_log('a033', '1')
  118. os.system('sudo reboot')
  119. time.sleep(10)
  120. ## Receive the system action to this device .
  121. def video1(msg):
  122. if(msg['value']=="on"):
  123. os.system('sudo su')
  124. os.system('cd /hmoe/pi')
  125. os.system('sudo nohup python3.5 /home/pi/udp_client.py>/home/pi/nohup.out 2>&1 &')
  126. time.sleep(2)
  127. server_log('video1', 'on')
  128. elif (msg['value'] == 'off'):
  129. os.system('sudo su')
  130. os.system("ps aux | grep /home/pi/udp_client.py | awk '{print $2}' | xargs kill -9")
  131. time.sleep(2)
  132. server_log('video1', "off")
  133. else:
  134. server_log('video1', "error")
  135. ## The callback function for connecting.
  136. # @param client [in] The client instance for this callback.
  137. # @param userdata [in] The private user data as set in Client() or user_data_set().
  138. # @param flags [in] Response flags sent by the broker.
  139. # @param rc [in] The connection result.
  140. def on_connect(client, userdata, flags, rc):
  141. # subscribe MQTT topic on connection
  142. client.subscribe(mqtt_sub_topic, qos=2)
  143. server_log('a035', '1')
  144. #logging.info('system running')
  145. #data = {'nr': nr, 'status': 'reboot'}
  146. #data = urllib.parse.urlencode(data)
  147. #data = data.encode('utf-8')
  148. #req = urllib.request.Request(reboot_path, data)
  149. #req.add_header('User-Agent', 'Magic Browser')
  150. #resp = urllib.request.urlopen(req)
  151. #respData = resp.read()
  152. print("reboot check ok")
  153. ## The callback function for processing messages from the server.
  154. # @param client [in] The client instance for this callback.
  155. # @param userdata [in] The private user data as set in Client() or user_data_set().
  156. # @param msg [in] An instance of MQTT message.
  157. def on_message(client, userdata, msg):
  158. # print(msg.payload)
  159. msg.payload = msg.payload.decode('utf-8')
  160. jsonmsg = json.loads(msg.payload)
  161. #print(jsonmsg)
  162. print('Received:')
  163. print(json.dumps(jsonmsg, sort_keys=True, indent=4, separators=(',', ':')))
  164. # processing the command from the server
  165. if (jsonmsg['command'] == 'a035'):
  166. system_reboot()
  167. elif (jsonmsg['command'] == 'a033'):
  168. system_update_code()
  169. elif (jsonmsg['command'] == 'vpn_connect'):
  170. vpn_connect()
  171. elif (jsonmsg['command'] == 'vpn_disconnect'):
  172. vpn_disconnect()
  173. elif (jsonmsg['command'] == 'video1'):
  174. video1(jsonmsg)
  175. else:
  176. server_log(jsonmsg['command'], 'ERROR: Unknown command')
  177. ## A thread used to subscribe to and wait for messages from the server.
  178. def thread_job():
  179. # create a MQTT client with a user name and password to subscribe to the messages
  180. mqtt_thread_client = mqtt.Client()
  181. mqtt_thread_client.on_connect = on_connect
  182. mqtt_thread_client.on_message = on_message
  183. mqtt_thread_client.username_pw_set(username='aisky-client', password='aiskyc')
  184. mqtt_thread_client.connect(mqtt_server, mqtt_port, mqtt_alive)
  185. mqtt_thread_client.loop_forever()
  186. # create a MQTT client with a user name and password to publish messages
  187. mqtt_client = mqtt.Client()
  188. mqtt_client.username_pw_set(username='aisky-client', password='aiskyc')
  189. mqtt_client.connect(mqtt_server, mqtt_port, mqtt_alive)
  190. # create a thread to subscribe to and wait for messages from the server
  191. mqtt_subscribe_thread = threading.Thread(target=thread_job)
  192. mqtt_subscribe_thread.start()
  193. mqtt_client.loop_forever()