devbis / z03mmc

Xiaomi LYWSD03MMC Zigbee Firmware
GNU General Public License v3.0
871 stars 43 forks source link

Add setting to change TX antenna power #18

Open Mostalk opened 11 months ago

Mostalk commented 11 months ago

Can you add ability to change antenna power in Z2M?

I have one sensor at a fairly large distance from the Zigbee stick and some data loosing. It would be a good idea to manually control the TX antenna power within reasonable limits

blinkzz commented 11 months ago

Would like to see the same for ZHA by exposing some number input or range slider, after upgrading from 1.0.1 to 1.0.2 some sensors fail to deliver their status now

pvvx commented 11 months ago

Without hardware improvements, it is impossible to increase the output of the transmitter. There is not enough CR2032 battery current. It will only work for the first few days on a fresh battery. Further, the internal resistance of the battery will increase and instead of increasing the recoil, there will be a decrease due to voltage drawdown during transmission.

Zigbee has a longer transmission time and requires the installation of a large capacitor in the power supply.

Mostalk commented 11 months ago

@pvvx, I assumed that it was possible to change the TX antenna power since the @devbis decreased it to 3 dBm in the latest release. I don’t know what the power was before, but my sensor, which I mentioned above, worked better at the previous power value

pvvx commented 11 months ago

+3 dB is the limit for Xiaomi LYWSD03MMC with CR2032. This already requires the installation of a capacitor in the place provided by the developers on the printed circuit board. The manufacturer has not installed capacitors - they save on everything. The following power steps (up to +10 dB) require a different battery... The peak current (TX) will be more than 25 mA, which will lead to a drawdown of the CR2032 below 2 volts.

Mostalk commented 11 months ago

Now I understand that this is why the battery was very drained on the previous firmware version. Judging by the file changes, the power was not specified at all. That is, the sensor tried to operate at a maximum of 10 dB?

pvvx commented 11 months ago

No. Special switching from the program is required. After +3 dB, the chip switches the transmitter power directly to the battery, without the built-in DC-DC (1.8V). As a result, with an increase in power, the supply voltage drops sharply, and the return on the CR2032 becomes even less than at -10..-20 dB :)

A half-discharged CR2032 battery has an internal resistance of 100 ohms. The thermometer must operate from a 3 V source with a series resistance of 100 ohms, otherwise the battery will be used up by 50% (to the dumpster).

The optimal operating mode for Xiaomi LYWSD03MMC (without circuit additions) from CR2032 is +0 dB (<8mA p-p). Less or more will be worse, because Zigbee receivers have poor sensitivity compared to BLE(5.0+). And there is no point in less return due to the total consumption of the CPU itself. Use a gateway or ZigBee Direct. Telink Zigbee-Direct or Telink SDK 'Zigbee + Bluetooth LE Concurrent Mode'

zzz676 commented 11 months ago

No. Special switching from the program is required. After +3 dB, the chip switches the transmitter power directly to the battery, without the built-in DC-DC (1.8V). As a result, with an increase in power, the supply voltage drops sharply, and the return on the CR2032 becomes even less than at -10..-20 dB :)

A half-discharged CR2032 battery has an internal resistance of 100 ohms. The thermometer must operate from a 3 V source with a series resistance of 100 ohms, otherwise the battery will be used up by 50% (to the dumpster).

The optimal operating mode for Xiaomi LYWSD03MMC (without circuit additions) from CR2032 is +0 dB (<8mA p-p). Less or more will be worse, because Zigbee receivers have poor sensitivity compared to BLE(5.0+). And there is no point in less return due to the total consumption of the CPU itself. Use a gateway or ZigBee Direct. Telink Zigbee-Direct or Telink SDK 'Zigbee + Bluetooth LE Concurrent Mode'

А что если дать возможность снижать мощность передатчика, для экономии батареи. У меня, допустим, эти датчики стоят в 50 см от выключателей с зигби, работающих как роутер. И возможно и с меньшей мощностью антенны нормально бы передавали информацию.

pvvx commented 11 months ago

