Skip to content

Commit

Permalink
entity id改用index命名
Browse files Browse the repository at this point in the history
  • Loading branch information
WeiYang1982 committed Feb 2, 2024
1 parent ce674b2 commit 2b41fa3
Show file tree
Hide file tree
Showing 3 changed files with 177 additions and 24 deletions.
162 changes: 162 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
### Python template
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

12 changes: 7 additions & 5 deletions custom_components/bj_water/bj_water.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ async def get_bill_cycle_range(self):
bill_list = json_body["data"]["months"]
bill_list = sorted(bill_list, reverse=True)[0:6] # 倒序排列后取最近6个账单周期
for bill in bill_list:
cycle_date = (datetime.strptime(bill, "%Y年%m月").date().strftime("%Y-%m-%d"))
cycle_date = (datetime.strptime(bill, "%Y年%m月").date().strftime("%Y-%m"))
self.bill_cycle.add(cycle_date)
self.info["cycle"].update(
{
Expand Down Expand Up @@ -83,22 +83,23 @@ async def get_payment_bill(self):
bill_list = json_body["data"]
if len(bill_list) == 0:
raise InvalidData("未查询到缴费记录,请检查水表户号!")
index = 0
for bill in json_body["data"]:
cycle_date = (datetime.strptime(bill["billDate"], "%Y年%m月").date().strftime("%Y-%m-%d"))
cycle_date = (datetime.strptime(bill["billDate"], "%Y年%m月").date().strftime("%Y-%m"))
if cycle_date in self.bill_cycle:
amount_detail = {
"index": index,
"fee": {
"pay": 1,
"date": datetime.strptime(bill["date"], "%Y.%m.%d")
.date()
.strftime("%Y-%m-%d"),
"date": datetime.strptime(bill["date"], "%Y.%m.%d").date().strftime("%Y-%m-%d"),
"amount": bill["amount"],
"szyf": bill["szyf"],
"wsf": bill["wsf"],
"sf": bill["sf"],
}
}
self.info["cycle"].update({cycle_date: amount_detail})
index += 1
LOGGER.info("get_payment_bill end " + str(self.info))
else:
LOGGER.error("get_payment_bill res state code: %s" % (response.status))
Expand All @@ -123,6 +124,7 @@ async def get_monthly_bill(self, bill_cycle):

if self.info["cycle"][bill_cycle]["fee"]["pay"] == 0:
amount_detail = {
"index": bill_cycle["index"],
"fee": {
"pay": 0,
"date": bill_cycle,
Expand Down
27 changes: 8 additions & 19 deletions custom_components/bj_water/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,13 +91,7 @@ async def async_setup_entry(
user_code = config["userCode"]
api = BJWater(async_create_clientsession(hass), user_code)

coordinator = DataUpdateCoordinator(
hass,
LOGGER,
name=DOMAIN,
update_interval=UPDATE_INTERVAL,
update_method=api.fetch_data,
)
coordinator = DataUpdateCoordinator(hass, LOGGER, name=DOMAIN, update_interval=UPDATE_INTERVAL, update_method=api.fetch_data,)
LOGGER.info("async_setup_entry: " + str(coordinator))
await coordinator.async_refresh()
data = coordinator.data
Expand All @@ -112,14 +106,9 @@ async def async_setup_entry(
elif key == "cycle":
dict_data = value
for k, v in dict_data.items():
sensors_list.append(
BJWaterHistoryFeeSensor(
coordinator, user_code, k, v["fee"])
)
sensors_list.append(
BJWaterHistoryUsageSensor(
coordinator, user_code, k, v["meter"])
)
index = v["index"]
sensors_list.append(BJWaterHistoryFeeSensor(coordinator, user_code, k, v["fee"], index))
sensors_list.append(BJWaterHistoryUsageSensor(coordinator, user_code, k, v["meter"], index))
async_add_entities(sensors_list, False)


Expand Down Expand Up @@ -190,9 +179,9 @@ def unit_of_measurement(self):


class BJWaterHistoryFeeSensor(BJWaterBaseSensor):
def __init__(self, coordinator, user_code, bill_date, sensor_attrs) -> None:
def __init__(self, coordinator, user_code, bill_date, sensor_attrs, index) -> None:
super().__init__(coordinator)
self._unique_id = f"{DOMAIN}.{user_code}_{bill_date}_Fee"
self._unique_id = f"{DOMAIN}.{user_code}_{index}_Fee"
self.entity_id = self._unique_id
self._bill_date = bill_date
self.sensor_attrs = sensor_attrs
Expand Down Expand Up @@ -232,9 +221,9 @@ def device_class(self) -> str | None:


class BJWaterHistoryUsageSensor(BJWaterBaseSensor):
def __init__(self, coordinator, user_code, bill_date, sensor_attrs) -> None:
def __init__(self, coordinator, user_code, bill_date, sensor_attrs, index) -> None:
super().__init__(coordinator)
self._unique_id = f"{DOMAIN}.{user_code}_{bill_date}_Usage"
self._unique_id = f"{DOMAIN}.{user_code}_{index}_Usage"
self.entity_id = self._unique_id
self._bill_date = bill_date
self.sensor_attrs = sensor_attrs
Expand Down

0 comments on commit 2b41fa3

Please sign in to comment.