Browse Source

[add] fixed backend data

master
caliskan 1 year ago
parent
commit
90235a73f1

+ 1
- 1
.idea/webServers.xml View File

<component name="WebServers"> <component name="WebServers">
<option name="servers"> <option name="servers">
<webServer id="1b3e9e3f-7394-4cbc-a32d-b95ef2abda52" name="backend"> <webServer id="1b3e9e3f-7394-4cbc-a32d-b95ef2abda52" name="backend">
<fileTransfer accessType="SFTP" host="192.168.137.197" port="22" sshConfigId="8ca8aafc-5b14-4074-b370-599a5b56368a" sshConfig="lego@192.168.137.197:22 password">
<fileTransfer accessType="SFTP" host="lego-K53SV" port="22" sshConfigId="40359a92-2c87-41df-943b-cfac73c7ea3d" sshConfig="lego@lego-K53SV:22 password">
<advancedOptions> <advancedOptions>
<advancedOptions dataProtectionLevel="Private" keepAliveTimeout="0" passiveMode="true" shareSSLContext="true" /> <advancedOptions dataProtectionLevel="Private" keepAliveTimeout="0" passiveMode="true" shareSSLContext="true" />
</advancedOptions> </advancedOptions>

+ 45
- 7
software/backend/data_functions.py View File

payload = json.loads(str_in) payload = json.loads(str_in)
logging.info("ROBOT_DATA_SENSORDATA Received data: " + json.dumps(payload)) logging.info("ROBOT_DATA_SENSORDATA Received data: " + json.dumps(payload))
drive_data = { drive_data = {
"PlantID": payload['PlantID'],
"PlantID": [payload['PlantID']],
"ActionID": payload['ActionID'] "ActionID": payload['ActionID']
} }


try: try:
print(drive_data)
print(robot.order_handler)
robot.delete_order(drive_data) robot.delete_order(drive_data)
mydatabase.insert_measurement_data(plant_id=payload['PlantID'], mydatabase.insert_measurement_data(plant_id=payload['PlantID'],
sensordata_temp=payload['AirTemperature'], sensordata_temp=payload['AirTemperature'],
sensordata_soil_moisture=payload['SoilMoisture'], sensordata_soil_moisture=payload['SoilMoisture'],
sensordata_brightness=payload['Brightness']) sensordata_brightness=payload['Brightness'])
logging.debug("Inserted to data base: " + json.dumps(payload)) logging.debug("Inserted to data base: " + json.dumps(payload))
action_getalldata(client, userdata, message, mydatabase)
except Exception as e: except Exception as e:
logging.error("Could not delete order: " + str(e)) logging.error("Could not delete order: " + str(e))


def data_sensordataall(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, mydatabase: PlantDataBase,
robot: Robot):
str_in = str(message.payload.decode("UTF-8"))
payload = json.loads(str_in)
logging.info("ROBOT_DATA_SENSORDATAALL Received data: " + json.dumps(payload))

plant_ids = []

for i in payload['SensorData']:
plant_ids.append(i["PlantID"])
print("Plant Names:", str(plant_ids))
drive_data = {
"PlantID": plant_ids,
"ActionID": payload['ActionID']
}

try:
print(robot.order_handler)
print(drive_data)
robot.delete_order(drive_data)
for i in payload['SensorData']:
mydatabase.insert_measurement_data(plant_id=i['PlantID'],
sensordata_temp=i['AirTemperature'],
sensordata_humidity=i['AirHumidity'],
sensordata_soil_moisture=i['SoilMoisture'],
sensordata_brightness=i['Brightness'])
logging.debug("Inserted to data base: " + json.dumps(payload))
action_getalldata(client, userdata, message, mydatabase)
except Exception as e:
logging.error("Could not delete order: " + str(e))




def data_position(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, robot: Robot): def data_position(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, robot: Robot):
logging.info("ROBOT_DATA_POSITION Received data: " + json.dumps(message.payload.decode("UTF-8"))) logging.info("ROBOT_DATA_POSITION Received data: " + json.dumps(message.payload.decode("UTF-8")))
"Timestamp": str(datetime.now()) "Timestamp": str(datetime.now())
} }
client.publish(Topics['BACKEND_DATA_BATTERY'], json.dumps(battery_data)) client.publish(Topics['BACKEND_DATA_BATTERY'], json.dumps(battery_data))
client.publish(Topics['BACKEND_DATA_ROBOTREADY'], str(robot.get_robot_status()))




