生活随笔
收集整理的這篇文章主要介紹了
Chrome API操作串口
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
NWJS使用chrome api連接/接收/發送串口數據
參考http://www.oschina.net/code/snippet_1379244_55248,本文對其代碼進行注釋和發表一些自己的見解
1.本機可以使用?串口虛擬串口程序(vspd?自行下載)
2.所需要環境node.js??并且安裝模塊:iconv-lite
3.nwjs所用的環境為nwjs13.*?sdk版本
<script type="text/javascript">var onGetDevices = function(ports) {//遍歷獲取串口名稱,一般只有一個串口判斷if(ports.length==1){port=ports[0].path}即可for (var i = 0; i < ports.length; i++) {console.log(ports[i].path);}}chrome.serial.getDevices(onGetDevices);//獲取串口設備名,并將串口設備信息當參數傳入指定的onGetDevices函數var iconv = require('iconv-lite');//若傳輸英文字符串則無需轉碼,此處注釋掉function convertArrayBufferToString(buf) {//將串口接收到的buffer數據轉化成字符串var bufView = new Uint8Array(buf);var encodedString = String.fromCharCode.apply(null, bufView);//nodejs轉編碼(不可直接轉utf-8否則亂碼)return iconv.decode(encodedString, 'gbk');//若傳輸英文字符串則無需轉碼,此處直接返回
}var onReceiveCallback = function(info) {//串口數據接收函數console.log('received', convertArrayBufferToString(info.data));};//convertStringToArrayBuffer('hello')var convertStringToArrayBuffer = function(str) {//將字符串轉化成buffer用于串口數據發送var buf = new ArrayBuffer(str.length);var bufView = new Uint8Array(buf);for (var i = 0; i < str.length; i++) {bufView[i] = str.charCodeAt(i);}return buf;};var onConnect = function(connectionInfo) {console.log(chrome.runtime.lastError, connectionInfo);//輸出連接信息chrome.serial.onReceive.addListener(onReceiveCallback);//指定串口數據接收函數var connectionId = connectionInfo.connectionId;//輸出串口連接id,用于區別多串口var buffer = new ArrayBuffer(1);var dataView = new DataView(buffer);dataView.setInt8(0, 0xaa);//構造buffer數據chrome.serial.send(connectionId, buffer, function() {//指定串口連接id,直接發送buffer數據,也可將字符串轉化成buffer再發送convertStringToArrayBuffer("hello")chrome.serial.update(connectionId, {//改變波特率等參數bitrate: 9600}, function(result) {console.log(chrome.runtime.lastError, result);//改變執行結果chrome.serial.send(connectionId, buffer, console.log.bind(console));//發送數據});});};chrome.serial.connect('COM3', {//以波特率9600,連接串口3,指定連接函數onConnectbitrate: 9600}, onConnect);</script>
package.json文件內容://因為使用的是原生chrome api,個人認為不需要nodejs串口配置
{"name": "serialportDemo","main": "index.html","version": "0.0.1","nodejs": true,"width": 100,"height": 200,"window": {"title": "windowdemo","toolbar": true,"width": 800,"height": 600,"resizable": true,"show_in_taskbar": true,"frame": true,"kiosk": false},
"permissions": ["serial"
],"webkit": {"plugin": true}
}
轉載于:https://www.cnblogs.com/leytton/p/8253313.html
總結
以上是生活随笔為你收集整理的Chrome API操作串口的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。