Code crushes when using unexport() (NodeJS)

Hi,

I’m using the code shown below to trigger a relay for a second. Because the relay is shared by various programs, it’s imperative that the gpio pin is released from this code.

However, the code crushes when unexport() function is reached. Without it, the code works fine.

Where do I err?

TIA
(BTW, I’m new to nodejs)

#!/usr/bin/env node

var Gpio = require('onoff').Gpio;
var Blynk = require('blynk-library');
var AUTH = '****';

var blynk = new Blynk.Blynk(AUTH,
    options = {
        connector: new Blynk.TcpClient()
    });

//set physical pins
const relayBlinds = new Gpio(21, 'out');

//set virtual pins
var btnBlinds = new blynk.VirtualPin(1);

const allRelaysOff = () => {
    relayBlinds.writeSync(1);
}
//turn off all relays @ start
allRelaysOff();

btnBlinds.on('write', function(param) {
    if (param) {
        relay_on(relayBlinds);
        setTimeout(function () {
          relay_off(relayBlinds);
        setTimeout(function () {
          relayBlinds.unexport(); //<-- fails
        }, 1000);
      }, 1000);
     }
});

function relay_on(gpio) {
  gpio.writeSync(1);
}

function relay_off(gpio) {
  gpio.writeSync(0);
}

// Handle Ctrl+C exit cleanly
process.on('SIGINT', () => {
    allRelaysOff();
    process.exit();
})

Hi,
from “onoff” documentation

unexport()

Reverse the effect of exporting the GPIO to userspace. A Gpio object should not be used after invoking its unexport method.

once the “unexport” function is called, you can no longer use the gpio,
try changing the code with this one

#!/usr/bin/env node

var Gpio = require('onoff').Gpio;
var Blynk = require('blynk-library');
var AUTH = '****';

var blynk = new Blynk.Blynk(AUTH,
    options = {
        connector: new Blynk.TcpClient()
    });

const relayPin = 21;

//set virtual pins
var btnBlinds = new blynk.VirtualPin(1);

const allRelaysOff = () => {
    const relayBlinds = new Gpio(relayPin, 'out');
    relayBlinds.writeSync(1);
    relayBlinds.unexport();
}
//turn off all relays @ start
allRelaysOff();

btnBlinds.on('write', function(param) {
    if (param) {
        const relayBlinds = new Gpio(relayPin, 'out');
        relay_on(relayBlinds);
        setTimeout(function () {
          relay_off(relayBlinds);
        setTimeout(function () {
          relayBlinds.unexport(); //<-- fails
        }, 1000);
      }, 1000);
     }
});

function relay_on(gpio) {
  gpio.writeSync(1);
}

function relay_off(gpio) {
  gpio.writeSync(0);
}

// Handle Ctrl+C exit cleanly
process.on('SIGINT', () => {
    allRelaysOff();
    process.exit();
})

let me know if it works!!

regards

Thanks @gab.lau. As I understand it, the gpio pin needs to be re-initialized when unexported.

Ok, I test it and it doesn’t crush.

Because I’m using more than 10 relays, isn’t there a better way of doing this like a try/catch and then use unexported() in finally. I know nodejs has similar functions but I’m not familiar with them.