Moving and Watering Examples


  • Import the necessary python libraries and modules.

from agribot import Agribot, StubHandler
import threading, time

  • Log in and create an Agribot instance.

bot = Agribot.login("zaxrok@gmail.com", "zeta@1234!")

  • Create a list of positions to go to.

target_positions = [
    (300, 150, 0),
    (300, 300, 0),
    (300, 450, 0),
    (550, 450, 0),
    (550, 300, 0),
    (550, 150, 0),
    (800, 150, 0),
    (800, 300, 0),
    (800, 450, 0),
    (1050, 450, 0),
    (1050, 300, 0),
    (1050, 150, 0),
]

  • Define a custom handler, CustomHandler, with methods:

    • on_connect: Prints a connection confirmation.

    • on_response: Stays idle on bot response.

    • on_change: Prints bot’s current position and disconnects the bot.

    • on_log: Prints the bot’s log status.

    • on_error: Prints the bot’s error status.

    • perform_task: Move the location according to the list, sprinkle water, and finally return to the initial position.

class CustomHandler(StubHandler):
    def on_connect(self, bot, client):
        print("Connected to Agribot")
        self.start_task()  # 연결 시 작업 시작

    def on_change(self, bot, state):
        pass

    def on_log(self, bot, log):
        self.log = log
        print(self.log,"\n")

    def on_error(self, bot, response):
        print("Received error response")
        print(response.errors)

    def on_response(self, bot, response):
        pass

    def perform_task(self):
        distance_threshold = 5  # 오차 범위(거리 기준) 설정 (예: 5mm)
        for i, position in enumerate(target_positions):
            self.remaining_targets = len(target_positions) - i - 1
            print(f"Moving to location {position}... ({self.remaining_targets} targets remaining)")
            self.move_to_position(position, distance_threshold)

            print("Watering...")
            self.water_plants()

            print(f"Watering completed. ({self.remaining_targets} targets remaining)")
            time.sleep(2)


        # 홈으로 이동
        bot.find_home()
        time.sleep(2)

        # 홈 위치로 이동 후 제대로 도착했는지 확인
        while True:
            current_position = bot.position()
            x_diff = abs(current_position[0])
            y_diff = abs(current_position[1])
            z_diff = abs(current_position[2])
            if x_diff < distance_threshold and y_diff < distance_threshold and z_diff < distance_threshold:
                break
            time.sleep(1)  # 1초마다 위치 확인

        print("Moved to home position")

        # 연결 종료
        bot.disconnect()

    def move_to_position(self, position, distance_threshold):
        bot.move_absolute(position[0], position[1], position[2])

        # 위치 도달까지 대기
        while True:
            current_position = bot.position()
            x_diff = abs(current_position[0] - position[0])
            y_diff = abs(current_position[1] - position[1])
            z_diff = abs(current_position[2] - position[2])
            if x_diff < distance_threshold and y_diff < distance_threshold and z_diff < distance_threshold:
                break
            time.sleep(1)  # 1초마다 위치 확인

        print(f"Arrived at location {position}")

        # Z 방향으로 200씩 내려가기
        bot.move_relative(x=0, y=0, z=-200)

        # 내려간 후 제대로 이동했는지 확인
        while True:
            current_position = bot.position()
            z_diff = abs(current_position[2] - (position[2] - 200))
            if z_diff < distance_threshold:
                break
            time.sleep(1)  # 1초마다 위치 확인

        print(f"Moved down successfully. ({self.remaining_targets} targets remaining)")

    def water_plants(self):
        bot.write_pin(8, 1)  # water_valve 장치 활성화
        time.sleep(2)  # 펌프 동작을 위해 2초 대기

        message = self.log['message']
        if 'water_valve' in message and 'ON' in message:
            bot.write_pin(10, 1)  # water_pump 장치 활성화
            time.sleep(2)  # 펌프 동작을 위해 2초 대기

            message = self.log['message']
            if 'water_pump' in message and 'ON' in message:
                time.sleep(2)
                bot.write_pin(10, 0)  # water_pump 장치 비활성화
                time.sleep(2)  # 펌프 동작 종료 후 2초 대기

                message = self.log['message']
                if 'water_pump' in message and 'OFF' in message:
                    bot.write_pin(8, 0)  # water_valve 장치 비활성화
                    time.sleep(2)  # 밸브 비활성화 후 2초 대기

                    print(f"Watering completed. ({self.remaining_targets} targets remaining)")
                else:
                    print("Watering was not completed successfully.")
            else:
                print("Watering was not started successfully.")
        else:
            print("Watering was not started successfully.")

        time.sleep(2)


    def start_task(self):
        # 작업을 별도의 스레드에서 실행
        thread = threading.Thread(target=self.perform_task)
        thread.start()

  • Connect the Agribot instance with the CustomHandler instance, resulting in the execution of the defined methods on respective triggers.

handler = CustomHandler()
bot.connect(handler)