查看Noduino OpenLight的源代码
←
Noduino OpenLight
跳转到:
导航
,
搜索
因为以下原因,你没有权限编辑本页:
您刚才请求的操作只有这个用户组中的用户才能使用:
用户
您可以查看并复制此页面的源代码:
== Open API == Afer you guys 'Link Device' in WeChat, Enter Official Account: * click "Devices" to list your binding devices * select your OpenLight in the list, enter control page, click upright corner, then Copy URL * paste the URL into web browser (Chrome or Safari) to access the control page in browser * check the source code of the page to get the following variables: <source lang=php> var devid = YOUR_DEVICE_ID; var mqtt_uname = YOUR_MQTT_UNAME; </source> <br><br> === Go === ==== Prepare ==== Prepare the Go lang: <source lang=bash> $ sudo apt-get install golang-go $ sudo apt-get install golang-eclipse-paho-dev $ export GOPATH=/usr/share/gocode </source> Refer to: * https://golang.org * http://www.eclipse.org/paho/clients/golang/ <br> ==== Turn On/Off ==== <source lang=cpp> package main import ( "fmt" "os" "strconv" "strings" "net/http" "encoding/json" MQTT "git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git" ) //define a function for the default message handler var f MQTT.MessageHandler = func(client *MQTT.Client, msg MQTT.Message) { fmt.Printf("TOPIC: %s\n", msg.Topic()) fmt.Printf("MSG: %s\n", msg.Payload()) } var uid string = "YOUR_mqtt_uname" func main() { if len(os.Args[1:]) >= 2 { devid := os.Args[1] cmd := os.Args[2] msg := "" if cmd == "on" { msg = "{\"m\":\"set\", \"d\":{\"s\":1}}" } else if cmd == "off" { msg = "{\"m\":\"set\", \"d\":{\"s\":0}}" } else if cmd == "ota" { msg = "ota" } else if _, err := strconv.Atoi(cmd); err == nil { msg = "{\"m\":\"bri\", \"d\":" + cmd + "}" } pass := get_token(uid) send_msg(devid, msg, pass) } else { help_msg() } } func help_msg() { fmt.Println("Supported cmd:") fmt.Println("\topenlight dev_id on") fmt.Println("\topenlight dev_id off") fmt.Println("\topenlight dev_id 23") fmt.Println("\topenlight dev_id ota") } func send_msg(devid string, msg string, pass string) { opts := MQTT.NewClientOptions().AddBroker("tcp://mqtt.noduino.org:1883") opts.SetClientID("cid_" + devid) opts.SetUsername(devid) opts.SetPassword(pass) opts.SetDefaultPublishHandler(f) c := MQTT.NewClient(opts) if token := c.Connect(); token.Wait() && token.Error() != nil { panic(token.Error()) } mqtt_tx_topic := "app2dev/" + devid token := c.Publish(mqtt_tx_topic, 0, false, msg) token.Wait() } func get_token(user_id string) (string) { url := "http://api.noduino.org/user/token" type Body struct { UID string `json:"user_id"` } var body = Body { UID: user_id, } data, err := json.Marshal(body) //fmt.Println(string(data)) if err == nil { resp, err := http.Post(url, "application/json", strings.NewReader(string(data))) if err != nil { fmt.Println(err) } defer resp.Body.Close() dec := json.NewDecoder(resp.Body) var v map[string]interface{} if err := dec.Decode(&v); err != nil { fmt.Printf("error: %v\n", err) } else { if val, ok := v["user_token"].(string); ok { return val } } } return "" } </source> <source lang=bash> $ go build openlight.go $ ./openlight MKD12343405300 on $ ./openlight MKD12343405300 off </source> <br><br> ==== Set Brightness ==== <source lang=bash> $ go build openlight.go $ ./openlight MKD12343405300 255 $ ./openlight MKD12343405300 10 </source> <br><br> === node.js === Prepare the node.js: <source lang=bash> # download the node-v6.9.1-xxx.tgz from http://nodejs.org $ tar xf node-v6.9.1-*.tar.xz $ sudo cp -a node-v6.9.1*/* /usr/local/ $ sudo npm install -g MQTTClient $ sudo npm install -g request </source> <br><br> ==== Turn Off ==== Using the node.js to switch off the OpenLigh: <source lang=bash> $ cat light-off.js #! /usr/bin/env node var opt = { username: "YOUR_mqtt_uname", password: "" }; var http_req = require('/usr/local/lib/node_modules/request'); http_req.post( 'http://api.noduino.org/user/token', { json: {user_id: opt.username} }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body); opt.password = body.user_token; var MQTTClient = require('MQTTClient').Client; var client = new MQTTClient('mqtt.noduino.org', 1883, opt); client.connect(function () { console.log("connect ok!"); var pubopt = { qos_level: 2 }; var state = { on: 0 <---- off }; var data = '{"m":"set", "d":{' + '"s":' + state.on + '}}'; client.publish('app2dev/YOUR_DEVICE_ID', data, pubopt, function (message_id) { console.log("public ok! message_id = " + message_id); process.exit(0); }); }); } else { console.log("Request the user token failed"); process.exit(1); } } ); $ ./light-off.js </source> <br><br> ==== Turn On ==== Turn on the OpenLight: <source lang=bash> $ cat light-on.js #! /usr/bin/env node var opt = { username: "YOUR_mqtt_uname", password: "" }; var http_req = require('/usr/local/lib/node_modules/request'); http_req.post( 'http://api.noduino.org/user/token', { json: {user_id: opt.username, app_id:"mj2030064278", app_key:"0077d4829f52b1b2d668f8a82c5f5ded"} }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body); opt.password = body.user_token; var MQTTClient = require('MQTTClient').Client; var client = new MQTTClient('mqtt.noduino.org', 1883, opt); client.connect(function () { console.log("connect ok!"); var pubopt = { qos_level: 2 }; var state = { on: 1 <---- on }; var data = '{"m":"set", "d":{' + '"s":' + state.on + '}}'; client.publish('app2dev/YOUR_DEVICE_ID', data, pubopt, function (message_id) { console.log("public ok! message_id = " + message_id); process.exit(0); }); }); } else { console.log("Request the user token failed"); process.exit(1); } } ); $ ./light-on.js </source> <br><br> ==== Set Color ==== Change the color of the OpenLight: <source lang=bash> $ cat light-color.js #! /usr/bin/env node var opt = { username: "YOUR_mqtt_uname", password: "" }; var http_req = require('/usr/local/lib/node_modules/request'); http_req.post( 'http://api.noduino.org/user/token', { json: {user_id: opt.username, app_id:"mj2030064278", app_key:"0077d4829f52b1b2d668f8a82c5f5ded"} }, function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body); opt.password = body.user_token; var MQTTClient = require('MQTTClient').Client; var client = new MQTTClient('mqtt.noduino.org', 1883, opt); client.connect(function () { console.log("connect ok!"); var pubopt = { qos_level: 2 }; var state = { red: 0, green: 0, blue: 255, <--------- outputting full power of the blue channel white: 0, on: 1 }; data = '{"m":"set", "d":{' + '"r":' + state.red + ',"g":' + state.green + ',"b":' + state.blue + ',"w":' + state.white + ',"s":' + state.on + '}}'; client.publish('app2dev/YOUR_DEVICE_ID', data, pubopt, function (message_id) { console.log("public ok! message_id = " + message_id); process.exit(0); }); }); } else { console.log("Request the user token failed"); process.exit(1); } } ); $ ./light-color.js </source> <br><br> ==== FAQ ==== <font color=red><b>If you get the following error:</b></font> <source lang=bash> /usr/local/lib/node_modules/MQTTClient/client.js:56 throw Error('user names are kept to 12 characters or fewer'); ^ Error: user names are kept to 12 characters or fewer </source> Please patch the /usr/local/lib/node_modules/MQTTClient/client.js to remove the line of checking the length of username and password: <source lang=bash> --- a/client.js +++ b/client.js @@ -52,10 +52,10 @@ var Client = exports.Client = function (host, port, options) { options.alive_timer = 30; options.ping_timer = parseInt(options.alive_timer * 0.6 * 1000); // 用户名和密码 - if (typeof options.username == 'string' && options.username.length > 12) - throw Error('user names are kept to 12 characters or fewer'); - if (typeof options.password == 'string' && options.password.length > 12) - throw Error('passwords are kept to 12 characters or fewer'); + //if (typeof options.username == 'string' && options.username.length > 12) + // throw Error('user names are kept to 12 characters or fewer'); + //if (typeof options.password == 'string' && options.password.length > 12) + // throw Error('passwords are kept to 12 characters or fewer'); // Will flag if (options.will_flag && (typeof options.will_topic != 'string' || typeof options.will_message != 'string')) throw Error('missing will_topic or will_message when will_flag is set'); </source> <br><br> === python === ==== Prepare ==== <source lang=bash> $ python3 --version Python 3.5.3rc1 $ pip3 install paho-mqtt Collecting paho-mqtt Downloading paho-mqtt-1.2.tar.gz (49kB) 100% |████████████████████████████████| 51kB 308kB/s Building wheels for collected packages: paho-mqtt Running setup.py bdist_wheel for paho-mqtt ... done Stored in directory: /home/comcat/.cache/pip/wheels/fa/db/fb/b495e37057e2f40534726b3c00ab26a58fc80fb8d17223df07 Successfully built paho-mqtt Installing collected packages: paho-mqtt Successfully installed paho-mqtt-1.2 </source> More infor: https://pypi.python.org/pypi/paho-mqtt <br> ==== Turn off ==== * replace the mqtt_uname in line 10 <source lang=python> $ cat openlight.py #!/usr/bin/python3 import json, requests import paho.mqtt.client as mqtt import sys # replace it to your id ########################################### mqtt_uname = 'o7okr76757879RfhBs_XM339' <---- YOUR_mqtt_uname devid = 'MJD123456789012' <---- YOUR_devid ########################################### # mqtt json message ########################################### # {"m":"set", "d":{"r":255,"g":255,"b":255,"w":255,"s":1}} # {"m":"bri", "d":23} --> bri:[0, 255] # {"m":"set_voice_name", "d":"room light"} # {"m":"get_voice_name"} # {"m":"get_state"} # ota ########################################### DEBUG = True def dbg(msg): global DEBUG if DEBUG: print(msg) sys.stdout.flush() #http://docs.python-requests.org/en/latest/user/quickstart/#json-response-content def help_msg(): print("Supported cmd:") print("\tlight.py dev_id on") print("\tlight.py dev_id off") print("\tlight.py dev_id 23") print("\tlight.py dev_id ota") print("\tlight.py dev_id set_vn \"kitchen light\"") print("\tlight.py dev_id get_vn") if len(sys.argv) >= 2: devid = sys.argv[1] set_state = sys.argv[2] else: help_msg() sys.exit(-2) if set_state == "on": mqtt_msg = '{"m":"set", "d":{"s":1}}' elif set_state == "off": mqtt_msg = '{"m":"set", "d":{"s":0}}' elif set_state.isdigit(): mqtt_msg = '{"m":"bri", "d":' + set_state + '}' elif set_state == "ota": mqtt_msg = "ota" elif set_state == "get_state": mqtt_msg = '{"m":"get_state", "d":""}' elif set_state == "set_vn": mqtt_msg = '{"m":"set_voice_name", "d":"' + sys.argv[3] + '"}' elif set_state == "get_vn": mqtt_msg = '{"m":"get_voice_name", "d":""}' elif set_state == "set_cold_on": mqtt_msg = '{"m":"set_cold_on", "d":' + sys.argv[3] + '}' elif set_state == "get_cold_on": mqtt_msg = '{"m":"get_cold_on", "d":""}' elif set_state == "set_grad_on": mqtt_msg = '{"m":"set_grad_on", "d":' + sys.argv[3] + '}' elif set_state == "get_grad_on": mqtt_msg = '{"m":"get_grad_on", "d":""}' elif set_state == "set_alexa_on": mqtt_msg = '{"m":"set_alexa_on", "d":' + sys.argv[3] + '}' elif set_state == "get_alexa_on": mqtt_msg = '{"m":"get_alexa_on", "d":""}' else: help_msg() sys.exit(-2) url = 'http://api.noduino.org/user/login' dat = dict ( user_id = mqtt_uname, app_id = 'mj2030064278', app_key = '0077d4829f52b1b2d668f8a82c5f5ded' ) #print(json.dumps(dat)) try: resp = requests.post(url = url, json = dat) except Exception as e: dbg(e) sys.exit(-1) mqtt_rx_topic = 'dev2app/' + devid mqtt_tx_topic = 'app2dev/' + devid mqtt_host = 'mqtt.noduino.org' mqtt_port = 1883 print("mqtt msg: " + mqtt_msg) def on_connect(client, u_dat, rc): if rc == 0: print("Connected successfully") else: print("Connection failed. rc = "+str(rc)) def on_publish(client, u_dat, rc): print("Message "+str(rc)+" published.") def on_subscribe(client, u_dat, mid, qos): print("Subscribe with "+str(mid)+" received") def on_message(client, udat, msg): print("Message received on topic "+msg.topic+" and payload "+str(msg.payload)) mqttc = mqtt.Client() mqttc.on_connect = on_connect mqttc.on_publish = on_publish mqttc.on_subscribe = on_subscribe mqttc.on_message = on_message #mqttc.username_pw_set(mqtt_uname, mqtt_pass) mqttc.username_pw_set(tu, tp) mqttc.connect(mqtt_host, mqtt_port) mqttc.publish(mqtt_tx_topic, mqtt_msg) mqttc.subscribe(mqtt_rx_topic) mqttc.loop_forever() </source> <source lang=bash> $ ./openlight.py your_dev_id off </source> <br> ==== Turn On ==== Turn on the bulb: <source lang=bash> $ ./openlight.py your_dev_id on </source> <br><br> ==== OTA ==== * upload your firmware through http://dev.noduino.org/openlight * request device to download your new firmware: <source lang=bash> $ ./openlight.py your_dev_id ota </source> <br><br> === HTML5 === The device control page in WeChat is a H5 page. Using a MQTT client implement in javascript , using the mqttws31.js library: <source lang=javascript> var client_id = parseInt(Math.random() * 10000, 10) + '_' + mqtt_uname; var client = new Paho.MQTT.Client(mqtt_server, mqtt_port, "/mqtt", client_id); function failConnect(e) { console.log("connect failed"); console.log(e); console.log("reconnecting ..."); client.connect({userName: mqtt_uname, password: mqtt_pass, onSuccess:onConnect, onFailure: failConnect, mqttVersion:3}); } function onConnect() { console.log("onConnect OK!"); subscribe('dev2app/' + devid); } function subscribe(topic) { client.subscribe(topic); } function onMessageArrived (message) { console.log("Arrived Message: [", message.payloadString, "]"); try { job = JSON.parse(message.payloadString); set = job.d; } catch(e) { console.log("JSON object error!"); alert("JSON error, RX data is: " + message.payloadString); return; } if(job.m == 'set' || job.m == 'status') { //console.log("set ui state"); set_ui_state(set); } if(job.m == 'offline') { blockUI(); } } function onDisConnect() { console.log("reconnecting ..."); client.connect({userName: mqtt_uname, password: mqtt_pass, onSuccess:onConnect, onFailure: failConnect, mqttVersion:3}); } function mqtt_publish(msg){ var topic = 'app2dev/' + devid; message = new Paho.MQTT.Message(msg); message.destinationName = topic; client.send(message); console.log("publish message: " + msg); } function mqtt_init() { client.connect({userName: mqtt_uname, password: mqtt_pass, onSuccess:onConnect, onFailure: failConnect, mqttVersion:3}); client.onMessageArrived = onMessageArrived; client.onConnectionLost = onDisConnect; } mqtt_init(); </source> <br><br>
返回到
Noduino OpenLight
。
个人工具
登录
名字空间
页面
讨论
变换
查看
阅读
查看源代码
查看历史
操作
搜索
导航
首页
社区专页
新闻动态
最近更改
随机页面
帮助
工具箱
链入页面
相关更改
特殊页面