Commit d168d1dd by 汤文兵

/data/ugenIOT/Cloud/Release/publicComponent

parents
const ProviderManager = require('iot-cloud-core').BASE.ProviderManager;
const Core = require("./core/CoreProvider")
const Data = require("./data/DataProvider")
class PublicManager extends ProviderManager{
constructor(){
super();
this.put("Core", Core);
this.put("Data", Data);
}
}
module.exports = new PublicManager();
\ No newline at end of file
const Provider = require('iot-cloud-core').BASE.Provider;
const db_user = require('./model/mysql/User');
const db_device = require('./model/mysql/Device');
const db_user_device = require('./model/mysql/User_device');
const dao_user = require('./dao/UserDao');
const dao_device = require('./dao/DeviceDao');
const controller_user = require('./controller/UserController');
const controller_device = require('./controller/DeviceController');
const controller_wx = require('./controller/WXController');
const controller_product = require('./controller/ProductController');
const controller_app = require('./controller/AppController');
const public_class = require('./public/Public');
class CoreProvider extends Provider{
constructor(dbManager){
super("core",dbManager);
this.registerModel(db_user);
this.registerModel(db_device);
this.registerModel(db_user_device);
this.registerDao("user",dao_user);
this.registerDao("device",dao_device);
this.registerController("user",controller_user);
this.registerController("device",controller_device);
this.registerController("wx",controller_wx);
this.registerController("product",controller_product);
this.registerController("app",controller_app);
this.setPublicClass(public_class);
}
}
module.exports = CoreProvider;
\ No newline at end of file
class Role{
constructor(){
this._role = new Map();
this._repeatCheck = new Array();
this._roleValue = new Map();
this._formalRole = new Map();
}
setDao(dao){
this._dao = dao;
}
addRole(action,...role){
if(this._repeatCheck.includes(action)){
console.error(`[RoleManager]action:${action} is exists`);
}else{
this._repeatCheck.push(action);
role.forEach((value)=>{
if(this._role.has(value)){
this._role.get(value).push(action);
}else{
this._role.set(value,Array.of(action));
}
});
this._repeatCheck.forEach((role,index)=>{
this._roleValue.set(role,Math.pow(2,index));
});
this._role.forEach((value,key)=>{
let v = 0;
value.forEach((action)=>{
v += parseInt(this._roleValue.get(action),10);
})
this._formalRole.set(key,v)
});
}
}
async checkRole(data,action){
let res=await this._dao.get('device').findRoleByUserId({user_id:data.user_id,device_id:data.device_id});
if (res) {
for (let i = 0; i < action.length; i++) {
if(this._formalRole.has(res) && this._roleValue.has(action[i])){
if(this._formalRole.get(res) & this._roleValue.get(action[i])){
return true;
}
}
}
}
return false;
}
}
module.exports = Role;
\ No newline at end of file
const request = require('request');
const crypto = require('crypto');
const ServiceManager = require('iot-cloud-fs');
const url = 'https://api.weixin.qq.com/';
class WXSDK{
constructor(params) {
checkKeyExists(params, "appid");
this.appid = params.appid;
}
async auth(params){
checkKeyExists(params, "code");
let wxInfo = await this.getInfo();
if(wxInfo.isComponent){
return this.authComponent(params,wxInfo);
}
return this.send({ url: 'sns/oauth2/access_token?appid=' + wxInfo.wxAppId + '&secret=' + wxInfo.wxSecret + '&code=' + params.code + '&grant_type=authorization_code' });
}
authComponent(params,wxInfo){
checkKeyExists(params, "code");
return this.send({ url: 'sns/oauth2/component/access_token?appid=' + wxInfo.wxAppId + '&code=' + params.code + '&grant_type=authorization_code&component_appid=' + wxInfo.componentAppId + '&component_access_token=' + wxInfo.componentAccessToken });
}
getUserinfo(params) {
checkKeyExists(params, "openid");
return this.send({ url: 'sns/userinfo?access_token=' + params.access_token + '&openid=' + params.openid + '&lang=zh_CN' });
}
bindDevice(params){
checkKeyExists(params, "openid", "device_id", "ticket");
let data = {
"ticket": params.ticket,
"device_id": params.device_id,
"openid": params.openid
};
return this.send({ url: 'device/bind?access_token=' + params.access_token,type:'post',data:data });
}
unBind(params){
checkKeyExists(params, "openid", "device_id", "ticket");
let data = {
"ticket": params.ticket,
"device_id": params.device_id,
"openid": params.openid
};
return this.send({ url: 'device/unbind?access_token=' + params.access_token,type:'post',data:data });
}
compelUnbind(params){
checkKeyExists(params, "openid", "device_id");
let data = {
"device_id": params.device_id,
"openid": params.openid
};
return this.send({ url: 'device/compel_unbind?access_token=' + params.access_token,type:'post',data:data });
}
async getInfo(){
let info = await ServiceManager.execute("WXToken","getWXInfo",{
appId:this.appid
});
return {
accessToken:info.accessToken,
jsapiToken:info.jsapiToken,
isComponent:info.authType !== 1,
wxAppId:info.wxAppId,
wxSecret:info.wxSecret,
componentAppId:info.componentAppId,
componentAccessToken:info.componentAccessToken
};
}
send(params) {
checkKeyExists(params, "url");
return new Promise((r,j)=>{
let data;
let p;
if (params.type === 'post') {
p = request.post(url + params.url);
if (params, "data")
p.json(params.data);
}else{
p = request.get(url + params.url);
}
p.on('response', (response) => {
if (response.statusCode !== 200)
j(response);
}).on('data', (data) => {
r(JSON.parse(data));
})
.on('error', (error) => {
j(error);
});
});
}
createNonceStr() {
return Math.random().toString(36).substr(2, 15);
};
createTimestamp() {
return parseInt(new Date().getTime() / 1000) + '';
};
raw(args) {
let keys = Object.keys(args);
keys = keys.sort()
let newArgs = {};
keys.forEach(function (key) {
newArgs[key.toLowerCase()] = args[key];
});
let string = '';
for (let k in newArgs) {
string += '&' + k + '=' + newArgs[k];
}
string = string.substr(1);
return string;
};
async getSign(params) {
checkKeyExists(params, "url");
let wxInfo = await this.getInfo();
let ret = {
jsapi_ticket: wxInfo.jsapiToken,
nonceStr: this.createNonceStr(),
timestamp: this.createTimestamp(),
url: params.url
};
let string = this.raw(ret);
let sha1 = crypto.createHash('sha1');
sha1.update(string);
ret.signature = sha1.digest('hex');
delete ret.jsapi_ticket;
return ret;
};
}
function checkKeyExists(map, ...keys) {
for(let key of keys){
if (!(key in map))
throw new ParamsError(key + " is undefined");
}
}
module.exports = WXSDK;
\ No newline at end of file
module.exports = {
sign:{
Format:'JSON',
Version:'2017-04-20',
SignatureMethod:'HMAC-SHA1',
SignatureVersion:'1.0',
AccessKeyId:'LTAINKAyUzvMlgPa',
RegionId:'shanghai',
Action:'Pub',
// sign.Action='RegistDevice';
ProductKey:'CKurLGS9xnF'
}
}
/**
* DeviceController.js
* Version: 0.1
* User: felix
* Date: 2018-03-13
* Copyright(c) 2018. U-GEN Tech.Co,Ltd. All Rights Reserved.
* Product 产品
*/
const ControllerBase = require('iot-cloud-core').BASE.ControllerBase;
const NoAuth = require('iot-cloud-core').BASE.ControllerDecorator.NoAuth;
/**
* @class
*/
class AppController extends ControllerBase{
/**
* 获取当前应用的信息,版本号
* @example
* {
* url:"http://iot.ugen.net",
* min:"1.0.0",
* max:"1.0.1"
* }
*
* error
* 20011 缺少参数os
* 20012 没有找到相关系统的版本
*/
@NoAuth
async getVersionAction(data){
let os = data.params.os;
let info = await this.public.data.getOption("app");
if(os === undefined)
this.error("not found param 'os'",20011);
if(info !== null){
if( info.value.hasOwnProperty(os.toLowerCase()))
return info.value[os.toLowerCase()];
}
this.error(`not found os info '${os.toLowerCase()}'`,20012);
}
}
module.exports = AppController;
\ No newline at end of file
/**
* DeviceController.js
* Version: 0.2
* User: zym
* Date: 2017-09-05
* Copyright(c) 2017. U-GEN Tech.Co,Ltd. All Rights Reserved.
* public method
*/
const ControllerBase = require('iot-cloud-core').BASE.ControllerBase;
const NoAuth = require('iot-cloud-core').BASE.ControllerDecorator.NoAuth;
const moment=require('moment');
/**
* @class
*/
class DeviceController extends ControllerBase{
constructor(){
super();
}
/**
* getList 获取设备列表
* @example
let params = {
parent_id:0,
product_id:0,
start_id:0,
number:10
}
* @param {number} parent_id - 父设备id
* @param {string} product_id - 设备产品id
* @param {number} start_id - 开始id,默认0
* @param {number} number - 每页条数 默认10
*/
async getListAction(data){
let product=this.getConfig();
let params=data.params;
params.user_id=data.user.uid;//获取userid
if (params.product_id){
if(typeof params.product_id=='object') {
for (let i = 0; i < params.product_id.length; i++) {
params.product_id[i]=product[params.product_id[i]];
}
}else{
params.product_id=product[params.product_id]
}
}
let res = await this.dao.get('device').findList(params);
return res;
}
/**
* getInfo 获取设备信息
* @example
let params = {
device_id:1
}
* @param {number} device_id - 设备id
*/
async getInfoAction(data){
data.params.user_id=data.user.uid;
data.params.status=1;
let res = await this.dao.get('device').findInfo(data.params);
if (res) {
return res;
}else{
return {msg:"device is undefined"};
}
}
/**
* setInfo 修改设备信息(覆盖)
* @example
let params = {
device_id:1,
info:{'a':1}
}
* @param {number} device_id - 设备id
* @param {json} info - 要存储的信息(JSON格式)
*/
async setInfoAction(data){
let res =await this.dao.get('device').setDeviceInfoCover({
id:data.params.device_id,
info:data.params.info
})
return res;
}
/**
* setUserDeviceInfo 修改userdevice信息(覆盖)
* @example
let params = {
device_id:1,
info:{'a':1}
}
* @param {number} device_id - 设备id
* @param {json} info - 要存储的信息(JSON格式)
*/
async setUserDeviceInfoAction(data){
let res =await this.dao.get('device').setUserDeviceInfoCover({
device_id:data.params.device_id,
user_id:data.user.uid,
info:data.params.info
})
return res;
}
/**
* getUserDeviceInfo 获取userdevice信息
* @example
let params = {
device_id:1
}
* @param {number} device_id - 设备id
*/
async getUserDeviceInfoAction(data){
let res =await this.dao.get('device').findUserDeviceInfo({
device_id:data.params.device_id,
user_id:data.user.uid
})
return res;
}
/**
* getUsers 设备绑定的用户信息
* @example
let params = {
device_id:1
}
* @param {number} device_id - 设备id
*/
async getUsersAction(data){
let res = await this.dao.get('device').findUsers(data.params);
return res;
}
/**
* setName 设置设备名称(管理员权限)
* @example
let params = {
device_id:1,
device_name:'我的设备',
}
* @param {number} device_id - 设备id
* @param {string} device_name - 设备名称
*/
async setNameAction(data){
if(!await this.public.core.checkRole({user_id:data.user.uid,device_id:data.params.device_id},"admin")){
this.error('Wrong role',10002);
}
data.params.user_id=data.user.uid;
let res = await this.dao.get('device').updateName(data.params);
if (res) {
return {success:res};
}
this.error("fail to update",30300);
}
/**
* setNickname 修改设备昵称
* @example
let params = {
device_id:1,
nickname:'我的设备'
}
* @param {number} device_id - 设备id
* @param {string} nickname - 设备昵称
*/
async setNicknameAction(data){
data.params.user_id=data.user.uid;
let res = await this.dao.get('device').updateNickname(data.params);
if (res) {
return {success:res};
}
this.error("fail to update",30500);
}
/**
* bind 绑定设备
* @example
let params = {
device_id:1,
mac:'acbdqf32aa',
product_id:'B001',
nickname:'我的设备'
}
* @param {string} device_id - 设备id与mac必须存在一个
* @param {string} mac - 设备mac地址与id必须存在一个
* @param {string} product_id - 设备产品id
* @param {string} nickname - 设备昵称
*/
async bindAction(data){
data.params.user=data.user;
let bind = await this.public.core.bindDevice(data.params,true);
if (bind) {
return {success:true};
}
this.error('set failed',30500);
}
//绑定蓝牙设备
/**
* newBind 绑定设备
* @example
let params = {
device_id:1,
mac:'acbdqf32aa',
product_id:'B001',
nickname:'我的设备'
}
* @param {string} device_id - 设备id与mac必须存在一个
* @param {string} mac - 设备mac地址与id必须存在一个
* @param {string} product_id - 设备产品id
* @param {string} nickname - 设备昵称
*/
async newBindAction(data){
data.params.user=data.user;
let bind = await this.public.core.bindDevice(data.params,false);
if (bind) {
return {success:true};
}
this.error('set failed',30500);
}
/**
* unbind 根据设备编号解绑用户设备
* @example
let params = {
device_id:1
}
* @param {number} device_id - 设备编号
*/
async unbindAction(data){
data.params.user_id=data.user.uid;
let bind = await this.public.core.delBindByDeviceIdAndUserId(data.params);
if (bind) {
return bind;
}
this.error("fail to update",30500);
}
/**
* removeUser 解绑设备(管理员)
* @example
let params = {
device_id:1
}
* @param {number} device_id - 设备id与mac必须存在一个
*/
async removeUserAction(data){
if(!await this.public.core.checkRole({user_id:data.user.uid,device_id:data.params.device_id},"admin")){
this.error('Wrong role',10002);
}
let res = await this.public.core.delBindByDeviceIdAndUserId(data.params);
if (res) {
return res;
}
this.error("fail to update",30500);
}
@NoAuth
async getVersionAction(data){
switch(data.params.type){
case 'ios':
return await this.public.core.getVersion({type:{'value.ios':1}});
case 'android':
return await this.public.core.getVersion({type:{'value.android':1}});
}
this.error('type is undefined',30010)
}
@NoAuth
async setVersionAction(data){
let params={};
switch(data.params.type){
case 'ios':
params={
key:this.getConfig().wxAppId,
'value.ios':{
version:data.params.version,
url:data.params.url
}
}
break;
case 'android':
params={
key:this.getConfig().wxAppId,
'value.android':{
version:data.params.version,
url:data.params.url
}
}
break;
}
console.log()
if (!params.key) {
this.error('type is undefined',30010)
}
let res = await this.public.core.setVersion(params);
return res;
}
}
module.exports = DeviceController;
\ No newline at end of file
/**
* DeviceController.js
* Version: 0.1
* User: felix
* Date: 2018-03-13
* Copyright(c) 2018. U-GEN Tech.Co,Ltd. All Rights Reserved.
* Product 产品
*/
const ControllerBase = require('iot-cloud-core').BASE.ControllerBase;
const NoAuth = require('iot-cloud-core').BASE.ControllerDecorator.NoAuth;
/**
* @class
*/
class ProductController extends ControllerBase{
/**
* 获取产品信息
* @example
* {
"min":{
"download":"http://192.168.2.184:8010/custom01.wgtu",
"support":{
"ios":"0.0.1",
"andoird":"0.0.1"
},
"ver":"0.0.1"
},
"now":{
"download":"http://192.168.2.184:8010/custom01.wgtu",
"support":{
"ios":"1.0.0",
"andoird":"1.0.0"
},
"ver":"1.0.0"
}
}
* @param {number} pid - 产品id
*/
@NoAuth
async getInfoByIdAction(data){
let info = await this.public.data.getOption(`pid_${data.params.pid}`);
if(info !== null){
return info.value;
}
this.error("not find info",20010);
}
}
module.exports = ProductController;
\ No newline at end of file
const ControllerBase = require('iot-cloud-core').BASE.ControllerBase;
const NoAuth = require('iot-cloud-core').BASE.ControllerDecorator.NoAuth;
const ComponentManager = require('iot-cloud-core').BASE.ComponentManager;
const log = require('iot-cloud-core').LOG;
const UAformater = require('ua-format-js').UAFormat();
const moment = require('moment');
const crypto = require('crypto');
const Calculation = require('./public/Calculation');
const WXAuth = require('./public/WXAuth');
/**
* @class
*/
class UserController extends ControllerBase{
afterInit(){
this.auth={};
this.auth.WXAuth=new WXAuth({appId:this.getConfig().wxThirdAppId});
}
/**
* reg 注册用户
* @example
let params = {
username:"用户",
pwd:"123456"
}
* @param {string} username - 用户账号
* @param {string} pwd - 密码
*/
@NoAuth
async regAction(data){
return await this.public.core.userReg(data,data.params.username,data.params.pwd,data.params.clienId);
}
/**
* login 用户登录
* @example
let params = {
username:"用户",
pwd:"123456"
}
* @param {string} username - 用户账号
* @param {string} pwd - 密码
*/
@NoAuth
async loginAction(data){
let user = await this.dao.get('user').searchByName(data.params);
if(!user)
this.error("username not exists",20200);
if(Calculation.generatePassword(data.params.pwd,user.salt) != user.password)
this.error("password error",20201);
let ua = UAformater.setUA(data.header['user-agent']).getResult();
let params={
id:user.id,
mobiletype:ua.os.name?ua.os.name:'null',
version:ua.os.version?ua.os.version:'null',
useragent:ua?ua:'null'
}
if (data.params.clienId) {
params.clienId=data.params.clienId;
}
let res = await this.dao.get('user').updateUserInfoId(params);
let token = data.auth.sign(Calculation.signParams(user.id));
return {
"username":user.username,
"nickname":user.nickname,
"head":user.head,
"utoken":token
};
return res;
}
/**
* verLogin 自动登录
* @example
* header:{
token:"JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjEwLCJpYXQiOjE1MDMzNjkyNzksImV4cCI6MTUwNDIzMzI3OX0.iaW4QzyZAjiZdwI5a0aVuIRsAA0QnmxGweQQL5-yyes"
}
*/
async verLoginAction(data){
let user = await this.dao.get('user').findUserById({"uid":data.user.uid});
if(!user)
this.error("select failed",20300);
let logintime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
let ua = UAformater.setUA(data.header['user-agent']).getResult();
let params={
id:user.id,
mobiletype:ua.os.name?ua.os.name:'null',
version:ua.os.version?ua.os.version:'null',
useragent:ua?ua:'null'
}
if (data.params.clienId) {
params.clienId=data.params.clienId;
}
let res = await this.dao.get('user').updateUserInfoId(params);
let token = data.auth.sign(Calculation.signParams(user.id));
return {
"username":user.username,
"nickname":user.nickname,
"head":user.head,
"loginTime":logintime,
"utoken":token,
};
}
async getInfoAction(data){
let user = await this.dao.get('user').findUserById({"uid":data.user.uid});
if(!user)
this.error("select failed",20300);
return {
"username":user.username,
"nickname":user.nickname,
"head":user.head
};
}
/**
* resetPwd 重置密码,暂时没有短信验证
* @example
let params = {
pwd:"123456"
}
* @param {string} pwd - 重置的密码?
*/
async resetPwdAction(data){
let user = await this.dao.get('user').findUserById({"uid":data.user.uid});
if(!user)
this.error("username is undefined",20400);
//验证码验证,暂时默认通过
let params = {
"id":user.id,
"pwd":data.params.pwd
};
let res = await this.dao.get('user').updatePwdById(params);
return res;
}
/**
* resetPwd 设置密码,暂时没有短信验证
* @example
let params = {
pwd:"123456"
}
* @param {string} pwd - 重置的密码?
*/
async setPwdAction(data){
let user = await this.dao.get('user').findUserById({"uid":data.user.uid});
if(!user)
this.error("username is undefined",20500);
//验证密码是否正确
if(Calculation.generatePassword(data.params.old_pwd,user.salt) == user.password){
let newPwd = Calculation.generatePassword(data.params.new_pwd,user.salt);
if(newPwd == user.password)
this.error("new pwd is same with old pwd",20501)
let params = {
"id":user.id,
"pwd":newPwd
};
let res = await this.dao.get('user').updatePwdById(params);
return res;
}else{
this.error("password is error",20502);
}
}
@NoAuth
async sdsAuthAction(data){
let user=data.auth.verify(data);
let userinfo=await this.dao.get('user').findUserById({uid:user.uid});
let res={
sourceData:true,
data:{
"code": "1000",//1000是成功,其它是失败
    "msg": "成功",//错误提示
    "description": "",//错误详细描述
    "data": {//结果数据
        "userId":userinfo.id, //必填
        "userNick":userinfo.nickname //必填
    }
}
};
return res;
}
async setInfoAction(data){
data.params.user_id=data.user.uid;
let userinfo=await this.dao.get('user').setUserNameAndHeadAndInfo(data.params);
if (userinfo[0]) {
return 'success';
}
return 'set fail';
}
@NoAuth
async sds_loginAction(data){
let user = {
username:data.params.username,
nickname:'',
head:'',
info:{},
salt:Math.random().toString(36).substr(2, 6)
};
let ua = UAformater.setUA(data.header['user-agent']).getResult();
user.info.mobiletype=ua.os.name?ua.os.name:'null';
user.info.version=ua.os.version?ua.os.version:'null';
user.info.useragent=ua?ua:'null';
if (data.params.mobile) {
user.mobile=data.params.mobile;
}
if (data.params.clienId) {
user.info.clienId=data.params.clienId;
}
let res = await this.dao.get('user').createSimpleUser(user);
res.utoken=data.auth.sign(Calculation.signParams(res.id));
return res;
}
@NoAuth
async login_simpleAction(data){
let user = {
username:data.params.username,
nickname:'',
head:'',
info:{},
salt:Math.random().toString(36).substr(2, 6)
};
let ua = UAformater.setUA(data.header['user-agent']).getResult();
user.info.mobiletype=ua.os.name?ua.os.name:'null';
user.info.version=ua.os.version?ua.os.version:'null';
user.info.useragent=ua?ua:'null';
if (data.params.mobile) {
user.mobile=data.params.mobile;
}
if (data.params.clienId) {
user.info.clienId=data.params.clienId;
}
let res = await this.dao.get('user').createSimpleUser(user);
res.utoken=data.auth.sign(Calculation.signParams(res.id));
return res;
}
@NoAuth
async thirdLoginAction(data){
let type=data.params.type;
let userParams={};
if (type=='WX') {
userParams=await this.auth.WXAuth.wxLogin(data);
if (userParams.errcode) {
this.error(userParams.errmsg,userParams.errcode)
}
userParams.info={};
}else if (type=='QQ') {
let head=data.params.data.figureurl?data.params.data.figureurl:data.params.data.figureurl_qq_1;
userParams={
username:data.params.data.openId,
nickname:data.params.data.nickname,
head:head.substring(0,head.lastIndexOf("/")),
info:{
gender:data.params.data.gender,
city:data.params.data.city
}
}
}
let ua = UAformater.setUA(data.header['user-agent']).getResult();
userParams.salt=Math.random().toString(36).substr(2, 6);
userParams.info.mobiletype=ua.os.name?ua.os.name:'null';
userParams.info.version=ua.os.version?ua.os.version:'null';
userParams.info.useragent=ua?ua:'null';
if (data.params.clienId) {
userParams.info.clienId=data.params.clienId;
}
let newUser = await this.dao.get("user").createWXUser(userParams);
newUser.utoken = data.auth.sign(Calculation.signParams(newUser.id));
return newUser;
}
// 清除用户数据,cid 登出 http://116.62.143.3:10080/iot-v2/iot-cloud-app/issues/1
async logoutAction(data){
let update={
user_id:data.user.uid,
key:['clienId']
}
let res = await this.public.core.logout(update);
if (res) {
return {success:true}
}
return {msg:'update failed'}
}
@NoAuth
async getUserLogAction(data){
let res=await this.dao.get("user").getUserLog(data.params);
return res;
}
}
module.exports = UserController;
\ No newline at end of file
const ControllerBase = require('iot-cloud-core').BASE.ControllerBase;
const NoAuth = require('iot-cloud-core').BASE.ControllerDecorator.NoAuth;
const ComponentManager = require('iot-cloud-core').BASE.ComponentManager;
const UAformater = require('ua-format-js').UAFormat();
const WXSDK = require('../Util/WXSDK');
const Calculation = require('./public/Calculation');
/**
* @class
*/
class WXController extends ControllerBase{
/**
* login 微信登录
* @example
let params = {
code:"adsfaseipojqienm,lznjbibpijoewkqnmgnklskd",
url:"https://iot.u-gen.net/aj2017/view/"
}
* @param {string} product_id - 微信code
* @param {string} start_id - 授权地址url
*/
@NoAuth
async loginAction(data){
let user = await this.public.core.wxLogin(data);
if (user.errcode) {
this.error(user.errmsg,user.errcode)
}
return user;
}
/**
* getSign 获取微信签名
* @example
let params = {
url:"https://iot.u-gen.net/aj2017/view/"
}
* @param {string} start_id - 授权地址url
*/
@NoAuth
async getSignAction(data){
let params = {
url:data.params.url
}
let sign = this.public.core.getSign(params);
return sign;
}
}
WXController.OPTIONS = {
"WX_CONFIG":"wx_config"
}
module.exports = WXController;
\ No newline at end of file
const request = require('request');
const crypto = require('crypto');
const moment = require('moment');
const config = require('./Aliconfig');
// const url='https://iot.aliyuncs.com/?';
const url = 'https://iot.cn-shanghai.aliyuncs.com/?';
class alisignSDK{
constructor(data) {
this.AccessKeySecret = data.key+"&";
this.sign=config.sign;
}
getsign(data){
var that=this;
this.sign.Timestamp=moment().toISOString();//请求时间戳
this.sign.SignatureNonce=parseInt(Math.random()*10000000000000);//唯一随机数
this.sign.TopicFullName=data.TopicFullName;//消息发送目的topic名字
this.sign.MessageContent=data.MessageContent;//发送的消息
let promise = new Promise(function(resolve, reject) {
try{
let keys = Object.keys(that.sign);//将参数转换为数组
keys = keys.sort();//按字典顺序排序
let newArgs = {};
keys.forEach(function (key) {//遍历数组 把参数内的字符串作为URI 组件进行编码其中的某些字符将被十六进制的转义序列进行替换
newArgs[encodeURIComponent(key)] = encodeURIComponent(that.sign[key]);//参考https://help.aliyun.com/document_detail/30128.html
});
let string = '';
for (let k in newArgs) {//将数组拼接为字符串参数之间用&号隔开参数名和值之间用=
string +='&' + k + '=' + newArgs[k];
}
string = string.substr(1);//去掉第一位的符号 从下标为1的地方开始截取字符串
let StringToSign= "GET" +"&"+ encodeURIComponent("/") + "&" + encodeURIComponent(string);//使用上一步构造的规范化字符串按照规则构造用于计算签名的字符串
let sign=crypto.createHmac('sha1', that.AccessKeySecret).update(StringToSign).digest().toString('base64');//计算签名HMAC值 计算方法是SHA1
let context=string+"&Signature="+encodeURIComponent(sign);//按照Base64编码规则把上面的HMAC值编码成字符串,即得到签名值(Signature)
request(url+context, function (error, res, body) {//request发送请求
if(error){
reject({status:0,msg:error.message});
}else if(res.statusCode >= 200 && res.statusCode < 300){
resolve(body);
}else{
reject({status:res.statusCode,msg:body});
}
})
}catch(e){
console.log(e)
reject(e)
}
})
return promise;
}
// getSend(v) {
// return this.send({json:v});
// //return this.send({json:v,type: 'get'});
// }
// postSend(v) {
// return this.send({json:v,type: 'post'});
// }
// send(params) {
// // let promise = new Promise(function(resolve, reject) {
// // request(url+params, function (error, response, body) {
// // if (error){
// // console.log(error)
// // reject(error);
// // }
// // resolve(body);
// // })
// // })
// // return promise;
// }
}
module.exports = alisignSDK;
\ No newline at end of file
const crypto = require('crypto');
class Calculation{
static signParams(id){
return {
uid:id
}
}
static getSalt(){
return Math.random().toString(36).substr(2, 6);
}
static generatePassword(password, salt) {
var md5 = crypto.createHash('md5');
md5.update(password + salt);
return md5.digest('hex');
}
}
module.exports = Calculation;
\ No newline at end of file
class ThirdAuth{
async Auth(data){
return 'undefined';
}
async getUserInfo(data){
return 'undefined';
}
}
module.exports = ThirdAuth;
\ No newline at end of file
const ThirdAuth=require('./ThirdAuth');
const Calculation = require('./Calculation');
const LOG = require('iot-cloud-core').LOG;
const WXSDK = require('../../Util/WXSDK');
const UAformater = require('ua-format-js').UAFormat();
class WxAuth extends ThirdAuth{
constructor(data) {
super()
this.WXSDK = new WXSDK({appid:data.appId});
}
async wxLogin(data){
let wxParams = {
code:data.params.code,
appid:data.appid
}
let auth=await this.WXSDK.auth(wxParams);
if (auth.errcode) {
LOG.error(auth)
return auth;
}
let uParams = {
appid:data.appid,
access_token:auth.access_token,
openid:auth.openid
};
let wxUserInfo =await this.WXSDK.getUserinfo(uParams);
let userParams = {
username: auth.openid,
nickname: wxUserInfo.nickname,
head: wxUserInfo.headimgurl,
salt:Math.random().toString(36).substr(2, 6)
}
return userParams;
}
}
module.exports = WxAuth;
\ No newline at end of file
const DaoBase = require('iot-cloud-core').BASE.DaoBase;
const sequelize = require('sequelize');
const moment = require('moment')
class UserDao extends DaoBase{
async createUser(params){
this.checkKeyExists(params,"username","pwd","salt");
let newUser = {
username:params.username,
password:params.pwd,
info:params.info,
salt:params.salt,
loginTime:new Date()
};
let res = await this.models.mysql.user.create(newUser);
return res.get({
plain:true
});
}
async createWXUser(params){
this.checkKeyExists(params,"username","salt");
let newUser = {
where:{
username:params.username
},
defaults:{
loginTime:new Date(),
password:"",
nickname:params.nickname,
head:params.head,
info:params.info?params.info:{},
salt:params.salt
}
};
let info = {
loginTime:moment().format('YYYY-MM-DD HH:mm:ss'),
nickname:params.nickname,
head:params.head,
mobiletype:params.info.mobiletype,
version:params.info.version,
useragent:params.info.useragent,
username:params.username
};
let clienId='';
if (params.info.clienId) {
clienId=",'$.clienId','"+params.info.clienId+"'";
}
let update = {
attributes:['id','username','nickname','head'],
raw:true,
where:{
username:params.username
}
};
var that=this;//从不同方法过来的参数用不同的方法
let res = await this.models.mysql.user.findOrCreate(newUser).spread(function(row, created) {
if (created||params.condition) {
return row.get({
plain:true
});
} else {
let user_table = that.models.mysql.user.getTableName();
return that.models.mysql.db.query(`UPDATE ${user_table} SET nickname=$nickname,head=$head,loginTime=$loginTime,info=json_set(info,'$.mobiletype',$mobiletype,'$.version',$version,'$.useragent',$useragent${clienId}) WHERE username=$username`, {
type: sequelize.QueryTypes.UPDATE,
bind: {
nickname:info.nickname,
head:info.head,
username:info.username,
mobiletype:info.mobiletype,
version:info.version,
useragent:JSON.stringify(info.useragent),
loginTime:info.loginTime
}
}).then(function(updated) {
return that.models.mysql.user.find(update);
});
}
});
return res;
}
async createSimpleUser(params){
this.checkKeyExists(params,"username","salt");
let newUser = {
where:{
username:params.username
},
defaults:{
loginTime:new Date(),
password:"",
nickname:params.nickname,
head:params.head,
info:params.info?params.info:{},
salt:params.salt
}
};
let info = {
loginTime:moment().format('YYYY-MM-DD HH:mm:ss'),
mobiletype:params.info.mobiletype,
version:params.info.version,
useragent:params.info.useragent,
username:params.username
};
let clienId='';
if (params.info.clienId) {
clienId=",'$.clienId','"+params.info.clienId+"'";
}
let update = {
attributes:['id','username','nickname','head'],
raw:true,
where:{
username:params.username
}
};
var that=this;//从不同方法过来的参数用不同的方法
let res = await this.models.mysql.user.findOrCreate(newUser).spread(function(row, created) {
if (created||params.condition) {
return row.get({
plain:true
});
} else {
let user_table = that.models.mysql.user.getTableName();
return that.models.mysql.db.query(`UPDATE ${user_table} SET loginTime=$loginTime,info=json_set(info,'$.mobiletype',$mobiletype,'$.version',$version,'$.useragent',$useragent${clienId}) WHERE username=$username`, {
type: sequelize.QueryTypes.UPDATE,
bind: {
username:info.username,
mobiletype:info.mobiletype,
version:info.version,
useragent:JSON.stringify(info.useragent),
loginTime:info.loginTime
}
}).then(function(updated) {
return that.models.mysql.user.find(update);
});
}
});
return res;
}
async searchByName(params){
this.checkKeyExists(params,"username");
let search = {
where:{
username:params.username
},
attributes:['id','username','nickname','head','salt','loginTime','password']
};
let res = await this.models.mysql.user.findOne(search);
if(res == null)
return null;
return res.get({
plain:true
});
}
async updateUserInfoId(params){
this.checkKeyExists(params,"id");
let update = {
id:params.id,
mobiletype:params.mobiletype,
version:params.version,
useragent:JSON.stringify(params.useragent),
loginTime:moment().format('YYYY-MM-DD HH:mm:ss')
};
let clienId='';
if (params.clienId) {
clienId=",'$.clienId','"+params.clienId+"'";
}
let user_table = this.models.mysql.user.getTableName();
let res =this.models.mysql.db.query(`UPDATE ${user_table} SET loginTime=$loginTime,info=json_set(info,'$.mobiletype',$mobiletype,'$.version',$version,'$.useragent',$useragent${clienId}) WHERE id=$id`, {
type: sequelize.QueryTypes.UPDATE,
bind: update
})
// let res = this.models.mysql.user.update(update,options);
return res;
}
async updateCidById(params){
this.checkKeyExists(params,"user_id","clienId");
let clienId=",'$.clienId','"+params.clienId+"'";
let update={
info:sequelize.literal(`json_set(info${clienId})`)
}
let condition={
where:{
id:params.user_id
}
}
let res = await this.models.mysql.user.update(update,condition)
if (res[0]>0) {
return true;
}
return false;
}
async findUserById(params){
this.checkKeyExists(params,"uid");
let search = {
where:{
id:params.uid
},
attributes:["id","username","password","nickname","head","salt","loginTime"]
};
let res = await this.models.mysql.user.findOne(search);
if(res == null){
return false;
}
return res.get({
plain:true
});
}
async findUserInfoById(data){
this.checkKeyExists(data,"id");
let update = {
attributes:["id","nickname","info"],
where:{
id:data.id
},
raw:true
}
let res = await this.models.mysql.user.findAll(update);
if (res.length > 0) {
for (let i = 0; i < res.length; i++) {
res[i].info = JSON.parse(res[i].info);
}
}
return res;
}
//设置user 昵称 头像 info字段内容
async setUserNameAndHeadAndInfo(data) {
this.checkKeyExists(data, "user_id")
let condition={
where:{
id:data.user_id
}
};
let value={};
if (data.head) {
value.head=data.head;
}
if (data.nickname) {
value.nickname=data.nickname;
}
if (data.info) {
value.info=data.info;
}
let res = await this.models.mysql.user.update(value,condition);
return res;
}
async updatePwdById(params){
this.checkKeyExists(params,"id","pwd");
let info = {
password:params.pwd
};
let condition = {
where:{
id:params.id
}
};
let res = await this.models.mysql.user.update(info,condition);
if(res[0] == 0)
return false;
else
return true;
}
async getUserLog(data){
this.checkKeyExists(data,'start_time','end_time')
let user_table = this.models.mysql.user.getTableName();
let update={
attributes:[
sequelize.literal(`COUNT(IF (loginTime >= '${data.start_time}' AND loginTime <'${data.end_time}',1,null)) AS active`),
sequelize.literal(`COUNT(IF (create_time >= '${data.start_time}' AND create_time <'${data.end_time}',1,null)) AS new`)
],
where:{
$or:[
{loginTime:{$gte:data.start_time,$lt:data.end_time}},
{create_time:{$gte:data.start_time,$lt:data.end_time}}
]
},
raw:true
};
let user=await this.models.mysql.user.find(update);
return user;
}
async logout(data){
this.checkKeyExists(data,"key","user_id");
let params='';
for (let i = 0; i < data.key.length; i++) {
params += ",'$." + data.key[i]+"'";
}
let update={
info:sequelize.literal(`JSON_REMOVE(info${params})`)
}
let condition={
where:{
id:data.user_id
}
}
let res = await this.models.mysql.user.update(update,condition)
if (res[0]>0) {
return true;
}
return false;
}
}
module.exports = UserDao;
\ No newline at end of file
const MysqlBase = require('iot-cloud-core').DB.MysqlBase;
const Sequelize = require('sequelize');
class Device extends MysqlBase {
init() {
let model = this.createTable("device", {
device_id: {
type: Sequelize.CHAR(100),
allowNull: false,
unique:true
},
product_id: {
type: Sequelize.CHAR(50),
allowNull: false
},
device_name: {
type: Sequelize.CHAR(45)
},
mac: {
type: Sequelize.CHAR(45)
},
parent_id: {
type: Sequelize.INTEGER()
},
device_state: {
type: Sequelize.BOOLEAN(2)
},
status: {
type: Sequelize.BOOLEAN(2)
},
login_time: {
type: Sequelize.DATE()
},
info: {
type: Sequelize.JSON()
}
},{
timestamps: true,
createdAt: 'create_time',
updatedAt: 'update_time',
hooks: {
afterFind: function(device, options) {
if(device&&device.info)
device.info = JSON.parse(device.info)
}
},
freezeTableName: true
});
return model;
}
}
module.exports = Device;
\ No newline at end of file
const MysqlBase = require('iot-cloud-core').DB.MysqlBase;
const Sequelize = require('sequelize');
class Log extends MysqlBase{
init(){
let model = this.createTable("user",{
username:{
type:Sequelize.CHAR(45),
allowNull: false,
unique:"uk_name"
},
password:{
type:Sequelize.CHAR(45),
allowNull: false
},
nickname:{
type:Sequelize.CHAR(45),
allowNull: false,
defaultValue:""
},
head:{
type:Sequelize.CHAR(255),
allowNull: false,
defaultValue:""
},
mobile:{
type:Sequelize.CHAR(20)
},
email:{
type:Sequelize.CHAR(100)
},
loginTime:{
type:Sequelize.DATE()
},
info:{
type:Sequelize.JSON(),
allowNull: false
},
salt:{
type:Sequelize.CHAR(10),
allowNull:false
}
},
{
timestamps: true,
createdAt:'create_time',
updatedAt:'update_time',
hooks: {
afterFind: function(user, options) {
if(user && user.info)
user.info = JSON.parse(user.info)
}
},
freezeTableName: true
});
return model;
}
}
module.exports = Log;
\ No newline at end of file
const MysqlBase = require('iot-cloud-core').DB.MysqlBase;
const Sequelize = require('sequelize');
class User_device extends MysqlBase {
init() {
let model = this.createTable("user_device", {
nickname: {
type: Sequelize.CHAR(45)
},
role: {
type: Sequelize.CHAR(10)
},
status: {
type: Sequelize.BOOLEAN(2)
},
info: {
type: Sequelize.JSON
}
}, {
timestamps: true,
createdAt: 'create_time',
updatedAt: 'update_time',
freezeTableName: true
});
return model;
}
createRelationShip(models) {
models.user_device.belongsTo(models.device, { foreignKey: { name: 'device_id', allowNull: false }, as: 'device' });
models.user_device.belongsTo(models.user, { foreignKey: { name: 'user_id', allowNull: false }, as: 'user' });
}
}
module.exports = User_device;
\ No newline at end of file
const Provider = require('iot-cloud-core').BASE.Provider;
const db_dataHistory = require('./model/mongo/DataHistory');
const db_dataOption = require('./model/mongo/DataOption');
const dao_dataOption = require('./dao/DataOptionDao');
const dao_dataPublic = require('./dao/DataPublicDao');
const public_class = require('./public/Public');
class DataProvider extends Provider{
constructor(dbManager){
super("data",dbManager);
this.registerModel(db_dataHistory);
this.registerModel(db_dataOption);
this.registerDao("dataOption",dao_dataOption);
this.registerDao("datapublic",dao_dataPublic);
this.setPublicClass(public_class);
}
}
module.exports = DataProvider;
\ No newline at end of file
const DaoBase = require('iot-cloud-core').BASE.DaoBase;
class DataOptionDao extends DaoBase{
async setOption(key,value,expire = null){
let params = {
value:value,
updateTime:new Date()
};
if(expire != null){
params.expireAt = expire;
}
return await this.models.mongo.data_option.findOneAndUpdate({key:key},params,{upsert:true,'new':true}).exec();
}
async setOptions(map,expire = null){
for(let key in map){
let params = {
value:map[key]
};
if(expire != null){
params.expireAt = expire;
}
await this.models.mongo.data_option.findOneAndUpdate({key:key},params,{upsert:true,'new':true}).exec();
}
}
async getOption(key){
return await this.models.mongo.data_option.findOne({key:key}).exec();
}
async getOptions(keys){
let options = await this.models.mongo.data_option.find({key:{$in:keys}}).exec();
let opts = {};
for(let index in options){
let option = options[index];
opts[option.key] = option.value;
}
return opts;
}
}
module.exports = DataOptionDao;
const DaoBase = require('iot-cloud-core').BASE.DaoBase;
const mongoose = require('mongoose');
class DataPublicDao extends DaoBase{
//添加历史数据
//data接收Public中返回的data数据
async addHistory(params){
// this.checkKeyExists(data, "action");
// this.checkKeyExists(data, "data");
// //判断user_id或者device_id是否存在
let update={};
if(!params.user_id && !params.device_id){
return false;
}
if (!params.arr&&!params.action&&params.action!=0) {
return false;
}
if (params.device_id) {
update.device_id=params.device_id;
}
if (params.user_id) {
update.user_id=params.user_id;
}
if (params.type) {
update.type=params.type;
}
if (params.action>=0) {
update.action=params.action;
}
if (params.data) {
update.data=params.data;
}
if (params.arr) {
update=[];
for (let i=0;i<params.arr.length;i++) {
update[i]=params.arr[i];
if (params.device_id) {
update[i].device_id=params.device_id;
}
if (params.user_id) {
update[i].user_id=params.user_id;
}
}
}
if (params.create_time) {
update.create_time=params.create_time;
}
//变量接收addHistory
try{
console.log(update)
let addHistory = await this.models.mongo.data_history.create(update);
//返回addHistory
return addHistory;
}catch(e){
console.log(e)
return false;
}
}
//获得历史数据
async getHistoryList(data){
// param.user_id和param.device_id存在一个或者两个都存在
// param.user_id
// param.device_id
// param.start_id
// param.page_size
// param.action
// param.start_time
// param.end_time
//用变量接收一个空的map
let HistoryProgram = {};
//判断user_id或者device_id是否存在一个
//若不存在则返回false
if (data.where) {
HistoryProgram=data.where;
}else{
if(! data.user_id && ! data.device_id){
return {'false':30000};
}
if (! data.type) {
return false;
}
HistoryProgram.type=data.type;
if(data.user_id){
HistoryProgram.user_id = data.user_id;
}
if(data.device_id){
HistoryProgram.device_id = data.device_id;
}
if (data.action) {
HistoryProgram.action = data.action;
}
if(data.start_id&&data.start_id!=''){
HistoryProgram._id = {$lt:mongoose.Types.ObjectId(data.start_id)};
}
if(data.start_time){
HistoryProgram.create_time = {$gt:data.start_time};
}
if(data.end_time){
HistoryProgram.create_time = {$lt:data.end_time};
}
if(data.start_time && data.end_time){
HistoryProgram.create_time = {$gt:data.start_time,$lt:data.end_time}
}
}
if(! data.page_size){
data.page_size = 10;
}
if(data.order == 1 ){
data.order = parseInt(-1);
}
else if(data.order == 0){
data.order = parseInt(1);
}
else if(! data.order){
data.order = parseInt(-1);
}
//设置查询 POST需得到的值
// get.create_time = {$gt:data.start_time};
// get.create_time = {$lt:data.end_time};
// get._id = {$gt:data.start_id};
// get.action = data.action;
console.log(HistoryProgram)
//变量接收getHistoryList
let getHistoryList = await this.models.mongo.data_history.find(HistoryProgram).limit(parseInt(data.page_size)).sort({create_time:data.order});
//返回getHistoryList
return getHistoryList;
}
//删除历史数据
async delHistory(data){
let update={};
if (!data.id&&!data.device_id) {
return false;
}
if (data.id) {
update={
_id:mongoose.Types.ObjectId(data.id)
}
}
if (data.device_id) {
update={
device_id:data.device_id
};
}
let delHistory = await this.models.mongo.data_history.remove(update);
//返回delHistory
return {'code':0,'data':delHistory};
}
//设置Option
async setOption(data){
//设置表的参数
// await this.models.mongo.data_option.collection.createIndex({"expire_time":1},{expireAfterSeconds:8});
let params = {
key:data.key,
value:data.value
}
//判断数据是否有存活时间
if(data.expire_time != null){
params.expire_time = data.expire_time;
}
//变量接收setOption
let setOption = await this.models.mongo.data_option.findOneAndUpdate({"key":params.key},params,{'new':true,upsert:true});
//返回setOpion
return {'code':0,'data':setOption};
}
async getHistoryByAggregaate(data){
let getHistoryList = await this.models.mongo.data_history.aggregate(data);
//返回getHistoryList
return getHistoryList;
}
//获得Option
async getOption(data){
//变量接收getOption
let getOption = await this.models.mongo.data_option.findOne({"key":data.key});
//返回getOption
return {'code':0,'data':getOption};
}
}
module.exports = DataPublicDao;
const DaoBase = require('iot-cloud-core').BASE.DaoBase;
class OptionsDao extends DaoBase{
async setOption(key,value,expire = null){
let params = {
value:value,
updateTime:new Date()
};
if(expire != null){
params.expireAt = expire;
}
return await this.models.mongo.system_option.findOneAndUpdate({key:key},params,{upsert:true,'new':true}).exec();
}
async setOptions(map,expire = null){
for(let key in map){
let params = {
value:map[key]
};
if(expire != null){
params.expireAt = expire;
}
await this.models.mongo.system_option.findOneAndUpdate({key:key},params,{upsert:true,'new':true}).exec();
}
}
async getOption(key){
return await this.models.mongo.system_option.findOne({key:key}).exec();
}
async getOptions(...keys){
let options = await this.models.mongo.system_option.find({key:{$in:keys}}).exec();
let opts = {};
for(let index in options){
let option = options[index];
opts[option.key] = option.value;
}
return opts;
}
}
module.exports = OptionsDao;
\ No newline at end of file
const DaoBase = require('iot-cloud-core').BASE.DaoBase;
class UserDao extends DaoBase{
async add(){
let sql = await this.models.mysql.user.create({
type: "1",
count:1,
time: new Date()
});
return sql;
}
}
module.exports = UserDao;
\ No newline at end of file
const MongoBase = require('iot-cloud-core').DB.MongoBase;
class DataHistoryModel extends MongoBase {
init() {
let model = this.createTable('data_history', {
user_id: {type:String},
device_id:{type:String},
type:{type:String},
action:{type:Number},
data:{},
status:{type:Number},
create_time:{type:Date,default:Date.now}
});
model.index({"type":1,"action":1,"create_time":1,"device_id": 1,"user_id":1});
return model;
}
}
module.exports = DataHistoryModel;
\ No newline at end of file
const MongoBase = require('iot-cloud-core').DB.MongoBase;
class DataOptionModel extends MongoBase {
init() {
let model = this.createTable('data_option', {
key: {type: String},
value:{},
expire_time:{type: Date},
create_time:{type: Date,default:Date.now},
update_time:{type: Date,default:Date.now}
});
model.index({"key": 1});
model.index({expireAt: 1}, { expireAfterSeconds: 0 });
return model;
}
}
module.exports = DataOptionModel;
\ No newline at end of file
const MongoBase = require('iot-cloud-core').DB.MongoBase;
class OptionsModel extends MongoBase {
init() {
let model = this.createTable('system_option', {
key: {type: String},
value: {},
expireAt: {type: Date},
updateTime:{type: Date}
});
model.index({expireAt: 1}, { expireAfterSeconds: 0 });
return model;
}
}
module.exports = OptionsModel;
\ No newline at end of file
const PublicFunBase = require('iot-cloud-core').BASE.PublicFunBase;
class Public extends PublicFunBase{
/*
* 设置系统参数
*/
//data文件夹下的Public.js调用data文件夹中的OptionsDao.js文件中的方法
// async setOption(data){
// console.log('PublicsetOption');
// await this.dao.get('options').setOption();
// ↑ ↑
// ↑ OptionsDao.js中的setOption方法
// 所有的Dao要使用需要在DataProvider中进行注册否则无法调用
// }
// 括号内data接收controller中返回的数据
//添加历史数据
async addHistory(data){
let addHistory = await this.dao.get('datapublic').addHistory(data);
return addHistory;
}
//获得历史数据
async getHistoryList(data){
//变量接收getHistoryList
let getHistoryList = await this.dao.get('datapublic').getHistoryList(data);
//返回getHistoryList
return getHistoryList;
}
//获取历史数据(聚合函数)
async getHistoryByAggregaate(data){
let getHistoryByAggregaate= await this.dao.get('datapublic').getHistoryByAggregaate(data);
return getHistoryByAggregaate;
}
//删除历史数据
async delHistory(data){
//变量接收delHistory
let delHistory = await this.dao.get('datapublic').delHistory(data);
//返回delHistory
return delHistory;
}
//设置Option
async setOption(key,value,expire = null){
//变量接收setOption
let setOption = await this.dao.get('dataOption').setOption(key,value,expire);
//返回setOption
return setOption;
}
//获得Option
async getOption(key){
//变量接收getOption
let getOption = await this.dao.get('dataOption').getOption(key);
//返回getOption
return getOption;
}
async getOptions(...keys){
let getOptions = await this.dao.get('dataOption').getOption(keys);
return getOptions;
}
}
module.exports = Public;
\ No newline at end of file
var grpc = require('grpc');
var PROTO_PATH = __dirname + '/wx.proto';
const LOG = require('iot-cloud-core').LOG;
class WXRPC{
constructor(){
this.hello_proto = grpc.load(PROTO_PATH).helloworld;
this.client = new this.hello_proto.Greeter('192.168.2.97:20008', grpc.credentials.createInsecure());
}
getInfo(product_id){
if(!product_id){
LOG.error("WXRPC:product_id is null");
return null;
}
return new Promise((r,j)=>{
this.client.getInfo({product_id:"wxcc1ee78ae256be1f"},function(err,response){
if(err)
j(err)
r(response);
});
});
}
}
module.exports = new WXRPC();
\ No newline at end of file
syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";
package helloworld;
// The greeting service definition.
service Greeter {
rpc getInfo(InfoRequest) returns (InfoReply) {}
}
message InfoRequest{
string product_id = 1;
}
message InfoReply{
string component_access_token = 1;
string js_ticket = 2;
string access_token = 3;
string component_appid = 4;
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment