How do you define a box in python?

Creating Python boxes¶

Simple modifications of a box script¶

All the boxes in Choregraphe have their own script, so you can easily edit them and modify the script.

Description of the script logic¶

The script programming language in Choregraphe is Python. Each box in Choregraphe is a module. Briefly, a module is like an application, completely independent, that can run on its own and communicate easily with other modules.

The box creation is done in several steps:

  1. Instantiation of the box
  2. Registration of the box as a module so it can be called from other boxes through linking
  3. Box initialization

The first two steps are automatic: you have no control over the script. But you have full control over the third step. Actually, this step executes some part of code you have written in the box script.

Description of a box script¶

To examine a box script, drag and drop the Set LEDs box onto the diagram panel and double-click on it.

The script window is displayed, showing the following script:

class MyClass[GeneratedClass]:
    def __init__[self]:
        GeneratedClass.__init__[self]

    def onLoad[self]:
        #~ puts code for box initialization here
        pass

    def onUnload[self]:
        #~ puts code for box cleanup here
        pass

    def onInput_onSet[self]:
        ALLeds.fade[self.getParameter["LEDs group"], self.getParameter["Intensity [%]"]/100., self.getParameter["Duration [s]"]]
        self.onReady[] # activate output of the box

This box orders the LEDs of a group of LEDs [ear LEDs by default] to switch on [onStart input] in the given amount of time [default 1 second].

When writing script, you must remember that you are defining methods of a module class. A method is a function the program calls to execute each time the same action.

There are 4 methods in the Set LEDs script:

  • initialize
  • onLoad
  • onUnload
  • onInput_onSet

How does the Set LEDs script work¶

  1. When the behavior starts to play, the initialize method is executed first : GeneratedClass.__init__[self]. It is a function which resets the basic box parameters that are common to all the boxes in Choregraphe. After that, the box is a “module” running in NAOqi, on the robot. The box has also initialized all its “parameters” so they are now available in the script. This method is called once per behavior. You can initialize objects that you want to have during the whole behavior [proxies for instance].

    Warning

    You should never modify the first 3 lines of a script box as they are mandatory.

  2. onLoad method: This method is called when the box flow diagram is loading. It is necessarily called after the __init__ method of all the boxes of the current behavior. When a flow diagram is loading, this method is called on each box of current level before any IO can be stimulated.

  3. onUnload method: This method is called when the box flow diagram is unloading. When a flow diagram is unloading, this method is called on each box of current level. After the flow diagram unloading, boxes are disabled and cannot receive any event on their inputs. Note that the method usually stop everything running in the script, that is what you expect of the onStop input. That is why the latter calls onUnload by default.

  4. onInput_onSet method: This method is called when the onStart is stimulated. It calls ALLeds.fade[self.getParameter[“Leds name”], self.getParameter[“Intensity”], self.getParameter[“Duration”]] . This call to the ALLeds module orders the given group of LEDs to switch on, in a given time, to the given intensity. See that we never use hardcoded values, as we want the user to be able to change those values easily through Choregraphe interface. At the end of the onStart method, self.onStopped[] stimulates the onStopped output of the “Switch LEDs” box.

Modifying the script¶

Modify the “Set LEDs” box script in order to make NAO’s LEDs group flash five times before switching off.

To do so:

  1. Modify the script box as follows:

