index.vue 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <template>
  2. <view class="index-box">
  3. <image src="@/static/img/box-bj.png" mode="scaleToFill"></image>
  4. <view class="box-border-box plr-28">
  5. <view class="save-box fs-42 fc-f text-align-center" @click="toList()">开始结账</view>
  6. </view>
  7. </view>
  8. </template>
  9. <script>
  10. import mqttClient from '@/common/js/mqtt.js'
  11. import ttsManager from '@/common/js/ttsManager.js';
  12. export default {
  13. data() {
  14. return {};
  15. },
  16. async onLoad() {
  17. // #ifdef APP-PLUS
  18. mqttClient.on('message', (data) => {
  19. // console.log('收到MQTT消息 (原始数据)', data); // 首先打印整个data
  20. try {
  21. // 假设 data 本身是 JSON 字符串,将其解析成对象
  22. const parsedData = JSON.parse(data);
  23. console.log('解析后的消息内容:', parsedData);
  24. uni.$emit('mqttEmit',parsedData.amount)
  25. uni.redirectTo({
  26. url: '/pages/index/success?amount=' + parsedData.amount
  27. })
  28. // 收到消息后直接进行语音播报
  29. // ttsManager.speak(parsedData.msg);
  30. } catch (error) {
  31. console.error('解析MQTT消息失败,数据可能不是有效的JSON格式:', error);
  32. // console.log('原始消息内容:', data);
  33. }
  34. });
  35. // 连接服务器
  36. await this.connectToMQTT();
  37. // 检查连接状态
  38. await mqttClient.checkConnection();
  39. //#endif
  40. },
  41. methods: {
  42. toList() {
  43. uni.redirectTo({
  44. url: "/pages/index/order"
  45. })
  46. },
  47. connectToMQTT() {
  48. // 连接MQTT服务器
  49. console.log("连接MQTT服务器------");
  50. try {
  51. mqttClient.on('connected', () => {
  52. console.log('MQTT连接成功,开始订阅主题...');
  53. setTimeout(() => {
  54. this.subscribeToTopic(); // 在连接成功后自动订阅
  55. }, 1000)
  56. });
  57. // 发起连接
  58. mqttClient.connect({
  59. url: 'tcp://mqtt.jhcs888.com:21883',
  60. username: 'hjkj',
  61. password: 'ali2021',
  62. clientId: 'client_' + Math.random().toString(16).substr(2, 8),
  63. keepalive: 60, // 增加心跳间隔,单位秒
  64. clean: false, // 允许断线重连后恢复会话
  65. reconnectPeriod: 1000, // 断开后自动重连的间隔
  66. connectTimeout: 4000 // 连接超时时间(毫秒)
  67. });
  68. console.log('连接成功');
  69. } catch (error) {
  70. console.error('连接失败:', error);
  71. }
  72. },
  73. subscribeToTopic() {
  74. // 订阅主题
  75. try {
  76. mqttClient.subscribe('zsshop128');
  77. console.log('订阅指令已发送');
  78. } catch (error) {
  79. console.error('订阅失败:', error);
  80. }
  81. }
  82. },
  83. };
  84. </script>
  85. <style scoped lang="scss">
  86. .index-box {
  87. width: 100%;
  88. image {
  89. width: 100%;
  90. height: 1122rpx;
  91. margin-bottom: 45rpx;
  92. }
  93. .save-box {
  94. width: 100%;
  95. height: 83rpx;
  96. line-height: 83rpx;
  97. background: linear-gradient(270deg, #1778FD 0%, #4AB6FF 100%);
  98. box-shadow: 0rpx 0rpx 6rpx 0rpx #358AFD;
  99. border-radius: 69rpx;
  100. }
  101. }
  102. </style>