chenyc
2026-05-20 c8ba0f92b3f84273a78f06de25359db20c1b2a4d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
const { EventEmitter } = require('events');
const { formatUploadTime } = require('./mqtt-service');
 
class AliyunService {
  constructor(config = {}, logger = console, options = {}) {
    this.config = config;
    this.logger = logger;
    this.fetchImpl = options.fetchImpl || global.fetch;
    this.aliyunSdk = options.aliyunSdk || null;
    this.contexts = new Map();
    this.started = false;
  }
 
  start() {
    if (!this.config.enabled) {
      this.logger.info('[ALIYUN] 阿里云通道未启用');
      this.started = false;
      return;
    }
 
    if (typeof this.fetchImpl !== 'function') {
      throw new Error('当前 Node.js 运行环境不支持 fetch,无法请求三元组接口');
    }
 
    this.started = true;
    this.logger.info(`[ALIYUN] 阿里云通道已启用 三元组接口=${this.getTupleUrl()} 自动注册=${this.config.autoRegister === false ? 0 : 1}`);
  }
 
  async stop() {
    const closeTasks = [];
 
    for (const context of this.contexts.values()) {
      this.clearConnectWaiter(context);
      context.tuplePromise = null;
 
      if (context.iotDevice && typeof context.iotDevice.end === 'function') {
        closeTasks.push(new Promise((resolve) => {
          try {
            context.iotDevice.end(false, resolve);
          } catch (_error) {
            resolve();
          }
        }));
      }
    }
 
    await Promise.all(closeTasks);
    this.contexts.clear();
    this.started = false;
    this.logger.info('[ALIYUN] 阿里云通道已停止');
  }
 
  buildPayload(message) {
    return {
      ...(message || {}),
      suedtime: formatUploadTime(),
    };
  }
 
  getTupleUrl() {
    if (this.config.tupleApiUrl) {
      return this.config.tupleApiUrl;
    }
 
    const baseUrl = String(this.config.tupleApiBaseUrl || '').replace(/\/$/, '');
    const apiPath = this.config.tupleApiPath || '/device/info/getAliyunDeviceSecret';
    return `${baseUrl}${apiPath}`;
  }
 
  getAliyunSdk() {
    if (!this.aliyunSdk) {
      this.aliyunSdk = require('aliyun-iot-device-sdk');
    }
 
    return this.aliyunSdk;
  }
 
  getContext(device) {
    const deviceId = device.deviceId;
 
    if (!this.contexts.has(deviceId)) {
      this.contexts.set(deviceId, {
        deviceId,
        tuple: null,
        tuplePromise: null,
        iotDevice: null,
        connected: false,
        connectPromise: null,
        resolveConnectPromise: null,
        rejectConnectPromise: null,
        connectTimer: null,
        lastRegisterAttempt: 0,
        lastRegisterError: '',
      });
      this.logger.info(`[ALIYUN] 创建设备上下文 设备=${deviceId}`);
    }
 
    return this.contexts.get(deviceId);
  }
 
  extractTuple(responseBody, deviceId) {
    const data = responseBody && typeof responseBody === 'object'
      ? (responseBody.data || responseBody.result || responseBody)
      : null;
 
    if (!data || typeof data !== 'object') {
      throw new Error('三元组接口返回为空');
    }
 
    const tuple = {
      productKey: data.productKey || data.ProductKey || '',
      deviceName: data.deviceName || data.DeviceName || deviceId,
      deviceSecret: data.deviceSecret || data.DeviceSecret || '',
    };
 
    if (!tuple.productKey || !tuple.deviceName || !tuple.deviceSecret) {
      throw new Error('三元组字段不完整');
    }
 
    return tuple;
  }
 
  async requestTuple(deviceId) {
    const formData = new URLSearchParams();
    formData.set('isAutoRegister', this.config.autoRegister === false ? '0' : '1');
    formData.set('deviceName', deviceId);
 
    const url = this.getTupleUrl();
    this.logger.info(`[ALIYUN] 请求三元组 设备=${deviceId} 地址=${url}`);
 
    const response = await this.fetchImpl(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: formData.toString(),
    });
 
    if (!response.ok) {
      throw new Error(`三元组接口请求失败 HTTP ${response.status}`);
    }
 
    const text = await response.text();
    let body;
 
    try {
      body = JSON.parse(text);
    } catch (_error) {
      throw new Error('三元组接口返回不是有效 JSON');
    }
 