def data_error(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, robot: Robot): def data_error(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, robot: Robot):
logging.info("Waiting Order send to Robot") logging.info("Waiting Order send to Robot")


logging.info("ROBOT_DATA_ROBOTREADY status updated: " + str(robot.get_robot_status())) logging.info("ROBOT_DATA_ROBOTREADY status updated: " + str(robot.get_robot_status()))
client.publish(Topics['BACKEND_DATA_ROBOTREADY'], message.payload.decode("UTF-8"))
client.publish(Topics['BACKEND_DATA_ROBOTREADY'], str(robot.get_robot_status()))




# FrontEnd Channel Reactions # FrontEnd Channel Reactions


def action_drive(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, mydatabase: PlantDataBase, def action_drive(client: mqtt.Client, userdata, message: mqtt.MQTTMessage, mydatabase: PlantDataBase,
robot: Robot): robot: Robot):
plant_id = mydatabase.get_plant_id(plant_name=json.loads(message.payload.decode("UTF-8"))["PlantName"])
plant_id = mydatabase.get_plant_id(plant_name=json.loads(str(message.payload.decode("UTF-8"))))
print(str(plant_id))
action_id = str(uuid.uuid4()) action_id = str(uuid.uuid4())
drive_data = { drive_data = {
"PlantID": plant_id, "PlantID": plant_id,
} }


if robot.get_order_number() < 6 and robot.get_robot_status() is True: if robot.get_order_number() < 6 and robot.get_robot_status() is True:
robot.add_order(drive_data)
robot.add_order({"PlantID": [plant_id], "ActionID": action_id})
client.publish(Topics['ROBOT_ACTION_DRIVE'], json.dumps(drive_data)) client.publish(Topics['ROBOT_ACTION_DRIVE'], json.dumps(drive_data))
logging.info("BACKEND_ACTION_DRIVE Drive Command published: " + json.dumps(drive_data)) logging.info("BACKEND_ACTION_DRIVE Drive Command published: " + json.dumps(drive_data))
else: else:
print(plant_names) print(plant_names)


for names in plant_names: for names in plant_names:
_id = mydatabase.get_plant_id(names)
_id = mydatabase.get_plant_id(names[0])
plant_ids.append(_id) plant_ids.append(_id)


action_id = str(uuid.uuid4()) action_id = str(uuid.uuid4())
print(drive_data) print(drive_data)
if robot.get_order_number() < 6 and robot.get_robot_status() is True: if robot.get_order_number() < 6 and robot.get_robot_status() is True:
robot.add_order(drive_data) robot.add_order(drive_data)
client.publish(Topics['ROBOT_ACTION_DRIVEALL'], json.dumps(plant_ids))
client.publish(Topics['ROBOT_ACTION_DRIVEALL'], json.dumps(drive_data))
logging.info("BACKEND_ACTION_DRIVEALL Drive Command published: " + json.dumps(drive_data)) logging.info("BACKEND_ACTION_DRIVEALL Drive Command published: " + json.dumps(drive_data))
else: else:
if robot.get_order_number() < 6: if robot.get_order_number() < 6:


def action_getalldata(client: mqtt.Client, userdata, message: Union[mqtt.MQTTMessage, list], mydatabase: PlantDataBase): def action_getalldata(client: mqtt.Client, userdata, message: Union[mqtt.MQTTMessage, list], mydatabase: PlantDataBase):
plant_names = mydatabase.get_plant_names() plant_names = mydatabase.get_plant_names()
print("SUIII" + str(plant_names))
alldata = [] alldata = []
for i in plant_names: for i in plant_names:
alldata.append(mydatabase.get_latest_data(plant_name=i))
alldata.append(mydatabase.get_latest_data(plant_name=i[0]))
client.publish(Topics['BACKEND_DATA_SENSORDATAALL'], json.dumps(alldata)) client.publish(Topics['BACKEND_DATA_SENSORDATAALL'], json.dumps(alldata))
logging.info("BACKEND_DATA_SENSORDATAALL got data from database:" + str(alldata)) logging.info("BACKEND_DATA_SENSORDATAALL got data from database:" + str(alldata))



