Just an update on this.
I have been reading several different articles about using Charts in Swift and have updated my ConnectView as shown below:
`struct ConnectView: View {
@ObservedObject var viewModel: ConnectViewModel
@Environment(\.dismiss) var dismiss
@State var isToggleOn: Bool = false
@State var isPeripheralReady: Bool = false
@State var lastPressure: Int = 0
public var startTime: Double = 0
public var nowTime: Double = 0
@State var graphData = [GraphData]()
var body: some View {
VStack {
Text(viewModel.connectedPeripheral.name ?? "Unknown")
.font(.title)
ZStack {
CardView()
VStack {
Text("Surface")
HStack {
Button("Flats") {
viewModel.flats()
}
.disabled(!isPeripheralReady)
.buttonStyle(.borderedProminent)
Button("FlatPoint") {
viewModel.flatPoint()
}
.disabled(!isPeripheralReady)
.buttonStyle(.borderedProminent)
Button("Points") {
viewModel.points()
}
.disabled(!isPeripheralReady)
.buttonStyle(.borderedProminent)
}
}
}
ZStack {
CardView()
VStack {
Text("\(lastPressure) kPa")
.font(.largeTitle)
HStack {
Spacer()
.frame(alignment: .trailing)
Toggle("Notify", isOn: $isToggleOn)
.disabled(!isPeripheralReady)
Spacer()
.frame(alignment: .trailing)
}
}
}
ZStack{
CardView()
Chart(graphData) {
LineMark(x: .value("Time", $0.time),
y: .value("Load", $0.load))
}
}
.padding()
.frame(maxHeight: .infinity)
Button {
dismiss()
} label: {
Text("Disconnect")
.frame(maxWidth: .infinity)
}
.buttonStyle(.borderedProminent)
.padding(.horizontal)
}
.onChange(of: isToggleOn) { newValue in
if newValue == true {
viewModel.startNotifyPressure()
} else {
viewModel.stopNotifyPressure()
}
// let startTime = Date().timeIntervalSince1970
}
.onReceive(viewModel.$state) { state in
switch state {
case .ready:
isPeripheralReady = true
case let .Pressure(temp):
lastPressure = temp
// let nowTime = (Date().timeIntervalSince1970 - startTime)
let newDataPoint = GraphData(time: nowTime, load: lastPressure)
graphData.append(newDataPoint)
let nowTime = nowTime+1
default:
print("Not handled")
}
}
}
With the Struct for my graph data below:
struct GraphData: Identifiable {
var time: Double
var load: Int
var id: Double {time}
}
This gives me the graph where I want it but the issue now is that it only plots the first data point it receives and does not update as new data comes in. I am also battling with getting the time on the x-axis.