Skip to Content
BonicBot A2DevelopmentPython ProgrammingLesson 18 - BonicBot Connection Lifecycle

Lesson 18 - BonicBot Connection Lifecycle

Learning Objective

  • Initialize BonicBot instances with custom host IP, port, and timeout arguments.
  • Utilize Python context managers (with statements) to guarantee safe resource connection and teardown.
  • Monitor active robot connection status using bot.is_connected().

Introduction

Communication with your robot relies on a steady network socket. The bonicbot_bridge SDK provides the BonicBot class to handle connection setup, heartbeat polling, and graceful disconnection.

Using Python context managers ensures your scripts close sockets properly even if an unexpected error occurs.


Code

connection_lifecycle.py
from bonicbot_bridge import BonicBot, ConnectionError ROBOT_HOST = "192.168.0.188" ROBOT_PORT = 9090 # 1. Recommended: Using context manager (with statement) try: with BonicBot(host=ROBOT_HOST, port=ROBOT_PORT, timeout=5) as bot: if bot.is_connected(): print(f"✅ Connected to robot at {bot.host}:{bot.port}") else: print("❌ Connection failed") # Sockets are automatically closed upon leaving the 'with' block print("Exited context manager block cleanly.") except ConnectionError as err: print(f"⚠️ Could not reach robot: {err}") # 2. Alternative: Manual lifecycle management print("\n--- Manual Connection Test ---") bot_manual = BonicBot(host=ROBOT_HOST) try: print("Is connected:", bot_manual.is_connected()) finally: bot_manual.disconnect() print("Disconnected manual instance.")

[!NOTE] Before running the code, make sure to replace ROBOT_HOST = "192.168.0.188" with your BonicBot’s actual IP address.


Expected Output

Click to see expected output

🤖 Connected to BonicBot at 192.168.0.188:9090 ✅ Connected to robot at 192.168.0.188:9090 🔌 Disconnected from BonicBot Exited context manager block cleanly. --- Manual Connection Test --- 🤖 Connected to BonicBot at 192.168.0.188:9090 Is connected: True 🔌 Disconnected from BonicBot Disconnected manual instance.

🔧 Under the Hood

How BonicBot manages socket threads in core.py

Instantiating BonicBot(host=..., port=...) runs core.py’s connect() method:

self.ros = Ros(host=self.host, port=self.port) self.ros.run()

It spins up a background thread (via Twisted) to maintain communication with rosbridge_server. Exiting the with block invokes disconnect(), which calls .shutdown() on sub-controllers before terminating self.ros.


Student Challenge

Challenge 1 — Python Only

Write a function test_robot_connection(ip_address) that attempts to connect using BonicBot. It must return True if successful, or catch ConnectionError and return False.

Click to see solution

test_connection.py
from bonicbot_bridge import BonicBot, ConnectionError def test_robot_connection(ip_address): try: with BonicBot(host=ip_address, timeout=3) as bot: return bot.is_connected() except ConnectionError: return False print("Connection test result:", test_robot_connection("192.168.0.188"))

Challenge 2 — Robot

Connect to the robot using a 5-second timeout, print whether bot.is_connected() is True, print bot.host and bot.port, and exit.

Click to see solution

challenge_connection.py
from bonicbot_bridge import BonicBot with BonicBot(host="192.168.0.188", timeout=5) as bot: print("Status:", bot.is_connected()) print("Address:", f"{bot.host}:{bot.port}")

Quick Reference

MethodDescription
BonicBot(host, port, timeout)Connect to robot at host:port with timeout in seconds
bot.connect(timeout)Explicitly initiate network connection
bot.disconnect()Terminate background sockets and sub-controllers
bot.is_connected()Returns True if network connection is healthy

Reflection Questions

Why is using Python’s with statement strongly recommended when working with physical hardware compared to manually calling connect() and disconnect()?

What happens internally when BonicBot.disconnect() is called during script exit?

Last updated on