dottedquad
dottedquad

Reputation: 1391

Uncaught TypeError: Cannot read property 'open' of undefined

I created a function called Sensors and instantiated the serialport object within it. I also created a prototype find that in theory should access the port object to open, write and bind on.

I'm receiving error:

Uncaught TypeError: Cannot read property 'open' of undefined

I'm not sure why....

Code:

  <script>
    var sp = require('serialport');
    var comports = [];

    //Object to connect to a specific comport and send the 'i' command
    function Sensors(com) {
      this.find();
      this.address = com;
      this.port = new sp(com, {
        baudrate: 9600,
        autoOpen: false
      });
    }
    Sensors.prototype.find = function() {
      console.log("ran");
      this.port.open(function(err) {
        if (err) {
          return console.log('Error opening port: ', err.message);
        }

        this.port.write('i' + String.fromCharCode(13), function(err) {
          if (err) {
            return console.log('Error on write: ', err.message);
          }
          console.log('message written');
        });

        this.port.on('data', function(data) {
          var sensorData = data;
          var splitString = sensorData.toString().split(',');
          console.log(splitString[1]);
          if (sensorData.length > 0) {
            if (splitString[1] == 'pH' || splitString[1] == 'EC' || splitString[1] == 'RTD') {
              console.log(splitString[1]);
            }
            this.port.close(function(err) {
              console.log('port closed', err);
            });
          }
        });
      });
    };

    function findSensors() {
      sp.list(function(err, ports) {
        for (i = 0; i < ports.length; i++) {
          var sensor = new Sensors(ports[i].comName);
          sensor.find();
        }

      });
    }
    //startup function to find comports and find the sensor(s)
    function startUp() {
      findSensors();
    }
  </script>

Upvotes: 0

Views: 5844

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370729

In the constructor, you're calling this.find(); before you've assigned to this.port, so the line this.port.open inside find results in an error. Change it so that this.find runs after the port property has been populated.

function Sensors(com) {
  this.address = com;
  this.port = new sp(com, {
    baudrate: 9600,
    autoOpen: false
  });
  this.find();
}

Upvotes: 1

Related Questions