npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

i2c-bus-promised

v1.1.3

Published

Bus and Device classes for i2c-bus, with promised functions.

Downloads

40

Readme

i2c-bus-promised CircleCI Greenkeeper badge

dependency status devDependency status

Bus and Device classes for i2c-bus, with promised functions.

Installation

npm install --save i2c-bus-promised

Usage

There's two main class exports in this library: Bus and Device.

Bus class wraps original i2c-bus methods and returns them promised, to make more comofrtable to work with them. The calls are queued to avoid blocking calls to the i2c bus. Device class abstracts an i2c device.The class is initialised with two arguments, bus and device address. Internally it will call the reciprocal methods on the bus object with it's address.

// @flow
/* eslint-disable no-console */
import { Bus, Device } from '../src';
import type { AddrType, WordType } from '../src/types';

const main = async () => {
  const bus = new Bus();
  await bus.open();

  // Print bus info
  await Promise.all([
    bus.i2cFuncs().then((funcs: {[string]: number}) => console.log(JSON.stringify(funcs, null, 2))),
    bus.scan().then((devices: Array<AddrType>) => console.log(JSON.stringify(devices, null, 2))),
  ]);

  // Initizalize devices
  const weatherSensor = new Device(bus, 0x77);
  const lightSensor = new Device(bus, 0x1d);

  await weatherSensor.writeByte(0x23, 0b1 | 0b100);
  await lightSensor.writeByte(0x25, 0x0f);

  return Promise.all([
    weatherSensor.readWord(0x50),
    weatherSensor.readWord(0x52),
    lightSensor.readWord(0x30),
  ])
    .then(([temperature, pressure, light]: Array<WordType>) => {
      console.log(`The temperature is ${temperature}`);
      console.log(`The pressure is ${pressure}`);
      console.log(`The light is ${light}`);
    });
};

main()
  .then(() => process.exit(0))
  .catch((error: Error) => {
    console.error(error.message);
    process.exit(1);
  });

File ./examples/usage.js

For more information, consult the API docs

Extending Device

However, you can also extend the Device to work with your i2c devices:

// @flow
/* eslint-disable no-console */
import { Bus, Device } from '../src';
import type { ByteType, WordType } from '../src/types';

class WeatherSensor extends Device {
  constructor(bus: Bus) {
    super(bus, 0x72);
  }

  writeConfig(config: ByteType) {
    return this.writeByte(0x24, config);
  }

  readTemperature() {
    return this.readWord(0x50);
  }

  readPressure() {
    return this.readWord(0x52);
  }
}

const main = async () => {
  const bus = new Bus();
  const weatherSensor = new WeatherSensor(bus);

  await bus.open();

  await weatherSensor.writeConfig(0b1 | 0b100);

  return Promise.all([
    weatherSensor.readTemperature(),
    weatherSensor.readPressure(),
  ])
    .then(([temperature, pressure]: Array<WordType>) => {
      console.log(`The temperature is ${temperature}°C`);
      console.log(`The pressure is ${pressure}Pa`);
    });
};

main()
  .then(() => process.exit(0))
  .catch((error: Error) => {
    console.error(error.message);
    process.exit(1);
  });

File ./examples/extendingDevice.js

For more information, consult the API docs

Tests

To run the tests just type:

yarn test

However it is recomended to run the e2e tests to ensure that everything works well.

BUS_NUMBER=1 yarn test:e2e

mock/createI2cBus

createI2cBus is a helper bus to be able to test your code using the library, and ensure that your code is doing what you want.

import { Bus } from '../src';

const BUS_NUMBER = 1;

jest.mock('i2c-bus', () => {
  const createI2cBus = require('../src/mock/createI2cBus').default; // eslint-disable-line global-require

  return createI2cBus({
    busNumber: 1,
    devices: {
      0x0f: Buffer.from(Array.from(Array(0xff).keys()).reverse()),
      0xf0: Buffer.from(Array.from(Array(0xff).keys())),
    },
    funcs: {
      read: 0x01,
      write: 0x02,
    },
  });
});

const setup = async (busNumber) => {
  const bus = new Bus(busNumber);

  await bus.open();

  return {
    bus,
    addToQueue: jest.spyOn(bus, 'addToQueue'),
    physicalBus: bus.bus.physicalBus,
  };
};

describe('Bus', () => {
  describe('i2cFuncs', () => {
    it('calls the i2cBus function through the promise queue', async () => {
      const { bus, addToQueue, physicalBus } = await setup(BUS_NUMBER);

      const result = await bus.i2cFuncs();

      expect(addToQueue).toHaveBeenCalledWith('i2cFuncsAsync');
      expect(result).toBe(physicalBus.funcs);
    });
  });
  describe('scan', () => {
    it('calls the i2cBus function through the promise queue', async () => {
      const { bus, addToQueue, physicalBus } = await setup(BUS_NUMBER);

      const result = await bus.scan();

      expect(addToQueue).toHaveBeenCalledWith('scanAsync');
      expect(result).toEqual(Object.keys(physicalBus.devices).map(addr => parseInt(addr, 10)));
    });
  });
});

File ./examples/tests.js

Be aware that you're working with a real device, the tests won't be much meaningful. And many things can fail IRL. It's always recommendable to write e2e tests to run in a real device.

Dependencies

  • bluebird: Full featured Promises/A+ implementation with exceptionally good performance
  • i2c-bus: I2C serial bus access with Node.js
  • p-queue: Promise queue with concurrency control

Documentation

Read the API

License

MIT © Alejandro Hernandez