碧桂园
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

267 lines
9.4 KiB

  1. import {CrsClient} from "./crsClient";
  2. import {CryptoJS} from "./CryptoJS";
  3. const systemInfo = wx.getSystemInfoSync();
  4. const SELECT_TYPE = {
  5. NONE: 0,
  6. IMAGE: 1,
  7. VIDEO: 2,
  8. };
  9. Page({
  10. data: {
  11. showOverlay: true,
  12. showSelect: false,
  13. SELECT_TYPE: SELECT_TYPE,
  14. selectType: 0,
  15. //CRS配置
  16. config: {
  17. apiKey: 'a9abd99b2dfb3a5bee964cbb0bced0ae', // EasyAR开发中心 - API KEY - API Key
  18. apiSecret: '483e000a38265687c058efb7ab66cbc0917a3331b6dbf5482df46c76cb749529', // EasyAR开发中心 - API KEY - API Secret
  19. crsAppId: '8911f4b8f03725e300ca4130c01f27e9', // EasyAR开发中心 - 云服务 - 云识别管理 - 云识别库信息 - CRS AppId
  20. token: '',
  21. clientHost: 'https://bd9b3490fe845642e600cf53f0cd64b8.cn1.crs.easyar.com:8443', //服务器一般不变
  22. jpegQuality: 0.7, //JPEG压缩质量,建议不低于70%
  23. minInterval: 2000, //最短的两次CRS请求间隔
  24. },
  25. //识别到这个数组中的ID就触发内容
  26. targetIds: [
  27. "6c27e0a1-e4ca-424d-9062-4c8ec676a5ad",
  28. "ec72a9a2-20d5-4b86-82db-05f29e1c0fbb",
  29. "f0bdba05-e610-4d1c-811a-5034ccc0d1f7",
  30. "79014ee9-60c7-4a0c-81ed-0d5889a7ecc9"
  31. ],
  32. showLoading: false,
  33. showLoadingText: "",
  34. },
  35. /** @type {CameraFrameListener} 相机帧回调 */
  36. listener: undefined,
  37. /** @type {HTMLCanvasElement} canvas对象 */
  38. canvas: undefined,
  39. /** @type {boolean} 是否需要持续识别,在点击“识别体验”之后和识别成功之前为true */
  40. runningCrs: undefined,
  41. /** @type {boolean} 当前是否正在进行CRS请求 */
  42. busy: undefined,
  43. /** @type {CrsClient} 负责发起CRS请求的对象 */
  44. crsClient: undefined,
  45. /** @type {number} 最后一次CRS请求的事件,用于判断是否满足最短请求间隔 */
  46. last: undefined,
  47. onLoad: function () {
  48. },
  49. onReady: function () {
  50. if (systemInfo.platform === "devtools") { //开发工具不会触发initdone事件,于是在onReady手动触发
  51. this.onCameraInit();
  52. }
  53. // 获取token
  54. this.queryToken().then(msg => {
  55. console.log('token1')
  56. console.log(msg)
  57. this.data.config.token = msg;
  58. }).catch(err => {
  59. console.info(err);
  60. });
  61. },
  62. showLoading(text) {
  63. this.setData({
  64. showLoading: true,
  65. showLoadingText: text,
  66. });
  67. },
  68. hideLoading() {
  69. this.setData({
  70. showLoading: false,
  71. });
  72. },
  73. //图像识别部分:
  74. onShow: function () {
  75. if (this.listener) this.listener.start(); //页面隐藏时相机帧的监听会自动停止,但恢复展示时不会自动启动,这里手动启动
  76. this.scan()
  77. },
  78. scan: function () {
  79. this.runningCrs = true;
  80. this.setData({
  81. showOverlay: false,
  82. showContent: false,
  83. selectType: SELECT_TYPE.NONE,
  84. });
  85. this.showLoading("识别中");
  86. },
  87. onCameraInit: function () {
  88. //找到canvas对象
  89. const query = wx.createSelectorQuery();
  90. query.select('#capture')
  91. .fields({node: true})
  92. .exec((res) => {
  93. const canvas = res[0].node;
  94. //设置canvas内部尺寸为480*640,frame-size="medium"的设置下相机帧大多是480*640
  95. canvas.width = 480;
  96. canvas.height = 640;
  97. this.canvas = canvas;
  98. this.crsClient = new CrsClient(this.data.config, this.canvas);
  99. //开始监听相机帧
  100. let cameraContext = wx.createCameraContext();
  101. this.listener = cameraContext.onCameraFrame(frame => {
  102. if (!this.canvas) return;
  103. let canvas = this.canvas;
  104. //如果尺寸不匹配,就修改canvas尺寸以适应相机帧
  105. if (canvas.width !== frame.width || canvas.height !== frame.height) {
  106. canvas.width = frame.width;
  107. canvas.height = frame.height;
  108. }
  109. this.queryImage(frame);
  110. });
  111. this.listener.start();
  112. });
  113. },
  114. queryImage: function (frame) {
  115. if (!this.runningCrs || this.busy || !this.crsClient) return;
  116. //最短的两次CRS请求间隔
  117. let now = new Date().getTime();
  118. if (this.last && (now - this.last < this.data.config.minInterval)) return;
  119. this.last = now;
  120. this.busy = true; //如果正在进行CRS请求,就不允许再次请求
  121. this.crsClient.queryImage(frame).then(res => {
  122. if (!this.runningCrs) return; //避免在停止后仍然触发
  123. let result = res.result;
  124. if (!result) return;
  125. if (result.target) {
  126. console.log("识别成功");
  127. this.runningCrs = false;
  128. this.hideLoading();
  129. let base64 = result.target.meta
  130. let web = this.base64_decode(base64)
  131. // 解析跳转链接
  132. wx.navigateTo({
  133. url: '../out/index?web=' + web + '&index=2',
  134. })
  135. // todo: 解析meta中的信息,触发业务逻辑
  136. //如果待触发的id列表中存在识别到的这个id,就触发
  137. if (this.data.targetIds.find(targetId => targetId === result.target.meta)) {
  138. this.onResult(result.target.meta);
  139. }
  140. } else {
  141. console.log("识别失败");
  142. }
  143. this.busy = false;
  144. }).catch(e => {
  145. this.busy = false;
  146. }); //小程序iOS端不支持finally,所以在then和catch里分别设置busy = false
  147. },
  148. onResult: function (target) {
  149. console.log("触发内容!");
  150. console.log(target);
  151. if (target) {
  152. console.log("meta base64:", target);
  153. }
  154. this.setData({
  155. showOverlay: false,
  156. showContent: true,
  157. selectType: SELECT_TYPE.IMAGE,
  158. });
  159. },
  160. //界面:
  161. back: function () {
  162. this.runningCrs = false;
  163. this.setData({
  164. showOverlay: true,
  165. showContent: false,
  166. selectType: SELECT_TYPE.NONE,
  167. });
  168. this.hideLoading();
  169. },
  170. experience: function () {
  171. this.setData({
  172. showOverlay: false,
  173. showContent: true,
  174. selectType: SELECT_TYPE.IMAGE,
  175. });
  176. },
  177. download: function () {
  178. wx.saveImageToPhotosAlbum({
  179. filePath: "/images/namecard.jpg",
  180. success: res => {
  181. wx.showToast({title: "已保存到相册", icon: "none"});
  182. },
  183. fail: res => {
  184. wx.showToast({title: "保存失败", icon: "none"});
  185. },
  186. });
  187. },
  188. selectContent: function (e) {
  189. this.setData({
  190. selectType: e.currentTarget.dataset.contenttype,
  191. });
  192. },
  193. queryToken: function() { // 获取token
  194. return new Promise((resolve, reject) => {
  195. wx.request({
  196. url: 'https://cktest.2weisou.com/meta/ar/ar/getToken',
  197. method: 'get',
  198. data: {},
  199. header: {
  200. 'content-type': 'application/json'
  201. },
  202. success: res => resolve(res.data),
  203. fail: err => reject(err)
  204. });
  205. });
  206. },
  207. base64_decode(input) { // 解码,配合decodeURIComponent使用
  208. var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  209. var output = "";
  210. var chr1, chr2, chr3;
  211. var enc1, enc2, enc3, enc4;
  212. var i = 0;
  213. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  214. while (i < input.length) {
  215. enc1 = base64EncodeChars.indexOf(input.charAt(i++));
  216. enc2 = base64EncodeChars.indexOf(input.charAt(i++));
  217. enc3 = base64EncodeChars.indexOf(input.charAt(i++));
  218. enc4 = base64EncodeChars.indexOf(input.charAt(i++));
  219. chr1 = (enc1 << 2) | (enc2 >> 4);
  220. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  221. chr3 = ((enc3 & 3) << 6) | enc4;
  222. output = output + String.fromCharCode(chr1);
  223. if (enc3 != 64) {
  224. output = output + String.fromCharCode(chr2);
  225. }
  226. if (enc4 != 64) {
  227. output = output + String.fromCharCode(chr3);
  228. }
  229. }
  230. return this.utf8_decode(output);
  231. },
  232. utf8_decode(utftext) { // utf-8解码
  233. var string = '';
  234. let i = 0;
  235. let c = 0;
  236. let c1 = 0;
  237. let c2 = 0;
  238. while (i < utftext.length) {
  239. c = utftext.charCodeAt(i);
  240. if (c < 128) {
  241. string += String.fromCharCode(c);
  242. i++;
  243. } else if ((c > 191) && (c < 224)) {
  244. c1 = utftext.charCodeAt(i + 1);
  245. string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
  246. i += 2;
  247. } else {
  248. c1 = utftext.charCodeAt(i + 1);
  249. c2 = utftext.charCodeAt(i + 2);
  250. string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
  251. i += 3;
  252. }
  253. }
  254. return string;
  255. }
  256. });