zigbee2mqtt icon indicating copy to clipboard operation
zigbee2mqtt copied to clipboard

[New device support]: ME202Z-TS0601 submersible liquid level sensor

Open MohammedAlhaid opened this issue 1 year ago • 7 comments

Link

https://a.aliexpress.com/_oBKGmZJ

Database entry

{"id":88,"type":"EndDevice","ieeeAddr":"0xa4c1387f309a6937","nwkAddr":19932,"manufId":4417,"manufName":"_TZE284_mxujdmxo","powerSource":"Battery","modelId":"TS0601","epList":[1],"endpoints":{"1":{"profId":260,"epId":1,"devId":81,"inClusterList":[4,5,61184,0,60672],"outClusterList":[25,10],"clusters":{"genBasic":{"attributes":{"65487":14400,"65503":"8BX0\u00198BX0\u0007\u0000\u0000\u0000\u0000\u0011","65506":56,"65508":1,"stackVersion":0,"dateCode":"","appVersion":80}}},"binds":[],"configuredReportings":[],"meta":{}}},"appVersion":80,"stackVersion":0,"hwVersion":1,"dateCode":"","zclVersion":3,"interviewCompleted":true,"interviewState":"SUCCESSFUL","meta":{},"lastSeen":1757764573155}

Zigbee2MQTT version

2.6.1

Comments

Device

  • Brand/Type: Tuya TS0601 submersible liquid level sensor (ME202Z)
  • Zigbee fingerprint:
    • modelID: TS0601
    • manufacturerName: _TZE284_mxujdmxo
  • Sensor range: 10–400 cm

Picture.

  • (Docs image PR submitted: < here >)

What it exposes (tested)

  • distance (cm) — liquid height, not air-gap
  • cfg_threshold_mm (mm) — tank depth write (100–40000 mm)
  • cfg_threshold_cm (cm) — read-only helper
  • liquid_height (cm) — mirrors distance
  • level_percent (%) — liquid_height / (cfg_threshold_cm) * 100
  • power_level_v (V)

Datapoint mapping (confirmed on my unit)

DP Meaning Unit/Type
2 distance (liquid height) cm (int)
1 distance (fallback) cm (int)
21 tank depth (cfg_threshold) mm/Q8.24/m (raw); write mm
5 power voltage V (various encodings)

Notes:

  • Depth writes succeed when sending mm (e.g., 160 for 16 cm).
  • Percentage is derived: height_cm / (depth_mm/10) × 100.
  • If depth is 0/invalid, derived values are null.
  • Alarm DPs exist on some variants; intentionally not exposed.

Example states (tested)

  • Empty (~0 cm height), depth 160 mm → level_percent ≈ 0
  • Full (~16 cm height), depth 160 mm → level_percent ≈ 100

External definition

const tuya = require('zigbee-herdsman-converters/lib/tuya');
const exposes = require('zigbee-herdsman-converters/lib/exposes');
const ea = exposes.access;

const dp = {
  distance1: 1,
  distance2: 2,
  power_v: 5,
  cfg_threshold: 21,
};

const cache = new Map();
const keyOf = (meta) => (meta && meta.device && meta.device.ieeeAddr) || 'global';
const setCache = (meta, patch) => {
  const k = keyOf(meta);
  const prev = cache.get(k) || {};
  const next = {...prev, ...patch};
  cache.set(k, next);
  return next;
};
const getCache = (meta) => cache.get(keyOf(meta)) || {};

function u32(d){ return (d[0]<<24)|(d[1]<<16)|(d[2]<<8)|d[3]; }
function decode(datatype, data){
  try{
    if (datatype===1) return data[0]===1;
    if (datatype===2) return u32(data);
    if (datatype===4) return data[0];
    if (datatype===0) return Buffer.from(data).toString('hex');
  }catch{}
  return data;
}
function clamp(n,a,b){ return Math.min(Math.max(n,a),b); }

