sunsynk icon indicating copy to clipboard operation
sunsynk copied to clipboard

Date and time

Open cc120689 opened this issue 1 year ago • 34 comments

hello, good morning, I have another new proposal. I don't know if the same would happen in South Africa, but in Spain, I think that due to the frequency of the network, our inverters have the ugly habit of being delayed by a few minutes every 30 or 40 days. I have tried to put the hours and minutes as the new sensor but it seems that there are 2 options for the same record and I have no idea how to put it. The idea would be once set to make an automation with home assistant to synchronize the time of the inverter. Thanks and regards.

cc120689 avatar Mar 21 '23 07:03 cc120689

That should be possible with the new sensor overrides - see the docs

add the sensor as date:now and here is an example mysensors.py (only read implemented!)

import attr

from sunsynk.rwsensors import RWSensor, ResolveType
from sunsynk.sensors import RegType, ValType, SensorDefinitions

SENSORS = SensorDefinitions()


@attr.define(slots=True, eq=False)
class TimeRWSensor(RWSensor):
    """Read & write time sensor."""

    def value_to_reg(self, value: ValType, resolve: ResolveType) -> RegType:
        """Get the reg value from a display value."""
        raise NotImplementedError()

    def reg_to_value(self, regs: RegType) -> ValType:
        """Decode the register."""
        y = ((regs[0] & 0xFF00) >> 8) + 2000
        m = regs[0] & 0xFF
        d = (regs[1] & 0xFF00) >> 8
        h = regs[1] & 0xFF
        mn = (regs[2] & 0xFF00) >> 8
        s = regs[2] & 0xFF
        return f"{y}-{m:02}-{d:02} {h}:{mn:02}:{s:02}"


SENSORS += TimeRWSensor((22, 23, 24), "Date", "")

kellerza avatar Mar 21 '23 20:03 kellerza

Ok i'll try and comment, thanks!

