-
Torne o consumo de energia da sua casa mais eficiente com o EnergyKit
Saiba como incluir o EnergyKit em seu app para que as pessoas possam otimizar o consumo de energia em casa. Isso pode ajudar as pessoas a usar eletrodomésticos ou carregar veículos elétricos durante os períodos em que a eletricidade é mais limpa e barata. Obtenha informações sobre o processo de integração, a criação de um cronograma de carregamento e o fornecimento de insights sobre o consumo de energia para os usuários por meio de feedback baseado no uso da eletricidade.
Capítulos
- 0:00 - Introdução
- 2:08 - Integrar o EnergyKit
- 3:28 - Gerar um cronograma de carregamento
- 7:35 - Insights
- 14:58 - Próximas etapas
Recursos
Vídeos relacionados
WWDC25
-
Buscar neste vídeo...
-
-
3:13 - Retrive an EnergyVenue
// Retrieve an EnergyVenue import EnergyKit import Foundation @Observable final class EnergyVenueManager { let venue: EnergyVenue init?(venueID: UUID) async { guard let energyVenue = await EnergyVenue.venue(for: venueID) else { return nil } venue = energyVenue } } -
6:03 - Fetch Electricity Guidance at a selected EnergyVenue
// Fetch ElectricityGuidance import EnergyKit import Foundation @Observable final class EnergyVenueManager { // The current active guidance. var guidance: ElectricityGuidance? fileprivate func streamGuidance( venueID: UUID, update: (_ guidance: ElectricityGuidance) -> Void ) async throws { let query = ElectricityGuidance.Query(suggestedAction: .shift) for try await currentGuidance in ElectricityGuidance.sharedService.guidance( using: query, at: venueID ) { update(currentGuidance) break } } } -
7:00 - Start monitoring Electricity Guidance
// Fetch ElectricityGuidance import EnergyKit import Foundation @Observable final class EnergyVenueManager { // The task used to stream guidance. private var streamGuidanceTask: Task<(), Error>? ///Start streaming guidance and store the value in the observed property 'guidance'. func startGuidanceMonitoring() { streamGuidanceTask?.cancel() streamGuidanceTask = Task.detached { [weak self] in if let venueID = self?.venue.id { try? await self?.streamGuidance(venueID: venueID) { guidance in self?.guidance = guidance if Task.isCancelled { return } } } } } } -
11:30 - Update charging measurements
// Update charging measurements import EnergyKit // A controller that handles an electric vehicle @Observable class ElectricVehicleController { fileprivate func chargingMeasurement() -> ElectricVehicleLoadEvent.ElectricalMeasurement { let stateOfCharge = Int(configuration.state.stateOfCharge.rounded(.down)) let power = Measurement<UnitPower>( value: configuration.properties.chargingPower * 1000000, unit: .milliwatts ) let energy = Measurement<UnitEnergy>( value: configuration.state.cummulativeEnergy * 1000000, unit: .EnergyKit.milliwattHours ) return ElectricVehicleLoadEvent.ElectricalMeasurement( stateOfCharge: stateOfCharge, direction: .imported, power: power, energy: energy ) } } -
11:50 - Start a session
// Start a session import EnergyKit // A controller that handles an electric vehicle @Observable class ElectricVehicleController { // The session var session: ElectricVehicleLoadEvent.Session? // The current guidance stored at the EV var currentGuidance: ElectricityGuidance // Whether the EV is following guidance var isFollowingGuidance: Bool = true fileprivate func beginSession() { session = ElectricVehicleLoadEvent.Session( id: UUID(), state: .begin, guidanceState: .init( wasFollowingGuidance: isFollowingGuidance, guidanceToken: currentGuidance.guidanceToken ) ) } } -
12:25 - Update a session
// Update a session import EnergyKit // A controller that handles an electric vehicle @Observable class ElectricVehicleController { fileprivate func updateSession() { if let session { self.session = ElectricVehicleLoadEvent.Session( id: session.id, state: .active, guidanceState: .init( wasFollowingGuidance: isFollowingGuidance, guidanceToken: currentGuidance.guidanceToken ) ) } } } -
12:31 - End a session
// End a session import EnergyKit // A controller that handles an electric vehicle. @Observable class ElectricVehicleController { fileprivate func endSession() { if let session { self.session = ElectricVehicleLoadEvent.Session( id: session.id, state: .end, guidanceState: .init( wasFollowingGuidance: isFollowingGuidance, guidanceToken: currentGuidance.guidanceToken ) ) } } } -
12:43 - Create a load event
// Create a ElectricVehicleLoadEvent @Observable class ElectricVehicleController { fileprivate func createLoadEvent( sessionState: ElectricVehicleLoadEvent.Session.State ) { switch sessionState { case .begin: beginSession() case .active: updateSession() case .end: endSession() @unknown default: fatalError() } if let session { let event = ElectricVehicleLoadEvent( timestamp: configuration.state.timestamp, measurement: chargingMeasurement(), session: session, deviceID: configuration.properties.vehicleID ) events.append(event) } } } -
12:50 - Submit events
// Submit events import EnergyKit // A controller that handles an electric vehicle @Observable class ElectricVehicleController { // EnergyVenue // The venue at which the EV uses energy var currentVenue: EnergyVenue // Electric EV Events // The list of generated EV load events var events = [ElectricVehicleLoadEvent]() func submitEvents() async throws { try await currentVenue.submitEvents(events) } } -
13:25 - Create an insight query
// Create an insight query import EnergyKit @Observable final class EnergyVenueManager { func createInsightsQuery(on date: Date) -> ElectricityInsightQuery { return ElectricityInsightQuery( options: .cleanliness.union(.tariff), range: self.dayInterval(date: date), granularity: .daily, flowDirection: .imported ) } } -
13:43 - Request insights
// Request an insights import EnergyKit @Observable final class EnergyVenueManager { func generateInsights(for vehicleIdentifier: String, on date: Date) async throws -> ElectricityInsightRecord<Measurement<UnitEnergy>>? { let query = createInsightsQuery(on: date) return try await ElectricityInsightService.shared.energyInsights( forDeviceID: vehicleIdentifier, using: query, atVenue: self.venue.id ).first { record in return record.range.start == query.range.start } } }
-
-
- 0:00 - Introdução
O framework EnergyKit permite integrar informações da rede elétrica local aos apps para que as pessoas reduzam o uso, economizem dinheiro e priorizem fontes de energia mais limpas ao utilizar dispositivos como termostatos inteligentes ou recarregar veículos elétricos.
- 2:08 - Integrar o EnergyKit
Para integrar o EnergyKit, os usuários escolhem usar o carregamento com energia limpa em um local específico. O app recupera o local (conhecido como EnergyVenue) e armazena o identificador dele.
- 3:28 - Gerar um cronograma de carregamento
O EnergyKit fornece orientações sobre eletricidade com base na localização, nas informações da rede e nos dados da concessionária para criar um cronograma de carregamento com energia limpa. Ele pode sugerir ações de redução (para dispositivos como termostatos inteligentes) ou de mudança (para usos como carregamento de veículos elétricos). As orientações sobre eletricidade priorizam horários fora de pico, que são mais puros e baratos, otimizando os custos e reduzindo o impacto ambiental.
- 7:35 - Insights
Os insights do EnergyKit ajudam a simplificar a apresentação das informações sobre eletricidade para os usuários e podem categorizar o uso da eletricidade com base na pureza da rede elétrica. Para que os fabricantes de veículos elétricos gerem informações, os apps fornecem feedback ao EnergyKit na forma de eventos de carga que acompanham o progresso durante a sessão de recarga. Ao enviar esses eventos em lote, o EnergyKit pode analisar com precisão os dados de recarga.
- 14:58 - Próximas etapas
Adote o EnergyKit nos seus apps que gerenciam o uso de eletricidade. Para obter mais informações, consulte a amostra de código que acompanha a sessão.