How to build smart foosball app - smartfoosball/fooscloud GitHub Wiki
How to build smart foosball app
注册机智云开发者
- 配置gokit, 请查看How To Build Smart FoosBall with GoKit
- 在机智云设备详细信息,取得app id 和product key, 如下图
使用open api与机智云通讯
- 使用API使用用户名和密码创建用户 注册openapi用户并获取token货uid,注册成功返回的JSON内容如下
{
"uid": "akkdlfeiow",
"token": "akdlfkad",
"expire_at": 13894002020
}
- 使用OPENAPI(用户登录)[http://site.gizwits.com/document/m2m/openapi/#post_4]通过用户名和密码获取token和uid,成功后返回的JSON内容如下:
{
"uid": "akkdlfeiow",
"token": "akdlfkad",
"expire_at": 13894002020
}
- 使用product key 和 mac 地址,通过API(查询设备)[http://site.gizwits.com/document/m2m/openapi/#appdevices] 获得设备did 和passcode,调用成功返回的JSON如下
{
"did": "abcada",
"passcode": "123456",
}
- 使用did和passcode通过api(绑定设备)[http://site.gizwits.com/document/m2m/openapi/#appbindings]绑定设备, 成功后返回的格式如下
{
"success": ['abc', 'add'],
"failed": ['adad', 'ee']
}
-
使用websocket实时获取gotkit反馈的数据
-
用户登录
function login() {
var data = {
"cmd": "login_req",
"data": {
"appid": "{{gw_obj.appid}}",
"uid": "{{gw_obj.uid}}",//通过API http://site.gizwits.com/document/m2m/openapi/#applogin获取
"token": "{{gw_obj.token}}",//通过API http://site.gizwits.com/document/m2m/openapi/#applogin获取
"p0_type": "attrs_v4",//当用户在登陆时参数"p0_type"的值等于"attrs_v4"时,云端会以标准数据点协议的方式和浏览器交 互。
"heartbeat_interval": 60//心跳的时间间隔,单位为秒,值必须小于等于180
}
};
send(data);
}
- 获取gokit反馈的数据(标准数据点操作)我们需要从云端获取设备状态,所以需要处理来自云端的标示为{"cmd": "s2c_noti"}的内容。
if (data["cmd"] == "s2c_noti" && data["data"]["did"] == did) {
var red = data["data"]["attrs"]["red_goals"];
var blue = data["data"]["attrs"]["blue_goals"];
update_score("#red_score", red);
update_score("#blue_score", blue);
if (red == 10 || blue == 10) {
$("#form_end_game").submit();
}
}
###与微信通信
-
申请微信公众号 立即注册
-
填写微信 echo调用url
- 使用wechatpy 0.7.2编写wechat echo 代码:
class WechatEcho(View):
def get(self, request):
signature = request.GET.get('signature', '')
timestamp = request.GET.get('timestamp', '')
nonce = request.GET.get('nonce', '')
echo_str = request.GET.get('echostr', '')
try:
check_signature(TOKEN, signature, timestamp, nonce)
except InvalidSignatureException:
return HttpResponse(status=403)
return HttpResponse(echo_str)
def post(self, request):
signature = request.GET.get('signature', '')
timestamp = request.GET.get('timestamp', '')
nonce = request.GET.get('nonce', '')
echo_str = request.GET.get('echostr', '')
try:
check_signature(TOKEN, signature, timestamp, nonce)
except InvalidSignatureException:
return HttpResponse(status=403)
msg = parse_message(request.body)
if msg.type == 'event':
if msg.event == 'subscribe' or msg.event == 'subscribe_scan':
# 订阅时的事件
reply = create_reply(u'菜鸟,来一局...', msg)
return HttpResponse(reply.render())
reply = TextReply(content=u'你好,有任何问题请直接回复,我们会尽快处理。', message=msg)
return HttpResponse(reply.render())
- 通过微信api创建自定义微信菜单
{ "button": [
{
"type":"view",
"name":"赛事",
"url":"http://foosball.gizwits.com/games"
},
{
"type":"view",
"name":"选手",
"url":"http://foosball.gizwits.com/players"
},
{
"type":"view",
"name":"我",
"url":"http://foosball.gizwits.com/me"
}
]
}
url(r'^wechat/oauth2$', views.wechat_oauth2, name="wechat_oauth2")
-
根据下图修改OAuth网页端授权页面:
-
获得授权后获取用心头像,依照微信文档网页授权获取用户基本信息,编写用户同意授权代码BaseWeixinView
-
拉取用户信息wechat_oauth2部份代碼如下:
class BaseWeixinView(View):
def dispatch(self, *args, **kwargs):
if not self.request.user.is_authenticated():
redirect_uri = urllib.urlencode({
'redirect_uri':
'http://' + self.request.get_host() + reverse("wechat_oauth2")})
return redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect' % (WX_APPID, redirect_uri))
return super(BaseWeixinView, self).dispatch(*args, **kwargs)
def wechat_oauth2(request):
code = request.GET.get('code')
if code:
params={'appid': WX_APPID,
'secret': WX_SECRET,
'code': code,
'grant_type': 'authorization_code'}
try:
resp = requests.get('https://api.weixin.qq.com/sns/oauth2/access_token',
params=params)
tokens = json.loads(resp.content)
openid = tokens['openid']
params = {'access_token': tokens['access_token'],
'openid': openid,
'lang': 'zh_CN'}
resp = requests.get('https://api.weixin.qq.com/sns/userinfo', params=params)
user = json.loads(resp.content)