:( Sorry I'm reading the documents but I have no idea of ​​programming beyond copy and paste and I don't quite understand what I should do, pasting your example I get the sensor as reading.

cc120689 avatar Mar 21 '23 22:03 cc120689

This sensor only reads the current time.

You probably only ever want to set this to the current system time?

kellerza avatar Mar 23 '23 09:03 kellerza

Yes, I would like to be able to update the current system time through a writable sensor so I could automate that every month, for example, it will be synchronized with the time of the home assistant

cc120689 avatar Mar 23 '23 13:03 cc120689

I've expanded on the write concept a bit here - https://kellerza.github.io/sunsynk/reference/mysensors#time-sensor

But still not 100% compete&tested, maybe you can test it and see if it works?

kellerza avatar Apr 17 '23 19:04 kellerza

Hello, I just tried it and it gives me an error. I have replaced the previous code with the new one, I paste the output

############################################################
Traceback (most recent call last):
  File "/usr/src/app/./run.py", line 373, in <module>
    LOOP.run_until_complete(main(LOOP))
  File "/usr/local/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
    return future.result()
  File "/usr/src/app/./run.py", line 312, in main
    await hass_discover_sensors(
  File "/usr/src/app/./run.py", line 61, in hass_discover_sensors
    ents = [s.create_entity(dev) for s in STATES.values() if not s.hidden]
  File "/usr/src/app/./run.py", line 61, in <listcomp>
    ents = [s.create_entity(dev) for s in STATES.values() if not s.hidden]
  File "/usr/src/app/state.py", line 153, in create_entity
    options=sensor.available_values(15, SS[0].state.get),
  File "/usr/local/lib/python3.9/site-packages/sunsynk/rwsensors.py", line 135, in available_values
    val = SSTime(string=str(resolve(self, 0))).minutes
  File "/usr/local/lib/python3.9/site-packages/sunsynk/helpers.py", line 80, in __init__
    self.str_value = string
  File "/usr/local/lib/python3.9/site-packages/sunsynk/helpers.py", line 104, in str_value
    self.minutes = int(hours) * 60 + int(minutes)
ValueError: invalid literal for int() with base 10: 'None'
[cmd] ./run.py exited 1
[cont-finish.d] executing container finish scripts...
[cont-finish.d] done.
[s6-finish] waiting for services.
[s6-finish] sending all processes the TERM signal.

And my sensores.py:

import attr
import re

# from sunsynk import AMPS, CELSIUS, KWH, VOLT, WATT
from sunsynk.rwsensors import RWSensor, ResolveType
from sunsynk.sensors import RegType, ValType, SensorDefinitions

SENSORS = SensorDefinitions()


@attr.define(slots=True, eq=False)
class SystemTimeRWSensor(RWSensor):
    """Read & write time sensor."""

    def value_to_reg(self, value: ValType, resolve: ResolveType) -> RegType:
        """Get the reg value from a display value."""
        redt = re.compile(r"(2\d{3})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})")
        match = redt.fullmatch(value)
        if not match:
            raise ValueError("Invalid datetime {value}")
        y, m, d = int(match.group(1)) - 2000, int(match.group(2)), int(match.group(3))
        h, mn, s = int(match.group(4)), int(match.group(5)), int(match.group(6))
        regs = (
            (y << 8) + m,
            (d << 8) + h,
            (mn << 8) + s,
        )
        raise ValueError(f"{y}-{m:02}-{d:02} {h}:{mn:02}:{s:02} ==> {regs}")
        return regs

    def reg_to_value(self, regs: RegType) -> ValType:
        """Decode the register."""
        y = ((regs[0] & 0xFF00) >> 8) + 2000
        m = regs[0] & 0xFF
        d = (regs[1] & 0xFF00) >> 8
        h = regs[1] & 0xFF
        mn = (regs[2] & 0xFF00) >> 8
        s = regs[2] & 0xFF
        return f"{y}-{m:02}-{d:02} {h}:{mn:02}:{s:02}"


SENSORS += SystemTimeRWSensor((22, 23, 24), "Date", unit="")

from sunsynk import AMPS, CELSIUS, KWH, VOLT, WATT
from sunsynk.rwsensors import NumberRWSensor, SelectRWSensor, TimeRWSensor
from sunsynk.sensors import (
    MathSensor,
    Sensor,
    SensorDefinitions,
    TempSensor,
)

SENSORS += TimeRWSensor((22, 23, 24), "Date", "")
SENSORS += NumberRWSensor(293, "Grid Peak Shaving Power", WATT, min=0, max=16000)
SENSORS += Sensor(164, "Inverter current", AMPS, 0.01),
SENSORS += Sensor(192, "Load frequency", "Hz", 0.01),

SENSORS += SelectRWSensor(
    247, "Solar Sell", options={0: "No", 1: "Yes"}
)

cc120689 avatar Apr 18 '23 15:04 cc120689

This line was for the previous sensor and should be removed (TieRWSensor is the class of the system settings time)

SENSORS += TimeRWSensor((22, 23, 24), "Date", "")

kellerza avatar Apr 18 '23 18:04 kellerza

ok now it does not give errors anymore, it is grouped as a configuration sensor inside the inverter device but there is no way to configure it, it does not allow writing, it seems like a read-only sensor.

cc120689 avatar Apr 18 '23 20:04 cc120689

Writing at the moment will only print something in the log.

If you are happy with what you see in the log you can comment out/delete the raise ValueError xxx line and the registers (return regs) will be returned for writing. Only then will it attempt to write...

        raise ValueError(f"{y}-{m:02}-{d:02} {h}:{mn:02}:{s:02} ==> {regs}")
        return regs

If the date you see in the log does not reflect the date you entered, it's better to fine-tune it a bit more before writing completely incorrect values

kellerza avatar Apr 19 '23 12:04 kellerza

Hello, I'm not sure I understand you, I've restarted the plugin but I don't see anything regarding the date sensor or the sunsynk plugin itself in the homeassistant log

cc120689 avatar Apr 19 '23 15:04 cc120689

Can you try the date_time sensor in the latest version?

kellerza avatar Apr 22 '23 21:04 kellerza

ok should i remove any old references in the mysensor.py file?

cc120689 avatar Apr 23 '23 08:04 cc120689

I have left it like this, and it seems to work, I will do more tests today and I will confirm but a priori it seems that it writes the records well

from sunsynk import AMPS, CELSIUS, KWH, VOLT, WATT from sunsynk.rwsensors import NumberRWSensor, SelectRWSensor from sunsynk.sensors import ( MathSensor, Sensor, SensorDefinitions, TempSensor, )

import attr import re

from sunsynk import AMPS, CELSIUS, KWH, VOLT, WATT

from sunsynk.rwsensors import RWSensor, ResolveType from sunsynk.sensors import RegType, ValType, SensorDefinitions

SENSORS = SensorDefinitions()

SENSORS += NumberRWSensor(293, "Grid Peak Shaving Power", WATT, min=0, max=16000) SENSORS += Sensor(164, "Inverter current", AMPS, 0.01), SENSORS += Sensor(192, "Load frequency", "Hz", 0.01),

SENSORS += SelectRWSensor( 247, "Solar Sell", options={0: "No", 1: "Yes"} )

edit: it writes the values correctly although it does not load new time data until the addon is restarted, if I put :now after the sensor name it gives me an error

cc120689 avatar Apr 23 '23 09:04 cc120689

date_time is part of the library and you do not need it in your mysensors.py file anymore

not sure about the read frequency/ why :now does not work

kellerza avatar Apr 23 '23 09:04 kellerza

hi again it seems like the reading updates every 4-5 minutes otherwise it works fine. should the :now? modifier work?

Another thing that I see, in the definitions file at the top I see that there is SystemTimeRwSensor and also TimeRwSensor. it's correct like this? Thankyou very much for your work! Edit: ah nothing sorry I see that the program&time sensors are also TimeRwSensor

cc120689 avatar Apr 23 '23 13:04 cc120689

Hi, I'm writing here again because I just realized that the plugin doesn't write the values ​​of the date and time, I guess since some update but I haven't looked at it for a long time. the plugin log throws me this message: 2023-08-07 19:21:45,398 CRITICAL Writing sensor date_time=2023-08-07 19:22:23 [(22, 23, 24)=(5896, 1811, 5655)]

cc120689 avatar Aug 07 '23 17:08 cc120689

Do you still have this defined in mysensors.py?

You should remove it from mysensors. And ONLY add it to your config:

SENSORS:
 - date_time

The log format from the sensors in the official library is different, so I expect you still use the example above - https://github.com/kellerza/sunsynk/blob/main/sunsynk/rwsensors.py#L155

kellerza avatar Aug 07 '23 18:08 kellerza

This is mysensors.py

from sunsynk import AMPS, CELSIUS, KWH, VOLT, WATT from sunsynk.rwsensors import NumberRWSensor, SelectRWSensor from sunsynk.sensors import ( MathSensor, Sensor, SensorDefinitions, TempSensor, )

import attr import re

from sunsynk import AMPS, CELSIUS, KWH, VOLT, WATT

from sunsynk.rwsensors import RWSensor, ResolveType from sunsynk.sensors import RegType, ValType, SensorDefinitions

SENSORS = SensorDefinitions()

SENSORS += NumberRWSensor(293, "Grid Peak Shaving Power", WATT, min=0, max=16000)

SENSORS += Sensor(192, "Load frequency", "Hz", 0.01),

SENSORS += SelectRWSensor( 247, "Solar Sell", options={0: "No", 1: "Yes"} )

cc120689 avatar Aug 07 '23 19:08 cc120689

Another turbo energy user from Spain has confirmed that the same thing is happening to him too. Is it better if we open a new error or does it not matter?

cc120689 avatar Aug 08 '23 19:08 cc120689

Hi, same problem here...I'm not able to write the data_time sensor. It always goes back to it previous state.

nanef27 avatar Aug 08 '23 21:08 nanef27

Can you share a log snippet with debug enabled while writing?

kellerza avatar Aug 09 '23 07:08 kellerza

Hello, I have deactivated the rest of the sensors because otherwise it was very difficult for me to take the date_time records, I don't know if the log file is saved in its entirety in any file. Deactivating all the sensors except date_time and writing a value I get this log: Sunsynk_date_time_log.txt

cc120689 avatar Aug 09 '23 10:08 cc120689

It seems that now it gives more information, I'll paste another log to see if it helps / datetimedebug.txt

cc120689 avatar Aug 27 '23 19:08 cc120689

Hello, good morning, with the new version it keeps failing, it seems that it is trying to write the value but it can't because after a minute the previous time appears again.

cc120689 avatar Sep 13 '23 07:09 cc120689

It seems like it is not possible to write to these registers. At least all the attempts on my inverter failed as well.

Maybe this is something you can ask Sunsynk?

Have you ever seen it done from other apps?

kellerza avatar Sep 13 '23 07:09 kellerza

Have you unckecked time sync function ?

Le mer. 13 sept. 2023 à 09:46, Johann Kellerman @.***> a écrit :

It seems like it is not possible to write to these registers. At least all the attempts on my inverter failed as well.

Maybe this is something you can ask Sunsynk?

Have you ever seen it done from other apps?

— Reply to this email directly, view it on GitHub https://github.com/kellerza/sunsynk/issues/112#issuecomment-1717116743, or unsubscribe https://github.com/notifications/unsubscribe-auth/AYDJ6M5YUWA7HQNK6QXPVGDX2FQDZANCNFSM6AAAAAAWCA6HIU . You are receiving this because you are subscribed to this thread.Message ID: @.***>

N1c084 avatar Sep 13 '23 10:09 N1c084

Yes i have this unchecked. From deye cloud y can writte it

cc120689 avatar Sep 13 '23 11:09 cc120689

Does anyone have an automation in home assistant to update the date and time that they would be willing to share?

I was able to update mine manually today, but it would be nice to automate it to happen once a week or so.

FYI, I noticed that once I had updated the time on my main inverter, the other two inverters running in parallel also updated to match the main inverter.... I always thought they needed to be adjusted separately. :)

cods4 avatar Sep 25 '23 02:09 cods4

Does anyone have an automation in home assistant to update the date and time that they would be willing to share?

I was able to update mine manually today, but it would be nice to automate it to happen once a week or so.

FYI, I noticed that once I had updated the time on my main inverter, the other two inverters running in parallel also updated to match the main inverter.... I always thought they needed to be adjusted separately. :)

Unfortunately that doesn't work for my Deye sun-8k (not automation, I can't change the value on inverter even through UI) But you can try this (/60 - trigger every 60mins, entity_id - your entity)

alias: upd_dy_date_time
description: ""
trigger:
  - platform: time_pattern
    minutes: /60
condition: []
action:
  - service: text.set_value
    data:
      value: "{{ now().strftime('%Y-%m-%d %H:%M:%S') }}"
    target:
      entity_id: text.dy_date_time
mode: single

ech0-py avatar Sep 26 '23 20:09 ech0-py

Hi.

Adding date_time as a sensor worked perfectly for me. It's a requirement to be able to do this in the 16kw inverter set up if you want to write via the wifi dongle port as opposed to the rs485.

The inverter had lost track of time quite significantly when off wifi. Inputting the correct value via home assistant text box fixed this.

ASomerN avatar Oct 24 '23 15:10 ASomerN