# SoftBank Robotics documentation What's new in NAOqi 2.8?

# ALBarcodeReader Tutorial

NAOqi Vision - Overview | API | Tutorial

## Introduction

This tutorial explains how to run the ALBarcodeReader module using Python. Two methods can be used to retrieve the results pushed by the module in ALMemory, query the memory regularly or subscribe to an event.

## Periodic query of ALMemory

This is done by calling the `ALMemoryProxy::getData` regularly.

`vision_barcodeReader_readMemory.py`

    #! /usr/bin/env python
    # -*- encoding: UTF-8 -*-

    """Example: Shows how images can be accessed through ALVideoDevice"""

    import qi
    import argparse
    import sys
    import time

    def main(session):
        """
        This is just an example script that shows how images can be accessed
        through ALVideoDevice in Python.
        Nothing interesting is done with the images in this example.
        """
        # Get the services ALBarcodeReader and ALMemory.

        barcode_service = session.service("ALBarcodeReader")
        memory_service = session.service("ALMemory")

        barcode_service.subscribe("test_barcode")

        # Query last data from ALMemory twenty times
        for range_counter in range(20):
            data = memory_service.getData("BarcodeReader/BarcodeDetected")
            print data
            time.sleep(1)

    if __name__ == "__main__":
        parser = argparse.ArgumentParser()
        parser.add_argument("--ip", type=str, default="127.0.0.1",
                            help="Robot IP address. On robot or Local Naoqi: use '127.0.0.1'.")
        parser.add_argument("--port", type=int, default=9559,
                            help="Naoqi port number")

        args = parser.parse_args()
        session = qi.Session()
        try:
            session.connect("tcp://" + args.ip + ":" + str(args.port))
        except RuntimeError:
            print ("Can't connect to Naoqi at ip \"" + args.ip + "\" on port " + str(args.port) +".\n"
                   "Please check your script arguments. Run with -h option for help.")
            sys.exit(1)
        main(session)

## Subscribe to an event

This method requires to write a small module which inherits from ALModule and contains a callback method which will be called each time the event `BarcodeReader/BarcodeDetected()` is raised.

Unlike the previous method, this one will only print new data.

`vision_barcodeReader_subscribeToEvent.py`

    #! /usr/bin/env python
    # -*- encoding: UTF-8 -*-

    """Example: A Simple class to get & read BarcodeDetection Events"""

    import qi
    import argparse
    import sys
    import time

    class BarcodeReader(object):
        """
        A simple class to react to barcode detection events.
        """
        def __init__(self, app):
            super(BarcodeReader, self).__init__()
            # start application and get session
            app.start()
            session = app.session
            # Get the services ALBarcodeReader and ALMemory.
            self.memory_service = session.service("ALMemory")
            self.barcode_service = session.service("ALBarcodeReader")
            self.subscriber = self.memory_service.subscriber("BarcodeReader/BarcodeDetected")
            self.subscriber.signal.connect(self.on_barcode_detected)
            self.barcode_service.subscribe("test_barcode")

        def on_barcode_detected(self, value):
            """
            Callback for event BarcodeReader/BarcodeDetected
            """
            print "I saw a barcode"
            print "The event data are: " +str(value)

        def run(self):
            """
            Loop on, wait for events until manual interruption.
            """
            print "Starting BarcodeReader"
            try:
                while True:
                    time.sleep(1)
            except KeyboardInterrupt:
                print "Interrupted by user, stopping BarcodeReader"
                self.barcode_service.unsubscribe("test_barcode")
                # Stop
                sys.exit(0)

    if __name__ == "__main__":
        parser = argparse.ArgumentParser()
        parser.add_argument("--ip", type=str, default="127.0.0.1",
                            help="Robot IP address. On robot or Local Naoqi: use '127.0.0.1'.")
        parser.add_argument("--port", type=int, default=9559,
                            help="Naoqi port number")

        args = parser.parse_args()
        try:
            # Initialize qi framework.
            connection_url = "tcp://" + args.ip + ":" + str(args.port)
            app = qi.Application(["BarcodeReader", "--qi-url=" + connection_url])
        except RuntimeError:
            print ("Can't connect to Naoqi at ip \"" + args.ip + "\" on port " + str(args.port) +".\n"
                   "Please check your script arguments. Run with -h option for help.")
            sys.exit(1)
        barcode_reader = BarcodeReader(app)
        barcode_reader.run()

### Example of output

    Received "BarcodeReader/BarcodeDetected" event with data: [['test', [[84.0, 14.0], [77.0, 72.0], [132.0, 77.0], [139.0, 22.0]]]]
    Received "BarcodeReader/BarcodeDetected" event with data: [['test', [[52.0, 11.0], [49.0, 91.0], [130.0, 100.0], [137.0, 15.0]]]]
    Received "BarcodeReader/BarcodeDetected" event with data: [['test', [[62.0, 12.0], [54.0, 92.0], [135.0, 103.0], [148.0, 19.0]]]]
    Received "BarcodeReader/BarcodeDetected" event with data: [['test', [[63.0, 13.0], [56.0, 93.0], [137.0, 105.0], [148.0, 20.0]]]]
    ...

Glossary Site map Index Support Contact Legal Notices