-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
68 changed files
with
7,451 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
"""The Lunar Calendar integration.""" | ||
from __future__ import annotations | ||
|
||
import logging | ||
|
||
from homeassistant.config_entries import ConfigEntry | ||
from homeassistant.const import Platform | ||
from homeassistant.core import HomeAssistant | ||
from homeassistant.exceptions import ConfigEntryNotReady | ||
from homeassistant.helpers import device_registry as dr | ||
from homeassistant.helpers.entity import DeviceInfo | ||
from homeassistant.helpers.typing import ConfigType | ||
|
||
from .const import ( | ||
CONF_SCAN_INTERVAL, | ||
DEFAULT_SCAN_INTERVAL, | ||
DOMAIN, | ||
PLATFORMS, | ||
SERVICE_REFRESH, | ||
SERVICE_SCHEMA_REFRESH, | ||
) | ||
from .sensor import LunarSensor | ||
|
||
_LOGGER = logging.getLogger(__name__) | ||
|
||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: | ||
"""Set up Lunar Calendar from a config entry.""" | ||
hass.data.setdefault(DOMAIN, {}) | ||
|
||
# Load configuration options | ||
scan_interval = entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) | ||
|
||
# Setup sensor platform | ||
hass.async_create_task( | ||
hass.config_entries.async_forward_entry_setup(entry, Platform.SENSOR) | ||
) | ||
|
||
# Register service to refresh lunar data | ||
hass.services.async_register( | ||
DOMAIN, SERVICE_REFRESH, async_refresh_lunar_data, schema=SERVICE_SCHEMA_REFRESH | ||
) | ||
|
||
# Store options in hass.data for future reference or use | ||
hass.data[DOMAIN][entry.entry_id] = { | ||
"scan_interval": scan_interval, | ||
} | ||
|
||
return True | ||
|
||
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: | ||
"""Unload a config entry.""" | ||
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) | ||
if unload_ok: | ||
hass.data[DOMAIN].pop(entry.entry_id) | ||
return unload_ok | ||
|
||
async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: | ||
"""Migrate old entry.""" | ||
_LOGGER.debug("Migrating from version %s", config_entry.version) | ||
# Implement migration logic here if needed | ||
config_entry.version = LATEST_VERSION # Replace with actual latest version constant | ||
hass.config_entries.async_update_entry(config_entry) | ||
return True | ||
|
||
async def async_refresh_lunar_data(hass: HomeAssistant, service_call: ServiceCall) -> None: | ||
"""Handle the refresh lunar data service call.""" | ||
# Here you would implement logic to refresh all or specific lunar sensors' data | ||
# For simplicity, let's assume we have a function to refresh all sensors | ||
# You need to implement this function based on your architecture | ||
await hass.async_add_executor_job(refresh_all_sensors) | ||
|
||
def refresh_all_sensors(): | ||
"""Placeholder function to refresh all lunar sensors.""" | ||
# Implement logic to refresh sensors here, if applicable | ||
# This is a placeholder and needs to be replaced with actual logic | ||
pass | ||
|
||
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: | ||
"""Set up the Lunar Calendar component.""" | ||
hass.data.setdefault(DOMAIN, {}) | ||
return True | ||
|
||
PLATFORMS = [Platform.SENSOR] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
from datetime import datetime | ||
from .lunar_python import Lunar # 引入自定义的农历计算库 | ||
from .lunar_python import Holiday # 引入自定义的节日查询库 | ||
|
||
class LunarCalculator: | ||
def __init__(self): | ||
pass | ||
|
||
def get_current_lunar_info(self): | ||
""" | ||
获取当前日期的农历信息并格式化输出。 | ||
""" | ||
now = datetime.now() | ||
|
||
# 使用Lunar库计算农历日期 | ||
lunar_date = Lunar.fromDate(now) | ||
|
||
# 获取当天的农历年月日等信息 | ||
lyear = lunar_date.getYearShengXiaoByLiChun() | ||
lmonth = lunar_date.getMonthInChinese() | ||
lday = lunar_date.getDayInChinese() | ||
time_ganzhi = lunar_date.getTimeInGanZhi() | ||
week = lunar_date.getWeekInChinese() | ||
ljie = lunar_date.getOtherFestivals() | ||
tian_gan_year = lunar_date.getYearInGanZhiExact() | ||
tian_gan_month = lunar_date.getMonthInGanZhiExact() | ||
tian_gan_day = lunar_date.getDayInGanZhiExact() | ||
day_lu = lunar_date.getDayLu() | ||
jie_qi = lunar_date.getPrevJieQi(True) | ||
xiu = lunar_date.getXiu() | ||
animal = lunar_date.getAnimal() | ||
xin_luck = lunar_date.getXiuLuck() | ||
zheng = lunar_date.getZheng() | ||
gong = lunar_date.getGong() | ||
peng_zu_gan = lunar_date.getPengZuGan() | ||
peng_zu_zhi = lunar_date.getPengZuZhi() | ||
xi_shen = lunar_date.getDayPositionXiDesc() | ||
yang_gui = lunar_date.getDayPositionYangGuiDesc() | ||
yin_gui = lunar_date.getDayPositionYinGuiDesc() | ||
fu_shen = lunar_date.getDayPositionFuDesc() | ||
cai_shen = lunar_date.getDayPositionCaiDesc() | ||
tai_shen = lunar_date.getDayPositionTai() | ||
chong_sha = f"冲{lunar_date.getDayChongDesc()} 煞{lunar_date.getDaySha()}" | ||
win_xing_na_year = lunar_date.getYearNaYin() | ||
wuxing_na_month = lunar_date.getMonthNaYin() | ||
wuxing_na_day = lunar_date.getDayNaYin() | ||
wu_xing_zhi_xing = f"{wuxing_na_day} {lunar_date.getZhiXing()}" | ||
ba_zi = lunar_date.getEightChar().toString() | ||
yi = lunar_date.getDayYi() | ||
ji = lunar_date.getDayJi() | ||
ji_shen = lunar_date.getDayJiShen() | ||
xiong_shen = lunar_date.getDayXiongSha() | ||
yue_xiang = lunar_date.getYueXiang() | ||
|
||
""" | ||
# 使用HolidayUtil库获取节日信息 | ||
year = now.year | ||
month = now.month | ||
day = now.day | ||
get_holiday = Holiday.getDay(year, month, day) | ||
""" | ||
|
||
# 计算时辰 | ||
hour = now.hour | ||
minute = now.minute | ||
time_index = (hour + 1 + (minute >= 30)) // 2 % 12 | ||
shi_chen = ['子时', '丑时', '寅时', '卯时', '辰时', '巳时', '午时', '未时', '申时', '酉时', '戌时', '亥时'][time_index] | ||
|
||
# 组合输出信息 | ||
lunar_data = { | ||
"Lunar": f"农历{lmonth}月{lday}", | ||
"Week": f"星期{week}", | ||
"NianGanZhi": f"{tian_gan_year}{lyear}年", | ||
"YueGanZhi": f"{tian_gan_month}月", | ||
"RiGanZhi": f"{tian_gan_day}日", | ||
"RiLu": day_lu, | ||
"JieQi": jie_qi._p.name if hasattr(jie_qi, '_p') else "", | ||
"DongFangXingXiu": f"{gong}方{xiu}{zheng}{animal}-{xin_luck}", | ||
"PengZuGan": peng_zu_gan, | ||
"PengZuZhi": peng_zu_zhi, | ||
"XiShen": xi_shen, | ||
"YangGui": yang_gui, | ||
"YinGui": yin_gui, | ||
"FuShen": fu_shen, | ||
"CaiShen": cai_shen, | ||
"TaiShen": tai_shen, | ||
"ChongSha": chong_sha, | ||
"WuXingNaYin": f"{win_xing_na_year} {wuxing_na_month} {wuxing_na_day}", | ||
"WuXingRi": wu_xing_zhi_xing + "执位", | ||
"BaZi": ba_zi, | ||
"Yi": "、".join(yi) if isinstance(yi, list) else yi, | ||
"Ji": "、".join(ji) if isinstance(ji, list) else ji, | ||
"JiShen": "、".join(ji_shen) if isinstance(ji_shen, list) else ji_shen, | ||
"XiongShen": "、".join(xiong_shen) if isinstance(xiong_shen, list) else xiong_shen, | ||
"YueXiang": f"{yue_xiang}月", | ||
#"JiaQi": get_holiday._p.name if get_holiday else "工作日", | ||
"ShiChen": shi_chen, | ||
} | ||
|
||
return lunar_data |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
from __future__ import annotations | ||
|
||
import voluptuous as vol | ||
|
||
from homeassistant import config_entries | ||
from homeassistant.const import CONF_SCAN_INTERVAL | ||
from homeassistant.core import callback | ||
import homeassistant.helpers.config_validation as cv | ||
from .const import DOMAIN # 引入你的组件域名 | ||
|
||
_LOGGER = logging.getLogger(__name__) | ||
|
||
# 定义配置流程的步骤 | ||
STEP_USER_DATA_SCHEMA = vol.Schema({ | ||
vol.Optional(CONF_SCAN_INTERVAL, default="00:05:00"): cv.time_period_str, | ||
}) | ||
|
||
@callback | ||
def async_get_options_flow(config_entry): | ||
"""Handle an options flow for this integration.""" | ||
return OptionsFlowHandler(config_entry) | ||
|
||
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): | ||
"""Handle a config flow for Lunar Calendar.""" | ||
|
||
VERSION = 1 | ||
|
||
async def async_step_user(self, user_input=None): | ||
"""Handle the initial step.""" | ||
errors = {} | ||
|
||
if user_input is not None: | ||
# 这里可以增加输入验证逻辑 | ||
return self.async_create_entry(title="农历日历", data=user_input) | ||
|
||
return self.async_show_form( | ||
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors | ||
) | ||
|
||
class OptionsFlowHandler(config_entries.OptionsFlow): | ||
"""Handle options flow for the component.""" | ||
|
||
def __init__(self, config_entry): | ||
"""Initialize options flow.""" | ||
self.config_entry = config_entry | ||
|
||
async def async_step_init(self, user_input=None): | ||
"""Manage options.""" | ||
if user_input is not None: | ||
return self.async_create_entry(title="", data=user_input) | ||
|
||
return self.async_show_form( | ||
step_id="init", | ||
data_schema=vol.Schema({ | ||
vol.Optional(CONF_SCAN_INTERVAL, default=self.config_entry.options.get(CONF_SCAN_INTERVAL, "00:05:00")): cv.time_period_str, | ||
}), | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
""" | ||
Constants for the Lunar Calendar custom component. | ||
""" | ||
|
||
import voluptuous as vol | ||
from datetime import timedelta | ||
|
||
# Component Domain | ||
DOMAIN = "lunar_calendar" | ||
|
||
# Default configuration options | ||
DEFAULT_SCAN_INTERVAL = timedelta(hours=1) # 默认扫描间隔为1小时 | ||
CONF_CUSTOM_NAME = "custom_name" # 自定义组件名称配置项 | ||
DEFAULT_CUSTOM_NAME = "农历日期" # 自定义名称的默认值 | ||
|
||
# Services | ||
SERVICE_REFRESH = "refresh_lunar_data" | ||
SERVICE_SCHEMA_REFRESH = vol.Schema({}) | ||
|
||
# Icons | ||
ICON_CALENDAR = "mdi:calendar" | ||
|
||
# Configuration options | ||
CONF_SCAN_INTERVAL = "scan_interval" | ||
|
||
|
||
# Sensor attribute keys | ||
ATTR_WEEK = "week" | ||
ATTR_LUNAR_YEAR = "lunar_year" | ||
ATTR_LUNAR_MONTH = "lunar_month" | ||
ATTR_LUNAR_DAY = "lunar_day" | ||
# ... 其他属性键,根据需要添加 | ||
|
||
# Additional constants as needed | ||
# ... | ||
|
||
# Platforms | ||
PLATFORMS = ["sensor"] | ||
|
||
# Services | ||
UPDATE_LUNAR_SERVICE = "update_lunar_data" |
Oops, something went wrong.