function decodeThresholdToMM(raw){
  if (typeof raw!=='number' || !Number.isFinite(raw)) return undefined;
  if (raw === 0) return 0;
  if (raw >= (1<<20)) return Math.round((raw/(1<<24))*1000);
  if (raw >= 50)       return raw;
  return Math.round(raw*1000);
}
function encodeThresholdFromMM(mm, meta){
  const m = Number(mm)/1000;
  if (!Number.isFinite(m) || m < 0) throw new Error('invalid cfg_threshold_mm');
  const lastRaw = meta && meta.state && meta.state._cfg_threshold_raw;
  if (typeof lastRaw === 'number' && lastRaw > 0){
    if (lastRaw >= (1<<20)) return Math.round(m*(1<<24));
    if (lastRaw >= 50)       return Math.round(mm);
    return Math.round(m);
  }
  return Math.round(mm);
}
function decodeVoltage(raw){
  if (typeof raw!=='number' || !Number.isFinite(raw)) return undefined;
  if (raw>=10000) return raw/1000;
  if (raw>=1000)  return raw/1000;
  if (raw>=100)   return raw/100;
  if (raw>=20)    return raw/10;
  return raw;
}
function computeDerived(out, meta){
  const c = getCache(meta);
  const height_cm = (typeof out.distance==='number') ? out.distance : c.distance_cm;
  const depth_mm  = (typeof out.cfg_threshold_mm==='number') ? out.cfg_threshold_mm : c.threshold_mm;
  if (!(typeof depth_mm==='number' && Number.isFinite(depth_mm) && depth_mm > 0) ||
      !(typeof height_cm==='number' && Number.isFinite(height_cm))) {
    out.cfg_threshold_cm = (typeof depth_mm==='number' && depth_mm>0) ? depth_mm/10 : null;
    out.liquid_height = null;
    out.level_percent = null;
    return out;
  }
  const depth_cm = depth_mm / 10;
  out.cfg_threshold_cm = depth_cm;
  out.liquid_height = height_cm;
  out.level_percent = clamp((height_cm / depth_cm) * 100, 0, 100);
  return out;
}

const fzLocal = {
  reportAll: {
    cluster: 'manuSpecificTuya',
    type: ['commandDataReport','commandDataResponse'],
    convert: (model, msg, publish, options, meta) => {
      const items = (msg.data && msg.data.dpValues) || [];
      const out = {};
      for (const {dp: id, datatype, data} of items){
        const val = decode(datatype, data);
        switch(id){
          case dp.distance1:
          case dp.distance2:
            if (typeof val==='number' && Number.isFinite(val)){
              out.distance = val;
              out.distance_raw = val;
              setCache(meta, {distance_cm: val});
            }
            break;
          case dp.power_v: {
            const v = decodeVoltage(val);
            if (typeof v==='number' && Number.isFinite(v)) out.power_level_v = v;
            break;
          }
          case dp.cfg_threshold: {
            if (typeof val==='number' && Number.isFinite(val)){
              const mm = decodeThresholdToMM(val);
              if (typeof mm === 'number'){
                out.cfg_threshold_mm = mm;
                out._cfg_threshold_raw = val;
                setCache(meta, {threshold_mm: (mm>0?mm:undefined)});
              }
            }
            break;
          }
          default:
            break;
        }
      }
      computeDerived(out, meta);
      return out;
    },
  },
};

const tzLocal = {
  cfg_threshold_mm: {
    key: ['cfg_threshold_mm'],
    convertSet: async (entity, key, value, meta) => {
      const mmInput = Number(value);
      const mm = Math.max(100, Math.min(40000, Math.round(mmInput)));
      const raw = encodeThresholdFromMM(mm, meta);
      await tuya.sendDataPointValue(entity, dp.cfg_threshold, raw);

      setCache(meta, {threshold_mm: (mm>0?mm:undefined)});
      const state = {cfg_threshold_mm: mm, _cfg_threshold_raw: raw};

      const c = getCache(meta);
      const height_cm = c.distance_cm;
      if (typeof height_cm==='number' && Number.isFinite(height_cm) && mm > 0){
        const depth_cm = mm/10;
        state.cfg_threshold_cm = depth_cm;
        state.liquid_height = height_cm;
        state.level_percent = clamp((height_cm / depth_cm) * 100, 0, 100);
      } else {
        state.cfg_threshold_cm = (mm>0?mm/10:null);
        state.liquid_height = null;
        state.level_percent = null;
      }
      return {state};
    },
  },
};

