Workshop IAAC Documentation

website·Indexed 30 days ago

https://lasaths.github.io/Workshop.IAAC.Documentation

Technical documentation for the IAAC workshop covering agent-based modeling (ABxM), robotic simulation with URSim and UR10e, and sensor integration. Includes guides on Python MQTT setup using Paho-MQTT, hand gesture recognition with MediaPipe and OpenCV, and Flask server implementation for web applications.

Tokens
8.8K
Snippets
34
Records
41
Agent score
25%

What's inside Workshop IAAC

  1. Overview of the ABxM Framework

    The ABxM Framework is an open platform for modeling and simulating agent-based (individual-based) systems consisting of locally interacting, discrete entities with autonomy and goal-orientation. It is designed to standardize research equipment to increase transparency and repeatability. The framework is built around the core agent library ABxM.Core; domain-specific applications typically expand this functionality by building add-ons on top of the core infrastructure.
  2. MQTT Core Terminology Reference

    The following terms are fundamental to configuring and using MQTT for device communication:

    • Broker: The central server that receives all messages from clients and routes them to the correct destinations.
    • Client: Any device that connects to the MQTT broker.
    • Publisher: A client that sends (publishes) messages to the broker.
    • Subscriber: A client that receives (subscribes to) messages from the broker.
    • Topic: A string identifier used by the broker to filter and route messages to specific clients.
    • QoS (Quality of Service): The delivery guarantee level.
      • QoS 0: Fastest, least reliable.
      • QoS 1: Balanced.
      • QoS 2: Slowest, most reliable.
  3. Understand MQTT basics for sensor data transmission to Grasshopper

    MQTT (Message Queuing Telemetry Transport) is a lightweight, publish-subscribe messaging protocol used to send data between devices. In this workflow, it is used to transmit sensor results to Grasshopper. It functions similarly to ROS (Robot Operating System) by facilitating communication between distributed devices.
  4. Understand UR10e robot communication protocols

    The workshop utilizes a UR10e robot equipped with a Robotiq gripper. Communication between the robot and computer is handled via two primary methods:

    1. Socket Communication: Used by the Robots Grasshopper plugin. It has a communication delay of 100ms (100Hz).
    2. Real-Time Data Exchange (RTDE): A faster communication method with a delay of 2ms (500Hz).

    For this workshop, Grasshopper components utilizing a commercial RTDE package from Underautomation are provided. Note that these specific components expire 30 days after installation.

  5. Create a reusable MQTT communication module

    To maintain clean code, create a separate mqtt.py file to handle MQTT logic. This module defines callbacks for connection events, a setup function to initialize the client and Last Will and Testament (LWT), and a publish function to send data to a broker.
    import paho.mqtt.client as paho
    
    # MQTT Callbacks definitions
    def on_connect(client, userdata, flags, rc, properties=None):
        print("CONNACK received with code %s." % rc)
    
    def on_publish(client, userdata, mid, properties=None):
        print("mid: " + str(mid))
    
    def on_subscribe(client, userdata, mid, granted_qos, properties=None):
        print("Subscribed: " + str(mid) + " " + str(granted_qos))
    
    def on_message(client, userdata, msg):
        print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
    
    def on_disconnect(client, userdata, rc, properties=None):
        print("MQTT Disconnected")
    
    def setup(client, topic, previousCheck):
        # MQTT Setup
        client.on_connect = on_connect
        client.on_publish = on_publish
        client.on_subscribe = on_subscribe
        client.on_message = on_message
        client.on_disconnect = on_disconnect
    
        # Last Will and Testament (LWT) must be set before connect
        client.will_set(topic, payload=previousCheck, qos=1, retain=True) 
        
        # Connect to HiveMQ Cloud on port 1883
        client.connect("mqtt-dashboard.com", 1883)
        
        # Send an Initial Value to the Broker
        client.publish(topic, payload=previousCheck, qos=1, retain=True)
        print("Data published to MQTT broker - " + str(previousCheck))
    
    def publish(value, client, topic, qos=1):
        try:
            if not client.is_connected():
                client.reconnect()
            client.publish(topic, payload=value, qos=qos, retain=True)
            print("Data published to MQTT broker - " + str(value))
        except Exception as e:
            print(f"Failed to publish message: {e}")
  6. Set up a basic Flask web server for hand tracking

    To create a web interface for a hand-tracking application, use the Flask framework. This involves initializing a Flask app, creating instances of custom tracking modules, and defining routes to handle camera feeds and data requests.
    from flask import Flask, Response, jsonify, render_template
    import sys
    
    # Add path to custom modules
    sys.path.append('02 Code/01 Python/02 Camera/01 Gestures')
    from hand_track import HandTrack
    from robot_behaviour import *
    
    app = Flask(__name__)
    my_hand_track = HandTrack()
    
    if __name__ == '__main__':
        # host='0.0.0.0' makes the server accessible from any network interface
        app.run(host='0.0.0.0', port=5000)
  7. Create a basic HTML template for a Flask web app

    To create a website template, create a directory named templates and place an index.html file inside it. The HTML structure should include a <!DOCTYPE html> declaration, a root <html> element, a <head> section for metadata and styles (such as Bootstrap CSS), and a <body> section for the main content and scripts.
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
        <title>Title of the Document</title>
        <style>This is the style setting</style>
    </head>
    
    <body>
        <div class="container">
    	<h1>This is the Heading</h1>
    	<p>This is the paragraph</p>
        </div>
        <script>This is the script setting</script>
    </body>
    </html>
  8. Visualize hand landmarks and gesture labels in OpenCV

    To visualize MediaPipe results on an OpenCV frame, you must convert the normalized coordinates (0.0 to 1.0) to pixel coordinates by multiplying them by the frame width and height. Use mp_drawing.draw_landmarks to render the hand skeleton and cv2.putText to display the gesture category and confidence score.
    # Convert normalized coordinates to pixels
    frame_height, frame_width = current_frame.shape[:2]
    x_min_px = int(x_min * frame_width)
    y_min_px = int(y_min * frame_height)
    
    # Draw Gesture Label
    if recognition_result_list[0].gestures:
        gesture = recognition_result_list[0].gestures[hand_index]
        category_name = gesture[0].category_name
        score = round(gesture[0].score, 2)
        result_text = f'{category_name} ({score})'
        cv2.putText(current_frame, result_text, (x_min_px, y_min_px - 10), 
                    cv2.FONT_HERSHEY_DUPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)
    
    # Draw Landmarks
    hand_landmarks_proto = landmark_pb2.NormalizedLandmarkList()
    hand_landmarks_proto.landmark.extend([
        landmark_pb2.NormalizedLandmark(x=landmark.x, y=landmark.y, z=landmark.z) 
        for landmark in hand_landmarks
    ])
    mp_drawing.draw_landmarks(
        current_frame, 
        hand_landmarks_proto, 
        mp_hands.HAND_CONNECTIONS, 
        mp_drawing_styles.get_default_hand_landmarks_style(),
        mp_drawing_styles.get_default_hand_connections_style()
    )
  9. Integrate MQTT communication into a main Python application

    Integrate the mqtt.py module into your main application (e.g., main.py) by importing the module, initializing the Paho client, and calling the setup and publish functions. Ensure the client is disconnected in a finally block to maintain a clean connection state.
    import paho.mqtt.client as paho
    import mqtt
    from mqtt import *
    
    # MQTT Parameters
    TOPIC = "IAACWorkshop/Gestures/Test"
    client = paho.Client(client_id="", protocol=paho.MQTTv311)
    previous_gesture = "None"
    
    def run():
        global client, previous_gesture
        # Initialize MQTT connection
        mqtt.setup(client, TOPIC, previous_gesture)
        
        try:
            # ... application logic ...
            # Example: Publish when a gesture is recognized
            if(previous_gesture != category_name and score > 0.55):
                mqtt.publish(category_name + "Lasath", client, TOPIC, 0)
                previous_gesture = category_name
        finally:
            # Clean disconnection
            client.disconnect()