8月 312015
 

有个项目需要通过网页读取串口数据,原来以为会很麻烦,用JavaApplet什么的,最后发现用Chrome的App就可以实现调用。
虽然需要花点时间自己写个Chrome App,但是还是比其他解决方案方便快捷许多。

Google提供了一个很健全的Sample文件,当然,你必须得翻墙才能下载。(我上传了一份到百度网盘:chrome-app-samples-master

Chrome App是什么?

Chrome App从用户角度来说,是独立于Chrome浏览器的,Google甚至允许你直接把这个App的图标放到桌面。当用户打开一个ChromeApp,仿佛就是打开了一个应用程序,完全不会意识到它是基于Chrome运行的。官方描述如下:

What Are Packaged Apps? – Google Chrome | developer.chrome.com/ap

Packaged apps deliver an experience as capable as a native app, but as safe as a web page. Just like web apps, packaged apps are written in HTML5, JavaScript, and CSS. But packaged apps look and behave like native apps, and they have native-like capabilities that are much more powerful than those available to web apps.

建立Chrome App

网上教程还是蛮多的,我就不详述了,最简单的方法就是把sample里的helloworld例子复制出来修改一下。
在这里需要注意,由于我需要访问串口,需要在manifest.json文件中增加权限:”permissions”: [“serial”]

访问串口

在Sample里有关于Serial访问的代码,这里需要把serial.js复制出来引用。adk.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
const COMPORT='COM3';//实际串口名称

//串口设备连接状态
var connection = null;
//初始化串口
var init = function() {
if (!serial_lib){
    throw "You must include serial.js before";  
}
}; 
//打开串口
var openDevice = function() {
    serial_lib.openDevice(COMPORT, onOpen);
};
var onOpen = function(newConnection) {
    if (newConnection === null) {
        console.log("Failed to open device.");
        return;
    }
    connection = newConnection;
    connection.onReceive.addListener(onReceive);
    connection.onError.addListener(onError);
    connection.onClose.addListener(onClose);
    console.log("Device connected.");
};
//发送消息
var sendSerial = function(message) {
    if (connection === null) {
        return;
    }
    if (!message) {
        console.log("Nothing to send!");
        return;
    }
    if (message.charAt(message.length - 1) !== '\n') {
        message += "\n";
    }
    connection.send(message);
};
//接收消息
var onReceive = function(data) {
    //处理接收到的消息
};
var onError = function(errorInfo) {
    if (errorInfo.error !== 'timeout') {
        console.log("Fatal error encounted. Dropping connection.");
        closeDevice();
    }
};
//关闭串口
var closeDevice = function() {
    if (connection !== null) {
        connection.close();
    }
};
var onClose = function(result) {
    connection = null;
}

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)