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.

data_functions.py 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. """
  2. created by caliskan at 19.04.2023
  3. This file contains all functions, which handle the different cases.
  4. Every function should return json format with the wanted data from the database
  5. """
  6. import paho.mqtt.client as mqtt
  7. from plantdatabase import PlantDataBase
  8. from defines import Topics, MAX_PLANT_COUNT
  9. import json
  10. import uuid
  11. from typing import Union
  12. from datetime import datetime
  13. import logging
  14. from robot import Robot
  15. # Robot Channel Reactions
  16. def data_sensordata(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, mydatabase: PlantDataBase,
  17. robot: Robot):
  18. str_in = str(message.payload.decode("UTF-8"))
  19. payload = json.loads(str_in)
  20. logging.info("ROBOT_DATA_SENSORDATA Received data: " + json.dumps(payload))
  21. drive_data = {
  22. "PlantID": payload['PlantID'],
  23. "ActionID": payload['ActionID']
  24. }
  25. try:
  26. robot.delete_order(drive_data)
  27. except Exception as e:
  28. logging.error("Could not delete order: " + str(e))
  29. mydatabase.insert_measurement_data(plant_id=payload['PlantID'],
  30. sensordata_temp=payload['AirTemperature'],
  31. sensordata_humidity=payload['AirHumidity'],
  32. sensordata_soil_moisture=payload['SoilMoisture'],
  33. sensordata_brightness=payload['Brightness'])
  34. logging.debug("Inserted to data base: " + json.dumps(payload))
  35. def data_position(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, robot: Robot):
  36. logging.info("ROBOT_DATA_POSITION Received data: " + json.dumps(message.payload.decode("UTF-8")))
  37. robot.store_position(json.loads(message.payload.decode("UTF-8"))["Position"])
  38. position_data = {
  39. "Position": robot.get_position(),
  40. "Timestamp": str(datetime.now())
  41. }
  42. client.publish(Topics['BACKEND_DATA_POSITION'], json.dumps(position_data))
  43. def data_battery(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, robot: Robot):
  44. logging.info("ROBOT_DATA_BATTERY Received data: " + str(json.dumps(message.payload.decode("UTF-8"))))
  45. robot.store_battery(json.loads(message.payload.decode("UTF-8"))["Battery"])
  46. battery_data = {
  47. "Battery": robot.get_battery(),
  48. "Timestamp": str(datetime.now())
  49. }
  50. client.publish(Topics['BACKEND_DATA_BATTERY'], json.dumps(battery_data))
  51. # FrontEnd Channel Reactions
  52. def action_drive(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, mydatabase: PlantDataBase,
  53. robot: Robot):
  54. plant_id = mydatabase.get_plant_id(plant_name=json.loads(message.payload.decode("UTF-8"))["PlantName"])
  55. action_id = str(uuid.uuid4())
  56. drive_data = {
  57. "PlantID": plant_id,
  58. "ActionID": action_id
  59. }
  60. if robot.get_order_number() < 6 and robot.get_robot_status() is True:
  61. robot.add_order(drive_data)
  62. client.publish(Topics['ROBOT_ACTION_DRIVE'], json.dumps(drive_data))
  63. logging.info("BACKEND_ACTION_DRIVE Drive Command published: " + json.dumps(drive_data))
  64. else:
  65. if robot.get_order_number() < 6:
  66. robot.add_order(drive_data)
  67. logging.info("BACKEND_ACTION_DRIVE New data added to order list: " + str(drive_data))
  68. elif robot.get_order_number() >= 6:
  69. logging.error("Could not add Order to list. Order discarded")
  70. client.publish(Topics['BACKEND_DATA_ERROR'], "Could not add Order to list. Order discarded")
  71. def action_driveall(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, mydatabase: PlantDataBase,
  72. robot: Robot):
  73. client.publish(Topics['ROBOT_ACTION_DRIVEALL'])
  74. def action_getposition(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, mydatabase: PlantDataBase):
  75. client.publish(Topics['ROBOT_ACTION_GETPOSITION'])
  76. logging.info("BACKEND_ACTION_GETPOSITION message forwarded to Robot")
  77. def action_getbattery(client: mqtt.Client, userdata, message: mqtt.MQTTMessage):
  78. client.publish(Topics['ROBOT_ACTION_GETBATTERY'])
  79. logging.info("BACKEND_ACTION_GETBATTERY message forwarded to Robot")
  80. def action_getalldata(client: mqtt.Client, userdata, message: Union[mqtt.MQTTMessage, list], mydatabase: PlantDataBase):
  81. plant_names = mydatabase.get_plant_names()
  82. alldata = []
  83. for i in plant_names:
  84. alldata.append(mydatabase.get_latest_data(plant_name=i[0]))
  85. client.publish(Topics['BACKEND_DATA_SENSORDATAALL'], json.dumps(alldata))
  86. logging.info("BACKEND_DATA_SENSORDATAALL got data from database:" + str(alldata))
  87. def action_newplant(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, mydatabase: PlantDataBase):
  88. plant_data = json.loads(message.payload.decode("UTF-8"))
  89. mydatabase.insert_plant(plantname=plant_data["PlantName"], plant_id=plant_data["PlantID"])
  90. mydatabase.insert_measurement_data(plant_id=plant_data["PlantID"],
  91. sensordata_temp=plant_data["AirTemperature"],
  92. sensordata_humidity=plant_data["AirHumidity"],
  93. sensordata_soil_moisture=plant_data["SoilMoisture"],
  94. sensordata_brightness=plant_data["Brightness"])
  95. logging.info("BACKEND_ACTION_NEWPLANT new plant data received and inserted: " + str(plant_data))
  96. action_getalldata(client, userdata, message, mydatabase)
  97. def action_configureplant(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, mydatabase: PlantDataBase):
  98. plant_data = json.loads(message.payload.decode("UTF-8"))
  99. mydatabase.configure_plant(plant_id=plant_data["PlantID"], plantname=plant_data["PlantName"])
  100. mydatabase.insert_measurement_data(plant_id=plant_data["PlantID"],
  101. sensordata_temp=plant_data["AirTemperature"],
  102. sensordata_humidity=plant_data["AirHumidity"],
  103. sensordata_soil_moisture=plant_data["SoilMoisture"],
  104. sensordata_brightness=plant_data["Brightness"])
  105. logging.info("BACKEND_ACTION_CONFIGUREPLANT configure plant data received and inserted: " + str(plant_data))
  106. action_getalldata(client, userdata, message, mydatabase)
  107. def action_deleteplant(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, mydatabase: PlantDataBase):
  108. delete_plant = json.loads(message.payload.decode("UTF-8"))
  109. mydatabase.delete_plant(plant_id=delete_plant)
  110. logging.info("BACKEND_ACTION_DELETEPLANT delete plant data received and deleted: " + str(delete_plant))
  111. action_getalldata(client, userdata, message, mydatabase)
  112. def action_countplants(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, mydatabase: PlantDataBase):
  113. count = mydatabase.plant_count()
  114. count_payload = {
  115. "CurrentCount": count,
  116. "MaxCount": MAX_PLANT_COUNT
  117. }
  118. client.publish(Topics["BACKEND_DATA_PLANTCOUNT"], json.dumps(count_payload))
  119. logging.info("BACKEND_DATA_PLANTCOUNT forwarded plant count to FrontEnd: " + str(count_payload))
  120. def data_error(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, robot: Robot):
  121. robot.store_last_error(message.payload.decode("UTF-8"))
  122. logging.error("ROBOT_DATA_ERROR new error received from Robot: " + robot.get_last_error())
  123. client.publish(Topics['BACKEND_DATA_ERROR'], message.payload.decode("UTF-8"))
  124. def data_robotready(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, robot: Robot):
  125. robot.change_robot_status(message.payload.decode("UTF-8") == 'True')
  126. if robot.get_robot_status() is True and robot.get_order_number() >= 1:
  127. client.publish(Topics['ROBOT_ACTION_DRIVE'], json.dumps(robot.get_next_order()))
  128. logging.info("Waiting Order send to Robot")
  129. logging.info("ROBOT_DATA_ROBOTREADY status updated: " + str(robot.get_robot_status()))
  130. client.publish(Topics['BACKEND_DATA_ROBOTREADY'], message.payload.decode("UTF-8"))