cowdungcart_schedule.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. import pymysql
  2. import rospy
  3. import paho.mqtt.client as mqtt
  4. from std_msgs.msg import String
  5. from geometry_msgs.msg import PoseStamped, PoseWithCovarianceStamped
  6. from move_base_msgs.msg import MoveBaseActionResult
  7. import json
  8. import threading
  9. from time import sleep as sl
  10. from datetime import datetime as dt
  11. from concurrent.futures import ThreadPoolExecutor
  12. class CowdungCartSchedule(object):
  13. def __init__(self):
  14. self.db = pymysql.connect(host='52.69.200.169', port=3306, user='cowdungcart', password='skyeye', database='CowdungCart', charset='utf8')
  15. self.cursor = self.db.cursor()
  16. self.client = mqtt.Client()
  17. self.goalStatus = "Got new plan"
  18. self.pool = ThreadPoolExecutor(10)
  19. def queryMySQL(self):
  20. while True:
  21. sl(60)
  22. current_time = dt.now()
  23. time = dt.strftime(current_time, "%H:%M")
  24. def query_job(time):
  25. #重新連線資料庫,即時更新
  26. db = pymysql.connect(host='52.69.200.169', port=3306, user='cowdungcart', password='skyeye', database='CowdungCart', charset='utf8')
  27. cursor = db.cursor()
  28. #搜尋排程時間
  29. sql = "select time1, time2, time3, time4, time5, time6, time7 from schedule order by datetime desc limit 1"
  30. cursor.execute(sql)
  31. schedules = cursor.fetchall()[0]
  32. for schedule in schedules:
  33. print(schedule)
  34. #將排程時間與現在時間做比對
  35. if schedule == time:
  36. #搜尋目標點座標
  37. sql = "select goal_change_x, goal_change_y from goal"
  38. cursor.execute(sql)
  39. goals = cursor.fetchall()
  40. #循環遍歷目標點
  41. for goal in goals:
  42. self.goalPublish(goal)
  43. while True:
  44. if self.goalStatus == 'Goal reached.':
  45. self.goalStatus = "Got new plan"
  46. break
  47. # 重新連線資料庫,即時更新
  48. db = pymysql.connect(host='52.69.200.169', port=3306, user='cowdungcart',
  49. password='skyeye', database='CowdungCart', charset='utf8')
  50. cursor = db.cursor()
  51. # 開始監測感測器的值
  52. # 超音波糞便高度
  53. sonic_sql = "select sonic from sonic order by datetime desc limit 1"
  54. cursor.execute(sonic_sql)
  55. sonic = cursor.fetchall()[0]
  56. # 水位
  57. water_level_sql = "select water_level from water_level order by datetime desc limit 1"
  58. cursor.execute(water_level_sql)
  59. water_level = cursor.fetchall()[0][0]
  60. cursor.close()
  61. db.close()
  62. sl(35)
  63. print("----------------------------------------------------")
  64. print(water_level)
  65. if water_level == 'top' or sonic == '':
  66. # 記住當下車子的位置
  67. currentPose = (self.currentPoseX, self.currentPoseY)
  68. # 發送基站前的目標點
  69. basePose = (-0.585351440576172, -0.5214363581840141)
  70. self.goalPublish(basePose)
  71. # 如果到達基站跳出循環
  72. while True:
  73. if self.goalStatus == 'Goal reached.':
  74. self.goalStatus = "Got new plan"
  75. break
  76. # MQTT
  77. pass
  78. # 回到原來紀錄位置
  79. self.goalPublish(currentPose)
  80. # 如果到達之前記錄位置跳出循環
  81. while True:
  82. if self.goalStatus == 'Goal reached.':
  83. self.goalStatus = "Got new plan"
  84. break
  85. # 往原來的目標點前進
  86. self.goalPublish(goal)
  87. # 如果到達原來目標點跳出循環
  88. while True:
  89. if self.goalStatus == 'Goal reached.':
  90. break
  91. cursor.close()
  92. db.close()
  93. self.pool.submit(query_job, time)
  94. def goalPublish(self, goal):
  95. # 定义发布器pub,发布的题目是chatter,消息类型是String,然后queue_size是在订阅者接受消息不够快的时候保留的消息的数量,如果对qos要求低的话可以设为0,不设置的话会出个报警,不过不会出错
  96. # pub = rospy.Publisher('chatter', String, queue_size=10)
  97. pub = rospy.Publisher('move_base_simple/goal', PoseStamped, queue_size=10)
  98. # 接下来这里初始化了一个名为talker的节点,节点的名字不能以‘ / ’开头,因为之后会自动给你加一个。anonymous参数在为True的时候会在原本节点名字的后面加一串随机数,来保证可以同时开启多个同样的节点,如果为false的话就只能开一个
  99. #rospy.init_node('goalPublish', anonymous=True)
  100. # 这里初始化一个Rate对象,通过后面的sleep()可以设定循环的频率
  101. rate = rospy.Rate(10) # 10hz
  102. ps = PoseStamped()
  103. ps.header.seq = 0
  104. ps.header.stamp.secs = 0
  105. ps.header.stamp.nsecs = 0
  106. ps.header.frame_id = 'map'
  107. ps.pose.position.x = float(goal[0])
  108. ps.pose.position.y = float(goal[1])
  109. ps.pose.position.z = 0.0
  110. ps.pose.orientation.x = 0.0
  111. ps.pose.orientation.y = 0.0
  112. ps.pose.orientation.z = 0.2
  113. ps.pose.orientation.w = 0.1
  114. # rospy.loginfo(ps)
  115. # pub.publish(ps)
  116. # while not rospy.is_shutdown():
  117. # # hello_str = "hello world %s" % rospy.get_time()
  118. # rospy.loginfo(ps)
  119. # #这里把hello_str发布出去了
  120. # pub.publish(ps)
  121. # rate.sleep()
  122. i = 0
  123. while i < 2:
  124. rospy.loginfo(ps)
  125. pub.publish(ps)
  126. rate.sleep()
  127. i += 1
  128. def mqttPublish(self, command):
  129. print (json.dumps(command))
  130. #要發布的主題和內容
  131. topic = 'AISKY/AppleFarm/MK-G/b8:27:eb:b4:59:3e'
  132. self.client.publish(topic, json.dumps(command))
  133. def workOn(self):
  134. #ROS結果回調函數
  135. def result_callback(data):
  136. rospy.loginfo(rospy.get_caller_id() + "I heard %s", data)
  137. self.goalStatus = data.status.text
  138. print(self.goalStatus)
  139. #ROS目標位置回調函數
  140. def pose_callback(data):
  141. # rospy.loginfo(rospy.get_caller_id() + "I heard %s", data)
  142. print(data.pose.pose.position.x, data.pose.pose.position.y, sep=',')
  143. self.currentPoseX = data.pose.pose.position.x
  144. self.currentPoseY = data.pose.pose.position.y
  145. #ROS訂閱
  146. def listener():
  147. rospy.init_node('goalAction', anonymous=False)
  148. # 这里初始化了一个订阅器,订阅了move_base/result这个主题,接收的消息类型为MoveBaseActionResult,每次接收到消息,就会开一个新线程来呼叫callback,每个订阅器只能有一个callback,另外似乎可以做到通过一个订阅器订阅多个主题或多个类型不同的消息,但我认为应该尽量避免这么做,尤其是涉及时间敏感度比较高的主题的时候,消息时间同步这类的事情很难处理
  149. rospy.Subscriber("move_base/result", MoveBaseActionResult, result_callback)
  150. #初始化目標點位置訂閱器,獲取車子當下座標位置
  151. rospy.Subscriber("amcl_pose", PoseWithCovarianceStamped, pose_callback)
  152. # spin() simply keeps python from exiting until this node is stopped
  153. # spin()的功能是让程序在手动停止前一直循环
  154. # rospy.spin()
  155. # MQTT當地端程式連線伺服器得到回應時,要做的動作
  156. def on_connect(client, userdata, flags, rc):
  157. print("Waiting for MQTT message...")
  158. # 將訂閱主題寫在on_connet中
  159. # 如果我們失去連線或重新連線時
  160. # 地端程式將會重新訂閱
  161. client.subscribe('AISKY/AppleFarm/MK-G/b8:27:eb:b4:59:3e/Log')
  162. # MQTT當接收到從伺服器發送的訊息時要進行的動作
  163. def on_message(client, userdata, msg):
  164. msg = msg
  165. def message_job(msg):
  166. db = pymysql.connect(host='52.69.200.169', port=3306, user='cowdungcart', password='skyeye',
  167. database='CowdungCart', charset='utf8')
  168. cursor = db.cursor()
  169. # 轉換編碼utf-8才看得懂中文
  170. print(msg.topic + " " + msg.payload.decode('utf-8'))
  171. payload = msg.payload.decode('utf-8')
  172. current_time = dt.now()
  173. time = dt.strftime(current_time, "%Y-%m-%d %H:%M:%S")
  174. if payload:
  175. p = json.loads(payload)
  176. if p['command'] == 'sonic':
  177. sql = "insert into actuator(sonic, datetime) values('%s', '%s')" % (p['rqnn'], time)
  178. cursor.execute(sql)
  179. db.commit()
  180. else:
  181. pass
  182. cursor.close()
  183. db.close()
  184. self.pool.submit(message_job, msg)
  185. # message_thread = threading.Thread(target=message_job, args=(msg,))
  186. # message_thread.daemon = True
  187. # message_thread.start()
  188. def thread_job(self):
  189. # 設定連線的動作
  190. self.client.on_connect = on_connect
  191. # 設定接收訊息的動作
  192. self.client.on_message = on_message
  193. # 設定登入帳號密碼
  194. self.client.username_pw_set("aisky-client", "aiskyc")
  195. # 設定連線資訊(IP, Port, 連線時間)
  196. self.client.connect("60.250.156.234", 1883, 60)
  197. # 開始連線,執行設定的動作和處理重新連線問題
  198. # 也可以手動使用其他loop函式來進行連接
  199. self.client.loop_forever()
  200. #創建執行序監聽MQTT訂閱消息
  201. mqtt_subscribe_thread = threading.Thread(target=thread_job, args=(self,))
  202. mqtt_subscribe_thread.daemon = True
  203. mqtt_subscribe_thread.start()
  204. #睡1秒等執行敘跑完才跑主程式
  205. sl(1)
  206. #創建ROS訂閱
  207. listener()
  208. self.queryMySQL()
  209. self.cursor.close()
  210. self.db.close()
  211. self.pool.shutdown(wait=True)
  212. if __name__ == '__main__':
  213. cowdungcart = CowdungCartSchedule()
  214. try:
  215. cowdungcart.workOn()
  216. except KeyboardInterrupt:
  217. cowdungcart.pool.shutdown(wait=True)
  218. cowdungcart.cursor.close()
  219. cowdungcart.db.close()