@@ -27,16 +27,29 @@ const {UDP_KEY} = require('./lib/config');
2727 * @param {String } options.key encryption key of device (also called `localKey`)
2828 * @param {String } [options.productKey] product key of device (currently unused)
2929 * @param {Number } [options.version=3.1] protocol version
30+ * @param {Boolean } [options.nullPayloadOnJSONError=false] if true, emits a data event
31+ * containing a payload of null values for on-device JSON parsing errors
3032 * @example
3133 * const tuya = new TuyaDevice({id: 'xxxxxxxxxxxxxxxxxxxx',
3234 * key: 'xxxxxxxxxxxxxxxx'})
3335 */
3436class TuyaDevice extends EventEmitter {
35- constructor ( { ip, port = 6668 , id, gwID = id , key, productKey, version = 3.1 } = { } ) {
37+ constructor ( {
38+ ip,
39+ port = 6668 ,
40+ id,
41+ gwID = id ,
42+ key,
43+ productKey,
44+ version = 3.1 ,
45+ nullPayloadOnJSONError = false
46+ } = { } ) {
3647 super ( ) ;
3748 // Set device to user-passed options
3849 this . device = { ip, port, id, gwID, key, productKey, version} ;
3950
51+ this . nullPayloadOnJSONError = nullPayloadOnJSONError ;
52+
4053 // Check arguments
4154 if ( ! ( isValidString ( id ) ||
4255 isValidString ( ip ) ) ) {
@@ -314,20 +327,22 @@ class TuyaDevice extends EventEmitter {
314327 try {
315328 packets = this . device . parser . parse ( data ) ;
316329
317- for ( const packet of packets ) {
318- if ( packet . payload && packet . payload === 'json obj data unvalid' ) {
319- this . emit ( 'error' , packet . payload ) ;
320-
321- packet . payload = {
322- dps : {
323- 1 : null ,
324- 2 : null ,
325- 3 : null ,
326- 101 : null ,
327- 102 : null ,
328- 103 : null
329- }
330- } ;
330+ if ( this . this . nullPayloadOnJSONError ) {
331+ for ( const packet of packets ) {
332+ if ( packet . payload && packet . payload === 'json obj data unvalid' ) {
333+ this . emit ( 'error' , packet . payload ) ;
334+
335+ packet . payload = {
336+ dps : {
337+ 1 : null ,
338+ 2 : null ,
339+ 3 : null ,
340+ 101 : null ,
341+ 102 : null ,
342+ 103 : null
343+ }
344+ } ;
345+ }
331346 }
332347 }
333348 } catch ( error ) {
0 commit comments