1 Star 0 Fork 33

洪爷007 / cjs

forked from cai / cjs 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
app.js 10.62 KB
一键复制 编辑 原始数据 按行查看 历史
const express = require('express');
const session = require('express-session');
const path = require('path');
const bodyParser = require('body-parser');
//模板引擎
const partials = require('express-partials');
const adminServer = require('./routes/adminServer');
const admin = require('./routes/admin');
const hapNodeJS = require('./routes/hapNodeJS');
const io = require('socket.io')();
const createLineReader = require('./utils/WatchFile');
/*实例化express对象*/
const app = express();
const Mqtt = require('mqtt');
const log = require('yalm');
const HAP = require('hap-nodejs');
const pkgHap = require('./node_modules/hap-nodejs/package.json');
const pkg = require('./package.json');
const config = require('./config.js');
log.setLevel(config.verbosity);
log(pkg.name + ' ' + pkg.version + ' starting');
//session配置
app.use(session({
secret: 'caibojian',
resave: false,
saveUninitialized: true
}));
app.use(bodyParser.json({limit: '50mb'})); // 限制上传5M
app.use(bodyParser.urlencoded({ extended: false , limit: '50mb' }));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(partials());
app.use(function(req, res, next){
// 针对注册会员
res.locals.logined = req.session.logined;
res.locals.userInfo = req.session.user;
// 针对管理员
res.locals.adminlogined = req.session.adminlogined;
res.locals.adminUserInfo = req.session.adminUserInfo;
res.locals.adminNotices = req.session.adminNotices;
// 指定站点域名
res.locals.myDomain = req.headers.host;
next();
});
//监听日志变化
var read = new createLineReader(path.join(__dirname, 'log/app.log'));
//事件监听
app.io = io;
io.on('connection', function(client){
// read.on('line', function(line){
// var arr = line.toString().split(" ");
// if(arr.length>4){
// var returnlog = {
// time: arr[0]+" "+arr[1],
// level: arr[2],
// type: arr[3],
// msg: arr.slice(4)
// }
// client.emit('logChange', returnlog);
// }
// });
client.emit('connect', 'connection');
// 监听发送消息
client.on('send.message', function(msg){
});
// 断开连接时,通知其它用户
client.on('disconnect', function(){
})
})
const mqttStatus = {}; // Holds the payloads of the last-received message, keys are the topics.
const mqttCallbacks = {}; // Holds arrays of subscription callbacks, keys are the topics.
let mqttConnected;
let bridgeListening;
log.info('mqtt trying to connect', config.url);
const mqtt = Mqtt.connect(config.url, {username:'83875',password:'JGKlQdjcMofCNtRYB0YknL=augQ='
,clientId:'11255898',protocolId:'MQTT',protocolVersion:4,keepalive:120,will: {topic: config.name + '/connected', payload: '0', retain: true}});
mqtt.on('connect', () => {
mqttConnected = true;
log.info('mqtt connected ' + config.url);
/* istanbul ignore if */
if (!bridgeListening) {
mqtt.publish(config.name + '/connected', '1', {retain: true});
}
});
/* istanbul ignore next */
mqtt.on('reconnect', () => {
log.info('mqtt reconnect');
});
/* istanbul ignore next */
mqtt.on('offline', () => {
log.info('mqtt offline');
});
/* istanbul ignore next */
mqtt.on('close', () => {
if (mqttConnected) {
mqttConnected = false;
log.info('mqtt closed ' + config.url);
}
});
/* istanbul ignore next */
mqtt.on('error', err => {
log.error('mqtt error ' + err);
});
mqtt.on('message', (topic, payload) => {
payload = payload.toString();
let state;
try {
// Todo - check for json objects in a less nasty way ;)
if (payload.indexOf('{') === -1) {
throw new Error('not an object');
} // We have no use for arrays here.
// We got an Object - let's hope it follows mqtt-smarthome architecture and has an attribute "val"
// see https://github.com/mqtt-smarthome/mqtt-smarthome/blob/master/Architecture.md
state = JSON.parse(payload).val;
} catch (err) {
// Nasty type guessing.
// Do we really need to cast the strings "true" and "false" to bool?
if (payload === 'true') {
state = true;
} else if (payload === 'false') {
state = false;
} else if (isNaN(payload)) {
state = payload;
} else {
state = parseFloat(payload);
}
}
log.debug('< mqtt', topic, state);
mqttStatus[topic] = state;
/* istanbul ignore else */
if (mqttCallbacks[topic]) {
mqttCallbacks[topic].forEach(cb => {
cb(state);
});
}
});
// MQTT subscribe function that provides a callback on incoming messages.
// Not meant to be used with wildcards!
function mqttSub(topic, callback) {
topic = String(topic);
/* istanbul ignore else */
if (typeof callback === 'function') {
if (mqttCallbacks[topic]) {
mqttCallbacks[topic].push(callback);
} else {
mqttCallbacks[topic] = [callback];
log.debug('mqtt subscribe', topic);
mqtt.subscribe(topic);
}
} else {
log.debug('mqtt subscribe', topic);
mqtt.subscribe(topic);
}
}
// MQTT publish function, checks for valid topic and converts payload to string in a meaningful manner.
function mqttPub(topic, payload, options) {
if (!topic || (typeof topic !== 'string')) {
log.error('mqttPub invalid topic', topic);
} else {
if (typeof payload === 'object') {
log.info('object');
payload = JSON.stringify(payload);
} else if (typeof payload !== 'string') {
log.info(topic);
topic = topic.replace(/\//g,'_');
log.info(topic);
const type1 = [0x01,0x00];
const type2 = [0x02,0x00];
const type3 = [0x03,0x00];
const type4 = [0x04,0x00];
const type5 = [0x05,0x00];
const type6 = [0x06,0x00];
const type7 = [0x07,0x00];
const msg = '{"'+topic+'":'+payload+'}';
log.info(msg);
const buf2 = Buffer.from(msg);
type3.push('0x'+buf2.length.toString(16));
const buf1 = Buffer.from(type3);
const totalLength = buf1.length + buf2.length;
const bufA = Buffer.concat([buf1, buf2], totalLength);
// payload = String(payload);
payload = bufA;
}
log.info(payload);
mqtt.publish('$dp', payload, options, err => {
/* istanbul ignore next */
if (err) {
log.error('mqtt publish error ' + err);
}
});
mqtt.publish(topic, payload, options, err => {
/* istanbul ignore next */
if (err) {
log.error('mqtt publish error ' + err);
}
});
}
}
/**
* hap_node setting
*/
log.info('using hap-nodejs version', pkgHap.version);
const uuid = HAP.uuid;
const Bridge = HAP.Bridge;
const Accessory = HAP.Accessory;
const Service = HAP.Service;
const Characteristic = HAP.Characteristic;
/* istanbul ignore next */
if (config.storagedir) {
log.info('using directory ' + config.storagedir + ' for persistent storage');
}
// If storagedir is not set it uses HAP-Nodejs default
// (usually /usr/local/lib/node_modules/homekit2mqtt/node_modules/node-persist/persist)
HAP.init(config.storagedir || undefined);
// Create Bridge which will host all Accessories
const bridge = new Bridge(config.bridgename, uuid.generate(config.bridgename));
// Listen for Bridge identification event
/* istanbul ignore next */
bridge.on('identify', (paired, callback) => {
log('< hap bridge identify', paired ? '(paired)' : '(unpaired)');
callback();
});
// Handler for Accessory identification events
/* istanbul ignore next */
function identify(settings, paired, callback) {
log.debug('< hap identify', settings.name, paired ? '(paired)' : '(unpaired)');
if (settings.topic.identify) {
log.debug('> mqtt', settings.topic.identify, settings.payload.identify);
mqttPub(settings.topic.identify, settings.payload.identify);
}
callback();
}
function newAccessory(settings) {
const acc = new Accessory(settings.name, uuid.generate(settings.id));
if (settings.manufacturer || settings.model || settings.serial) {
acc.getService(Service.AccessoryInformation)
.setCharacteristic(Characteristic.Manufacturer, settings.manufacturer || '-')
.setCharacteristic(Characteristic.Model, settings.model || '-')
.setCharacteristic(Characteristic.SerialNumber, settings.serial || '-');
}
if (!settings.payload) {
settings.payload = {};
}
/* istanbul ignore next */
acc.on('identify', (paired, callback) => {
identify(settings, paired, callback);
});
return acc;
}
const createAccessory = {};
function loadAccessory(acc) {
const file = 'accessories/' + acc + '.js';
log.debug('loading', file);
createAccessory[acc] = require(path.join(__dirname, file))({mqttPub, mqttSub, mqttStatus, log, newAccessory, Service, Characteristic, io});
}
// Load and create all accessories
log.info('loading HomeKit to MQTT mapping file ' + config.mapfile);
const mapping = require(config.mapfile);
let accCount = 0;
Object.keys(mapping).forEach(id => {
const a = mapping[id];
a.id = id;
if (!createAccessory[a.service]) {
loadAccessory(a.service);
}
log.debug('addBridgedAccessory ' + a.service + ' ' + a.name);
bridge.addBridgedAccessory(createAccessory[a.service](a));
accCount++;
});
log.info('hap created', accCount, 'Accessories');
log('hap publishing bridge "' + config.bridgename + '" username=' + config.username, 'port=' + config.port, 'pincode=' + config.c);
bridge.publish({
username: config.username,
port: config.port,
pincode: config.c,
category: Accessory.Categories.OTHER
});
bridge._server.on('listening', () => {
bridgeListening = true;
mqtt.publish(config.name + '/connected', '2', {retain: true});
log('hap Bridge listening on port', config.port);
});
bridge._server.on('pair', username => {
log('hap paired', username);
});
/* istanbul ignore next */
bridge._server.on('unpair', username => {
log('hap unpaired', username);
});
/* istanbul ignore next */
bridge._server.on('verify', () => {
log('hap verify');
});
log.info(createAccessory);
/*指定路由控制*/
app.use('/admin', admin);
app.use('/admin', adminServer);
app.use('/hapnodejs', function(req, res, next) {
req.accessories = mapping;
next();
});
app.use('/hapnodejs', hapNodeJS);
module.exports = app;
NodeJS
1
https://gitee.com/senhuxi/cjs.git
git@gitee.com:senhuxi/cjs.git
senhuxi
cjs
cjs
v3.0

搜索帮助