В текущей реализации передача (при +0 дБ) дает потребление на длительность посылки самой передачи где-то в 8 мА. При этом основное время в ZigBee уходит на прием ответа и обработку "стека". И CPU ещё разогнан на 48MHz, что дает потребление в этих режимах 5..6 мА. Т.е. вы хотите немного убрать короткий горбик передачи, вылезающий среди общей активности во время периода пробуждения SoC на пару мА? Т.е. ужать общее потребление на пару процентов? См. текущие диаграммы. https://github.com/devbis/z03mmc/issues/11#issuecomment-1777707509

devbis commented 11 months ago

В моей прошивке частота выставлена в 24 МГц.

telegram-cloud-photo-size-4-5893151316224621799-y

По графику зависимости мощности от тока видно что где-то после 2.5 dBm потребление начинает расти круче.

Mostalk commented 11 months ago

По графику зависимости мощности от тока видно что где-то после 2.5 dBm потребление начинает расти круче.

Хмм, интересно, почему между 2.5 и 3.5 такой сильный скачек, а потом идет более гладко

zzz676 commented 11 months ago

В моей прошивке частота выставлена в 24 МГц.

telegram-cloud-photo-size-4-5893151316224621799-y

По графику зависимости мощности от тока видно что где-то после 2.5 dBm потребление начинает расти круче.

Судя по графику может имеет место и сделать 2.5 (до редкого повышения)

devbis commented 11 months ago

Да, уже снизил до 2dBm, чтобы с небольшим запасом. В будущей версии будет так.

pvvx commented 11 months ago

Этот график не соответствует пиковому потреблению при передаче (работе передатчика). В LYWSD03MMC расчетные разработчиками и рекомендуемые производителем чипов конденсаторы в питание Xiaomi не впаял - пожадничал милли-доллар - оставив пустые позиции на плате. Или им заплатили производители батареек :)

https://www.ti.com/lit/wp/swra349/swra349.pdf ...

для забаненных в google :) https://disk.yandex.ru/i/FCI2cF02obUBdA https://disk.yandex.ru/i/va5kSYfSVlCzpg https://disk.yandex.ru/i/6dNf5Dgx86Bj9Q

image

Рисунок 1: Полная емкость батареи CR2032 мА·ч доступна только при номинальном токе 1 мА.

При RF TX 0 дБ ток 8+ мА (сумма с потреблением CPU), напряжение полу-разряженной CR2032 падает до 3-100*0.008=2.2В Где: 3 - это 3B выдаваемое электрохимическое напряжение данного типа батареек при +20..25С (даже у полностью севшей) 100 - это 100 Ом внутреннего сопротивления у полу-разряженной батареи. Батарея CR2032 садится именно увеличивая внутреннее сопротивление:

image

0.008 - это ток в Амперах.

При +3дБ падение напряжения уже приводит к перезагрузке или зависанию чипа. При резких бросках напряжения питания у TLSR825x первым сбрасывается-нарушается отсчет внутренних таймеров. Это влияет на распределение процессов обработки событий приема-передачи – временную диаграмму для обслуживания Zibee или BLE. Для корректной работы нарушения тайминга не должны достигать 1 us на пару сек.

И т.к. Zigbee использует запись в Flash, а рекомендация от Telink гласит – перед каждой работой с Flash проверять наличие напряжения питания на уровень не менее 2.0В. Сам чип работоспособен до 1.8В.

Т.е. при вылавливании падения напряжения ниже 2.0В чип должен проследовать в deep-sleep на несколько минут. Проснувшись – проверить, восстановилось или нет питание и действовать далее – опять спать или можно работать. Такой сценарий с CR2032 отрабатывает часто, когда температура падает в отрицательные значения или термометр работает от солнечной батареи с малым АКБ. Утром нагреется и заработает. Без реализации такой процедуры батарея будет высажена в ноль в первый раз при падении напряжения.

pvvx commented 11 months ago

Хмм, интересно, почему между 2.5 и 3.5 такой сильный скачек, а потом идет более гладко

