logo elektroda
logo elektroda
X
logo elektroda

Smart cube with power metering, 2 phase with clamps, 2x BL0942, CBU module, BK7231N

XJ_ 3399 118
ADVERTISEMENT
  • #31 21321489
    p.kaczmarek2
    Moderator Smart Home
    Whoa, @XJ_ , very good job on checking UART code! There was indeed a bug:
    Screenshot of Visual Studio IDE with UART test code and output console showing test failure results.
    Screenshot of C language program code showing the Test_UART() function.
    I've added a self-test:
    https://github.com/openshwprojects/OpenBK7231...mmit/a2f3b020686633c643ab8790875e00173bb9d354
    and merged your PR:
    https://github.com/openshwprojects/OpenBK7231T_App/pull/1436
    The test should now pass correctly.

    That was indeed a very good job, keep it on, we need more fixes like that.

    Let me know what's the state of full double BL0942 support, can I help with it somehow? Do you have a list of things changed or a quick summary, how does it maintain compatibility with older versions?
    Helpful post? Buy me a coffee.
  • ADVERTISEMENT
  • #32 21321593
    XJ_
    Level 11  
    p.kaczmarek2 wrote:
    Let me know what's the state of full double BL0942 support, can I help with it somehow? Do you have a list of things changed or a quick summary, how does it maintain compatibility with older versions?

    I'm testing it in my own "junction box", it works like a charm. The only thing that needs to be done to make it available to others on BK7231N is to merge https://github.com/openshwprojects/OpenBK7231N/pull/21 .

    For BK7231T I have to wait for the module and try to find a bug in BK7231T SDK as well as BK7231N.

    Added after 42 [seconds]:

    p.kaczmarek2 wrote:
    That was indeed a very good job, keep it on, we need more fixes like that.

    Thank you

    Added after 2 [minutes]:

    p.kaczmarek2 wrote:
    I've added a self-test:

    Great 👍
  • #33 21321672
    p.kaczmarek2
    Moderator Smart Home
    So I see you've added index here:
    Code: C / C++
    Log in, to see the code

    but now, how does HA Discovery works? What is the MQTT name of first and second BL0942 readouts values?
    Helpful post? Buy me a coffee.
  • #34 21321681
    XJ_
    Level 11  
    p.kaczmarek2 wrote:
    but now, how does HA Discovery work? What is the MQTT name of first and second BL0942 readout values?

    @Src/driver/drv_bl_shared.c
    typedef struct energysensor energysensor_t;
    typedef struct {
      energysensor_t sensors[OBK__NUM_SENSORS];
    } energysensdataset_t;
    
    energysensdataset_t datasetlist[BL_SENSDATASETS_COUNT] = {
      { {      //.hass_dev_class,    .units,      .name_friendly,         .name_mqtt,       .hass_uniq_id_suffix, .rounding_decimals, .changeSendThreshold      
          {{"voltage",      "V",      "Voltage",            "voltage",               "0",      },  1,         (float)0.25,      },   // OBK_VOLTAGE
          {{"current",      "A",      "Current",            "current",               "1",      },   
    ...
    
        } }
    ,
       { {
           //.hass_dev_class,    .units,      .name_friendly,         .name_mqtt,       .hass_uniq_id_suffix, .rounding_decimals, .changeSendThreshold      
           {{"voltage",      "V",      "Voltage B",            "voltage_b",               "0",      },  1,         (float)0.25,      },   // OBK_VOLTAGE
           {{"current",      "A",      "Current B",            "current_b",               "1",      },   3,   
    
    

    Fragment of C code defining structures related to energy sensors.
  • #35 21321701
    p.kaczmarek2
    Moderator Smart Home
    If the "voltage" MQTT name has changed to "voltage_b", then it will break compatibility with existing HASS configurations.

    Most likely the preferred (but a bit dirty) solution is to introduce voltages as "voltage" (no name change) and "voltage2", I guess?
    Helpful post? Buy me a coffee.
  • #36 21321705
    XJ_
    Level 11  
    p.kaczmarek2 wrote:
    What is the MQTT name of first and second BL0942 readouts values

    At this time, the energy calculation is performed as before only for channel 0, channel 1 is only voltage, current and power with the suffix _b

    Added after 2 [minutes]:

    p.kaczmarek2 wrote:
    then it will break compatibility with existing HASS configurations

    How? Tuya driver uses _a and _b.

    Added after 6 [minutes]:

    XJ_ wrote:
    How? Tuya driver uses _a and _b.

    By the way, the _a suffix was not a good decision, I always delete it on Tuya.

    Added after 4 [minutes]:

    @>>21321672
    I suggest you to look at this PR first
    https://github.com/openshwprojects/OpenBK7231T_App/pull/1437
    and then at
    https://github.com/xjikka/OpenBK7231T_App/tree/twinbl0942mod
  • #37 21321729
    p.kaczmarek2
    Moderator Smart Home
    XJ_ wrote:

    p.kaczmarek2 wrote:
    then it will break compatibility with existing HASS configurations

    How? Tuya driver uses _a and _b.


    Maybe I misunderstood the code, but as far as I know, the Home Assistant Discovery mechanism works by telling HA which topics are used for stuff like relays, voltage, power, energy, etc. So, once you do this process:



    the Home Assistant begins to remember that it should listen to, specifically, "voltage" MQTT topic (with device name prefix, etc etc) and show it on panel.
    If you then update OBK, to publish voltage on "voltage_a" instead of "voltage", it will break HA connectivity. HA will no longer receive voltage data under expected topic.

    So, here are my two current concerns:
    1. Does the current solution maintain compatibility with older HASS configurations (either via Discovery or configuration.yaml)
    2. Did you also include your changes in the HASS Discovery code, so Home Assistant "can see" both measuring chips?
    Helpful post? Buy me a coffee.
  • ADVERTISEMENT
  • #38 21321740
    XJ_
    Level 11  
    p.kaczmarek2 wrote:
    "voltage_a" instead of "voltage", it will break HA connectivity.

    Maybe I wrote it wrong, I don't want to use the suffix _a in any case. On the contrary, for the TuyaMCU driver (I have also one cube meter with TuyaMCU), I delete it (suffix _a) in HASS so that it works properly in HASS.

    Added after 9 [minutes]:

    p.kaczmarek2 wrote:
    So, here are my two current concerns:
    1. Does the current solution maintain compatibility with older HASS configurations (either via Discovery or configuration.yaml)
    2. Did you also include your changes in the HASS Discovery code, so Home Assistant "can see" both measuring chips?


    - ad 1 Yes - but only channel 0 as before
    - ad 2 Not yet, it only sends MQTT messages, which is enough for my needs at the moment. Once I have verified that it is ok this way, I will add discovery.

    That is why I have not made a PR for this modification yet.

    Added after 6 [minutes]:

    p.kaczmarek2 wrote:
    specifically, "voltage" MQTT topic

    I think it's based on dev_class and unit_of_measurement and state_topic topic has no effect on it, however when I do discovery I'll check it.

    state_topic: pwr_main_2nd/voltage_b/get
    unit_of_measurement: V
    name: Voltage
    unique_id: bkn_pwr_main_2nd_sensor_10
    state_class: measurement
    device_class: voltage


    Anyway, thanks for the suggestion, I'll check it out and change it if necessary before I make a PR. I'm doing it for HASS after all, so why would I complicate it for myself ;-)
  • #39 21321794
    p.kaczmarek2
    Moderator Smart Home
    In a meantime, I will check if we already have a self-test for BL0942/BL0937/etc MQTT topics and if not, I will add it. This will help us to make sure that all topics stayed compatible with previous versions.

    Probably I will have to extend this:
    https://github.com/openshwprojects/OpenBK7231...blob/main/src/selftest/selftest_energyMeter.c
    Helpful post? Buy me a coffee.
  • #40 21321819
    XJ_
    Level 11  
    p.kaczmarek2 wrote:
    This will help us to make sure that all topics stayed compatible with previous versions

    👍

    Added after 50 [minutes]:

    p.kaczmarek2 wrote:
    stayed compatible with previous versions.

    It wouldn't be bad to at least check device_class state_class and unit_of_measurement - that would reveal, for example, my typo here https://github.com/openshwprojects/OpenBK7231T_App/pull/1433.
  • ADVERTISEMENT
  • #41 21321989
    p.kaczmarek2
    Moderator Smart Home
    I've double checked and it seems that selftest_energyMeter.c already checks for:
    Code: C / C++
    Log in, to see the code

    We also have Test_HassDiscovery_BL0942 in selftest_hass_discover.c:
    Code: C / C++
    Log in, to see the code

    The main drawback of current approach is that the tests don't check for keyword presence in given publish, but they check all publishes, but I will try to improve it as well. Still, they should detect missing MQTT topics well.

    Added after 8 [minutes]:

    Ok I am improving it:
    Code: C / C++
    Log in, to see the code


    Added after 12 [minutes]:

    Much better? Almost..
    Test code in Visual Studio editor regarding MQTT tests.
    Helpful post? Buy me a coffee.
  • #42 21322078
    XJ_
    Level 11  
    p.kaczmarek2 wrote:
    Much better? Almost..

    Wow, 3key, impressive!

    So you'll add a check according to drv_bl_shared.c, right?

    Screenshot of a text editor showing a fragment of C code related to sensor definitions.
  • #43 21322110
    p.kaczmarek2
    Moderator Smart Home
    More or less, I guess, but I need to do without using the C table you mentioned, otherwise it would defeat the purpose... if I were to use exactly the data from table, then I wouldn't be able to catch typo in it anyway.
    Helpful post? Buy me a coffee.
  • #44 21322141
    XJ_
    Level 11  
    p.kaczmarek2 wrote:
    but I need to do without using the C table you mentioned, otherwise it would defeat the purpose

    Of course, I didn't even mean to use a structure, that wouldn't make sense (as you wrote)
  • #45 21324450
    XJ_
    Level 11  
    >>21321593
    I got some WB2S today. I compiled it using PR https://github.com/openshwprojects/OpenBK7231T/pull/20 and the stock app using:

        git clone https://github.com/xjikka/OpenBK7231T -b uart2 ./bk7231t
        git clone https://github.com/openshwprojects/OpenBK7231T_App ./bk7231t/apps/OpenBK7231T_App
        cd bk7231t
        ./build_app.sh apps/OpenBK7231T_App OpenBK7231T_App 1.17.777-uart2sdk
    

    And BL0942 on UART2 works without any problems with this autoexec.bat:

       logtype none
       setflag 26 1
       startDriver BL0942
    


    Also, when I send some dummy bytes to UART2, I get as expected:

       Warn:EnergyMeter:Consumed 30 unwanted non-header byte in BL0942 buffer 
    


    So I can confirm that this UART2 patch is also ok for the BK7231T chip and it is mergeable from my side.

    As a bonus I checked the twinbl0942mod branch and both channels on both UARTs working with this PR.

    And as an added bonus, here's my test build. Just so you know how not to do it ;-)

    Prototype setup with electronic components on breadboards with wires and a power adapter.
  • #46 21324542
    p.kaczmarek2
    Moderator Smart Home
    Nice, I see you're using the same variable power supply that I did once a teardown of:
    https://www.elektroda.pl/rtvforum/topic3919579.html
    As for the protoboard power supply, well, I have my own version:
    https://www.elektroda.pl/rtvforum/topic3752773.html

    Today I extended the self test a bit:
    https://github.com/openshwprojects/OpenBK7231...mmit/a6dcddb6a533901c38a0d1b03939e4cf449babc2
    ... but for some reasons now, self test fails on Github but not on my PC? I need to investigate... maybe it times out on the cloud build. I can't see anything wrong in Github logs.

    I've merged the BK7231T PR.
    Helpful post? Buy me a coffee.
  • #47 21324642
    XJ_
    Level 11  
    p.kaczmarek2 wrote:
    As for the protoboard power supply,

    The red wire is there to make it hot and spicy, right? |;)

    Breadboard with a red wire connected to a blue electronic board.

    Added after 17 [minutes]:

    p.kaczmarek2 wrote:
    I extended the self test a bit:

    ANY_4KEY – You are unstoppable

    Added after 11 [minutes]:

    p.kaczmarek2 wrote:
    I've merged the BK7231T PR.

    👌

    Added after 1 [minutes]:

    p.kaczmarek2 wrote:
    self test fails on Github but not on my PC?

    Can I help You somehow with that?

    Added after 25 [minutes]:

    p.kaczmarek2 wrote:
    well, I have my own version:


    Nice work and Powerfull - up to 1,2A !
    The version from Ali is really weak (current) and the stabilizers get hot even at low load. However, it is enough for me for testing.

    Power module with USB output and power connector, polarity marked with arrows.

    I have also another version, and it almost blew up my processor.
    !!! plus and minus are reversed !!!

    Electronic module with highlighted reversed power supply polarity.

    Fortunately, I noticed it in time!
  • #48 21324728
    p.kaczmarek2
    Moderator Smart Home
    XJ_ wrote:
    p.kaczmarek2 wrote:
    As for the protoboard power supply,

    The red wire is there to make it hot and spicy, right? |;)
    [/quote]
    Exactly! This protoboard power supply is shortcircuit-proof, it just lights up a LED when there is a short.

    XJ_ wrote:

    ANY_4KEY – You are unstoppable

    When something is stupid but works, then it's not stupid :D

    XJ_ wrote:

    p.kaczmarek2 wrote:
    self test fails on Github but not on my PC?

    Can I help You somehow with that?

    For now, I am investigating myself, it seems that two of self tests fail on Github but not on my machine:
    
    ERROR: SelfTest failed for SIM_HasMQTTHistoryStringWithJSONPayload("homeassistant", 1, 0, 0, "dev_cla", "energy", "stat_t", "~/energycounter/get", "unit_of_meas", "Wh", "stat_cla", "measurement")
    Check D:\a\OpenBK7231T_App\OpenBK7231T_App\src\selftest\selftest_hass_discovery.c - Test_VerifyForCommonPowerMeteringStuff - line 339
    Total SelfTest errors so far: 3
    ERROR: SelfTest failed for SIM_HasMQTTHistoryStringWithJSONPayload("homeassistant", 1, 0, 0, "dev_cla", "energy", "stat_t", "~/energycounter_last_hour/get", "unit_of_meas", "Wh", "stat_cla", "measurement")
    Check D:\a\OpenBK7231T_App\OpenBK7231T_App\src\selftest\selftest_hass_discovery.c - Test_VerifyForCommonPowerMeteringStuff - line 345
    Total SelfTest errors so far: 4
    Info:MAIN:Drv BL0937 stopped.
    

    I've added SIM_DumpMQTTHistory and if it does not lead to the solution I will investigate in the separate branch (to avoid spamming main releases).


    XJ_ wrote:

    !!! plus and minus are reversed !!!

    Electronic module with highlighted reversed power supply polarity.

    Fortunately, I noticed it in time!

    So seller is so greedy that he actually tries to sell the product with obvious flaw instead of scrapping it? Well, maybe it's not that bad, assuming that he sells it under special discount price..

    Added after 5 [minutes]:

    EDIT - regarding my issue:
    Screenshot of a build simulator with several entries related to Home Assistant sensor configurations.
    ahhh it has stat_cla total_increasing and not measurement. But it does not explain why it didn't fail on my machine! Did Visual Studio again failed on full rebuild?!

    Added after 6 [minutes]:

    Wait, it fails after rebuild... and by fail, I mean it works correctly... so it was the "rebuild" problem, after all, Visual Studio did not refresh all .o files.
    Helpful post? Buy me a coffee.
  • #49 21324754
    XJ_
    Level 11  
    p.kaczmarek2 wrote:
    it has total_increasing and not measurement

    Super, is it solved then, right?

    Maybe in the future it would help to add a log where the difference is

    bool CheckForKeyVal(cJSON *tmp, const char *key, const char *value) {
    ...
    if (!strcmp(ret, value)) {
    return true;
     } else {
     printf("CheckForKeyVar error '%s'<>'%s'",ret, value))   just typed, not tested
    }
    ...
    
    and so on

    Added after 1 [minutes]:

    p.kaczmarek2 wrote:
    correctly... so it was the "rebuild" problem, after all, Visual Studio did n

    I've come across it a few times too
  • ADVERTISEMENT
  • #50 21324851
    p.kaczmarek2
    Moderator Smart Home
    Your generic idea is good, but the following code snippet will not work correctly - it would print lots of data. I think it's better to just do once a SIM_DumpMQTTHistory call when the MQTT publish check fails.

    I've added some more checks and pushed changes to github
    Helpful post? Buy me a coffee.
  • #51 21324965
    XJ_
    Level 11  
    p.kaczmarek2 wrote:
    it would print lots of data

    I meant printf if not matching (strcmpi } else { ) - means only in case of error. i.e total_increasing <> measurement
  • #52 21325850
    p.kaczmarek2
    Moderator Smart Home
    As I said, the mechanism is checking every entry in MQTT publish history until it finds a match, so if entry, I don't know, 10 of 12 is a match, then it would print info for all 9 entries before that.

    The better solution is to just dump whole MQTT history once MQTT assert/test fails....

    PS: Of course this "mqtt history" is cleared per each asserts, so there are no older entries polluting the tests
    Helpful post? Buy me a coffee.
  • #53 21325939
    XJ_
    Level 11  
    p.kaczmarek2 wrote:
    10 of 12 is a match, then it would print info for all 9 entries before that.

    Ah. I understand now. Thanks for the explanation.
  • #54 21327444
    p.kaczmarek2
    Moderator Smart Home
    This whole Windows/Simulator build is indeed a bit wild, especially that MQTT library from LWIP port to Windows that I did so that I can test HASS integration directly from my Windows PC. The MQTT self tests are similiar, they are injected at publish call level and store whatever was published so I can externally check later if all functionality is within expectations.

    Added after 19 [seconds]:

    Btw, are you able to compile and run the simulator on your machine?
    Helpful post? Buy me a coffee.
  • #55 21327691
    XJ_
    Level 11  
    >>21327444
    p.kaczmarek2 wrote:
    Btw, are you able to compile and run the simulator on your machine?

    Sure, I use it often, I modify everything in it. Sometimes I have to "bend" it a bit, e.g. when I need to test early.bat, a lot of things are not clear - what is implemented there and what is not. However, I was weaned from assembler and machine code in the 80s, so I can always manage. It's still just a program for some processor ;-)
    But without the simulator I wouldn't actually do any of what I did - because I wouldn't even start ;-9
  • #57 21404961
    XJ_
    Level 11  
    >>21404671
    https://github.com/openshwprojects/OpenBK7231N/pull/21 has been merged now?[/quote]
    It is merged already...

    Added after 1 [minutes]:

    >>21404671
    randomalias324 wrote:
    to a very similar device tomorrow.

    If it is a device with two BL0942, I suggest You to compile and try this:
    https://github.com/xjikka/OpenBK7231T_App/tree/twinbl0942mod

    Autoexec.bat
    logtype none
    startDriver NTP
    ntp_timeZoneOfs +01:00
    BL0942opts 3
    startDriver BL0942


    BL0942opts 3 is used to set options so that startDriver BL0942 starts the driver for two BL0942 on both UARTs (Beken)
    Flag 26 ([UART] Use alternate UART for BL0942) should be disabled
  • #58 21405654
    randomalias324
    Level 8  
    >>21404961

    Yep that's what I attempted to build.

    Looks like my Cygwin build pipeline is broken, or I'm doing something wrong. Seems to complete, but the OTA won't flash and flashing over UART bricks it.

    Don't suppose you could share a binary?

    Added after 6 [hours] 33 [minutes]:

    Alright, got it working.

    Looks like Home Assistant self discovery doesn't work

    How do we add Voltage B and Current B?

    Added after 3 [minutes]:

    Now Voltage A and Voltage B don't display in the device page.

    Seems like the dual measurement is buggy, potentially triggered by calling self discovery

    Added after 4 [minutes]:

    Yep, cant get dual measurement back by restarting, toggling BL0942opts, so far whatever I try

    Added after 4 [minutes]:

    By playing around with SetFlag 26 it appears it has lost the ability to read UART2

    Added after 35 [minutes]:

    I have taken some logs from the UART ports
    I think despite logtype none being included in autoexec, UART2 is being spammed.

    I have attached some UART logs, where logging is started just prior or just after sending the reset command from the native UI page
  • #60 21405808
    randomalias324
    Level 8  
    >>21405788

    Reading off UART2 has failed altogether though, it won't show up on the UI page of the device itself now.

    Either with the autoexec line FlagSet 26 1 (and no BL0942opts 3) or with the line BL0942opts 3 (and no FlagSet 26 1)

    When I first had it working I could see both sets of voltages/currents, just like in your screen shots; The 'normal' voltage/currents on UART1, and voltage B Current B from UART 2 underneath

Topic summary

The discussion focuses on integrating and troubleshooting a smart energy power meter device featuring two BL0942 power metering chips connected via UART1 and UART2 on a Beken BK7231N module (CBU). The primary issue was that the BL0942 on UART1 functioned correctly, while UART2 returned zero values with flag 26 enabled. Investigation revealed that UART2 receive interrupts were broken at the SDK level, requiring a workaround by polling UART2 RX manually. A patch was developed and tested, enabling stable UART2 communication and simultaneous operation of both BL0942 chips. Firmware modifications introduced a new command, BL0942opts, to support dual BL0942 operation with energy calculation from UART1 and informative data from UART2, using MQTT suffix "_b" for the second sensor. Home Assistant (HASS) MQTT discovery was extended to support dual sensors while maintaining backward compatibility. The patch increased firmware size, leading to the introduction of a compile-time flag (ENABLE_BL_TWIN) to enable or disable dual BL0942 support. Testing confirmed stable operation on BK7231N and BK7231T platforms. Additional features such as frequency measurement publication and moving average filtering were added. Users reported calibration and polarity issues with clamps, resolved by reversing clamp polarity and enabling specific flags. The final solution includes firmware branches and pull requests on GitHub, with detailed configuration instructions and community-shared binaries. The discussion also covers logging behavior on UART ports, flashing procedures without desoldering, and troubleshooting steps for consistent sensor data reading.
Summary generated by the language model.
ADVERTISEMENT