+ 1
- 1
software/backend/defines.py View File

contains all constants for the backend architecture of the smart garden project contains all constants for the backend architecture of the smart garden project
""" """


MQTT_BROKER_LOCAL = "192.168.137.197"
MQTT_BROKER_LOCAL = "192.168.0.102"
MQTT_BROKER_GLOBAL = "mqtt.eclipseprojects.io" MQTT_BROKER_GLOBAL = "mqtt.eclipseprojects.io"
RASPI_CLIENT_ID = "smart_farming_raspi" RASPI_CLIENT_ID = "smart_farming_raspi"
BACKEND_CLIENT_ID = "smart_farming_server" BACKEND_CLIENT_ID = "smart_farming_server"

+ 12
- 0
software/backend/dev_test_examples/json_test.py View File


test_dict = {
"PlantData": [ {"PlantID":1, "Test": 0}, {"PlantID": 2, "Test": 0}],
"ActionID": "SUIIII"
}


plant_ids = []
for i in test_dict["PlantData"]:
plant_ids.append(i["PlantID"])

print(plant_ids)

+ 5
- 2
software/backend/main.py View File

_client.message_callback_add(Topics['ROBOT_DATA_SENSORDATA'], lambda client, userdata, message: data_functions. _client.message_callback_add(Topics['ROBOT_DATA_SENSORDATA'], lambda client, userdata, message: data_functions.
data_sensordata(client, userdata, message, _mydatabase, _robot)) data_sensordata(client, userdata, message, _mydatabase, _robot))


_client.subscribe(Topics['ROBOT_DATA_ALL'])
_client.message_callback_add(Topics['ROBOT_DATA_ALL'], lambda client, userdata, message: data_functions.
data_sensordataall(client, userdata, message, _mydatabase, _robot))
_client.subscribe(Topics['ROBOT_DATA_POSITION']) _client.subscribe(Topics['ROBOT_DATA_POSITION'])
_client.message_callback_add(Topics['ROBOT_DATA_POSITION'], data_functions.data_position) _client.message_callback_add(Topics['ROBOT_DATA_POSITION'], data_functions.data_position)


robot = Robot() robot = Robot()
my_database = PlantDataBase(database_name=DATABASE_NAME) my_database = PlantDataBase(database_name=DATABASE_NAME)
my_database.create_tables() my_database.create_tables()
mqttclient = mqtt.Client(BACKEND_CLIENT_ID)
mqttclient = mqtt.Client(BACKEND_CLIENT_ID, transport="websockets")
mqttclient.on_connect = lambda client, userdata, flags, rc: on_connect(_client=client, mqttclient.on_connect = lambda client, userdata, flags, rc: on_connect(_client=client,
_userdata=userdata, _userdata=userdata,
_flags=flags, _flags=flags,
_rc=rc, _rc=rc,
_mydatabase=my_database, _mydatabase=my_database,
_robot=robot) _robot=robot)
mqttclient.connect(MQTT_BROKER_GLOBAL)
mqttclient.connect(MQTT_BROKER_LOCAL)
logging.basicConfig(filename="server.log", filemode="a", encoding="utf-8", level=logging.DEBUG, logging.basicConfig(filename="server.log", filemode="a", encoding="utf-8", level=logging.DEBUG,
format='%(asctime)s %(name)s %(levelname)s %(message)s', format='%(asctime)s %(name)s %(levelname)s %(message)s',
datefmt="%d-%m-%Y %H:%M:%S") datefmt="%d-%m-%Y %H:%M:%S")

+ 1
- 2
software/backend/plantdatabase.py View File

import sqlite3 import sqlite3
from typing import Optional from typing import Optional
import logging import logging
from itertools import chain




class PlantDataBase: class PlantDataBase:
def get_plant_names(self) -> list: def get_plant_names(self) -> list:
try: try:
self.cur.execute("SELECT PlantName FROM plants") self.cur.execute("SELECT PlantName FROM plants")
return [row[0] for row in self.cur.fetchall()]
return self.cur.fetchall()
except Exception as e: except Exception as e:
logging.error("Could not get plant names: " + str(e)) logging.error("Could not get plant names: " + str(e))



Loading…
Cancel
Save