Giter Site home page Giter Site logo

reactual / async-i2c-bus Goto Github PK

View Code? Open in Web Editor NEW

This project forked from alejandroherr/async-i2c-bus

0.0 3.0 0.0 840 KB

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

Home Page: https://async-i2c-bus.alejandroherr.io

License: MIT License

JavaScript 1.80% TypeScript 98.20%

async-i2c-bus's Introduction

async-i2c-bus

Npm Package Dependencies Dev Dependencies CircleCI semantic-release MIT License

Promised Bus and Device factories for i2c-bus.

This package replaces i2c-bus-promised

Installation

Choose your flavour, yarn:

yarn add async-i2c-bus

or npm:

npm i -P async-i2c-bus

And you're ready to go.

Requirements

The package requires node v8.10.x or higher. If you need a compatibility with lower versions of node, you can build it. To do so clone the repo in your workspace, and modify the target options in the tsconfig.json, e.g:

{
  "compilerOptions": {
    "target": "es5", // <-- Line changed
    "outDir": "dist/main",
    "rootDir": "src",
    // ..
  }
}

And build the module with yarn build or npm run build.

Usage

The package exports the Bus factory to create a BusInterface. The BusInterface is an object with the same methods available in the original i2c-bus but promised. The signature of the factory is the following:

const Bus = ({ busNumber = 1, openBus = openI2cBus } = {}): BusInterface
  • busNumber is the i2c bus number, and defaults to 1. Unless your devices has more than one bus, it will suit you.
  • openBus is the function to open the bus. It defaults to i2c.openBus, but it would accept any function with the same signature. You shouldn't pass this value, except if you're in a testing environment.

The package also exports the Device factory to create a DeviceInterface. This is a helper method to call the i2cBus methods with the address of your device. It has the following signature:

const Device = ({ address, bus }: { address: number; bus: BusInterface }): DeviceInterface

You don't need to use a DeviceInterface in order to work with this library, but it helps.

For more details, check the full auto-generated documentation.

Example

const WEATHER_SENSOR_ADDRESS = 0x77;

const main = async () => {
  const bus = Bus();

  await bus.open();

  const devices = await bus.scan();

  console.log(`Connected devices ${devices}`);

  const weatherSensor = Device({ address: WEATHER_SENSOR_ADDRESS, bus });

  // Configure Weather Sensor (BMP280)
  await weatherSensor.writeByte(0xf4, 0b00100101);
  await weatherSensor.writeByte(0xf5, 0b00100100);

  // Read temperature
  const temperatureBuffer = Buffer.alloc(3);
  await weatherSensor.readI2cBlock(0xfa, 3, temperatureBuffer);
  const temperature = temperatureBuffer.readUIntBE(0, 3) >>> 4;

  console.log(`Temperature: ${temperature}`);
};

Example extending device

Also you can extend your device to implement specific methods. Take the previous case:

const WeatherSensor = ({ bus }) => ({
  ...Device({ address: 0x77, bus }),
  async init() {
    await this.writeByte(0xf4, 0b00100101);
    await this.writeByte(0xf5, 0b00100100);

    return this;
  },
  async readTemperature() {
    const buffer = Buffer.alloc(3);

    await this.readI2cBlock(0xfa, 3, buffer);

    return buffer.readUIntBE(0, 3) >>> 4;
  },
});

const main = async () => {
  const bus = Bus();

  await bus.open();

  const weatherSensor = await WeatherSensor({ bus }).init();
  const temperature = await weatherSensor.readTemperature();

  console.log(`Temperature: ${temperature}`);
};

Testing

Testing i2c code can be expensive and slow. It may take some time to deploy and run your e2e tests/code in a low powered device. For that, you can use the createI2cBusMock function and write some unit tests. Although you shouldn't relay too much on the values read and written (it works as if the i2c bus is just a memory), it can help you to test that the right functions are being invoked.

import { Bus, Device } from '../dist/main';

jest.mock('i2c-bus', () => {
  const createI2cBusMock = require('../dist/main/lib/createI2cBusMock').default; // eslint-disable-line global-require

  return {
    open: createI2cBusMock({
      devices: {
        0xab: Buffer.allocUnsafe(0xff),
      },
    }),
  };
});

describe('Device', () => {
  it('should write the right command', async () => {
    const busNumber = 1;
    const bus = Bus({ busNumber });
    const address = 0xab;
    const device = Device({ address, bus });

    await bus.open();

    const spyOnWriteByte = jest.spyOn(bus, 'writeByte');
    await device.writeByte(0x0f, 0xff);
    expect(spyOnWriteByte).toHaveBeenCalledWith(address, 0x0f, 0xff);
  });
});

async-i2c-bus's People

Contributors

alejandroherr avatar renovate-bot avatar

Watchers

 avatar  avatar  avatar

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.