当前位置:   article > 正文

微信蓝牙设备开发之初步接入微信硬件jsapi接口(4)_wx refresh

wx refresh

文章来源:http://www.vxzsk.com/145.html 

已推出最新微 信硬件jsapi学习笔记 地址 http://www.vxzsk.com/282.html

微信app和蓝牙设备接入通信,通信交互通道有两种,如下图通道路径结构图@V型知识库原创


黑色箭头 公众号html界面发送命令到设备,设备最终返回数据到厂商服务器,厂商服务器也就是咱们开发者自己工程项目的服务器后端(数据返回到服务器配置url的 servelet的post方法中了)。这也是导致初学者开发者在开发h5界面发送指令后,无论如何在h5前端界面也得不到蓝牙设备返回数据包的原因,这是个坑,大家注意。

红色箭头 也就是我们接下来介绍的通道路径,公众号html界面发送指令到设备,设备最终返回数据到发送html命令的界面,意思就是H5界面发送指令到设备,设备返回响应数据包到H5界面,而不是服务器端。

点击公众号菜单或链接跳转到H5界面的java方法(案例用的springMVC),在此方法中获取timestamp,nonceStr,signature三个参数。

1、spring的controller方法

  1. //V型知识库 www.vxzsk.com
  2. @RequestMapping(value="/goReadCardAnniu")
  3. public ModelAndView goReadCardAnniu2(HttpServletRequest request,HttpServletResponse response){
  4. String appId="";//应用id
  5. String appsecret="";//应用秘钥
  6. //1,获取access_token
  7. AccessToken accessToken = WeixinUtil.getAccessToken(appId, appsecret);
  8. String access_token=accessToken.getToken();
  9. //2,获取调用微信jsapi的凭证
  10. String ticket = WeixinUtil.getJsapiTicket(access_token);
  11. Map<String,String> map = WeixinUtil.sign(ticket, AppConst.SITE_DOMAIN+"lanya/card/goReadCardAnniu.do");
  12. request.setAttribute("timestamp", map.get("timestamp"));
  13. request.setAttribute("nonceStr", map.get("nonceStr"));
  14. request.setAttribute("signature", map.get("signature"));
  15. request.setAttribute("appId", appId);
  16. return new ModelAndView("/weixin/device/b_chat_s_anniu");
  17. }

注意第12行的WeixinUtil.sign方法,第二个参数路径一定是跳转H5界面的路径,否则在H5界面初始化微信硬件jsapi会报错。

2、获取access_token请参考http://www.vxzsk.com/28.html

3、获取getJsapiTicket方法

  1. public static String getJsapiTicket(String access_token){
  2. String getticket_url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=";//接口凭据
  3. String jsonData=HttpUtil.sendGet(getticket_url+access_token+"&type=jsapi", "utf-8", 30000);
  4. JSONObject jsonObj = JSONObject.fromObject(jsonData);
  5. String errcode = jsonObj.getString("errcode");
  6. String ticket = null;
  7. if(errcode.equals("0")){
  8. ticket = jsonObj.getString("ticket");
  9. }
  10. return ticket;
  11. }

HttpUtil.sendGet方法 请参考http://www.vxzsk.com/doc/25.html

