UNPKG

ws2801-connect

Version:

A javascript class to control a WS2801 led stripe

3 lines (2 loc) 1.62 kB
/*! ws2801-connect 12-04-2018 */ var colorLib=require("color");class WS2801{constructor(t){this.count=t.count,this.spiWrite="function"==typeof t.spiWrite?t.spiWrite:function(){},Array.isArray(t.rgbIndex)&&3===t.rgbIndex.length?(WS2801.assert(t.rgbIndex.every(t=>t>=0&&t<=2),"Wrong index supplied"),this.rgbIndex=t.rgbIndex):this.rgbIndex=[0,1,2],this.rgbMap=Array(3),this.rgbIndex.forEach(function(t,r){this.rgbMap[t]=r},this)}static assert(t,r){if(!t)throw r}set count(t){WS2801.assert(t>0,"Only natural numbers are valid"),this.rgbLights=Array(3*t),this.clear()}get count(){return this.rgbLights.length/3}static rgbFrom(t){switch(t.length){case 1:return t[0]instanceof Array?WS2801.rgbFrom(t[0]):colorLib(t[0]).array();case 3:return t;default:WS2801.assert(!1,"Wrong number of arguments")}}setLight(t,...r){WS2801.assert(t>=0&&t<this.count,"Given Number is out of range");let s,i,e;return[s,i,e]=WS2801.rgbFrom(r),this.rgbLights[3*t+this.rgbIndex[0]]=255&s,this.rgbLights[3*t+this.rgbIndex[1]]=255&i,this.rgbLights[3*t+this.rgbIndex[2]]=255&e,this}setAll(t){return WS2801.assert(t instanceof Array,"Parameter must be an array"),this.clear(),t.forEach(function(t,r){r<this.count&&this.setLight(r,t)},this),this}*[Symbol.iterator](){for(let t=0,r=this.count;t<r;++t)yield[this.rgbLights[3*t+this.rgbIndex[0]],this.rgbLights[3*t+this.rgbIndex[1]],this.rgbLights[3*t+this.rgbIndex[2]]]}show(){return this.spiWrite(this.rgbLights),this}clear(){return this.rgbLights.fill(0),this}fill(...t){let r=WS2801.rgbFrom(t);return this.rgbLights.forEach(function(t,s,i){i[s]=r[this.rgbMap[s%3]]},this),this}}module.exports=WS2801;