顯示具有 js 標籤的文章。 顯示所有文章
顯示具有 js 標籤的文章。 顯示所有文章

2021年11月4日

MQTT記事

 

參考:https://ithelp.ithome.com.tw/articles/10226629

1.安裝MQTT server 

sudo apt install mosquitto
2.安裝MQTT client
sudo apt install mosquitto-clients 
 
mosquitto_sub : 訂閱
mosquitto_pub : 發布
-d : debug 模式 => debug
-t : 訂閱的主題 => topic
-h : Broker 的 IP => host
-m : 發送的內容 => message
-v : 顯示主題名稱 => verbosely
 

終端機-1 (Subscribe)訂閱

mosquitto_sub -d -t Try/MQTT 
或
mosquitto_sub -d -h 54.xx.xx.xx -t Try/MQTT

終端機-2 (Publish)發佈

mosquitto_pub -d -t Try/MQTT -m "Try Message"
mosquitto_pub -d -h 54.xx.xx.xx -t Try/MQTT -m "Try Message"

使用帳密

mosquitto_passwd -c <passwordfile> <username>
指定密碼檔案 
sudo mosquitto_passwd -c /etc/mosquitto/passwd try   
這樣會覆蓋掉原來的passwd檔。先編一個帳密碼
vim usr.pwd
內容如下
user:123456
student:123
使用指令轉成加密檔 
mosquitto_passwd  -U usr.pwd 
sudo mv  usr.pwd /etc/mosquitto/
 

設定ACL(Access Control List)

sudo vi /etc/mosquitto/acl 
內容如下 
# 用戶 try 能夠讀寫 Try/MQTT這個主題
#user try 
#topic readwrite Try/MQTT
(設定後失敗,先註解掉) 

在mosquitto.conf 參數檔案,開啟模式

打開 mosquitto.conf 參數檔案
設定檔位置在 /etc/mosquitto/mosquitto.conf

增加

listener 1883
protocol mqtt
listener 8081 127.0.0.1
protocol websockets
allow_anonymous true
這樣js 才能用ws://127.0.0.1:8081連線 
 
password_file /etc/mosquitto/passwd
per_listener_setting true
acl_file /etc/mosquitto/acl
 
per_listener_setting參數設成true,代表個別設置每個偵聽器物件的安全性: 
allow_anonymous 允許匿名存取,設成false 代表需使用者名稱。
password_file 帳號密碼的檔案
acl_file 對於使用者權限的設置檔案
 
重啟服務
sudo service mosquitto stop
sudo service mosquitto start 
訂閱 
mosquitto_sub -v -d -t Try/MQTT -u "try" -P "xxxx"  
mosquitto_sub -d -t Try/MQTT 
mosquitto_sub -d -h 54.xx.xx.xx -t Try/MQTT
發佈 
mosquitto_pub -d -t Try/MQTT -m "Try Message"  
mosquitto_pub -d -h 54.xx.xx.xx -t Try/MQTT -m "Try Message"
  

 

 測試了一下一個網站還不錯:

http://mqttgo.io/

使用osep離線版線線網址為:

ws://MQTTGO.io:8000/mqtt


 

 

2021年8月7日

web serial api記事

不錯的文章 

https://wicg.github.io/serial/

https://github.com/svendahlstrand/web-serial-api

https://github.com/rafaelaroca/web-serial-terminal

 https://ithelp.ithome.com.tw/articles/10161189

 連線

port = await navigator.serial.requestPort({});
await port.open({ baudRate: 9600 });

寫入資料

const encoder = new TextEncoder();
const writer = port.writable.getWriter();
await writer.write(encoder.encode(value));
writer.releaseLock();

讀出資料

reader = port.readable.getReader();
let value = await reader.read();
let uint8array = new TextEncoder().encode("¢");
let string = new TextDecoder().decode(value.value);
string = string.split('\r\n');
analog_inputs[pin] = string[0];
//console.log('analog_inputs[pin]=',analog_inputs[pin]);
reader.releaseLock();

 

scratch-gui無法用async 需要npm  install  babel-polyfill

//async await estea
require('babel-polyfill');


arduino code

void setup() {
  Serial.begin(115200);
  pinMode(13, OUTPUT);
}
void loop() {
  int cmd = Serial.parseInt();
  if(cmd == 1){
    digitalWrite(13, HIGH);   
  }else if (cmd == -1){
    digitalWrite(13, LOW);   
  }
  Serial.println(analogRead(A0));
}