4、WeixinUtil.sign方法获取timestamp,nonceStr,signature三个参数方法

  1. /***
  2. * 获取界面调用jsapi的所需参数
  3. * @param jsapi_ticket 凭据
  4. * @param url 界面请求地址
  5. * @return
  6. V型知识库 www.vxzsk.com
  7. */
  8. public static Map<String, String> sign(String jsapi_ticket, String url) {
  9. Map<String, String> ret = new HashMap<String, String>();
  10. String nonce_str = create_nonce_str();
  11. String timestamp = create_timestamp();
  12. String string1;
  13. String signature = "";
  14. //注意这里参数名必须全部小写,且必须有序
  15. string1 = "jsapi_ticket=" + jsapi_ticket +
  16. "&noncestr=" + nonce_str +
  17. "×tamp=" + timestamp +
  18. "&url=" + url;
  19. System.out.println(string1);
  20. try
  21. {
  22. MessageDigest crypt = MessageDigest.getInstance("SHA-1");
  23. crypt.reset();
  24. crypt.update(string1.getBytes("UTF-8"));
  25. signature = byteToHex(crypt.digest());
  26. }
  27. catch (NoSuchAlgorithmException e)
  28. {
  29. e.printStackTrace();
  30. }
  31. catch (UnsupportedEncodingException e)
  32. {
  33. e.printStackTrace();
  34. }
  35. ret.put("url", url);
  36. ret.put("jsapi_ticket", jsapi_ticket);
  37. ret.put("nonceStr", nonce_str);
  38. ret.put("timestamp", timestamp);
  39. ret.put("signature", signature);
  40. return ret;
  41. }
  42. private static String byteToHex(final byte[] hash) {
  43. Formatter formatter = new Formatter();
  44. for (byte b : hash)
  45. {
  46. formatter.format("%02x", b);
  47. }
  48. String result = formatter.toString();
  49. formatter.close();
  50. return result;
  51. }
  52. private static String create_nonce_str() {
  53. return UUID.randomUUID().toString();
  54. }
  55. private static String create_timestamp() {
  56. return Long.toString(System.currentTimeMillis() / 1000);
  57. }

以上便是跳转H5界面的controller方法,跳转到b_chat_s_anniu.jsp界面的代码如下,先来个分割线


1、jsp界面引入微信硬件jsapi的js库,jquery库

  1. <script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
  2. <script src="http://res.wx.qq.com/open/js/jweixin-1.1.0.js"> </script>

2、 <body></body>之间的html代码

  1. <!--标题行-->
  2. <h2 style="color: white;background-color: green;text-align: center;background-position: center;">蓝牙设备</h2>
  3. <div class="page">
  4. <div class="bd spacing">
  5. <div class="weui_cells weui_cells_form">
  6. <div class="weui_cell">
  7. <div class="weui_cell_hd"><label class="weui_label" style="width: auto;">当前设备: </label></div>
  8. <div class="weui_cell_bd weui_cell_primary">
  9. <label id="lbdeviceid" class="weui_label" style="width: auto;"></label>
  10. </div>
  11. </div>
  12. <div class="weui_cell">
  13. <div class="weui_cell_hd"><label class="weui_label" style="width: auto;">状态信息: </label></div>
  14. <div class="weui_cell_bd weui_cell_primary">
  15. <label id="lbInfo" class="weui_label" style="width: auto;"></label>
  16. </div>
  17. </div>
  18. <div class="weui_cell" >
  19. <div class="weui_cell_hd"><label class="weui_label">日志: </label></div>
  20. <div class="weui_cell_bd weui_cell_primary">
  21. <textarea id="logtext" class="weui_textarea" placeholder="日志" rows="5"></textarea>
  22. </div>
  23. </div>
  24. </div>
  25. <div class="weui_btn_area weui">
  26. <button class="weui_btn weui_btn weui_btn_warn" id="CallGetWXrefresh">获取设备</button><br>
  27. </div>
  28. </div>
  29. <div class="weui_dialog_alert" id="Mydialog" style="display: none;">
  30. <div class="weui_mask"></div>
  31. <div class="weui_dialog">
  32. <div class="weui_dialog_hd" id="dialogTitle"><strong class="weui_dialog_title">着急啦</strong></div>
  33. <div class="weui_dialog_bd" id="dialogContent">亲,使用本功能,请先打开手机蓝牙!</div>
  34. <div class="weui_dialog_ft">
  35. <a href="#" class="weui_btn_dialog primary">确定</a>
  36. </div>
  37. </div>
  38. </div>
  39. <!--BEGIN toast-->
  40. <div id="toast" style="display: none;">
  41. <div class="weui_mask_transparent"></div>
  42. <div class="weui_toast">
  43. <i class="weui_icon_toast"></i>
  44. <p class="weui_toast_content" id="toast_msg">已完成</p>
  45. </div>
  46. </div>
  47. <!--end toast-->
  48. <!-- loading toast -->
  49. <div id="loadingToast" class="weui_loading_toast" style="display:none;">
  50. <div class="weui_mask_transparent"></div>
  51. <div class="weui_toast">
  52. <div class="weui_loading">
  53. <div class="weui_loading_leaf weui_loading_leaf_0"></div>
  54. <div class="weui_loading_leaf weui_loading_leaf_1"></div>
  55. <div class="weui_loading_leaf weui_loading_leaf_2"></div>
  56. <div class="weui_loading_leaf weui_loading_leaf_3"></div>
  57. <div class="weui_loading_leaf weui_loading_leaf_4"></div>
  58. <div class="weui_loading_leaf weui_loading_leaf_5"></div>
  59. <div class="weui_loading_leaf weui_loading_leaf_6"></div>
  60. <div class="weui_loading_leaf weui_loading_leaf_7"></div>
  61. <div class="weui_loading_leaf weui_loading_leaf_8"></div>
  62. <div class="weui_loading_leaf weui_loading_leaf_9"></div>
  63. <div class="weui_loading_leaf weui_loading_leaf_10"></div>
  64. <div class="weui_loading_leaf weui_loading_leaf_11"></div>
  65. </div>
  66. <p class="weui_toast_content" id="loading_toast_msg">数据加载中</p>
  67. </div>
  68. </div>
  69. <!-- End loading toast -->
  70. <!--BEGIN dialog1-->
  71. <div class="weui_dialog_confirm" id="dialog1" style="display: none;">
  72. <div class="weui_mask"></div>
  73. <div class="weui_dialog">
  74. <div class="weui_dialog_hd"><strong class="weui_dialog_title">弹窗标题</strong></div>
  75. <div class="weui_dialog_bd">自定义弹窗内容,居左对齐显示,告知需要确认的信息等</div>
  76. <div class="weui_dialog_ft">
  77. <a href="javascript:;" class="weui_btn_dialog default" id="qxBtn">取消</a>
  78. <a href="javascript:;" class="weui_btn_dialog primary" id="okBtn">确定</a>
  79. </div>
  80. </div>
  81. </div>
  82. <!--END dialog1-->
  83. <!--BEGIN dialog2-->
  84. <div class="weui_dialog_alert" id="dialog2" style="display: none;">
  85. <div class="weui_mask"></div>
  86. <div class="weui_dialog">
  87. <div class="weui_dialog_hd"><strong class="weui_dialog_title">弹窗标题</strong></div>
  88. <div class="weui_dialog_bd">弹窗内容,告知当前页面信息等</div>
  89. <div class="weui_dialog_ft">
  90. <a href="javascript:;" class="weui_btn_dialog primary">确定</a>
  91. </div>
  92. </div>
  93. </div>
  94. <!--END dialog2-->
  95. </div>
  96. <div id="myparams" style="display: none">
  97. <span id="timestamp">${timestamp }</span>
  98. <span id="nonceStr">${nonceStr }</span>
  99. <span id="signature">${signature }</span>
  100. <span id="appId">${appId }</span>
  101. </div>

