Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Date and time #112

Open
cc120689 opened this issue Mar 21, 2023 · 34 comments
Open

Date and time #112

cc120689 opened this issue Mar 21, 2023 · 34 comments

Comments

@cc120689
Copy link
Contributor

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.

@kellerza
Copy link
Owner

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", "")

@cc120689
Copy link
Contributor Author

cc120689 commented Mar 21, 2023

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.

@kellerza
Copy link
Owner

This sensor only reads the current time.

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

@cc120689
Copy link
Contributor Author

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

@kellerza
Copy link
Owner

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?

@cc120689
Copy link
Contributor Author

cc120689 commented Apr 18, 2023

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"}
)

@kellerza
Copy link
Owner

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", "")

@cc120689
Copy link
Contributor Author

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.

@kellerza
Copy link
Owner

kellerza commented Apr 19, 2023

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

@cc120689
Copy link
Contributor Author

cc120689 commented Apr 19, 2023

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

@kellerza
Copy link
Owner

Can you try the date_time sensor in the latest version?

@cc120689
Copy link
Contributor Author

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

@cc120689
Copy link
Contributor Author

cc120689 commented Apr 23, 2023

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

@kellerza
Copy link
Owner

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

@cc120689
Copy link
Contributor Author

cc120689 commented Apr 23, 2023

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
Copy link
Contributor Author

cc120689 commented Aug 7, 2023

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)]

@kellerza
Copy link
Owner

kellerza commented Aug 7, 2023

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

@cc120689
Copy link
Contributor Author

cc120689 commented Aug 7, 2023

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
Copy link
Contributor Author

cc120689 commented Aug 8, 2023

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?

@nanef27
Copy link

nanef27 commented Aug 8, 2023

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

@kellerza
Copy link
Owner

kellerza commented Aug 9, 2023

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

@kellerza kellerza reopened this Aug 9, 2023
@cc120689
Copy link
Contributor Author

cc120689 commented Aug 9, 2023

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
Copy link
Contributor Author

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

@cc120689
Copy link
Contributor Author

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.

@kellerza
Copy link
Owner

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?

@N1c084
Copy link
Contributor

N1c084 commented Sep 13, 2023 via email

@cc120689
Copy link
Contributor Author

cc120689 commented Sep 13, 2023

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

@cods4
Copy link

cods4 commented Sep 25, 2023

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. :)

@ech0-py
Copy link

ech0-py commented Sep 26, 2023

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

@ASomerN
Copy link

ASomerN commented Oct 24, 2023

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.

@ech0-py
Copy link

ech0-py commented Oct 24, 2023

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.

Sorry, but do I understand correctly that you're using inverter's rs232 port (wifi dongle port) to read/write data as through rs485?

@ASomerN
Copy link

ASomerN commented Oct 24, 2023

Sorry, but do I understand correctly that you're using inverter's rs232 port (wifi dongle port) to read/write data as through rs485?

Yes, the 16kw inverters may not be able to write sensors on the rs485, see this issue I raised: #156 (When trying to write to a 16kw inverter via rs485 the add-on would crash).

Adding date_time onto the home assistant interface, and then changing the value there, updated the inverter with the correct time and it resolved an issue for me where the inverter was trying to charge the battery at the wrong time of day (for some reason the inverter had jumped forward 12 hours after being without an internet connection for a few days).

@cc120689
Copy link
Contributor Author

cc120689 commented Nov 6, 2023

It is definitely not a failure of the accessory, looking at it closely it is not able to change the time either with deye cloud or with solarman smart. apparently the value changes but when you check it again it still has the previous one

@cc120689
Copy link
Contributor Author

cc120689 commented Sep 4, 2024

I have seen that the time change is working again from the Solarman Smart application, in the plugin it still does not write the change to the inverter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

7 participants