module.exports = [{
  fingerprint: [{modelID:'TS0601', manufacturerName:'_TZE284_mxujdmxo'}],
  model: 'ME202Z-TS0601',
  vendor: 'Tuya',
  description: 'Submersible liquid level sensor — liquid height in cm; depth in mm; fill %',
  fromZigbee: [fzLocal.reportAll],
  toZigbee: [tzLocal.cfg_threshold_mm],
  exposes: [
    exposes.numeric('distance', ea.STATE).withUnit('cm').withDescription('Liquid height (cm)'),
    exposes.numeric('distance_raw', ea.STATE).withDescription('Raw liquid height (cm)'),
    exposes.numeric('liquid_height', ea.STATE).withUnit('cm').withDescription('Liquid height (cm)'),
    exposes.numeric('level_percent', ea.STATE).withUnit('%').withDescription('Fill percentage'),
    exposes.numeric('cfg_threshold_mm', ea.ALL).withUnit('mm').withValueMin(100).withValueMax(40000)
      .withDescription('Tank depth (mm)'),
    exposes.numeric('cfg_threshold_cm', ea.STATE).withUnit('cm').withDescription('Tank depth (cm)'),
    exposes.numeric('power_level_v', ea.STATE).withUnit('V').withDescription('Supply voltage'),
  ],
  onEvent: async (type, data, device) => {
    if (type==='deviceAnnounce' || type==='deviceInterview'){
      const ep = device.getEndpoint(1);
      try { await tuya.sendDataPointQuery(ep, 0); } catch {}
      try { await tuya.sendDataPointQuery(ep, dp.distance1); } catch {}
      try { await tuya.sendDataPointQuery(ep, dp.distance2); } catch {}
      try { await tuya.sendDataPointQuery(ep, dp.cfg_threshold); } catch {}
      try { await tuya.sendDataPointQuery(ep, dp.power_v); } catch {}
    }
  },
}];

What does/doesn't work with the external definition?

What works

  • Measurement: distance (DP2 primary, DP1 fallback) reports liquid height in cm. Verified from ~0–16 cm; values change immediately with level.
  • Depth config: cfg_threshold_mm writes to DP21 (device expects mm). Examples: 160 → 16 cm. Reflected as helper cfg_threshold_cm.
  • Fill %: level_percent = liquid_height(cm) / depth(cm) × 100. Correct at empty (~0%) and full (~100%). Clamped 0–100.
  • Safety: If cfg_threshold_mm is unset/0 → level_percent and liquid_height are null (no bogus 100%).
  • Range guard: Writer enforces device range 10–400 cm (100–40000 mm).
  • Power reading: power_level_v decoded from DP5 (heuristic scaling). Typical ~4.9–5.0 V observed.

What doesn't (or intentionally not included)

  • Alarms: High/Low alarm thresholds and flags are not exposed. (Different variants use different DPs; users can implement HA automations from level_percent instead.)
  • Unit mode: Not exposed (not required for operation).
  • Battery/Temp: Not exposed (device is DC-powered on our unit; no confirmed temperature DP).
  • Pump/relay: Not exposed (no physical terminals on this hardware).

Caveats / notes

  • Set depth first: Derived values require a valid cfg_threshold_mm. Until then, % is null.
  • Firmware variance: Some firmwares may send height on DP1 instead of DP2; the definition accepts either.
  • DP21 encoding: Reads can arrive as mm / Q8.24 meters / integer meters; encoder handles these, writes as mm by default.

MohammedAlhaid avatar Sep 16 '25 08:09 MohammedAlhaid

I am also interested in this device

Ruugy avatar Sep 28 '25 21:09 Ruugy

✅ Update: Fixed incorrect range (now 10–400 cm), corrected decimal rounding (single decimal place), and simplified exposes to only essential fields.

This version:

  • Uses 10–400 cm range
  • Rounds percentage to one decimal
  • Removes redundant exposes
  • Keeps voltage, tank depth, height, and percent only
  • Fully valid and tested in Zigbee2MQTT with external converters.
// Tuya ME202Z / TS0601 — _TZE284_mxujdmxo
// Submersible Liquid Level Sensor (range: 10–400 cm)

const tuya = require('zigbee-herdsman-converters/lib/tuya');
const exposes = require('zigbee-herdsman-converters/lib/exposes');
const ea = exposes.access;