上述html最后四行代码就是我们在controller中存储在request对象中的四个参数

3、重点来了,初始化微信硬件jsapi库,代码如下

  1. jQuery(document).ready(function(){
  2. //初始化库
  3. loadXMLDoc();
  4. //初始化库结束
  5. //点击获取设备按钮的函数 开始
  6. $("#CallGetWXrefresh").on("click",function(e){
  7. //1. 打开微信设备
  8. my_openWXDeviceLib();
  9. //2. 获取设备信息
  10. my_getWXDeviceInfos();
  11. });
  12. //点击获取设备按钮的函数 结束
  13. });

loadXMLDoc();方法是初始化微信硬件jsapi库,后面方法是给"获取设备"按钮绑定一个点击事件

1)、loadXMLDoc();方法代码

  1. //初始化 微信硬件jsapi库 V型知识库 www.vxzsk.com
  2. function loadXMLDoc()
  3. {
  4. var appId =jQuery("#appId").text();
  5. var timestamp=jQuery("#timestamp").text();
  6. var nonceStr =jQuery("#nonceStr").text();
  7. var signature=jQuery("#signature").text();
  8. wx.config({
  9. beta: true,
  10. debug: true,// 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
  11. appId: appId,
  12. timestamp: timestamp,
  13. nonceStr: nonceStr,
  14. signature: signature,
  15. jsApiList: [
  16. 'openWXDeviceLib',
  17. 'closeWXDeviceLib',
  18. 'getWXDeviceInfos',
  19. 'getWXDeviceBindTicket',
  20. 'getWXDeviceUnbindTicket',
  21. 'startScanWXDevice',
  22. 'stopScanWXDevice',
  23. 'connectWXDevice',
  24. 'disconnectWXDevice',
  25. 'sendDataToWXDevice',
  26. 'onWXDeviceBindStateChange',
  27. 'onWXDeviceStateChange',
  28. 'onScanWXDeviceResult',
  29. 'onReceiveDataFromWXDevice',
  30. 'onWXDeviceBluetoothStateChange',
  31. ]
  32. });
  33. alert("初始化库结束");
  34. }

