Search code examples
pythongnuradio

Can I hook a variable to a custom non-processing block?


I'm implementing a custom block for GRC which sends a command via serial to hardware. I need it to send the command each time a variable (e.g. a QT GUI range) changes. I'm quite new to GNU radio, so I don't know what would be the best approach. Do I need to derive my class from one of GNU radio's block classes (e.g. sync block) or should I create a custom block with a custom class and hook it up some other way into the system? How can I set it up so that the variable that changes calls my block's serial send function?

MESSAGE_STR = 'SET '


class SerialBlock:
    def __init__(self):
        self.ser = detect_device()

    def send_var(self, var):
        if self.ser is None:
            raise RuntimeError("No device found")

        bytes_to_write = bytearray(f"{MESSAGE_STR}{int(var)}", 'utf8')
        self.ser.write(bytes_to_write)

This is the class. If I want a change in the slider to call send_var() with the new value, how is the best course of action?


Solution

  • When you define a block's structure for GRC (in a .xml (3.7) or .block.yml (3.8) file), you specify "callbacks" which are code that should be inserted in the GRC-generated code to be called whenever a parameter (of your block) which depends on a variable (that the GRC user created) changes, which is usually calling a "setter method". You just need to write such a callback.

    I haven't personally written such a file for GR 3.8, but from examining examples, it looks like your .block.yml should resemble:

    templates:
        [...other things in the templates section...]
        callbacks:
        - send_var(${var})
    

    In 3.7 it would be the XML

    <callback>send_var($var)</callback>
    

    I wrote var to match your code, but it is actually the name of the parameter of your block, not the name of the variable. Your block definition doesn't know and doesn't need to know whether a parameter is a constant, a variable, or an expression containing a variable.