How to build smart foosball app - smartfoosball/fooscloud GitHub Wiki

How to build smart foosball app

注册机智云开发者

app_id_pk

使用open api与机智云通讯

{ 
    "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

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())
    { "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"
          }
        ]
    }
  • 使用oauth获取用户授权, 登录微信sanbox, 扫描二维码并登陆。在urls.py下增加一条url设置
url(r'^wechat/oauth2$', views.wechat_oauth2, name="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)