    return this.extractTuple(body, deviceId);
  }
 
  async ensureTuple(context, device) {
    if (context.tuple) {
      return context.tuple;
    }
 
    if (context.tuplePromise) {
      return context.tuplePromise;
    }
 
    const retryMs = this.config.registerRetryMs || 60000;
    const now = Date.now();
 
    if (context.lastRegisterAttempt > 0 && (now - context.lastRegisterAttempt) < retryMs && context.lastRegisterError) {
      throw new Error(`三元组请求重试冷却中: ${context.lastRegisterError}`);
    }
 
    context.lastRegisterAttempt = now;
    context.tuplePromise = (async () => {
      try {
        const tuple = await this.requestTuple(device.deviceId);
        context.tuple = tuple;
        context.lastRegisterError = '';
        this.logger.info(`[ALIYUN] 三元组获取成功 设备=${device.deviceId} 阿里云设备名=${tuple.deviceName}`);
        return tuple;
      } catch (error) {
        context.lastRegisterError = error.message;
        this.logger.error(`[ALIYUN] 三元组获取失败 设备=${device.deviceId}: ${error.message}`);
        throw error;
      } finally {
        context.tuplePromise = null;
      }
    })();
 
    return context.tuplePromise;
  }
 
  createIotDevice(tuple) {
    const sdk = this.getAliyunSdk();
 
    if (!sdk || typeof sdk.device !== 'function') {
      throw new Error('aliyun-iot-device-sdk 不可用');
    }
 
    return sdk.device({
      ProductKey: tuple.productKey,
      DeviceName: tuple.deviceName,
      DeviceSecret: tuple.deviceSecret,
    });
  }
 
  clearConnectWaiter(context) {
    if (context.connectTimer) {
      clearTimeout(context.connectTimer);
    }
 
    context.connectPromise = null;
    context.resolveConnectPromise = null;
    context.rejectConnectPromise = null;
    context.connectTimer = null;
  }
 
  resolveConnectWaiter(context, iotDevice) {
    if (context.connectPromise && context.resolveConnectPromise) {
      const resolve = context.resolveConnectPromise;
      this.clearConnectWaiter(context);
      resolve(iotDevice);
    }
  }
 
  rejectConnectWaiter(context, error) {
    if (context.connectPromise && context.rejectConnectPromise) {
      const reject = context.rejectConnectPromise;
      this.clearConnectWaiter(context);
      reject(error instanceof Error ? error : new Error(String(error)));
    }
  }
 
  bindIotDeviceEvents(context, device, iotDevice) {
    const isCurrentDevice = () => context.iotDevice === iotDevice;
 
    iotDevice.on('connect', () => {
      if (!isCurrentDevice()) {
        return;
      }
 
      context.connected = true;
      this.logger.info(`[ALIYUN] 设备连接成功 设备=${device.deviceId}`);
      this.resolveConnectWaiter(context, iotDevice);
    });
 
    iotDevice.on('error', (error) => {
      if (!isCurrentDevice()) {
        return;
      }
 
      context.connected = false;
      this.logger.error(`[ALIYUN] 设备连接异常 设备=${device.deviceId}: ${error.message || error}`);
      this.rejectConnectWaiter(context, error);
    });
 
    iotDevice.on('offline', () => {
      if (isCurrentDevice()) {
        context.connected = false;
        this.logger.warn(`[ALIYUN] 设备离线 设备=${device.deviceId}`);
      }
    });
 
    iotDevice.on('close', () => {
      if (isCurrentDevice()) {
        context.connected = false;
        this.logger.warn(`[ALIYUN] 连接已关闭 设备=${device.deviceId}`);
      }
    });
  }
 
  async ensureIotDevice(context, device) {
    if (context.iotDevice && context.connected) {
      return context.iotDevice;
    }
 
    if (context.connectPromise) {
      return context.connectPromise;
    }
 
    if (!context.iotDevice) {
      const tuple = await this.ensureTuple(context, device);
      const iotDevice = this.createIotDevice(tuple);
      context.iotDevice = iotDevice;
      this.bindIotDeviceEvents(context, device, iotDevice);
      this.logger.info(`[ALIYUN] 创建 SDK 设备实例 设备=${device.deviceId}`);
    }
 
    if (context.connected) {
      return context.iotDevice;
    }
 
    const connectTimeoutMs = this.config.connectTimeoutMs || 15000;
    context.connectPromise = new Promise((resolve, reject) => {
      context.resolveConnectPromise = resolve;
      context.rejectConnectPromise = reject;
      context.connectTimer = setTimeout(() => {
        this.rejectConnectWaiter(context, new Error('阿里云连接超时'));
      }, connectTimeoutMs);
    });
 
    return context.connectPromise;
  }
 
  async publish(device, message) {
    if (!this.started || !this.config.enabled) {
      this.logger.warn(`[ALIYUN] 跳过上报 设备=${device.deviceId} 原因=通道未启用`);
      return { skipped: true, reason: 'disabled' };
    }
 
    const context = this.getContext(device);
    const payload = this.buildPayload(message);
 
    try {
      const iotDevice = await this.ensureIotDevice(context, device);
      this.logger.info(`[ALIYUN] 开始属性上报 设备=${device.deviceId} 字段=${Object.keys(payload).join(',')}`);
      await new Promise((resolve, reject) => {
        iotDevice.postProps(payload, (result) => {
          if (result && (result.message === 'success' || result.success === true || result.code === 200)) {
            resolve(result);
            return;
          }
 
          reject(new Error(result && (result.message || result.code) ? String(result.message || result.code) : '属性上报失败'));
        });
      });
      this.logger.info(`[ALIYUN] 属性上报成功 设备=${device.deviceId} 数据=${JSON.stringify(payload)}`);
      return { ok: true, payload };
    } catch (error) {
      this.logger.error(`[ALIYUN] 上报失败 设备=${device.deviceId}: ${error.message}`);
      return { ok: false, reason: error.message, payload };
    }
  }
}
 
class FakeAliyunDevice extends EventEmitter {
  postProps(payload, callback) {
    callback({ message: 'success', payload });
  }
}
 
module.exports = {
  AliyunService,
  FakeAliyunDevice,
};