此方法需要四个参数,我们已经在controller中获取并存放到request对象中了。

2)、打开设备方法my_openWXDeviceLib()代码

  1. function my_openWXDeviceLib(){
  2. var x=0;
  3. WeixinJSBridge.invoke('openWXDeviceLib', {},
  4. function(res){
  5. mlog("打开设备返回:"+res.err_msg);
  6. if(res.err_msg=='openWXDeviceLib:ok')
  7. {
  8. if(res.bluetoothState=='off')
  9. {
  10. showdialog("太着急啦","亲,使用前请先打开手机蓝牙!");
  11. $("#lbInfo").innerHTML="1.请打开手机蓝牙";
  12. $("#lbInfo").css({color:"red"});
  13. x=1;
  14. isOver();
  15. };
  16. if(res.bluetoothState=='unauthorized')
  17. {
  18. showdialog("出错啦","亲,请授权微信蓝牙功能并打开蓝牙!");
  19. $("#lbInfo").html("1.请授权蓝牙功能");
  20. $("#lbInfo").css({color:"red"});
  21. x=1;
  22. isOver();
  23. };
  24. if(res.bluetoothState=='on')
  25. {
  26. //showdialog("太着急啦","亲,请查看您的设备是否打开!");
  27. $("#lbInfo").html("1.蓝牙已打开,未找到设备");
  28. $("#lbInfo").css({color:"red"});
  29. //$("#lbInfo").attr(("style", "background-color:#000");
  30. x=0;
  31. //isOver();
  32. };
  33. }
  34. else
  35. {
  36. $("#lbInfo").html("1.微信蓝牙打开失败");
  37. x=1;
  38. showdialog("微信蓝牙状态","亲,请授权微信蓝牙功能并打开蓝牙!");
  39. }
  40. });
  41. return x; //0表示成功 1表示失败
  42. }


3)、获取设备信息方法my_getWXDeviceInfos代码

  1. function my_getWXDeviceInfos(){
  2. WeixinJSBridge.invoke('getWXDeviceInfos', {}, function(res){
  3. var len=res.deviceInfos.length; //绑定设备总数量
  4. for(i=0; i<=len-1;i++)
  5. {
  6. //alert(i + ' ' + res.deviceInfos[i].deviceId + ' ' +res.deviceInfos[i].state);
  7. if(res.deviceInfos[i].state==="connected")
  8. {
  9. $("#lbdeviceid").html(res.deviceInfos[i].deviceId);
  10. C_DEVICEID = res.deviceInfos[i].deviceId;
  11. $("#lbInfo").html("2.设备已成功连接");
  12. $("#lbInfo").css({color:"green"});
  13. break;
  14. }
  15. }
  16. });
  17. return;
  18. }

4)、日志输出方法

  1. //打印日志
  2. function mlog(m){
  3. var log=$('#logtext').val();
  4. //log=log+m;
  5. log = m;
  6. $('#logtext').val(log);
  7. }

好了,至此代码都已经写玩了,咱们来看看效果吧。

第一、打开手机蓝牙并登录微信,扫描设备的二维码,具体如何生成设备二维码和授权设备请参考左上角菜单中的其它章节。

第二,绑定设备-进入公众号,然后我们可以看到公众号头部已经有"已连接1个设备或未连接"


第三、点击我们上面所说的controller方法,进入H5界面


第四、点击获取设备按钮


如图所示,当前设备的deviceid已经被输出来了, 并且打开设备的日志也被打印输出。

第五,完整的jsp页面代码 请前往www.vxzsk.com 微信蓝牙设备开发频道查看




声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/321134
推荐阅读
相关标签
  

闽ICP备14008679号