openi2c
Version:
This library is a set of cross platform drivers for common I2C devices.
84 lines (83 loc) • 3.23 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseDevice = void 0;
class BaseDevice {
constructor() {
// private i2c: any; // Specify the correct type for i2c
this.debug = console;
}
readByte(adrs) {
return __awaiter(this, void 0, void 0, function* () {
return yield this.bus.readByte(this.address, adrs);
});
}
readBytes(adrs, length) {
return __awaiter(this, void 0, void 0, function* () {
const buf = Buffer.alloc(length);
yield this.bus.readI2cBlock(this.address, adrs, length, buf);
return buf;
});
}
writeByte(adrs, value) {
return __awaiter(this, void 0, void 0, function* () {
yield this.bus.writeByte(this.address, adrs, value);
});
}
readBit(adrs, bit) {
return __awaiter(this, void 0, void 0, function* () {
var buf = yield this.readByte(adrs);
return (buf >> bit) & 1;
});
}
;
bitMask(bit, length) {
return ((1 << length) - 1) << bit;
}
;
vectorToYesNo(v) {
var str = '(';
str += v[0] ? 'No, ' : 'Yes, ';
str += v[1] ? 'No, ' : 'Yes, ';
str += v[2] ? 'No' : 'Yes';
str += ')';
return str;
}
/**
* Write a sequence of bits. Note, this will do a read to get the existing value, then a write.
* @param {number} adrs The address of the byte to write.
* @param {number} bit The nth bit to start at.
* @param {number} length The number of bits to change.
* @param {number} value The values to change.
*/
writeBits(adrs, bit, length, value) {
return __awaiter(this, void 0, void 0, function* () {
const oldValue = yield this.readByte(adrs);
const mask = this.bitMask(bit, length);
const newValue = oldValue ^ ((oldValue ^ (value << bit)) & mask);
yield this.writeByte(adrs, newValue);
});
}
;
/**
* Write one bit. Note, this will do a read to get the existing value, then a write.
* @param {number} adrs The address of the byte to write.
* @param {number} bit The nth bit.
* @param {number} value The new value, 1 or 0.
*/
writeBit(adrs, bit, value) {
return __awaiter(this, void 0, void 0, function* () {
yield this.writeBits(adrs, bit, 1, value);
});
}
;
}
exports.BaseDevice = BaseDevice;