You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
2.0 KiB
66 lines
2.0 KiB
using RobotLib.Communication;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Text.Json;
|
|
|
|
namespace RobotLib.Battery
|
|
{
|
|
public class DevBattery : DevBase
|
|
{
|
|
private float voltage;
|
|
|
|
private const string TOPIC_ROBO_REQ_BATTERY = "/mobile/cmd/battery/get_volt";
|
|
private const string TOPIC_ROBO_RESP_BATTERY = "/mobile/state/battery/voltage";
|
|
|
|
public event EventHandler<BatteryEventArgs> BatteryChanged;
|
|
|
|
public float Voltage
|
|
{
|
|
get { return voltage; }
|
|
private set
|
|
{
|
|
// value changed?
|
|
if (voltage != value)
|
|
{
|
|
// set new voltage and raise event
|
|
voltage = value;
|
|
BatteryChanged?.Invoke(this, new BatteryEventArgs(voltage));
|
|
}
|
|
}
|
|
}
|
|
|
|
public DevBattery(IPublisherSubscriber com) : base(com, new List<string>() { TOPIC_ROBO_RESP_BATTERY }) { }
|
|
|
|
public override void Refresh()
|
|
{
|
|
this.RequestBatteryVoltage();
|
|
}
|
|
|
|
public void RequestBatteryVoltage()
|
|
{
|
|
base.SendMessage(TOPIC_ROBO_REQ_BATTERY, true.ToString());
|
|
}
|
|
|
|
protected override void ParseMessage(string fromTopic, string message)
|
|
{
|
|
if (fromTopic == TOPIC_ROBO_RESP_BATTERY)
|
|
{
|
|
var parsedVoltageString = GetValueFromMesage<string>("voltage", message);
|
|
if (parsedVoltageString == null) parsedVoltageString = "?";
|
|
|
|
// example message = "Battery: 1.25 V"
|
|
var valueUnit = message.Trim().Split(' ');
|
|
string voltage = valueUnit[0].Trim();
|
|
|
|
this.Voltage = float.Parse(voltage);
|
|
}
|
|
}
|
|
|
|
private T GetValueFromMesage<T>(string parameter, string message)
|
|
{
|
|
var data = JsonSerializer.Deserialize<Dictionary<string, T>>(message);
|
|
data.TryGetValue(parameter, out T value);
|
|
return value;
|
|
}
|
|
}
|
|
}
|
|
|