import { mtopRequest, resultDataFormat } from './core' import ERROR_CODE from './errorCode' import { get } from 'jsonuri' const ERROR_LIMIT: number = 1 let errorCount: number = 0 /** * 获取设备状态 * @param data * @returns {*} */ interface DeviceParam { productKey: string devId: string skillId: string } /** * 获取设备状态 * @param data * @returns {*} */ export function getDeviceStatus(data: DeviceParam) { return mtopRequest({ api: 'mtop.alibaba.aicloud.iot.getDeviceStatus', data }, getDeviceStatusChecker) } /** * 设置设备状态 * @param data * @returns {*} */ export function setDeviceControl(data: DeviceParam, params: any) { console.log('setDeviceControl', params) return mtopRequest({ api: 'mtop.alibaba.aicloud.iot.deviceControl', data: Object.assign({ params: JSON.stringify(params) }, data) }) } /** * @name 获取设备的数据校验函数 * @param re */ function getDeviceStatusChecker (re) { let errRet let sucRet if (!re) { errRet = resultDataFormat(ERROR_CODE.NET_ERR) } if (!re.data) { errRet = resultDataFormat(ERROR_CODE.NET_ERR) } if (re.data.success !== 'true') { errRet = resultDataFormat(ERROR_CODE.NET_ERR) } if (!re.data.model) { errRet = resultDataFormat(ERROR_CODE.DEV_ERR) } const model = re.data.model || {} // 未激活 if (model.status === 0) { errRet = resultDataFormat(Object.assign(ERROR_CODE.DEV_NOT, { model })) } // 离线 if (model.status === 3) { errRet = resultDataFormat(Object.assign(ERROR_CODE.DEV_OFF, { model })) } // 设备禁用 if (model.status === 8) { errRet = resultDataFormat(Object.assign(ERROR_CODE.DEV_DIS, { model })) } // 设备异常 TODO 长度为1的空对象 [{}] if ( model.errorInfo && model.errorInfo.length && (model.errorInfo.length === 1 && Object.keys(model.errorInfo[0]).length > 0) ) { let errorCode = getErrorInfoErrorCode(model.errorInfo) if (errorCode !== 0) { errRet = resultDataFormat( Object.assign(ERROR_CODE.DEV_ABN, { model, code: errorCode }) ) } } // 设备在线 if (model.status === 1) { sucRet = resultDataFormat({ type: 'succeed', model: model }) } if (errRet) { errorCount++ if (errorCount < ERROR_LIMIT && sucRet) { return sucRet } return errRet } else { errorCount = 0 return sucRet } } function getErrorInfoErrorCode(errorInfo) { if (!errorInfo && !errorInfo.length) return for (let i = 0; i < errorInfo.length; i++) { if (errorInfo[i].eventCode === 'Error') { return get(errorInfo[i], 'eventBody/ErrorCode') } } }