using BPA.ApolloClient;
using BPA.Message;
using BPASmartClient.Model;
using Microsoft.Extensions.Configuration;
using System.Xml.Linq;
using System.Xml.XPath;
namespace BPASmartClient.Business
{
///
/// 配置管理器
///
public class ConfigMgr : IPlugin
{
///
/// 门店ID
///
public int ClientId { get; set; }
///
/// MQTT Broker
///
public MQTT_Entity MQTT_Config { get; set; }
//Apollo地址
private string apolloUri;
//设备集合
private List deviceConfigs;
public void Dispose()
{
}
public void Initialize()
{
ClientId = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ClientId"]);
apolloUri = System.Configuration.ConfigurationManager.AppSettings["ApolloUri"].ToString();
InternetInfo.OrderServer= System.Configuration.ConfigurationManager.AppSettings["OrderServiceUri"].ToString();
InternetInfo.StockServer= System.Configuration.ConfigurationManager.AppSettings["StockServiceUri"].ToString();
InitDeviceModel();
InitMQTT();
}
public List GetDeviceConfigs()
{
if (null == deviceConfigs)
InitDeviceModel();
return deviceConfigs;
}
///
/// 加载设备模型
///
private void InitDeviceModel()
{
deviceConfigs = new List();
var devicePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DeviceInfo.xml");
var xdoc = XDocument.Load(devicePath);
var devices = xdoc.XPathSelectElements("//Device");
foreach (var device in devices)
{
DeviceConfig deviceConfig = new DeviceConfig();
deviceConfig.Name = device.Attribute("Name").Value;
deviceConfig.Module = device.Attribute("Module").Value;
deviceConfig.DeviceId =int.Parse(device.Attribute("DeviceId").Value);
foreach (var peripheralEl in device.XPathSelectElements("//Peripheral"))
{
BPASmartClient.Model.Peripheral peripheral = new BPASmartClient.Model.Peripheral();
peripheral.Module = peripheralEl.Attribute("Module").Value;
foreach (XElement parameter in peripheralEl.Element("Parameters").Elements())
{
peripheral.Parameters.Add(parameter.Name.LocalName, parameter.Value);
}
deviceConfig.Peripherals.Add(peripheral);
}
deviceConfigs.Add(deviceConfig);
}
}
///
/// 加载MQTT配置
///
private void InitMQTT()
{
IConfigurationBuilder configurationBuilder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory());
configurationBuilder.AddApolloConfiguration(p =>
{
p.AppId = "dev1_order";
p.MetaServer = apolloUri;
p.Namespaces = new List() { "DEV.Config" };
});
IConfiguration config = configurationBuilder.Build();
var mqttBroker = config.GetSection("BrokerHostSettings");
MQTT_Config = mqttBroker.Value.FromJSON();
}
public class MQTT_Entity
{
public string Host { get; set; }
public int Port { get; set; }
}
}
}