logo elektroda
logo elektroda
X
logo elektroda

Tuya LSPA9 smart socket - teardown, OpenBeken flashing guide for CB2S, BL0942

p.kaczmarek2 92835 378
ADVERTISEMENT
Treść została przetłumaczona polish » english Zobacz oryginalną wersję tematu
  • #271 21011645
    Wimmi
    Level 4  
    Are you sure that your plug uses the BL0937for energy measurements? Your start-up command loads this driver. The CUCO-6Z devices in this topic above make use of the BL0942 device at baudrate 9600.

    BR Wimmi
  • ADVERTISEMENT
  • #272 21011720
    Dark Man
    Level 13  
    Problems with energy measurement suddenly started to appear without any software changes or fiddling/changes in the software.
    Then I updated the firmware via OTA, thinking that maybe it would solve the problem, but unfortunately it didn`t :(

    Today I desoldered two main electrolytic capacitors for 10V and 400V and the capacity measurement showed no loss, in fact they had more than on the label.
  • #273 21011721
    p.kaczmarek2
    Moderator Smart Home
    To be sure - are we talking about BL0942? I don`t think it`s visible on your screenshots.

    BL0937 doesn`t like PowerSave. With BL0937 you can disable PowerSave.
    Helpful post? Buy me a coffee.
  • #274 21011734
    Dark Man
    Level 13  
    No, I have the BL0937 system.
    Turning off Powersave does not mean that it no longer shows 0V even when the relay is on and there is no load :(
  • #275 21011737
    p.kaczmarek2
    Moderator Smart Home
    Are you sure PowerSave is disabled? Perform a reboot.

    Maybe recalibrating will help?
    Helpful post? Buy me a coffee.
  • #276 21011747
    Dark Man
    Level 13  
    Yes, I`m sure.
    I executed the Powersave 0 command and added it to the startup commands + restarted.
    As I wrote yesterday, I calibrated the 40W bulb yesterday and when it is connected as a load, the measurements show well (with slight +- jumps), but if I connect another load, it is completely inappropriate, even the voltage - e.g. 42V
  • #277 21011839
    p.kaczmarek2
    Moderator Smart Home
    I`m running out of ideas. The problems I suspected were:
    - PowerSave (its absence or, paradoxically, its activation with BL0937)
    - calibration is broken
    - The OTA firmware broke something
    - capacitors in the power supply
    If none of the above, you can also consider resetting the OBK configuration using the clearConfig command from here (or in the Tools tab):
    https://github.com/openshwprojects/OpenBK7231T_App/blob/main/docs/commands.md
    Another thing I would try is, unfortunately, replacing the BK module with another one to at least know which side is at fault.
    Helpful post? Buy me a coffee.
  • #278 21014072
    cdtdsilva
    Level 10  
    It might be worth to check those resistors that feed the PGA on pin 4. I've repaired many that went open circuit and can cause strange behaviour, because the impedance of these pins is so high! That would affect the voltage and Wh meter readings.
  • #279 21014402
    p.kaczmarek2
    Moderator Smart Home
    @DarkMan1 please see this topic: https://www.elektroda.com/rtvforum/topic4044135.html#21011887
    User had similiar problem and it was capacitor.
    Helpful post? Buy me a coffee.
  • #280 21014854
    cdtdsilva
    Level 10  
    Dark Man wrote:
    Problems with energy measurement suddenly started to appear without any software changes or fiddling/changes in the software. Then I updated the firmware via OTA, thinking that maybe it would solve the problem, but unfortunately it didn`t :( Today I desoldered two main electrolytic capacitors for 10V and 400V and the capacity measurement showed no loss, in fact they had more than on the label.


    Dark man, when you tested the capacitors, did you also tested their ESR? Worth to parallel another one on the 3.3V line or decouple with a ceramic, just to be sure that's not high ripple affecting it.
  • ADVERTISEMENT
  • #281 21034493
    alexej550271
    Level 5  
    Доброго времени суток парни! Выручайте пожалуйста... Исследую устройство (готового решения не смог найти к сожалению... Устройство компании EARU, на борту модуль MCU, убрав экран увидел чип bk7231n и энергомонитор BL0942. Убив достаточно не мало времени и получая информацию из различных ресурсов удалось заставить его работать почти полностью, но не получается запустить измерение напряжения, тока, потреблённой мощности и прочего.. То есть микросхема BL 0942 как понимаю не работает или что-то типа того, так как в веб интерфейсе все показатели равны 0.00, не показывает частоту сети, напряжение, ток, мощность и прочее, просто 0... Перепробовал все варианты и spi драйвер и устанавливать скорость 9600, ничего не помогает, драйвер spi, отправляет только шум, все остальные манипуляции никакого решения не дали, данные постоянно равны 0... Единственное я не знаю, нужно ли в конфигурации назначить что-то на пины rx и tx? Если что-то нужно указать на пины rx и tx? подскажите пожалуйста что нужно указать. Помогите пожалуйста решить мою проблему и будет ещё одно поддерживаемое устройство..
  • #282 21034516
    p.kaczmarek2
    Moderator Smart Home
    @alexej550271 no, you don't need to assign RX and TX for BL0942 in the config page. You just need to do:
    
    startDriver BL0942
    

    and then most likely also calibrate.
    If you suspect you have different baud rate setting, try:
    
    startDriver BL0942 9600
    


    Alternatively, your device may be TuyaMCU, so see:
    TuyaMCU flashing, setup and configuration guide - configure dpIDs for Home Assistant


    @alexej550271 Please show photos of your device.
    Helpful post? Buy me a coffee.
  • #283 21034586
    alexej550271
    Level 5  
    Я пробовал уже оба варианта драйвера, в том числе с указанием скорости 9600 и вариант spi, к сожалению так ничего и не получилось... Даже не знаю уже что делать... A device with a WiFi module by EARU, mounted on a power strip.

    Added after 5 [minutes]:

    >>21034516
    Скажите пожалуйста, если там используется TuyaMCU, вы можете мне помочь настроить драйвер BL0942, а то не смог найти инструкцию и не очень хорошо понимаю в этом деле... В логе устройства, вообще нет никакой информации от 0942...

    Added after 6 [minutes]:

    >>21034516 А может быть такое, что я использую не правильную прошивку? У меня стоит Build on Apr 5 2024 08:08:17 version 1.17.535, скажите пожалуйста, она подходит?..

    Added after 12 [minutes]:

    Photo showing a display with a configuration code for an electronic device. >>21034516 скорость пробовал разную 9600, 4800, 115200, возможно нужно ещё какую то попробовать?

    Added after 52 [minutes]:

    >>21034516 Ещё в логах увидел такие строки
    Info:EnergyMeter:Read ENERGYMETER status values. sizeof(ENERGY_METERING_DATA)=32
    Info:MAIN:Started BL0942.
    Info:CMD:LFS_ReadFile: failed to file autoexec.bat
    Info:CMD:CMD_StartScript: failed to get file autoexec.bat
    Info:MAIN:Main_Init_After_Delay done
    скажите пожалуйста, в этом может быть проблема?
    Просто других идей у меня больше нет, перепробовал уже все скорости уарт, В логе есть информация о запуске драйвера BL 0942, но нет совершенно никаких данных, только 0, в каждом параметре...

    Added after 5 [hours] 55 [minutes]:

    >>21034516 Ещё фото устройства Close-up of a circuit board with a mounted microprocessor and colorful wires attached to connectors.
    Electronic components and a circuit board inside a device. Electronic module with connected wires on a wooden surface background.

    Added after 15 [minutes]:

    >>21034516 В общем установил "родную" прошивку, чтобы проверить микросхему bl0942, с родной прошивкой есть показания напряжения, тока и мощности, всё работает исправно. Так что дело в драйвере или в чём то ещё... Нужно разобраться и в этом мне очень нужна ваша помощь! Сам разобраться не смогу. Ещё такой момент, когда ставил родную прошивку, в ком порт постоянно отправлялись какие то знаки, проверял в ком порту Ардуино Иде, идентифицировать их не удалось, так как на любой скорости были непонятные не читаемые символы, точнее квадратики и вопросительные знаки, только на скорости 9600 было типа такого?ff?ff?ff?ff и так далее. После прошивки OpenBeken в ком порт ничего не отправляется и показаний нет.. может быть проблема в этом? Нет запроса? Но я не программист и моих знаний совершенно недостаточно для понимания проблемы и решения её, может быть у кого-то есть решение и инструкция как сделать, чтобы всё работало?.. Буду очень благодарен и признателен!
  • #284 21035114
    cdtdsilva
    Level 10  
    If Nothing is set, then maybe the pin allocation is wrong? Some devices use an alternative serial port.
    Also check you didn't short any serial port pin with a multimeter. I know it's stupid, but I've made that mistake in more than one ocasion.

    You can manually send data to the BL0942 using a serial port and your PC
    You need to send Hexadecimal Data - You wont be able to use or read it with the Arduino terminal as that only supports ASCI.

    Please use real term software: Link and if you need some help, just follow the video below. I know it's in English, but should be straightforward to understand.




    Here's an example. You just need to send HEX 58 AA and it should repply.
    On real term you write it as '0x58 0xAA' - No line termination characters

    Serial communication data output in hexadecimal format.
  • #285 21035178
    alexej550271
    Level 5  
    Большое спасибо за вашу помощь! Я попробую, надеюсь, что-нибудь получится)) Контакты прозванивал, именно они используются, насколько я проверил мультиметром.
  • ADVERTISEMENT
  • #286 21035184
    divadiow
    Level 35  
    @alexj550271 have you posted your original Tuya config download or a whole factory firmware dump anywhere yet? Screenshot of the Flash section in an application interface related to Tuya device configuration and file downloads.
  • #287 21035287
    alexej550271
    Level 5  
    >>21035178 В общем пришлось снова прошить родную прошивку, чтобы проверить (на OpenBeken были тишина в ответ на мои запросы 0х58 0хАА на обоих портах, на втором порту на 115200 была отладочная информация), получилась следующая ситуация На первом порту, который используется для перепрошивки постоянно(раз в секунду) бегут строки 58 АА 58 АА и так далее, на втором порту раз в несколько секунд (точно не замерял) тоже проскакивают различные данные 90 29 8C 6A EC C4 D6 FD 09 A9 FE 6C 0B C0 88 C6 8C 72 C7 D6 FD AC C4 21 D1 типа такого.. На отправку команд по-моему не реагирует насколько я смог понять разницы нет. Но если отправить команду в первый порт, а ответ получить из второго (TX1>>RX2) Тогда мгновенно приходит ответ примерно такого типа 58 AA 05 F9 0A CE 84 84 FD 58 AA 0C 90 58 AA 05 81 58 AA 01 C1 D1 6D E6 B1 14 74 AD 58 AA 41 FD 21 59 E6 6A C4 58 AA B6 2E 6C 04 C4 E8 8C 86 24 AA FD AA 7D как правило сначала два числа, затем еще несколько, если запросы не отправлять, данные периодически (примерно раз в 5 сек) приходят новые. Возможно эта информация поможет как решить проблему?..

    Added after 16 [minutes]:

    >>21035184 Нет, никто не просил её разместить, но есть одна проблема, там же прописаны все мои данные как понимаю, для подключения к сети и к приложению... В связи с тем, что ещё есть устройства которые я использую с этим приложением, мне не хотелось бы скидывать так сказать на всеобщее обозрение... Подскажите пожалуйста как можно поступить в данной ситуации?...

    Added after 5 [minutes]:

    >>21035184 Подскажите пожалуйста как сделать то, что нужно дамп заводской прошивки или бэкап заводской прошивки без моих данных))) У меня сейчас есть бэкап заводской прошивки, из него я и загружаю заводскую прошивку, но она содержит все мои персональные данные, так как устройство сразу подключается к сети и приложению.. Как можно поступить в данной ситуации, подскажите пожалуйста..
  • #288 21035316
    divadiow
    Level 35  
    oh. not 100% sure if it's just the config data and not the full factory fw. I know the SSID and password is retrievable from the full dump if the dump was taken with the device paired/not reset.

    Here's one of my config files and the extracted info from it. nothing tied to me. I don't have a Tuya account.

    Code: JSON
    Log in, to see the code
  • #289 21035397
    cdtdsilva
    Level 10  
    >>21035287


    @alexej550271
    You need two serial ports, if you're probing an existing communication between the BL0942 and the Becken chip. That's because you need two RX lines: One to listen the request from the host and the other to listen to the repply from the BL0942. Can you confirm this is what you're using?

    With open becken, you should be seing a request once a second to the BL0942, once you start the driver. You need to figure out what pin that is and if it is the one connected to the BL0942. The BL0942 repply is 23 bytes long, so 23 sets of two letters in hex.
  • #290 21035584
    alexej550271
    Level 5  
    https://www.elektroda.com/rtvforum/posting.ph...itpost&p=21035584#[postid:3923cceabc]21035316[/postid:3923cceabc] Как уже говорил, в этом деле я чайник... И не понимаю как добыть какой дамп памяти.. У меня есть бэкап заводской прошивки, который был сделан когда устройство уже было настроено, проверено и сопряжено со Smart Life.. Как понимаю, мне нужно отвязать устройство и попробовать сделать ещё один бэкап заводской прошивки? Или это не поможет?

    Да, я использовал два порта в tx1 отправил команду в rx2 получил ответ. Не уверен что все правильно делаю так как у меня не очень большой опыт в этом деле и цифры (байты) которые я отправил были получены на скорости 4800, так как было почти пять часов утра и был не внимательным.. Когда заметил и исправил скорость на 9600 (байты) поменялись и их стало больше, а также по-моему они стали стабильнее))

    Added after 1 [hours] 50 [minutes]:

    >>21035316 Надеюсь правильно понял и это то, что нужно.
    Code: JSON
    Log in, to see the code


    Device configuration, as extracted from Tuya:
    - Button (channel 1) on P7
    - LED (channel 1) on P6
    - Bridge Relay On (channel 1) on P24
    - Bridge Relay Off (channel 1) on P26
    - WiFi LED on P8
    Device seems to be using CBU module, which is using BK7231N.
    And the Tuya section starts, as usual, at 2023424

    Единственное кое что я изменил на прочерки, опасаюсь, что это конфиденциальная информация, если какие то данные таковыми не являются и нужны для работы, укажите пожалуйста какие и я вам их предоставлю.

    Так же как говорил ранее, у меня есть бэкап заводской прошивки, могу скинуть в личную почту, если это поможет решить данную проблему. Ещё раз спасибо, что помогаете мне!
  • ADVERTISEMENT
  • #292 21035718
    alexej550271
    Level 5  
    Извините пожалуйста, не совсем понимаю, что мне нужно сделать... Если вы это конечно мне)))
  • #293 21036066
    p.kaczmarek2
    Moderator Smart Home
    On this picture:
    Image of a circuit board labeled EZB-WCH60AN-A V1.0, showing electronic components and two capacitors.
    1. Are you sure it is BL0942? Can you show better photo? What is the chip marking?
    Diagram of BL0942 integrated circuit with pin labels.
    Close-up of an integrated circuit labeled BL0942 with additional numbers and letters.
    2. Take multimeter to hand:
    Digital multimeter with black and red probes
    2.1 Is there connectivity between BL0942 RX and WiFi module TX1?
    2.2 Is there connectivity between BL0942 TX and WiFi module RX1?
    2.3 Is there connectivity between WiFi module RX1 and WiFi module TX1?

    3. Take a look at this section:
    Diagram of BL0942 integrated circuit with pin labels.
    Table describing pins of SSOP10L with highlighted SEL pin (7).
    How is SEL (pin 7) connected?
    3.1 Take multimeter, is there a connectivity between SEL and GND?
    3.2 Take multimeter, is there a connectivity between SEL and VDD?

    Please answer the questions above so we can debug the issue futher.
    Helpful post? Buy me a coffee.
  • #294 21036340
    alexej550271
    Level 5  
    Извините сейчас нет возможности сделать более удачное фото, но поверьте пожалуйста на слово, смотрел под микроскопом, там действительно BL0942.
    2.1 всё ок, связь есть.
    2.2 ок, связь есть.
    2.3 ок, связи нет.
    3.1 при подаче питания -3в gnd есть
    3.2 Vdd питание отсутствует

    7 ножка (SEL) подтянута к GND.

    Added after 38 [minutes]:

    Парни думаю этот вопрос можно считать закрытым, драйвер работает!!! Не знаю пока в чём проблема, но разбираться буду уже не сегодня... Установил по новой OBK, удалил совершенно всё из конфигурации (все пины) И запустил только драйвера без указания скорости и ооо чудо, драйвер начал показывать напряжение!!!
  • #296 21037249
    alexej550271
    Level 5  
    Ребята извините пожалуйста, что не по теме, но начал вникать в суть прошивки и очень начинает нравиться! Но у меня есть несколько вопросов...
    1. Подскажите пожалуйста где можно посмотреть список поддерживаемых датчиков, дисплеев, сенсоров и прочего.
    2. Как понимаю, можно задавать взаимодействие датчиков, дисплеев, сенсоров и поочее, это нужно задавать как-то, писать код, скрипт или что-то типа того, тоже очень интересно где об этом можно почитать.э, чтобы понимать, что и как делать правильно.
    3.как понимаю можно настроить взаимодействие между устройствами по http, mqtt, об этом тоже хотелось бы почитать и поучиться.
    4. Ну и вообще хотелось бы более подробно изучить именно эту прошивку, её возможности, функционал и прочее, где можно обо всём этом почитать?...
    Ещё раз прошу прощения, что не по теме и заранее благодарю вас за ответ! С уважением Алексей! И огромное спасибо за ваш труд и за такую отличную прошивку!

    Added after 37 [minutes]:

    И ещё такой вопрос нужен ли разбор двух устройств, которые у вас я не смог найти, но которые удалось прошить вашей прошивкой. Если да, то как и куда их нужно опубликовать и как правильно оформить?

    И ещё такой вопрос подскажите пожалуйста, у меня есть ещё одно устройство которое хочу прошить, это ИК пульт, но я не могу понять, как мне на вашей прошивке считать коды устройств и сохранить их, а также как их использовать без НА, а только mqtt и http.
    Скажите пожалуйста где можно почитать об этом и получить полную информацию.
  • #297 21037363
    p.kaczmarek2
    Moderator Smart Home
    alexej550271 wrote:

    1. Подскажите пожалуйста где можно посмотреть список поддерживаемых датчиков, дисплеев, сенсоров и прочего.

    Many devices are supported. Almost all basic device types are supported, even if they are not listed.
    But you can see:
    https://openbekeniot.github.io/webapp/devicesList.html
    You can also check drivers list:
    https://github.com/openshwprojects/OpenBK7231T_App/blob/main/docs/drivers.md
    And Youtube channel:
    https://www.youtube.com/@elektrodacom
    But please remember, that any device can be supported, it does not have to be listed.

    alexej550271 wrote:

    2. Как понимаю, можно задавать взаимодействие датчиков, дисплеев, сенсоров и поочее, это нужно задавать как-то, писать код, скрипт или что-то типа того, тоже очень интересно где об этом можно почитать.э, чтобы понимать, что и как делать правильно.

    For simple things, you just use WWW panel, set pin roles for GPIO etc:
    https://github.com/openshwprojects/OpenBK7231T_App/blob/main/docs/ioRoles.md
    For more advanced you can write autoexec.bat
    https://github.com/openshwprojects/OpenBK7231T_App/blob/main/docs/autoexecExamples.md

    alexej550271 wrote:

    3.как понимаю можно настроить взаимодействие между устройствами по http, mqtt, об этом тоже хотелось бы почитать и поучиться.

    OpenBeken can:
    - receive commands via GET like Tasmota, cmnd syntax
    - send GET and POST with SendGet/SendPOST
    - host a custom HTML+Javascript page
    - and much more

    Here is HTTP API for REST tutorial:
    OpenBeken as a mini HTTP hosting - writing pages in Javascript, Tasmota REST
    Here is an example:
    OpenBeken on BW-AF1 fryer with WiFi - interior, TYWE3S/WB3S, configuration


    alexej550271 wrote:

    4. Ну и вообще хотелось бы более подробно изучить именно эту прошивку, её возможности, функционал и прочее, где можно обо всём этом почитать?....

    To study OpenBeken, check OBK docs:
    https://github.com/openshwprojects/OpenBK7231T_App/blob/main/docs/README.md
    Check Youtube tutorials:
    https://www.youtube.com/@elektrodacom
    Check smart home tutorials:
    https://www.elektroda.com/rtvforum/forum517.html

    To find info on particular topic, use search function. For example, for SendGET:
    https://www.elektroda.com/rtvforum/find.php?q=SendGET


    alexej550271 wrote:

    И ещё такой вопрос нужен ли разбор двух устройств, которые у вас я не смог найти, но которые удалось прошить вашей прошивкой. Если да, то как и куда их нужно опубликовать и как правильно оформить?

    Open a new topic, put device name, manufacturer, maybe shop, type, etc, in the title.
    If you have, post some device photos. Write name of ICs inside.
    If you can, copy OpenBeken JSON template.
    If something is not working, we can help you. We can guide you with flashing, etc.
    See example device topic:
    https://www.elektroda.com/rtvforum/topic4036567.html
    You can also post shorter questions if you don't know how to flash and we will help.



    alexej550271 wrote:

    И ещё такой вопрос подскажите пожалуйста, у меня есть ещё одно устройство которое хочу прошить, это ИК пульт, но я не могу понять, как мне на вашей прошивке считать коды устройств и сохранить их, а также как их использовать без НА, а только mqtt и http.

    Ok, so for IR, you need to open commands doc:
    https://github.com/openshwprojects/OpenBK7231T_App/blob/main/docs/commands.md
    A section of a table with IR commands like IREnable and IRSend.
    You can also check on forum:
    https://www.elektroda.com/rtvforum/find.php?q=IRSend
    You can watch short IR hack presentation:




    If you need more guidance on some particular topic, please open a new topic and we will discuss there:
    https://www.elektroda.com/rtvforum/posting.php?mode=newtopic&f=51
    Helpful post? Buy me a coffee.
  • #298 21037616
    alexej550271
    Level 5  
    Большое вам спасибо! Вы очень добры ко мне и мне очень приятно иметь дело с вами и вашей замечательной прошивкой! Думаю что когда изучу её более подробно, досконально и буду в ней понимать больше, она мне ещё больше понравится!))) А после того как добавите чип rtl 8710bx, я буду ещё более счастлив!)) Ещё раз огромное вам спасибо! С уважением Алексей.
  • #299 21108415
    kyrychenkoqa
    Level 2  
    Hello guys. Can some one help me out where i can locate Tx and VCC, from main board? Because i damaged those 2 pads when desoldered CB2S module. Is that located on BL0937 ? Any help would be appreciated.
  • #300 21109663
    p.kaczmarek2
    Moderator Smart Home
    Hey @kyrychenkoqa , have you managed to read Tuya partition from your CB2S? Maybe we can use it to guess what was TX used for.

    As for VCC, the 3.3V, I guess it may be at the output of AMS1117-3.3. Do you have such LDO on your board?

    Can you provide photos of your PCB?
    Helpful post? Buy me a coffee.

Topic summary

The discussion centers on the Tuya LSPA9 smart socket teardown and the process of flashing OpenBeken firmware on devices based on the CB2S (BK7231N) module with BL0942 or BL0937 energy metering chips. Detailed guides cover hardware disassembly, UART programming, pin configurations, and calibration commands for accurate voltage, current, and power measurements. Users report variations in internal components, such as different pinouts and energy metering chips (BL0942 vs. BL0937), requiring tailored firmware settings. The OpenBeken firmware supports features like automatic calibration data saving, MQTT integration with Home Assistant discovery, and configurable precision for telemetry data. Issues discussed include OTA update behavior, negative power measurement spikes, device stability problems with CB2S, and DNS resolution in MQTT. Solutions involve firmware updates, command-line calibration, and community-shared device templates. The project supports multiple chip platforms (BK7231T/N, W600/W601, W800/W801, BL602, XR809) and aims to provide cloud-free, customizable IoT device firmware. Users also share experiences with alternative devices like Aubess and Arlec smart plugs, including pin mappings and flashing tips. The community actively contributes to device template databases and firmware improvements.
Summary generated by the language model.
ADVERTISEMENT