Blog | Phodal - A Growth Engineerhttp://www.phodal.com/blog/2015-02-05T18:06:08.222041+00:00Blog物联网系统与CoAP之Hello,World2014-08-13T00:55:00+00:002014-08-14T14:21:55.095152+00:00Phodal Huanghttp://www.phodal.com/blog/author/root/http://www.phodal.com/blog/use-node-coap-create-a-coap-server/##物联网系统与CoAP Hello,World
关于CoAP与物联网系统我们在上一篇中(ps:[CoAP与物联网系统](http://www.phodal.com/blog/use-constrained-application-protocol-in-internet-of-things/))中做一个简单的介绍,接着我们便开始试试CoAP协议的应用
##CoAP应用
开始之前我们需要能访问[coap://localhost/](coap://localhost/),于是我们便需要安装一个Firefox的插件Copper。
###Firefox Copper
下载地址: [https://addons.mozilla.org/en-US/firefox/addon/copper-270430/](https://addons.mozilla.org/en-US/firefox/addon/copper-270430/)
作为测试我们可以访问 [coap://vs0.inf.ethz.ch:5683/](coap://vs0.inf.ethz.ch:5683/)
###Node CoAP
> node-coap is a client and server library for CoAP modelled after the http module.
Node-CoAP是一个客户端和服务端的库用于CoAP的模块建模。创建一个package.json文件,添加我们的库
{
"dependencies":{
"coap": "0.7.2"
}
}
接着执行
npm install
就可以安装好我们的依赖
###CoAP 示例
于是我们就可以创建这样一个app.js文件
const coap = require('coap')
, server = coap.createServer()
server.on('request', function(req, res) {
res.end('Hello ' + req.url.split('/')[1] + '\n')
})
server.listen(function() {
console.log('server started')
})
接着执行
node app.js
我们就可以在浏览器上访问了,只是现在什么也没有。 接着我们再创建一个client端的js,并运行之
const coap = require('coap')
, req = coap.request('coap://localhost/World')
req.on('response', function(res) {
res.pipe(process.stdout)
})
req.end()
就可以在console上输出
Hello World
也就达到了我们的目的,用CoAP协议创建一个服务,接着我们应该用它创建更多的东西,如产生JSON数据,以及RESTful。
##其他
物联网系统CoAP版进行时
[https://github.com/gmszone/iot-coap](https://github.com/gmszone/iot-coap)最小物联网系统(七)——与服务器通讯2013-12-25T16:25:44+00:002015-02-05T18:06:08.222041+00:00Phodal Huanghttp://www.phodal.com/blog/author/root/http://www.phodal.com/blog/bare-minimum-iot-system-date-commucation/这里写的数据通讯指的是两部分,一部分是与服务器,一部分是与单片机。这样设计的另外一个原因是,更好的分层,能让我们更好的理解这个系统。负责这个功能的这里用的是Raspberry PI,或者是你的PC两者都可以,我想你也看到了之前的代码。那么先让我们看看与服务器通信的这部分。
##服务器通讯##
示例中的代码是这样子的,如果你没有看懂的话,那么等等 。
<pre><code class="python">
import json,urllib2
url="http://b.phodal.com/athome/1"
while True:
status=json.load(urllib2.urlopen(url))[0]['led1']
</code></pre>
###GET###
看看get.py的代码,这个是没有压缩的,换句话说,会比较好理解一点
<pre><code class="python">
import json
import urllib2
url="http://b.phodal.com/athome/1"
while 1:
date=urllib2.urlopen(url)
result=json.load(date)
status=result[0]['led1']
print status
</code></pre>
这里做的事情有两件,一件是从服务器GET,另外一个就是解析JSON数据。
如果你用的是*nix,应该就自带curl了,可以试着用下面的命令来GET
curl http://b.phodal.com/athome/1
那么应该返回的是下面的结果
[{"id":1,"temperature":14,"sensors1":12,"sensors2":12,"led1":0}]
用在python里面就是
urllib2.open("http://b.phodal.com/athome/1")
###数据解析###
python带有json解析模块,我们在这里只需要用json.load()来解析获取下面的date就可以了
result=json.load(date)
解析完的result相当于是C语言里面的数组,在这里相当于是一个二维数组,我们只需要result[0]['led1'],在python里面叫做字典,意思就是和字典一样。
"led1":0
led1的值是0,所以result[0]['led1]的值是0,如果你用过Ruby,那么这个和其中的Hash差不多。
因此在这里我们拿到了服务器上面的控制状态的指令,也就是0。我们还需要传给单片机,也就是Arduino。。