Skip to content

Commit

Permalink
fix: historic updates
Browse files Browse the repository at this point in the history
  • Loading branch information
janwo committed Jun 23, 2024
1 parent 08bd143 commit f652d08
Show file tree
Hide file tree
Showing 4 changed files with 100 additions and 82 deletions.
116 changes: 56 additions & 60 deletions smartblueberry/backend/plugins/homeassistant/modules/irrigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,70 +238,66 @@ async function getPastIrrigationRecords(
) {
// Get irrigation amounts of valve
const now = dayjs()
return await server.plugins.hassConnect.rest
.get<Pick<State, 'entity_id' | 'state' | 'last_changed'>[][]>(
`/history/period/${dayjs(sinceDay).startOf('day').toISOString()}?${[
`end_time=${now.toISOString()}`,
`filter_entity_id=${entityId}`
].join('&')}`
)
.then(({ ok, json }) => {
const recordMap = (ok ? json! : [])
.flat()
.reduce(
(recordMap: IrrigationRecordMap, newRecord, index, array) => {
const recordDate = dayjs(newRecord.last_changed)
const recordKey = recordDate.format('YYYY-MM-DD')
let isFirstOfDay = recordMap[recordKey] === undefined
recordMap[recordKey] = isFirstOfDay
? {
irrigation: 0,
lastChanged: recordDate.startOf('day').toISOString(),
lastState: newRecord.state === 'off' ? 'on' : 'off'
}
: {
...recordMap[recordKey],
lastChanged: newRecord.last_changed,
lastState: newRecord.state
}

recordMap[recordKey].irrigation +=
newRecord.state === 'off'
? ((recordDate.unix() -
dayjs(recordMap[recordKey].lastChanged).unix()) /
60) *
irrigationVolumePerMinute
: 0

let isLastRecord = array.length - 1 === index
if (isLastRecord) {
recordMap = Object.fromEntries(
Object.entries(recordMap).map(([key, value]) => {
if (value.lastState === 'on') {
const recordDate = dayjs(value.lastChanged)
const recordDateEndOfDay = recordDate.endOf('day')
value.irrigation +=
((recordDateEndOfDay.unix() - recordDate.unix()) /
60) *
irrigationVolumePerMinute
}
return [key, value]
})
)
}
return await server.app.hassRegistry
.history({
startTime: dayjs(sinceDay).startOf('day').toISOString(),
endTime: now.toISOString(),
entityIds: [entityId]
})
.then((result) => {
const recordMap = (result?.[entityId] || []).reduce(
(recordMap: IrrigationRecordMap, newRecord, index, array) => {
const recordDate = dayjs(newRecord.lu)
const recordKey = recordDate.format('YYYY-MM-DD')
let isFirstOfDay = recordMap[recordKey] === undefined
recordMap[recordKey] = isFirstOfDay
? {
irrigation: 0,
lastChanged: recordDate.startOf('day').toISOString(),
lastState: newRecord.s === 'off' ? 'on' : 'off'
}
: {
...recordMap[recordKey],
lastChanged: newRecord.lu,
lastState: newRecord.s
}

return recordMap
},
{}
recordMap[recordKey].irrigation +=
newRecord.s === 'off'
? ((recordDate.unix() -
dayjs(recordMap[recordKey].lastChanged).unix()) /
60) *
irrigationVolumePerMinute
: 0

let isLastRecord = array.length - 1 === index
if (isLastRecord) {
recordMap = Object.fromEntries(
Object.entries(recordMap).map(([key, value]) => {
if (value.lastState === 'on') {
const recordDate = dayjs(value.lastChanged)
const recordDateEndOfDay = recordDate.endOf('day')
value.irrigation +=
((recordDateEndOfDay.unix() - recordDate.unix()) / 60) *
irrigationVolumePerMinute
}
return [key, value]
})
)
}

return recordMap
},
{}
)

const amount = Object.values(recordMap).reduce(
(summed, next) => summed + next.irrigation,
0
)
const amount = Object.values(recordMap).reduce(
(summed, next) => summed + next.irrigation,
0
)

return [amount, recordMap] as [number, IrrigationRecordMap]
})
return [amount, recordMap] as [number, IrrigationRecordMap]
})
}

/**
Expand Down
35 changes: 14 additions & 21 deletions smartblueberry/backend/plugins/homeassistant/modules/light.ts
Original file line number Diff line number Diff line change
Expand Up @@ -340,10 +340,7 @@ async function setupSimulateLightMode(server: hapi.Server) {
const { mode, options } =
(await getAreaLightMode(server, area_id)) || {}
if (mode == 'simulate') {
const historyTimestamp = dayjs(dayjs())
.subtract(1, 'month')
.toISOString()

const pastTimestamp = dayjs().subtract(1, 'week').toISOString()
const lightEntityNames = server.app.hassRegistry
.getStates({
...LIGHT_ENTITY,
Expand All @@ -352,23 +349,19 @@ async function setupSimulateLightMode(server: hapi.Server) {
.map(({ entity_id }) => entity_id)

if (lightEntityNames.length > 0) {
const { ok, json } = await server.plugins.hassConnect.rest.get<
Pick<State, 'entity_id' | 'state'>[][]
>(
`/history/period/${historyTimestamp}?${[
`end_time=${historyTimestamp}`,
`minimal_response=true`,
`filter_entity_id=${lightEntityNames.join(',')}`
].join('&')}`
)

const hadActiveLight =
ok &&
!!json?.some((entityHistory) => {
return entityHistory.some(
(entityHistoryRecord) => entityHistoryRecord.state == 'on'
)
})
const historicLightStates = await server.app.hassRegistry.history({
startTime: pastTimestamp,
endTime: pastTimestamp,
entityIds: lightEntityNames
})

const hadActiveLight = Object.values(
historicLightStates || {}
).some((historicLightState) => {
return historicLightState.some(
(historicLightStateItem) => historicLightStateItem.s == 'on'
)
})

const service = hadActiveLight ? 'turn_on' : 'turn_off'
const service_data: { brightness?: number } = {}
Expand Down
29 changes: 29 additions & 0 deletions smartblueberry/backend/plugins/homeassistant/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ interface StateAttributes {
| StateAttributes
}

interface HistoryPayload {
s: StatePayload['state']
lu: StatePayload['last_updated']
a: StateAttributes
}

interface StatePayload {
entity_id: string
state: string
Expand Down Expand Up @@ -479,6 +485,29 @@ class Registry {
})
}

public async history<EntityIds extends string[]>({
startTime,
endTime,
entityIds
}: {
startTime: string
endTime: string
entityIds: EntityIds
}) {
const connection = await this.server.plugins.hassConnect.globalConnect()

return connection
?.sendMessagePromise<{
result?: { [key: string]: HistoryPayload[] }
}>({
type: 'history/history_during_period',
start_time: startTime,
end_time: endTime,
entity_ids: entityIds
})
.then((response) => response.result)
}

/**
* Updates parameters of an entity.
* @param entityId The id of the entity to update.
Expand Down
2 changes: 1 addition & 1 deletion smartblueberry/config.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"slug": "smartblueberry",
"name": "Smart Blueberry 🫐",
"version": "1.0.9",
"version": "1.0.10",
"description": "Smart Blueberry is a Home Assistant environment providing multiple extensions to simplify the configuration of light, presence and irrigation management.",
"url": "https://github.com/janwo/smartblueberry/tree/main/smartblueberry",
"image": "janwo/smartblueberry-{arch}",
Expand Down

0 comments on commit f652d08

Please sign in to comment.