const dp = {
    distance: 2,          // liquid height (cm)
    cfg_threshold: 21,    // tank depth (mm)
    power_level_v: 5,     // power voltage (raw)
};

function round1(v) {
    return Math.round(v * 10) / 10;
}

const fzLocal = {
    reportAll: {
        cluster: 'manuSpecificTuya',
        type: ['commandDataReport', 'commandDataResponse'],
        convert: (model, msg, publish, options, meta) => {
            const out = {};
            const items = msg.data?.dpValues || [];

            let distanceCm, depthMm;

            for (const {dp: id, datatype, data} of items) {
                if (id === dp.distance) {
                    distanceCm = tuya.getDataValue(datatype, data);
                    out.liquid_height = distanceCm;
                } else if (id === dp.cfg_threshold) {
                    depthMm = tuya.getDataValue(datatype, data);
                    out.cfg_threshold_mm = depthMm;
                } else if (id === dp.power_level_v) {
                    const val = tuya.getDataValue(datatype, data);
                    out.power_level_v = round1(val / 10);
                }
            }

            // derive percentage if both values known
            if (distanceCm != null && depthMm != null && depthMm > 0) {
                out.level_percent = round1((distanceCm / (depthMm / 10)) * 100);
            } else if (distanceCm != null) {
                out.level_percent = null;
            }

            return out;
        },
    },
};

const tzLocal = {
    cfg_threshold_mm: {
        key: ['cfg_threshold_mm'],
        convertSet: async (entity, key, value) => {
            const val = Math.min(4000, Math.max(100, Math.round(Number(value))));
            await tuya.sendDataPointValue(entity, dp.cfg_threshold, val);
            return {state: {cfg_threshold_mm: val}};
        },
    },
};

module.exports = [{
    fingerprint: [{modelID: 'TS0601', manufacturerName: '_TZE284_mxujdmxo'}],
    model: 'ME202Z-TS0601',
    vendor: 'Tuya',
    description: 'ME202Z submersible liquid level sensor (range 10–400 cm)',
    fromZigbee: [fzLocal.reportAll],
    toZigbee: [tzLocal.cfg_threshold_mm],
    exposes: [
        exposes.numeric('liquid_height', ea.STATE)
            .withUnit('cm')
            .withDescription('Measured liquid height in centimeters'),
        exposes.numeric('level_percent', ea.STATE)
            .withUnit('%')
            .withDescription('Liquid level as percentage of tank depth (1 decimal)'),
        exposes.numeric('cfg_threshold_mm', ea.ALL)
            .withUnit('mm')
            .withValueMin(100)
            .withValueMax(4000)
            .withDescription('Configured tank depth (in millimeters)'),
        exposes.numeric('power_level_v', ea.STATE)
            .withUnit('V')
            .withDescription('Power supply voltage'),
    ],
    onEvent: async (type, data, device) => {
        if (['deviceAnnounce', 'deviceInterview'].includes(type)) {
            const ep = device.getEndpoint(1);
            try { await tuya.sendDataPointQuery(ep, dp.distance); } catch {}
            try { await tuya.sendDataPointQuery(ep, dp.cfg_threshold); } catch {}
            try { await tuya.sendDataPointQuery(ep, dp.power_level_v); } catch {}
        }
    },
}];

MohammedAlhaid avatar Oct 17 '25 05:10 MohammedAlhaid

🙏 Thank you for creating this issue and sharing your external converter!

In case all features work, please submit a pull request on this repository so the device can be supported out-of-the-box with the next release. For instructions on how to create a pull request see the docs.

If NOT all features work, please follow the How To Support new devices Since this is a Tuya also consider How To Support new Tuya devices

If you need help with the process, feel free to ask here and we'll be happy to assist.

github-actions[bot] avatar Oct 17 '25 05:10 github-actions[bot]

Hi, below code is an updated and tested one.

// Tuya ME202Z / TS0601 — _TZE284_mxujdmxo
// Submersible Liquid Level Sensor (range: 10–400 cm)

const tuya = require('zigbee-herdsman-converters/lib/tuya');
const exposes = require('zigbee-herdsman-converters/lib/exposes');
const ea = exposes.access;

