Files
SmartPetFeeder_STM32/wex_small/app.js

218 lines
5.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// app.js
const mqtt = require('./utils/mqtt.min.js');
const { MQTT_CONFIG } = require('./utils/mqtt.config.js');
App({
globalData: {
mqttClient: null,
isMQTTConnected: false,
// 自定义导航栏相关数据
navBarHeight: 0, // 整个自定义导航栏总高度
menuBottom: 0, // 标题栏上下边距
menuHeight: 0, // 胶囊按钮高度
statusBarHeight: 0 // 状态栏高度
},
onLaunch() {
// 计算导航栏高度
this.calcNavBarInfo();
// 小程序启动时初始化MQTT连接
this.initMQTT();
},
/**
* 计算导航栏高度信息
*/
calcNavBarInfo() {
try {
const systemInfo = wx.getSystemInfoSync();
const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
// 核心计算公式
const statusBarHeight = systemInfo.statusBarHeight;
const menuBottom = menuButtonInfo.top - statusBarHeight;
const navBarHeight = menuBottom * 2 + menuButtonInfo.height + statusBarHeight;
this.globalData.statusBarHeight = statusBarHeight;
this.globalData.navBarHeight = navBarHeight;
this.globalData.menuBottom = menuBottom;
this.globalData.menuHeight = menuButtonInfo.height;
console.log('导航栏信息:', {
statusBarHeight,
menuBottom,
menuHeight: menuButtonInfo.height,
navBarHeight
});
} catch (error) {
console.error('计算导航栏信息失败:', error);
// 使用默认值
this.globalData.statusBarHeight = 20;
this.globalData.navBarHeight = 44;
this.globalData.menuBottom = 4;
this.globalData.menuHeight = 32;
}
},
/**
* 初始化MQTT连接
*/
initMQTT() {
const that = this;
try {
// 构建MQTT连接URL微信小程序使用wxs协议
const url = `wxs://${MQTT_CONFIG.host}:${MQTT_CONFIG.port}/mqtt`;
console.log('[MQTT] 正在连接服务器...', url);
// 创建MQTT客户端
const client = mqtt.connect(url, {
clientId: MQTT_CONFIG.clientId,
username: MQTT_CONFIG.username,
password: MQTT_CONFIG.password,
keepalive: MQTT_CONFIG.keepalive,
reconnectPeriod: MQTT_CONFIG.reconnectPeriod,
connectTimeout: MQTT_CONFIG.connectTimeout,
will: MQTT_CONFIG.will
});
// 连接成功
client.on('connect', () => {
console.log('[MQTT] 连接成功');
that.globalData.isMQTTConnected = true;
that.globalData.mqttClient = client;
// 订阅主题
that.subscribeTopics(client);
// 发布上线消息
client.publish('device/status', JSON.stringify({
device: 'SmartPetFeeder',
status: 'online',
timestamp: new Date().toISOString()
}), { qos: 1, retain: true });
});
// 接收消息
client.on('message', (topic, message) => {
console.log(`[MQTT] 收到消息 - Topic: ${topic}, Message: ${message.toString()}`);
// 将消息分发到各个页面
that.handleMQTTMessage(topic, message);
});
// 连接断开
client.on('disconnect', () => {
console.log('[MQTT] 连接断开');
that.globalData.isMQTTConnected = false;
});
// 错误处理
client.on('error', (error) => {
console.error('[MQTT] 连接错误:', error);
that.globalData.isMQTTConnected = false;
});
// 重新连接
client.on('reconnect', () => {
console.log('[MQTT] 正在重新连接...');
});
} catch (error) {
console.error('[MQTT] 初始化失败:', error);
}
},
/**
* 订阅MQTT主题
*/
subscribeTopics(client) {
if (!client || !client.connected) {
console.error('[MQTT] 客户端未连接,无法订阅主题');
return;
}
MQTT_CONFIG.topics.forEach(topic => {
client.subscribe(topic, { qos: MQTT_CONFIG.qos }, (err) => {
if (err) {
console.error(`[MQTT] 订阅主题失败: ${topic}`, err);
} else {
console.log(`[MQTT] 订阅主题成功: ${topic}`);
}
});
});
},
/**
* 处理MQTT消息
*/
handleMQTTMessage(topic, message) {
// 将消息发送到当前显示的页面
const pages = getCurrentPages();
if (pages.length > 0) {
const currentPage = pages[pages.length - 1];
if (currentPage && typeof currentPage.onMQTTMessage === 'function') {
currentPage.onMQTTMessage(topic, message);
}
}
},
/**
* 发布MQTT消息
*/
publishMQTT(topic, message, options = {}) {
const client = this.globalData.mqttClient;
if (!client || !client.connected) {
console.error('[MQTT] 客户端未连接,无法发布消息');
return false;
}
const defaultOptions = {
qos: MQTT_CONFIG.qos,
retain: false
};
const publishOptions = { ...defaultOptions, ...options };
try {
client.publish(topic, JSON.stringify(message), publishOptions);
console.log(`[MQTT] 发布消息成功 - Topic: ${topic}`, message);
return true;
} catch (error) {
console.error(`[MQTT] 发布消息失败 - Topic: ${topic}`, error);
return false;
}
},
/**
* 断开MQTT连接
*/
disconnectMQTT() {
const client = this.globalData.mqttClient;
if (client && client.connected) {
// 发布离线消息
client.publish('device/status', JSON.stringify({
device: 'SmartPetFeeder',
status: 'offline',
timestamp: new Date().toISOString()
}), { qos: 1, retain: true }, () => {
client.end();
this.globalData.isMQTTConnected = false;
console.log('[MQTT] 已断开连接');
});
}
},
onHide() {
// 小程序隐藏时可以选择断开连接(根据实际需求决定)
// this.disconnectMQTT();
},
onError(msg) {
console.error('[App] 错误:', msg);
}
})