repository to manage all files related to the makeathon farm bot project (Software + Documentation).
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

functions.py 5.7KB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. import paho.mqtt.client as mqtt
  2. import json
  3. import threading
  4. import os
  5. import logging
  6. import raspy_sensors as Sensors
  7. from defines import Topics, SENSORDATA
  8. def measure_send_data(plantID, actionID, client: mqtt.Client):
  9. """
  10. Reads all sensors and publishes data via MQTT in form of SENSORDATA
  11. Args:
  12. plantID (_type_): plant to measure
  13. actionID (_type_): current ID of driving action
  14. client (mqtt.Client): current mqtt client for publishing
  15. """
  16. sensorData = SENSORDATA
  17. try:
  18. sensorData = Sensors.readSensors()
  19. except Exception as e:
  20. logging.error(str(e))
  21. client.publish(Topics["ROBOT_DATA_ERROR"], str(e), qos=1)
  22. sensorData["PlantID"] = plantID
  23. sensorData["ActionID"] = actionID
  24. client.publish(Topics["ROBOT_DATA_SENSORDATA"], json.dumps(sensorData, indent=4), qos=1)
  25. def drive_plant_thread(plantID, actionID, client: mqtt.Client):
  26. """
  27. Function to drive to plant according to number from MQTT message in thread
  28. Meassure and publish data via MQTT
  29. Drive home to starting point
  30. Args:
  31. plantID (_type_): plant to measure
  32. actionID (_type_): current ID of driving action
  33. client (mqtt.Client): current mqtt client for publishing
  34. """
  35. # FIXME Change to color code driving
  36. errorCode = os.system(f'sshpass -p maker ssh robot@ev3dev.local python3 /home/robot/Programme/plant_{plantID}.py')
  37. # errorCode = os.system(f'sshpass -p maker ssh robot@ev3dev.local python3 /home/robot/Programme/drive_plant.py {plantID}')
  38. if errorCode != 0:
  39. logging.error(f"Robot Error {errorCode} occurred")
  40. logging.info("Drive Plant aborted, Robot at starting position")
  41. client.publish(Topics["ROBOT_DATA_ERROR"], "Drive Plant aborted, Robot at starting position", qos=1)
  42. client.publish(Topics["ROBOT_DATA_ROBOTREADY"], "True", qos=1)
  43. return
  44. logging.info("Measuring Sensors")
  45. measure_send_data(plantID, actionID, client)
  46. # FIXME Send Picture
  47. # sendPicture()
  48. logging.info("Robot driving home")
  49. errorCode = os.system(f'sshpass -p maker ssh robot@ev3dev.local python3 /home/robot/Programme/drive_back.py {plantID}')
  50. if errorCode != 0:
  51. logging.error(f"Robot Error {errorCode} occurred")
  52. logging.info(f"Drive Home aborted, Robot at plant {plantID}")
  53. client.publish(Topics["ROBOT_DATA_ERROR"], f"Drive Home aborted, Robot at plant {plantID}", qos=1)
  54. client.publish(Topics["ROBOT_DATA_ROBOTREADY"], "True", qos=1)
  55. return
  56. logging.info("Robot home")
  57. client.publish(Topics["ROBOT_DATA_ROBOTREADY"], "True", qos=1)
  58. #region MQTT callbacks
  59. # TODO Test with all sensors
  60. def drive_plant(client: mqtt.Client, userdata, message: mqtt.MQTTMessage):
  61. """
  62. Function to drive to plant according to request
  63. Starting Drive in Thread to not block main programm
  64. Args:
  65. client (mqtt.Client): current mqtt client
  66. userdata (_type_): _description_
  67. message (mqtt.MQTTMessage): received DRIVE message with PlantID and ActionID
  68. """
  69. dictMessage = json.loads(str(message.payload.decode("UTF-8")))
  70. print(dictMessage)
  71. plantID = dictMessage["PlantID"]
  72. actionID = dictMessage["ActionID"]
  73. logging.info(f"Received Drive-request to plant {plantID}, ActionID: {actionID}")
  74. client.publish(Topics["ROBOT_DATA_ROBOTREADY"], "False", qos=1)
  75. thread = threading.Thread(target= drive_plant_thread, args=(plantID, actionID, client), daemon=True)
  76. thread.start()
  77. def get_position(clients: mqtt.Client, userdata, message: mqtt.MQTTMessage):
  78. """
  79. Callback function for GPS position request
  80. Function to send actual GPS position via MQTT in form of POSITION
  81. Args:
  82. client (mqtt.Client): current mqtt client
  83. userdata (_type_): _description_
  84. message (mqtt.MQTTMessage): received message
  85. """
  86. logging.info("Received position request")
  87. # TODO Write GPS Sensor Function
  88. position = {
  89. "Position": ""
  90. }
  91. clients.publish(Topics["ROBOT_DATA_POSITION"], json.dumps(position, indent=4), qos=1)
  92. def get_BatteryStatus(client: mqtt.Client, userdata, message: mqtt.MQTTMessage):
  93. """
  94. Callback function for battery status request
  95. Function to read battery status from ev3 and send via MQTT in form of BATTERY
  96. 8,5V -> 100%
  97. 5V -> 0%
  98. Args:
  99. client (mqtt.Client): current mqtt client
  100. userdata (_type_): _description_
  101. message (mqtt.MQTTMessage): received message
  102. """
  103. logging.info("Received battery status request")
  104. try:
  105. batteryLevel = int(os.popen('sshpass -p maker ssh robot@ev3dev.local cat /sys/devices/platform/battery/power_supply/lego-ev3-battery/voltage_now').read())
  106. except:
  107. logging.error("Robot not connected")
  108. client.publish(Topics["ROBOT_DATA_ERROR"], "Robot not connected", qos=1)
  109. return
  110. batteryLevel = round(batteryLevel / 1000000, 2) # Voltage
  111. batteryLevel = batteryLevel - 5
  112. batteryLevel = round(batteryLevel / 3.5, 3) *100 # Percentage
  113. battery = {
  114. "Battery": batteryLevel
  115. }
  116. client.publish(Topics["ROBOT_DATA_BATTERY"], json.dumps(battery, indent=4), qos=1)
  117. # TODO Test needed
  118. def sendPicture(client: mqtt.Client):
  119. """
  120. Takes picture and publish via MQTT
  121. Args:
  122. client (mqtt.Client): current mqtt client
  123. """
  124. try:
  125. Sensors.takePicture()
  126. except Exception as e:
  127. logging.error(str(e))
  128. client.publish(Topics["ROBOT_DATA_ERROR"], str(e), qos=1)
  129. with open("picture.txt", "rb") as f:
  130. file = f.read()
  131. byteArr = bytearray(file)
  132. print(byteArr)
  133. client.publish(Topics["ROBOT_DATA_IMAGE"], byteArr)
  134. print("Published")
  135. #endregion