Wednesday, August 23, 2023

SwiftUI Charts to monitor power generation and use

We have 6kW of solar panels here but it's important to know when the sun is shining on them so I can use that power to charge the car or dry clothes. In recent months I've been learning Apple's SwiftUI and one of the gems is the new Charts View. Here's how it looks:


This wonderful chart is created with very little code:

Chart {

                ForEach(model.netHistory) { sample in

                    LineMark(

                        x: .value("time", sample.id),

                        y: .value("Generating", sample.generating)

                    )

                    .foregroundStyle(by: .value("", "Generating"))

                    .interpolationMethod(.catmullRom)

                    

                    LineMark(

                        x: .value("time", sample.id),

                        y: .value("Using", -sample.using)

                    )

                    .foregroundStyle(by: .value("", "Using"))

                    .interpolationMethod(.catmullRom)

                    

                    BarMark(

                        x: .value("time", sample.id),

                        y: .value("Net", sample.net)

                    )

                    .foregroundStyle(by: .value("", "Net"))

                    

                }

                

            }

            .chartForegroundStyleScale(domain: ["Generating", "Using", "Net"], range: [.green, .orange, .blue])


No comments: