Coder Social home page Coder Social logo

alejandroherr / i2c-bus-promised Goto Github PK

View Code? Open in Web Editor NEW
1.0 3.0 1.0 507 KB

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

License: MIT License

JavaScript 100.00%
i2c-bus i2c i2c-interface i2c-device i2c-sensors i2c-master i2c-display promise-functions

i2c-bus-promised's Introduction

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.

  • 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

i2c-bus-promised's People

Contributors

alejandroherr avatar greenkeeper[bot] avatar semantic-release-bot avatar

Stargazers

 avatar

Watchers

 avatar  avatar  avatar

Forkers

alanbueno

i2c-bus-promised's Issues

An in-range update of bluebird is breaking the build 🚨

The dependency bluebird was updated from 3.5.3 to 3.5.4.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

bluebird is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ci/circleci: checkout: Your tests failed on CircleCI (Details).

Release Notes for v3.5.4
  • Proper version check supporting VSCode(#1576)
Commits

The new version differs by 6 commits.

  • e0222e3 Release v3.5.4
  • 4b9fa33 missing --expose-gc flag (#1586)
  • 63b15da docs: improve and compare Promise.each and Promise.mapSeries (#1565)
  • 9dcefe2 .md syntax fix for coming-from-other-languages.md (#1584)
  • b97c0d2 added proper version check supporting VSCode (#1576)
  • 499cf8e Update jsdelivr url in docs (#1571)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.