-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathweblight-card.html
104 lines (86 loc) · 2.83 KB
/
weblight-card.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<link rel="import" href="../bower_components/polymer/polymer-element.html">
<link rel="import" href="../bower_components/paper-button/paper-button.html">
<link rel="import" href="../bower_components/paper-card/paper-card.html">
<dom-module id="weblight-card">
<template>
<style include="shared-styles">
:host {
display: block;
padding: 10px;
}
</style>
<paper-card heading="{{device.serialNumber}}">
<div class="card-content">
Pick a color: <input id="lightPicker" type="color" on-change="lightCustom">
</div>
<div class="card-actions">
<paper-button on-tap="lightRed">Red</paper-button>
<paper-button on-tap="lightGreen">Green</paper-button>
<paper-button on-tap="lightBlue">Blue</paper-button>
<paper-button on-tap="lightWhite">White</paper-button>
<paper-button on-tap="lightOff">Off</paper-button>
</div>
</paper-card>
</template>
<script>
function componentToHex(c) {
let hex = c.toString(16);
return hex.length == 1 ? '0' + hex : hex;
}
function rgbToHex(r, g, b) {
return '#' + componentToHex(r) + componentToHex(g) + componentToHex(b);
}
function hexToRgb(hex) {
let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
} : null;
}
class WebLightCard extends Polymer.Element {
static get is() { return 'weblight-card'; }
async setDeviceColor(r, g, b) {
if (this.device.opened) {
let payload;
if (this.device.usbVersionMajor === 2) {
payload = new Uint8Array([0xFF, r, g, b])
} else if (this.device.usbVersionMajor === 1) {
payload = new Uint8Array([r, g, b]);
}
if (payload == null) {
throw new Error(`Unknown device firmware version ${this.device.usbVersionMajor}`);
}
await this.device.controlTransferOut({
requestType: 'vendor',
recipient: 'device',
request: 1,
value: 0,
index: 0,
}, payload);
this.$.lightPicker.value = rgbToHex(r, g, b);
}
}
lightRed() {
this.setDeviceColor(64, 0, 0);
}
lightGreen() {
this.setDeviceColor(0, 64, 0);
}
lightBlue() {
this.setDeviceColor(0, 0, 64);
}
lightWhite() {
this.setDeviceColor(255, 255, 255);
}
lightOff() {
this.setDeviceColor(0, 0, 0);
}
lightCustom() {
let color = hexToRgb(this.$.lightPicker.value);
this.setDeviceColor(color.r, color.g, color.b);
}
}
window.customElements.define(WebLightCard.is, WebLightCard);
</script>
</dom-module>