Problems with uart rx handler

I have included a handler for RX data as shown in the code below.

`//
// dj2 Interface Object - Simple abstraction of the interface connected to the imp
//
class dj2_if {

// Hardware interface
serPort = null;
nCTSo = null;
nRTSi = null;

constructor(sPort, ctsIO, rtsIO) {
    // Configure the imp's hardware
    serPort = sPort;
    serPort.configure(57600, 8, PARITY_NONE, 1, NO_CTSRTS, _HandleRxChar);

    // other constructor code
 }

// Internal handler for incoming serial data
function _HandleRxChar() {
    local ch = serPort.read();
    while (ch != -1) {
        server.log("handleRx for " + ch);
        _ProcessRxChar(ch);
        
        // See if there is any additional data
        ch = serPort.read();
    }
}

}

dj2if <- dj2_if(hardware.uart57, hardware.pin1, hardware.pin2);
`

I get the following error when a character is received.

Sat May 11 2013 12:33:24 GMT-0600 (MDT): Device booting Sat May 11 2013 12:33:24 GMT-0600 (MDT): Device configured to be "dj2_serial" Sat May 11 2013 12:33:24 GMT-0600 (MDT): ERROR: the index 'serPort' does not exist Sat May 11 2013 12:33:24 GMT-0600 (MDT): ERROR: at _HandleRxChar:181

It is like the variable serPort is not defined in the handler in the instantiated object. Am I doing something wrong? If so, how do I fix this? Other methods in the object use serPort successfully to write to the serial port (serPort.write(ch)). These methods are called directly by the main code and are not callbacks.

I wondered if the callback was attempting to access a global routine so I did two things.

  1. I added “this.” to the callback in the object. It did not change the result.

serPort.configure(57600, 8, PARITY_NONE, 1, NO_CTSRTS, this._HandleRxChar);

  1. I added a global routine before the definition of the object and changed the callback name in the configure to point to it. This worked.

dj2if<-null; function foobar() { dj2if._HandleRxChar(); } class dj2_if { constructor(sPort, ctsIO, rtsIO) { // Configure the imp's hardware serPort = sPort; serPort.configure(57600, 8, PARITY_NONE, 1, NO_CTSRTS, foobar); } } dj2if <- dj2_if(hardware.uart57, hardware.pin1, hardware.pin2);

This makes sense. However I would think that there should be some way to pass in the object’s method to the callback in the serial port configure call. I am wondering if:

a) There is a way to pass an object’s own method to the callback
b) The language won’t allow this

You need to “bind” the _HandleRxChar method to the class instance required – otherwise, when it was called, how would it know which dj2_if it was a member of? In Squirrel turning a class method into a standalone function is done with bindenv:
serPort.configure(...,_HandleRxChar.bindenv(this));

Peter

Thank you Peter. I figured out it had to be something like that. Another day, another thing to learn about this strange little language. :slight_smile: