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 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. mydatabase.insert_measurement_data(plant_id=payload['PlantID'],
  28. sensordata_temp=payload['AirTemperature'],
  29. sensordata_humidity=payload['AirHumidity'],
  30. sensordata_soil_moisture=payload['SoilMoisture'],
  31. sensordata_brightness=payload['Brightness'])
  32. logging.debug("Inserted to data base: " + json.dumps(payload))
  33. except Exception as e:
  34. logging.error("Could not delete order: " + str(e))
  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. def data_error(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, robot: Robot):
  52. robot.store_last_error(message.payload.decode("UTF-8"))
  53. logging.error("ROBOT_DATA_ERROR new error received from Robot: " + robot.get_last_error())
  54. client.publish(Topics['BACKEND_DATA_ERROR'], message.payload.decode("UTF-8"))
  55. def data_robotready(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, robot: Robot):
  56. robot.change_robot_status(message.payload.decode("UTF-8") == 'True')
  57. if robot.get_robot_status() is True and robot.get_order_number() >= 1:
  58. client.publish(Topics['ROBOT_ACTION_DRIVE'], json.dumps(robot.get_next_order()))
  59. logging.info("Waiting Order send to Robot")
  60. logging.info("ROBOT_DATA_ROBOTREADY status updated: " + str(robot.get_robot_status()))
  61. client.publish(Topics['BACKEND_DATA_ROBOTREADY'], message.payload.decode("UTF-8"))
  62. # FrontEnd Channel Reactions
  63. def action_drive(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, mydatabase: PlantDataBase,
  64. robot: Robot):
  65. plant_id = mydatabase.get_plant_id(plant_name=json.loads(message.payload.decode("UTF-8"))["PlantName"])
  66. action_id = str(uuid.uuid4())
  67. drive_data = {
  68. "PlantID": plant_id,
  69. "ActionID": action_id
  70. }
  71. if robot.get_order_number() < 6 and robot.get_robot_status() is True:
  72. robot.add_order(drive_data)
  73. client.publish(Topics['ROBOT_ACTION_DRIVE'], json.dumps(drive_data))
  74. logging.info("BACKEND_ACTION_DRIVE Drive Command published: " + json.dumps(drive_data))
  75. else:
  76. if robot.get_order_number() < 6:
  77. robot.add_order(drive_data)
  78. logging.info("BACKEND_ACTION_DRIVE New data added to order list: " + str(drive_data))
  79. elif robot.get_order_number() >= 6:
  80. logging.error("Could not add Order to list. Order discarded")
  81. client.publish(Topics['BACKEND_DATA_ERROR'], "Could not add Order to list. Order discarded")
  82. def action_driveall(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, mydatabase: PlantDataBase,
  83. robot: Robot):
  84. plant_names = mydatabase.get_plant_names()
  85. plant_ids = []
  86. print(plant_names)
  87. for names in plant_names:
  88. _id = mydatabase.get_plant_id(names)
  89. plant_ids.append(_id)
  90. action_id = str(uuid.uuid4())
  91. drive_data = {
  92. "PlantID": plant_ids,
  93. "ActionID": action_id
  94. }
  95. print(drive_data)
  96. if robot.get_order_number() < 6 and robot.get_robot_status() is True:
  97. robot.add_order(drive_data)
  98. client.publish(Topics['ROBOT_ACTION_DRIVEALL'], json.dumps(plant_ids))
  99. logging.info("BACKEND_ACTION_DRIVEALL Drive Command published: " + json.dumps(drive_data))
  100. else:
  101. if robot.get_order_number() < 6:
  102. robot.add_order(drive_data)
  103. logging.info("BACKEND_ACTION_DRIVEALL New data added to order list: " + str(drive_data))
  104. elif robot.get_order_number() >= 6:
  105. client.publish(Topics['BACKEND_DATA_ERROR'], "Could not add Order to list. Order discarded")
  106. logging.error("Could not add Order to list. Order discarded")
  107. def action_getposition(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, mydatabase: PlantDataBase):
  108. client.publish(Topics['ROBOT_ACTION_GETPOSITION'])
  109. logging.info("BACKEND_ACTION_GETPOSITION message forwarded to Robot")
  110. def action_getbattery(client: mqtt.Client, userdata, message: mqtt.MQTTMessage):
  111. client.publish(Topics['ROBOT_ACTION_GETBATTERY'])
  112. logging.info("BACKEND_ACTION_GETBATTERY message forwarded to Robot")
  113. battery_data = {
  114. "Battery": 66,
  115. "Timestamp": str(datetime.now())
  116. }
  117. print(battery_data)
  118. client.publish(Topics['BACKEND_DATA_BATTERY'], json.dumps(battery_data))
  119. def action_getalldata(client: mqtt.Client, userdata, message: Union[mqtt.MQTTMessage, list], mydatabase: PlantDataBase):
  120. plant_names = mydatabase.get_plant_names()
  121. alldata = []
  122. for i in plant_names:
  123. alldata.append(mydatabase.get_latest_data(plant_name=i))
  124. client.publish(Topics['BACKEND_DATA_SENSORDATAALL'], json.dumps(alldata))
  125. logging.info("BACKEND_DATA_SENSORDATAALL got data from database:" + str(alldata))
  126. def action_newplant(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, mydatabase: PlantDataBase):
  127. plant_data = json.loads(message.payload.decode("UTF-8"))
  128. mydatabase.insert_plant(plantname=plant_data["PlantName"], plant_id=plant_data["PlantID"])
  129. mydatabase.insert_measurement_data(plant_id=plant_data["PlantID"],
  130. sensordata_temp=plant_data["AirTemperature"],
  131. sensordata_humidity=plant_data["AirHumidity"],
  132. sensordata_soil_moisture=plant_data["SoilMoisture"],
  133. sensordata_brightness=plant_data["Brightness"])
  134. logging.info("BACKEND_ACTION_NEWPLANT new plant data received and inserted: " + str(plant_data))
  135. action_getalldata(client, userdata, message, mydatabase)
  136. def action_configureplant(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, mydatabase: PlantDataBase):
  137. plant_data = json.loads(message.payload.decode("UTF-8"))
  138. mydatabase.configure_plant(plant_id=plant_data["PlantID"], plantname=plant_data["PlantName"])
  139. mydatabase.insert_measurement_data(plant_id=plant_data["PlantID"],
  140. sensordata_temp=plant_data["AirTemperature"],
  141. sensordata_humidity=plant_data["AirHumidity"],
  142. sensordata_soil_moisture=plant_data["SoilMoisture"],
  143. sensordata_brightness=plant_data["Brightness"])
  144. logging.info("BACKEND_ACTION_CONFIGUREPLANT configure plant data received and inserted: " + str(plant_data))
  145. action_getalldata(client, userdata, message, mydatabase)
  146. def action_deleteplant(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, mydatabase: PlantDataBase):
  147. delete_plant = json.loads(message.payload.decode("UTF-8"))
  148. mydatabase.delete_plant(plant_id=delete_plant)
  149. logging.info("BACKEND_ACTION_DELETEPLANT delete plant data received and deleted: " + str(delete_plant))
  150. action_getalldata(client, userdata, message, mydatabase)
  151. def action_countplants(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, mydatabase: PlantDataBase):
  152. count = mydatabase.plant_count()
  153. count_payload = {
  154. "CurrentCount": count,
  155. "MaxCount": MAX_PLANT_COUNT
  156. }
  157. client.publish(Topics["BACKEND_DATA_PLANTCOUNT"], json.dumps(count_payload))
  158. logging.info("BACKEND_DATA_PLANTCOUNT forwarded plant count to FrontEnd: " + str(count_payload))