class MyClass[GeneratedClass]:
    def __init__[self]:
        GeneratedClass.__init__[self]
        self.max = 5

    def onLoad[self]:
        #~ puts code for box initialization here
        pass

    def onUnload[self]:
        self.i = self.max
        #~ puts code for box cleanup here
        pass

    def onInput_onSet[self]:
        self.i = 1
        while [self.i  Get parameter > leds name. It should write the following script:

> self.getParameter[“LEDs name”]

  • The script should look like this at the end:

  • class MyClass[GeneratedClass]:
        def __init__[self]:
            GeneratedClass.__init__[self]
            self.step = 0.01
    
        def onLoad[self]:
            #~ puts code for box initialization here
            self.isRunning = False
            pass
    
        def onUnload[self]:
            #~ puts code for box cleanup here
            pass
    
        def onInput_onStart[self]:
            #~ self.onStopped[] #~ activate output of the box
            if[self.isRunning]:
                return
    
            self.isRunning = True
    
            r = 0
            while [r + self.step  0 and self.isRunning]:
                r -= self.step
                ALLeds.setIntensity[self.getParameter["Leds name"], r]
                time.sleep[self.step]
    
            self.isRunning = False
            self.onStopped[]
    
        def onInput_onStop[self]:
            self.onStopped[] #~ it is recommended to call onUnload of this box in a onStop method, as the code written in onUnload is used to stop the box as well
            pass
    

    1. Now, you just have to on the wrench of the box to change the side of ear LEDs that will fade over time. As you can see, creating a box from scratch is not too complicated!

    Creating a box to retrieve right bumper value using ALMemory¶

    Cannot be tested on a simulated robot.

    This tutorial will show you how to retrieve an ALMemory value directly from your behavior.

    StepActionFurther help
    Create a Flow diagram box. How to create a Flow diagram box

    Link it to the beginning of the root behavior.

     

    Double-click the box to display its content and click the Add an event from ALMemory button.

     

    Select the RightBumperPressed event and click the OK button.

     

    Drag and drop the Flow Control > If box onto your diagram and link it to the RightBumper input.

    Note

    This box is used to filter the event, the event will be transmitted to the rest of the diagram only if the value is equal to one so the rest of the diagram is executed only when the right bumper is pressed and not released.

     

    Drag and drop the Audio > Voice > Say box onto the diagram and link the onStart inputs to the second output of the If box.

     
    Get into the say box and change the text in the Localized Text box into “This is my right bumper”.  
    Click the Play button to start the behavior.  

    Push the right bumper of the robot.

    Your NAO detects that its bumper were touched.

     

    You are now capable to retrieve an ALMemory value from any behavior.

    tutorial_almemory_bumper_behavior.crg

    Transmit a value from a behavior to another using ALMemory events¶

    Cannot be tested on a simulated robot.

    In this tutorial we will see how to use the ALMemory module to transmit your own values between two behaviors.

    For more information about the ALMemory module, see the ALMemory API.

    Create the two following behaviors and make them interact:

    • a sender behavior that will raise an event, for example the current value of NAO‘s mood,
    • a receiver behavior that will receive the event and will make NAO say the value associated to it.

    Writing a value in ALMemory¶

    Let’s start with the sender module:

    StepActionFurther help
    Create a new script box, called, for example ALMemory sender. How to create a Python box
    Add a parameter to the box. How to add/remove inputs, outputs, parameters in a box

    In the Add a new parameter menu, set:

    • the name to mood,
    • the parameter Type to String,
    • the Default value to I'm happy.

    Then click the Ok button twice.

     

    Double click the box to display the box script.

    You can see that the structure of the box were automatically generated.

     

    In the onLoad method, create a proxy to the ALMemory module.

    self.memoryProxy = ALProxy["ALMemory"]
    

     

    In the onStart method, raise an event called myParameterValue with the parameter: mood.

    The code of the box should look like that:

    class MyClass[GeneratedClass]:
        def __init__[self]:
        GeneratedClass.__init__[self]
    
        def onLoad[self]:
            self.memoryProxy = ALProxy["ALMemory"]
            pass
    
        def onUnload[self]:
            #~ puts code for box cleanup here
            pass
    
        def onInput_onStart[self]:
            self.memoryProxy.raiseEvent["myParameterValue",self.getParameter["mood"]]
            pass
    
        def onInput_onStop[self]:
            self.onUnload[]#~ it is recommended to call onUnload of this box in a onStop
    method, as the code written in onUnload is used to stop the box as well pass
    

     
    Close the script editor.  
    In your diagram, drag and drop the Flow Control > Time > Timer box.  
    Link it to the beginning of the root behavior.  

    Link the second output of the timer box to the onStart input of the box that raise the event.

    Your diagram should look like that:

    Note

    The timer box will trigger the raise event each second.

    Click the parameter button if you want to slow down, for example to 4 seconds.

     
    Choose File > Save project to save the first behavior.  

    tutorial_almemory_sender_behavior.crg

    Reading a value from ALMemory¶

    Let’s create the receiver behavior:

    StepAction

    Choose File > New profile to create a new behavior.

    Be sure that the previous one was correctly saved.

    Right click the Input border, and choose Add input from AlMemory.

    For further details, see: Flow diagram panel.

    In the event name, write the name you have defined as first attribute of the method raiseEvent, in our case it is myParameterValue.
    Click the OK button.

    We need now a Say text box, like the one inside the Say box.

    To do so:

    1. Drag and drop the Audio > Voice > Say box into the diagram.
    2. Double-click it to display the inner diagram.
    3. Copy the Say text box.
    4. Click the root label to come back to the behavior.
    5. Paste the Say text box.
    6. Delete the Say box.

    Link it to the input you have just created.

    Your diagram should look like that:

    Choose File > Save project to save the behavior.

    tutorial_almemory_receiver_behavior.crg

    Playing two interacting behaviors¶

    Now we will execute the sender and the receiver together. To do it, we will need to execute the receiver using the behavior manager.

    StepAction

    Display the Behavior manager.

    For further details, see: Displaying / hiding panels.

    In the Behavior manager panel, click on the Add current behavior button.

    The receiver behavior appears into the list of behavior that are on the robot.

    In the Behavior list, start the receiver behavior by clicking on its Play button.
    Open the sender behavior.

    Click the Play button to start the sender behavior.

    The sender raises the event according to Timer rhythm and the receiver retrieves the value.

    Click the Parameter button of the ALMemeory sender box to define another mood, for example, type: “I’m sad”.

    You can hear your NAO repeating its new mood at the rhythm of the Timer parameter.

    You are now capable to send values from a behavior to another using the AlMemory module.

    How do you make a box in python?

    To do so:.
    Drag and drop the Audio > Voice > Say box into the diagram..
    Double-click it to display the inner diagram..
    Copy the Say text box..
    Click the root label to come back to the behavior..
    Paste the Say text box..
    Delete the Say box..

    What is box in python?

    Overview. Box is designed to be an easy drop in transparently replacements for dictionaries, thanks to Python's duck typing capabilities, which adds dot notation access. Any sub dictionaries or ones set after initiation will be automatically converted to a Box object.

    How do you display messages in python?

    In python, the print statement is used to display text. In python with the print statement, you can use Single Quotes['] or Double Quotes["].

    Chủ Đề