fivdi / i2c-bus

I2C serial bus access with Node.js
MIT License
348 stars 57 forks source link

Question - Thread Safety/Mutexing - Are the methods on an I2CBus thread safe on a RaspberryPi in Node.JS? #121

Closed lynniemagoo closed 9 months ago

lynniemagoo commented 9 months ago

I know behind the scenes, the module uses ioctl to access the bus. Are the reads/writes serialized and are they mutexed (thread safe)?

Example 1 - Common Bus Number, 2 Bus instances const i2c = require('i2c-bus'); /./ create 2 distinct bus objects. const bus1 = i2c.openSync(1); const bus2 = i2c.openSync(1);

// Create 2 different instances of an MCP class, one for PortA of the chip and one for PortB of the chip. // The MCP23017 uses address 0x20 but we pass in different busses.

const ioChip1 = new MPC23017PortA(bus1, 0x20); cosnt ioChip2 = new MPC23017PortB(bus2, 0x20);

Is it possible to read/write to I2C in both chip implementations safely using either the callback or promisifiedBus?

Or, is the recommendation to use an I2C operation queue such that I would serialize requests?

Example 2 - Common Bus Number, 1 Bus instance const i2c = require('i2c-bus'); /./ create 1 distinct bus object. const bus1 = i2c.openSync(1);

// Create 2 different instances of an MCP class, one for PortA of the chip and one for PortB of the chip. // The MCP23017 uses address 0x20 but we pass in different busses.

const ioChip1 = new MPC23017PortA(bus1, 0x20); cosnt ioChip2 = new MPC23017PortB(bus1, 0x20);

Same questions as for Example 1

fivdi commented 9 months ago

The calls to ioctl are serialized by the operating system and each call to ioctl can be regarded as a transaction that will not be interrupted by another call to ioctl.

Is it possible to read/write to I2C in both chip implementations safely using either the callback or promisifiedBus?

Yes.

Or, is the recommendation to use an I2C operation queue such that I would serialize requests?

This is not recommended and not necessary. In fact, it will not work if two different Node.js processes are using the same I2C bus and potentially even the same I2C device concurrently.

lynniemagoo commented 9 months ago

Thanks so much for the clarification.