Потому, что на уровнях +3дБ производится переключение питания передатчика напрямую к внешнему питанию, минуя встроенный в чип DC-DC. Уровень выходной мощности в SDK задается специальными значениями, в которых некоторые биты указывают к какому питанию будет подключен передатчик и возможны разные комбинации на уровнях 0..+3дБ. График показывает потребление только части RF, без учета потребления CPU и остальной включенной периферии в чипе, да в каких-то идеальных условиях (например как это делает Ti - замер на максимально возможном напряжении питания с включенным DC-DC, или при какой-то скважности передачи указывают средний ток - что только не сделаешь ради рекламы :)). Реальные показатели тока при передаче на уровне +10дБ уходят далеко за 25 мА.

Вы можете сами снять реальную диаграмму зависимости используя Telink SDK Driver с примерами RF_Demo. И купив самый дешевый, немного пригодный для таких измерений, измеритель - nRF Power-Profiler-Kit-2, но учтя, что он сильно искажает измерения импульсных сигналов из-за встроенного авто-переключения диапазонов :)

aurbod commented 1 month ago

I have a follow up question: I'd like to power my sensors via a power supply: a central dc-dc converter providing 3.3v where all my sensors are attached too with cable length < 10m. In addition each sensor will get a 100nF ceramic capacitor locally (which should add as a buffer?). My question is: does anybody see any problems with this approach or should it work? And how do I change the transmit power? From my understanding I should change g_zb_txPowerSet in src/common/main.c):

int main(void){ g_zb_txPowerSet = RF_POWER_INDEX_P1p99dBm;

But I can't find those constants documented anywhere? What would be possible values? And what would be the max supported output power (+10dB)? Thanks for your answers!

Edit: found https://github.com/devbis/tl_zigbee_sdk/blob/565e2de8157da9698d0edb5b441d7fb1526f64bf/platform/chip_8258/rf_drv.h#L161, if I understand this correctly, setting g_zb_txPowerSet to RF_POWER_INDEX_P10p46dBm would mean the TX power would be +10.46 dbm?

pvvx commented 1 month ago

if I understand this correctly, setting g_zb_txPowerSet to RF_POWER_INDEX_P10p46dBm would mean the TX power would be +10.46 dbm?

Yes.

aurbod commented 1 month ago

Ok thanks for your quick reply. Do you have any insights as to whether powering the sensors via a wired power supply and with a local buffering capacitor should work or if there could be any problems?

pvvx commented 1 month ago

The voltage of the source should not exceed 3.6V. The resistance of the wires should not be more than 100 Ohms. The rest is not particularly important.

aurbod commented 3 weeks ago

Ok, so I've implemented the changes, here are the results: Before I had a Linkquality lqi of around 30 on the floor above my zigbee stick with the original devbis firmware After setting RF_POWER_INDEX_P10p46dBm the lqi doubled to at least 65 I'm happy, this should work fine for my needs. Note that there are only a few meters between the two floors with only wood in between, so your z03mmcs probably won't cover more than 2 floors and/or concrete floors. I for example did not get a signal in the cellar probably because the humidity is higher?

pvvx commented 3 weeks ago

It is advisable to try changing the direction of the antenna (thermometer body and receiving antenna). They all had directionality. Rotating the receiver with an internal antenna often gives an increase of more than +10 dBm.


I have normal reception from the second house, located 200 meters away. 3 walls made of timber, siding - galvanized sheet. Reception is carried out in BLE in LE Long Range mode. The thermometer in the other house has a transmission level of +0 dBm. USB-BT RTL8761B receiver with an internal antenna, reception level: -105..107 dBm (with Zigbee and WiFi this is not possible.).

image

image

Thermometer - https://pvvx.github.io/MJWSD05MMC/, the battery included in the kit has been working for more than 1.5 years.

image

Previous data was erased - HA was transferred to a new microcomputer in March 2023.

If the USB-BT adapter is installed in the wrong position, then there will be no reception.

At the window the level is about -90..95 dBm (window - 200 meters - timber wall).