-
Notifications
You must be signed in to change notification settings - Fork 4
/
gk-arduino.html
95 lines (77 loc) · 2.2 KB
/
gk-arduino.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
<element name="gk-arduino">
<template>
<div id="{{id}}" device="{{device}}"></div>
</template>
<script>
function getBtConnection(device) {
return bluetoothSerial;
}
function generateOnError(cause) {
return function(err) {
this.status = cause + ': ' + JSON.stringify(err);
this.$ele.trigger('error', [this.status]);
};
}
registerElement('gk-arduino', {
device: '',
status: 'disconnected',
_connection: null,
_pinMappings: {},
init: function() {
this.device = this.$ele.attr('device');
this._connection = getBtConnection(this.device);
this._connection.subscribe("\n\n", this._dispatch, generateOnError('Subscribe Failed').bind(this));
this.connect();
},
connect: function() {
this.status = 'connecting';
var self =this;
this._connection.connect(this.device, this._onconnect.bind(this) , this._ondisconnect.bind(this));
},
_onconnect: function() {
this.status = 'connected';
this.$ele.trigger('ready', [this.arduino()]);
},
disconnect: function() {
this.status = 'disconnecting';
this._connection.disconnect(this._ondisconnect);
},
_ondisconnect: function(cause) {
this.status = 'disconnected';
this.$ele.trigger('disconnect');
},
sendData: function(data) {
this._connection.write(data);
},
_dispatch: function(data) {
var lines = data.split('\n');
if (lines.length === 3) {
switch (lines[0]) {
case 'digitalRead':
var handler = this._pinMappings[lines[1]];
if (typeof handler === 'function') {
handler.apply(null, lines[2]);
}
break;
default:
break;
}
}
},
arduino: function() {
var self = this;
return {
pinMode: function(pin, mode) {
self.sendData('pinMode\n' + pin + '\n' + mode + '\n\n');
},
digitalWrite: function(pin, value) {
self.sendData('digitalWrite\n' + pin + '\n' + value + '\n\n');
},
digitalRead: function(pin, callback) {
self._pinMappings[pin] = callback;
}
};
}
});
</script>
</element>