-
Notifications
You must be signed in to change notification settings - Fork 0
/
uart.js
84 lines (69 loc) · 1.47 KB
/
uart.js
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
/* example of JS module importing a C module */
import * as net from "socket.so";
import * as utils from "../res/utils.js";
var uartFd = -1;
function read_uart(sock, bytes) {
var data = new ArrayBuffer(bytes+1);
var total = 0;
try
{
total = os.read(sock, data,0,bytes);
}
catch (e)
{
console.log("read error: " + e);
return;
}
if (total === bytes)
{
console.log("->recv ok: " + data[0]);
}
else if (total == 0)
{
console.log("read but closed: " + bytes);
fault();
}
else{
console.log("read fail: " + total);
return;
}
}
function uart_read_cb(sock) {
console.log("read cb called");
read_uart(sock, 1);
}
function fault() {
//close();
if (errorCb)
{
errorCb('disconnect');
}
}
function open()
{
var rv;
uartFd = os.open("/dev/ttyUSB0", os.O_RDWR);
if (uartFd < 0)
{
console.log("Open UART FAILED");
return;
}
console.log("open result: " + uartFd);
rv = net.setUart(uartFd,net.B115200,8,'N',1);
console.log("setUart result: " + rv);
rv = net.nonblock(uartFd);
console.log("nonblock result: " + rv);
os.setReadHandler(uartFd, uart_read_cb);
read_uart(uartFd,255);
//var getKeyCmd = utils.encodeUTF8("AT\r\n");
var getKeyCmd = new Uint8Array([0x02, 0xc0, 0x01]);
var total = os.write(uartFd, getKeyCmd.buffer,0,getKeyCmd.length);
if (total != getKeyCmd.length)
{
console.log("write uart failed: " + total);
return;
}
console.log("UART Write:" + getKeyCmd.length);
}
console.log("OS Platform: " + os.platform);
open();