const dp = {
    distance: 2,          // liquid height (cm)
    cfg_threshold: 21,    // tank depth (mm)
    power_level_v: 5,     // power voltage (raw)
};

function round1(v) {
    return Math.round(v * 10) / 10;
}

function getDataValue(datatype, data) {
    try {
        if (Buffer.isBuffer(data)) {
            return data.readUIntBE(0, data.length);
        } else if (Array.isArray(data)) {
            return data.reduce((acc, b) => (acc << 8) + b, 0);
        } else {
            return Number(data);
        }
    } catch {
        return Number(data);
    }
}

// cache object to remember the last threshold
const lastKnown = {};

const fzLocal = {
    reportAll: {
        cluster: 'manuSpecificTuya',
        type: ['commandDataReport', 'commandDataResponse'],
        convert: (model, msg, publish, options, meta) => {
            const out = {};
            const items = msg.data?.dpValues || [];
            const deviceId = meta.device.ieeeAddr;

            let distanceCm;
            let depthMm = lastKnown[deviceId]?.depthMm;

            for (const {dp: id, datatype, data} of items) {
                if (id === dp.distance) {
                    distanceCm = getDataValue(datatype, data);
                    out.liquid_height = distanceCm;
                } else if (id === dp.cfg_threshold) {
                    depthMm = getDataValue(datatype, data);
                    lastKnown[deviceId] = {depthMm};
                    out.cfg_threshold_mm = depthMm;
                } else if (id === dp.power_level_v) {
                    const val = getDataValue(datatype, data);
                    out.power_level_v = round1(val / 10);
                }
            }

            if (distanceCm != null && depthMm != null && depthMm > 0) {
                out.level_percent = round1((distanceCm / (depthMm / 10)) * 100);
            }

            return out;
        },
    },
};

const tzLocal = {
    cfg_threshold_mm: {
        key: ['cfg_threshold_mm'],
        convertSet: async (entity, key, value, meta) => {
            const val = Number(value);
            await tuya.sendDataPointValue(entity, dp.cfg_threshold, val);
            // update cache
            lastKnown[meta.device.ieeeAddr] = {depthMm: val};
            return {state: {cfg_threshold_mm: val}};
        },
    },
};

module.exports = [{
    fingerprint: [{modelID: 'TS0601', manufacturerName: '_TZE284_mxujdmxo'}],
    model: 'ME202Z-TS0601',
    vendor: 'Tuya',
    description: 'ME202Z submersible liquid level sensor (range 10–400 cm)',
    fromZigbee: [fzLocal.reportAll],
    toZigbee: [tzLocal.cfg_threshold_mm],
    exposes: [
        exposes.numeric('liquid_height', ea.STATE)
            .withUnit('cm')
            .withDescription('Measured liquid height in centimeters'),
        exposes.numeric('level_percent', ea.STATE)
            .withUnit('%')
            .withDescription('Liquid level as percentage of tank depth (1 decimal)'),
        exposes.numeric('cfg_threshold_mm', ea.ALL)
            .withUnit('mm')
            .withValueMin(100)
            .withValueMax(4000)
            .withDescription('Configured tank depth (in millimeters)'),
        exposes.numeric('power_level_v', ea.STATE)
            .withUnit('V')
            .withDescription('Power supply voltage'),
    ],
    onEvent: async (type, data, device) => {
        if (['deviceAnnounce', 'deviceInterview'].includes(type)) {
            const ep = device.getEndpoint(1);
            try { await tuya.sendDataPointQuery(ep, dp.distance); } catch {}
            try { await tuya.sendDataPointQuery(ep, dp.cfg_threshold); } catch {}
        }
    },
}];

MohammedAlhaid avatar Nov 07 '25 04:11 MohammedAlhaid

Thank you for your efforts. I copied it into a.json file and stored it in extern_convertes folder. But it does not yet work. Can you maybe give an advise what I missed to do or what I did wrong?

hofmara avatar Nov 16 '25 16:11 hofmara

folder

I could work it out. It's running now. Thank you very much for posting!

hofmara avatar Nov 16 '25 19:11 hofmara

Added in https://github.com/Koenkk/zigbee-herdsman-converters/pull/11210

Changes will be available in the dev branch in a few hours from now and in the next release which is every 1st of the month.

Koenkk avatar Jan 06 '26 20:01 Koenkk