67 lines
2.4 KiB
Python
Raw Normal View History

"""
created by waldluis
This file contains the main script for the RaspberryPi of smart garden project
It has the task to control the EV3 robot and take measurements with the mounted sensor
The sensor data is published to MQTT topics to be available for the backend server
Used protocol for interaction: mqtt (paho-mqtt module)
Interaction with the EV3 via SSH
"""
import paho.mqtt.client as mqtt
import functions
2023-05-12 13:56:56 +02:00
import logging
import sys
from defines import Topics, RASPI_CLIENT_ID, MQTT_BROKER_GLOBAL, MQTT_BROKER_LOCAL
2023-04-27 17:33:24 +02:00
2023-04-22 12:32:27 +02:00
def on_connect(client: mqtt.Client, userdata, flags, rc):
"""
This method gets called, when it connects to a mqtt broker.
It is used to subscribe to the specific topics
2023-04-22 12:32:27 +02:00
Args:
client (mqtt.Client): current mqtt client
userdata (_type_): _description_
flags (_type_): _description_
rc (_type_): _description_
"""
if rc == 0:
2023-05-10 15:58:27 +02:00
#Add callbacks
client.message_callback_add(Topics["ROBOT_ACTION_DRIVE"], functions.drive_plant)
client.message_callback_add(Topics["ROBOT_ACTION_GETPOSITION"], functions.get_position)
2023-05-31 14:22:17 +02:00
client.message_callback_add(Topics["ROBOT_ACTION_GETBATTERY"], functions.get_batteryStatus)
2023-05-17 21:35:58 +02:00
client.message_callback_add(Topics["ROBOT_ACTION_DRIVEALL"], functions.drive_plant_all)
#Subscribe to topics
client.subscribe(Topics["ROBOT_ACTION_DRIVE"])
client.subscribe(Topics["ROBOT_ACTION_GETPOSITION"])
client.subscribe(Topics["ROBOT_ACTION_GETBATTERY"])
2023-05-17 21:35:58 +02:00
client.subscribe(Topics["ROBOT_ACTION_DRIVEALL"])
2023-05-12 13:56:56 +02:00
logging.info("MQTT initialized")
2023-04-22 14:34:46 +02:00
def main():
2023-04-24 13:04:03 +02:00
"""
Initialises MQTT and Sensors
Runs forever and controlls all robot functions
"""
2023-05-12 13:56:56 +02:00
logging.basicConfig(filename="robot.log", filemode="a", encoding="utf-8", level=logging.DEBUG, format='%(asctime)s %(name)s %(levelname)s %(message)s',
datefmt="%d-%m-%Y %H:%M:%S")
logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
client = mqtt.Client(RASPI_CLIENT_ID)
# client = mqtt.Client(RASPI_CLIENT_ID, transport="websockets") # Local Broker
client.on_connect = on_connect
client.connect(MQTT_BROKER_GLOBAL)
# client.connect("192.168.137.197") # Local Broker
2023-05-12 16:51:31 +02:00
logging.info("Robot initialised")
client.loop_forever() # Loop_start not needed
if __name__ == "__main__":
main()