base.js 2.41 KB
/**
 * @fileOverview 读写器指令模块基类
 * @author qiqi.zhou@yoho.cn
 */
import _ from 'lodash';
import orders from '../interface';
import {
    log, returnProc, locateOrder
}
from '../util';



/**
 * @class 读写器的指令操作基类
 * @module lib/directive/Base
 * @member {Object} reproc 预处理方法
 * @member {object} proc 返回结果处理
 */
class Base {
    /**
     * 构造函数
     * @return {void}
     */
    constructor() {
        this.reproc = {};
        this.proc = {};
    }

    /**
     * @method send
     * @description 发送读写器模块指令
     * @param {Connector} connector 链接器socket客户端
     * @param {Object} order 指令
     * @param {Object} param 传参
     * @return {void} 无返回
     */
    send(connector, order, param) {
        let sendOrder = order.input;
        if (this.reproc[order.input]) {
            sendOrder = this.reproc[order.input](param);
        }
        connector.send(sendOrder);
        let address = connector.client.remoteAddress;
        //log.info('读写器(' + address + ')发送指令:' + sendOrder);
    }

    /**
     * @method receive
     * @description 接收读写器模块
     * @param {client} client socket客户端
     * @param {Array} data 接收指令
     * @return {Object} 标准输出
     */
    receive(client, data) {
        let procFunc = this.procFunc,
            ret = null,
            order;

        if (!_.isArray(data) || _.size(data) < 1) {
            return;
        }

        //log.info('读写器(' + client.remoteAddress + ')接收指令:' + data.join(' '));

        //读取命令配置
        order = locateOrder(orders, data);
        if (order.name) {
            if (this.proc[order.name]) {

                ret = this.proc[order.name](data, client);
            } else {
                ret = procFunc(data, client, order.name);
            }
        }
        return ret;
    }

    /**
     * @method procFunc
     * @description 处理返回结果
     * @param {Array} data 返回的结果数组
     * @param {Socket} client socket客户端
     * @param {String} method 方法名
     * @return {Object} 标准输出
     */
    procFunc(data, client, method) {
        return returnProc(data, client.remoteAddress, orders[method].output);
    }

}
/**
 * @exports lib/directive/Base
 */
export default Base;