NXX 2 лет назад
Родитель
Сommit
ec7b3b4f12
69 измененных файлов: 4654 добавлений и 1090 удалений
  1. +69
    -32
      BPASmartClient.Business/Plugin/ConfigMgr.cs
  2. +75
    -40
      BPASmartClient.Business/Plugin/DeviceMgr.cs
  3. +4
    -0
      BPASmartClient.CustomResource/BPASmartClient.CustomResource.csproj
  4. Двоичные данные
     
  5. Двоичные данные
     
  6. +599
    -0
      BPASmartClient.CustomResource/RecDictionarys/DatePickeerDictionary.xaml
  7. +8
    -4
      BPASmartClient.CustomResource/Themes/GenricStyle.xaml
  8. +5
    -6
      BPASmartClient.CustomResource/Themes/MyStyle.xaml
  9. +329
    -103
      BPASmartClient.CustomResource/UserControls/UserKeyBoard.xaml
  10. +0
    -1
      BPASmartClient.DRCoffee/BPASmartClient.DRCoffee.csproj
  11. +1
    -1
      BPASmartClient.DRCoffee/CoffeeMachine.cs
  12. +57
    -56
      BPASmartClient.Device/Alarm.cs
  13. +13
    -20
      BPASmartClient.Device/AlarmHelper.cs
  14. +1
    -0
      BPASmartClient.Device/BPASmartClient.Device.csproj
  15. +25
    -25
      BPASmartClient.Device/BaseDevice.cs
  16. +10
    -10
      BPASmartClient.Device/DeviceStatus.cs
  17. +29
    -1
      BPASmartClient.Device/IDevice.cs
  18. +0
    -1
      BPASmartClient.GSIceCream/BPASmartClient.GSIceCream.csproj
  19. +2
    -1
      BPASmartClient.Helper/BPASmartClient.Helper.csproj
  20. +49
    -0
      BPASmartClient.Helper/Sqlite.cs
  21. +13
    -12
      BPASmartClient.IoT/BPASmartClient.IoT.csproj
  22. +70
    -21
      BPASmartClient.IoT/DataVClient.cs
  23. +247
    -0
      BPASmartClient.IoT/Model/CRC.cs
  24. +66
    -12
      BPASmartClient.IoT/Model/DataVReport.cs
  25. +373
    -0
      BPASmartClient.IoT/Model/FileUpload.cs
  26. +95
    -95
      BPASmartClient.IoT/Model/IOT/IOTDevModel.cs
  27. +26
    -0
      BPASmartClient.IoT/Model/IOT/IOTDevServer.cs
  28. +269
    -0
      BPASmartClient.IoT/Model/OSS_Helper.cs
  29. +0
    -1
      BPASmartClient.KLMCoffee/BPASmartClient.KLMCoffee.csproj
  30. +0
    -1
      BPASmartClient.Lebai/BPASmartClient.Lebai.csproj
  31. +0
    -1
      BPASmartClient.MORKSM.BK.PLC/BPASmartClient.PLC.csproj
  32. +74
    -42
      BPASmartClient.MORKSM.BK.PLC/PLCMachine.cs
  33. +0
    -4
      BPASmartClient.Message/BPASmartClient.Message.csproj
  34. +22
    -25
      BPASmartClient.Message/MessageLog.cs
  35. +198
    -131
      BPASmartClient.Modbus/ModbusTcp.cs
  36. +58
    -0
      BPASmartClient.Model/Alarm.cs
  37. +184
    -0
      BPASmartClient.Model/DeviceConfigModelJson.cs
  38. +0
    -1
      BPASmartClient.Model/KeepDataBase.cs
  39. +87
    -15
      BPASmartClient.MorkS/Alarm.cs
  40. +89
    -33
      BPASmartClient.MorkS/Control_Morks.cs
  41. +3
    -0
      BPASmartClient.MorkS/GVL_MORKS.cs
  42. +1
    -0
      BPASmartClient.MorkS/OrderLocInfo.cs
  43. +4
    -0
      BPASmartClient.Peripheral/BPASmartClient.Peripheral.csproj
  44. +7
    -2
      BPASmartClient.Peripheral/BasePeripheral.cs
  45. +19
    -1
      BPASmartClient.Peripheral/IPeripheral.cs
  46. +0
    -1
      BPASmartClient.SCChip/BPASmartClient.SCChip.csproj
  47. +158
    -0
      BPASmartClient.ViewModel/AlarmViewModel.cs
  48. +117
    -0
      BPASmartClient.ViewModel/LogOrAlarmIOTViewModel.cs
  49. +0
    -10
      BPASmartClient.ViewModel/LogOrAlarmViewModel.cs
  50. +10
    -0
      BPASmartClient.ViewModel/LogViewModel.cs
  51. +181
    -191
      BPASmartClient.ViewModel/Model/DeviceConfigModel.cs
  52. +32
    -13
      BPASmartClient.ViewModel/ShopDeviceConfigViewModel.cs
  53. +46
    -0
      BPASmartClient.ViewModel/SystemSetViewModel.cs
  54. +3
    -4
      BPASmartClient/App.config
  55. +1
    -0
      BPASmartClient/App.xaml
  56. +2
    -0
      BPASmartClient/App.xaml.cs
  57. +37
    -29
      BPASmartClient/Control/AdminstratorsView.xaml
  58. +378
    -0
      BPASmartClient/Control/AlarmView.xaml
  59. +28
    -0
      BPASmartClient/Control/AlarmView.xaml.cs
  60. +74
    -0
      BPASmartClient/Control/LogOrAlarmIOTView.xaml
  61. +70
    -0
      BPASmartClient/Control/LogOrAlarmIOTView.xaml.cs
  62. +0
    -10
      BPASmartClient/Control/LogOrAlarmView.xaml.cs
  63. +7
    -7
      BPASmartClient/Control/OrderStatusView.xaml
  64. +3
    -3
      BPASmartClient/Control/ShopDeviceConfigView.xaml
  65. +5
    -5
      BPASmartClient/Control/ShopDeviceConfigView.xaml.cs
  66. +142
    -10
      BPASmartClient/Control/SystemSetView.xaml
  67. +9
    -7
      BPASmartClient/DeviceInfo.xml
  68. +35
    -50
      BPASmartClient/MainWindow.xaml
  69. +135
    -52
      BPASmartClient/MainWindow.xaml.cs

+ 69
- 32
BPASmartClient.Business/Plugin/ConfigMgr.cs Просмотреть файл

@@ -1,8 +1,11 @@
using BPA.ApolloClient;
using BPA.Message;
using BPASmartClient.Helper;
using BPASmartClient.Message;
using BPASmartClient.Model;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.Xml.Linq;
using System.Xml.XPath;

@@ -58,38 +61,72 @@ namespace BPASmartClient.Business
/// </summary>
private void InitDeviceModel()
{
deviceConfigs = new List<DeviceConfig>();
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);

var Peripherals = device.XPathSelectElements("Peripherals/Peripheral");
if (Peripherals != null)
{
foreach (var Per in Peripherals)
{
BPASmartClient.Model.Peripheral peripheral = new BPASmartClient.Model.Peripheral();
peripheral.Module = Per.Attribute("Module").Value;

var Parameters = Per.Element("Parameters").Elements();
if (Parameters != null)
{
foreach (var item in Parameters)
{
peripheral.Parameters.Add(item.Name.LocalName, item.Value);
}
}
deviceConfig.Peripherals.Add(peripheral);
}
}
deviceConfigs.Add(deviceConfig);
}
//var text = TextHelper.GetInstance.ReadTextInfo("StartShop", "DeviceConfig");
//string path = $"{LocaPath.GetInstance().GetDeviceConfigPath}{text}.json";
//deviceConfigs = new List<DeviceConfig>();
//if (File.Exists(path))
//{
// string JsonString = File.ReadAllText(path);
// var result = JsonConvert.DeserializeObject<ObservableCollection<DeviceConfigModelJson>>(JsonString);
// if (result != null)
// {
// foreach (var shop in result)
// {
// foreach (var device in shop.deviceModels)
// {

// DeviceConfig deviceConfig = new DeviceConfig();
// deviceConfig.Name = device.DeviceName;
// deviceConfig.Module = device.DeviceNamespace;
// deviceConfig.DeviceId = int.Parse(device.DeviceId);

// foreach (var comms in device.communicationDevcies)
// {
// BPASmartClient.Model.Peripheral peripheral = new BPASmartClient.Model.Peripheral();
// peripheral.Module = comms.CommunicationNamespace;
// }
// deviceConfigs.Add(deviceConfig);
// }
// }
// }
//}





//deviceConfigs = new List<DeviceConfig>();
//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);

// var Peripherals = device.XPathSelectElements("Peripherals/Peripheral");
// if (Peripherals != null)
// {
// foreach (var Per in Peripherals)
// {
// BPASmartClient.Model.Peripheral peripheral = new BPASmartClient.Model.Peripheral();
// peripheral.Module = Per.Attribute("Module").Value;

// var Parameters = Per.Element("Parameters").Elements();
// if (Parameters != null)
// {
// foreach (var item in Parameters)
// {
// peripheral.Parameters.Add(item.Name.LocalName, item.Value);
// }
// }
// deviceConfig.Peripherals.Add(peripheral);
// }
// }
// deviceConfigs.Add(deviceConfig);
//}
}

/// <summary>


+ 75
- 40
BPASmartClient.Business/Plugin/DeviceMgr.cs Просмотреть файл

@@ -9,6 +9,7 @@ using BPASmartClient.Peripheral;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Text;
@@ -47,43 +48,77 @@ namespace BPASmartClient.Business
/// </summary>
private void LoadDevice()
{
var devices = Plugin.GetInstance().GetPlugin<ConfigMgr>().GetDeviceConfigs();
foreach (var device in devices)
{
var deviceTemp = Assembly.Load(device.Module.Substring(0, device.Module.LastIndexOf('.'))).CreateInstance(device.Module) as IDevice;
deviceTemp.Name = device.Name;
deviceTemp.DeviceId = device.DeviceId;
foreach (var pars in device.Parameters)
{
deviceTemp.GetType().GetProperty(pars.Key).SetValue(deviceTemp, Convert.ChangeType(pars.Value, deviceTemp.GetType().GetProperty(pars.Key).PropertyType));
}

List<IPeripheral> peripherals = new List<IPeripheral>();
foreach (var peripheral in device.Peripherals)
#region 启动设备对象

var text = TextHelper.GetInstance.ReadTextInfo("StartShop", "DeviceConfig");
string path = $"{LocaPath.GetInstance().GetDeviceConfigPath}{text}.json";
if (File.Exists(path))
{
string JsonString = File.ReadAllText(path);
var result = JsonConvert.DeserializeObject<ObservableCollection<DeviceConfigModelJson>>(JsonString);
if (result != null)
{
try
foreach (var shop in result)//店铺集合
{
var peripheralTemp = Assembly.Load(peripheral.Module.Substring(0, peripheral.Module.LastIndexOf('.'))).CreateInstance(peripheral.Module,true) as IPeripheral;

foreach (var pars in peripheral.Parameters)
foreach (var device in shop.deviceModels)//设备集合
{
peripheralTemp.GetType().GetProperty(pars.Key).SetValue(peripheralTemp, Convert.ChangeType(pars.Value, peripheralTemp.GetType().GetProperty(pars.Key).PropertyType));
}
peripherals.Add(peripheralTemp);
}
catch (Exception ex)
{

throw ex;
string Namespace = device.DeviceNamespace.Substring(0, device.DeviceNamespace.LastIndexOf('.'));
//string startModel = device.DeviceNamespace.Substring(device.DeviceNamespace.LastIndexOf('.') + 1);
var deviceTemp = Assembly.Load(Namespace).CreateInstance(device.DeviceNamespace) as IDevice;
deviceTemp.Name = device?.DeviceName;
deviceTemp.DeviceId = int.Parse(device.DeviceId);

//通讯模块
List<IPeripheral> peripherals = new List<IPeripheral>();
foreach (var comms in device.communicationDevcies)//通讯集合
{
string IPeripheralNamespace = comms.CommunicationNamespace.Substring(0, comms.CommunicationNamespace.LastIndexOf('.'));
//string IPeripheralStartModel = comms.CommunicationNamespace.Substring(comms.CommunicationNamespace.LastIndexOf('.'));
var peripheralTemp = Assembly.Load(IPeripheralNamespace).CreateInstance(comms.CommunicationNamespace) as IPeripheral;
peripheralTemp.variables = comms.variables;
peripheralTemp.communicationPar = comms.communicationPar;
peripherals.Add(peripheralTemp);
}

deviceTemp.Initliaze(peripherals);
this.devices.Add(deviceTemp);
}
}
;
}
deviceTemp.Initliaze(peripherals);
this.devices.Add(deviceTemp);
}
}


#endregion



//var devices = Plugin.GetInstance().GetPlugin<ConfigMgr>().GetDeviceConfigs();
//foreach (var device in devices)
//{
// var deviceTemp = Assembly.Load(device.Module.Substring(0, device.Module.LastIndexOf('.'))).CreateInstance(device.Module) as IDevice;
// deviceTemp.Name = device.Name;
// deviceTemp.DeviceId = device.DeviceId;
// foreach (var pars in device.Parameters)
// {
// deviceTemp.GetType().GetProperty(pars.Key).SetValue(deviceTemp, Convert.ChangeType(pars.Value, deviceTemp.GetType().GetProperty(pars.Key).PropertyType));
// }

// List<IPeripheral> peripherals = new List<IPeripheral>();
// foreach (var peripheral in device.Peripherals)
// {
// var peripheralTemp = Assembly.Load(peripheral.Module.Substring(0, peripheral.Module.LastIndexOf('.'))).CreateInstance(peripheral.Module) as IPeripheral;

// foreach (var pars in peripheral.Parameters)
// {
// peripheralTemp.GetType().GetProperty(pars.Key).SetValue(peripheralTemp, Convert.ChangeType(pars.Value, peripheralTemp.GetType().GetProperty(pars.Key).PropertyType));
// }
// peripherals.Add(peripheralTemp);
// }
// deviceTemp.Initliaze(peripherals);
// this.devices.Add(deviceTemp);
//}
}

public void StartService()
{
@@ -106,21 +141,23 @@ namespace BPASmartClient.Business

if (PushType == 1)
{
EventBus.EventBus.GetInstance().Publish(new RecipeBomEvent()
{
DeviceId = device.DeviceId,
recipeBoms = JsonConvert.DeserializeObject<RecipeBoms>(result)
});
device.recipeBoms = JsonConvert.DeserializeObject<RecipeBoms>(result);
//EventBus.EventBus.GetInstance().Publish(new RecipeBomEvent()
//{
// DeviceId = device.DeviceId,
// recipeBoms = JsonConvert.DeserializeObject<RecipeBoms>(result)
//});
MessageLog.GetInstance.Show("接收到辅料信息");
}
else if (PushType == 0)
{
var apiData = JsonConvert.DeserializeObject<OrderMaterialDelivery>(result);
EventBus.EventBus.GetInstance().Publish(new MaterialDeliveryEvent()
{
DeviceId = device.DeviceId,
orderMaterialDelivery = apiData
});
device.orderMaterialDelivery = apiData;
//EventBus.EventBus.GetInstance().Publish(new MaterialDeliveryEvent()
//{
// DeviceId = device.DeviceId,
// orderMaterialDelivery = apiData
//});
MessageLog.GetInstance.Show("接收到物料信息");
apiData?.BatchingInfo?.ForEach(x =>
{
@@ -138,8 +175,6 @@ namespace BPASmartClient.Business
});
}



public void StopService()
{
this.devices.ForEach(device => device.Stop());


+ 4
- 0
BPASmartClient.CustomResource/BPASmartClient.CustomResource.csproj Просмотреть файл

@@ -16,6 +16,8 @@
<None Remove="Image\buttonOn.png" />
<None Remove="Image\Cb_Checked.png" />
<None Remove="Image\Cb_HalfChecked.png" />
<None Remove="Image\ComboBoxPopSelect.png" />
<None Remove="Image\ComboBoxSelect.png" />
<None Remove="Image\Exp.png" />
<None Remove="Image\hbl.ico" />
<None Remove="Image\HBL.png" />
@@ -167,6 +169,8 @@

<ItemGroup>
<Resource Include="Image\btn_close.png" />
<Resource Include="Image\ComboBoxPopSelect.png" />
<Resource Include="Image\ComboBoxSelect.png" />
<Resource Include="Image\Exp.png" />
<Resource Include="Image\上箭头.png" />
<Resource Include="Image\临时模板.png" />


Двоичные данные
Просмотреть файл


Двоичные данные
Просмотреть файл


+ 599
- 0
BPASmartClient.CustomResource/RecDictionarys/DatePickeerDictionary.xaml Просмотреть файл

@@ -0,0 +1,599 @@
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=System.Runtime">


<!-- 使用该资源字典记得安装Util.Control Nutget包 -->
<!--#region Window窗体-->
<SolidColorBrush x:Key="WindowBackground" Color="#007ACB" />
<SolidColorBrush x:Key="WindowInnerBackground" Color="Transparent" />
<SolidColorBrush x:Key="WindowBorderBrush" Color="#920892" />
<DropShadowEffect
x:Key="WindowDropShadow"
BlurRadius="8"
Direction="0"
Opacity="0.7"
ShadowDepth="0"
Color="Red" />
<SolidColorBrush x:Key="CaptionForeground" Color="White" />
<LinearGradientBrush x:Key="CaptionBackground" StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Offset="0" Color="#571457" />
<GradientStop Offset="1" Color="#6A196A" />
</LinearGradientBrush>
<!--#endregion-->

<!--#region MessageBoxX-->
<SolidColorBrush x:Key="InfoForeground" Color="White" />
<SolidColorBrush x:Key="QuestionForeground" Color="#74B80C" />
<SolidColorBrush x:Key="WarningForeground" Color="DarkOrange" />
<SolidColorBrush x:Key="ErrorForeground" Color="#E74E4E" />
<!--#endregion-->

<!--#region WaitingBox-->
<SolidColorBrush x:Key="WaitingBoxBackground" Color="#921692" />
<!--#endregion-->

<!--#region 边框:Menu-->
<DropShadowEffect
x:Key="DefaultDropShadow"
BlurRadius="5"
Direction="315"
Opacity="0.6"
ShadowDepth="2"
Color="Black" />
<!--#endregion-->

<!--#region 输入组件-->
<SolidColorBrush x:Key="TextForeground" Color="Black" />
<SolidColorBrush x:Key="TextBackground" Color="White" />
<SolidColorBrush x:Key="TextSelectionBrush" Color="#8F8787" />
<!--#endregion-->

<!--#region TextBox默认Label颜色-->
<SolidColorBrush x:Key="TextLabelBackground" Color="#508AB6" />
<!--#endregion-->

<!--#region 输入框-->
<SolidColorBrush x:Key="ControlBorderBrush" Color="#999C9F" />
<SolidColorBrush x:Key="MouseOverBorderBrush" Color="#F6D1D1" />
<SolidColorBrush x:Key="FocusBackground" Color="#365080" />
<SolidColorBrush x:Key="FocusBorderBrush" Color="#EBCECE" />
<!--#endregion-->

<!--#region ScrollBar-->
<SolidColorBrush x:Key="ScrollBarForeround" Color="#877F7F" />
<SolidColorBrush x:Key="ScrollBarBackground" Color="#3E3E42" />
<!--#endregion-->

<!--#region ItemsControl:DataGrid,Tree-->
<system:Double x:Key="HeaderFontSize">14</system:Double>
<SolidColorBrush x:Key="HeaderBorderBrush" Color="#A6FFA500" />
<SolidColorBrush x:Key="HeaderBackground" Color="Purple" />
<SolidColorBrush x:Key="ItemsContentBackground" Color="#1389D7" />
<SolidColorBrush x:Key="ItemsAlternationContentBackground" Color="#128EE0" />
<SolidColorBrush x:Key="GridLinesBrush" Color="#A6D0C2A7" />
<SolidColorBrush x:Key="ItemSelectedForeground" Color="red" />
<SolidColorBrush x:Key="ItemSelectedBackground" Color="#BC8BEA" />
<SolidColorBrush x:Key="ItemMouseOverBackground" Color="#BC8BEA" />
<SolidColorBrush x:Key="ItemMouseOverForeground" Color="White" />
<!--#endregion-->

<!--#region 高亮:日历Today-->
<SolidColorBrush x:Key="ItemHighlighteBackground" Color="#BC8BEA" />
<SolidColorBrush x:Key="ItemHighlighteForeground" Color="#BC8BEA" />
<!--#endregion-->

<!--#region 普通无背景按钮-->
<SolidColorBrush x:Key="CheckedForeground" Color="#F7B63E" />
<SolidColorBrush x:Key="MouseOverForeground" Color="Orange" />
<SolidColorBrush x:Key="PressedForeground" Color="#F7B63E" />
<SolidColorBrush x:Key="LinkForeground" Color="#0816BB" />
<!--#endregion-->

<!--#region Popup,ComboBox-->
<SolidColorBrush x:Key="PopupBackground" Color="red" />
<!--#endregion-->

<!--#region Button-->
<SolidColorBrush x:Key="ButtonBackground" Color="#1D4A9A" />
<SolidColorBrush x:Key="ButtonForeground" Color="White" />
<SolidColorBrush x:Key="ButtonMouseOverBackground" Color="Orange" />
<SolidColorBrush x:Key="ButtonMouseOverForeground" Color="White" />
<SolidColorBrush x:Key="ButtonPressedBackground" Color="DarkOrange" />
<SolidColorBrush x:Key="ButtonPressedForeground" Color="White" />
<!--#endregion-->

<!--#region Menu-->
<SolidColorBrush x:Key="MenuForeground" Color="#920892" />
<SolidColorBrush x:Key="MenuBackground" Color="#DDD1D1" />
<SolidColorBrush x:Key="MenuBorderBrush" Color="DarkBlue" />
<SolidColorBrush x:Key="MenuMouseOverBackground" Color="#0D3CD2" />
<SolidColorBrush x:Key="MenuMouseOverForeground" Color="White" />
<SolidColorBrush x:Key="MenuPressedBackground" Color="#082CA0" />
<SolidColorBrush x:Key="MenuPressedForeground" Color="White" />
<!--#endregion-->

<!--#region State brush-->
<SolidColorBrush x:Key="SuccessfulfaiBrush" Color="#16B32A" />
<SolidColorBrush x:Key="FailedBrush" Color="#B92222" />
<!--#endregion-->

<!--#region DatePickerCalendarStyle-->
<Style x:Key="DatePickerCalendarStyle" TargetType="{x:Type Calendar}">
<Setter Property="Background" Value="#103153" />
<Setter Property="FontSize" Value="18" />
<Setter Property="CalendarButtonStyle" Value="{DynamicResource ButtonStyle}" />
<Setter Property="CalendarDayButtonStyle" Value="{DynamicResource DayButtonStyle}" />
<Setter Property="BorderBrush" Value="Purple" />
<Setter Property="CalendarItemStyle" Value="{DynamicResource CalendarItemsStyle}" />
</Style>
<!--#endregion-->

<!--#region 年,月按钮样式-->
<Style x:Key="ButtonStyle" TargetType="CalendarButton">
<Setter Property="Background" Value="#103153" />
<Setter Property="FontSize" Value="14" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type CalendarButton}">
<Grid x:Name="Grid" Margin="0">
<Border x:Name="Bg" Background="{TemplateBinding Background}" />
<ContentPresenter
x:Name="NormalText"
Margin="5,2,5,2"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
TextElement.Foreground="{TemplateBinding Foreground}" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Purple" />
<Setter Property="Foreground" Value="White" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!--#endregion-->

<!--#region DayButtonStyle-->
<Style x:Key="DayButtonStyle" TargetType="CalendarDayButton">
<Setter Property="Background" Value="#103153" />
<Setter Property="FontSize" Value="14" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type CalendarDayButton}">
<Grid x:Name="Grid" Margin="0">
<Border
x:Name="Bg"
Background="#103153"
BorderBrush="Purple"
BorderThickness="0" />
<ContentPresenter
x:Name="NormalText"
Margin="5,2,5,2"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
TextElement.Foreground="{TemplateBinding Foreground}" />
</Grid>
<ControlTemplate.Triggers>
<!-- 不在当月的日期 -->
<Trigger Property="IsInactive" Value="True">
<Setter TargetName="Grid" Property="Opacity" Value="0.5" />
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Foreground" Value="red" />
</Trigger>
<Trigger Property="IsToday" Value="True">
<Setter Property="Foreground" Value="yellow" />
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="Aqua" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!--#endregion-->

<!--#region FButton_Transparency-->
<Style x:Key="FButton_Transparency" TargetType="{x:Type Button}">
<Setter Property="Background" Value="White" />
<Setter Property="Foreground" Value="white" />
<Setter Property="FontFamily" Value="../Fonts/#iconfont" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="Height" Value="Auto" />
<Setter Property="Width" Value="Auto" />
<Setter Property="FontSize" Value="13" />
<Setter Property="Padding" Value="3,1,3,1" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border
Background="Transparent"
BorderBrush="Transparent"
BorderThickness="1">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Purple" />
</Trigger>
</Style.Triggers>
</Style>
<!--#endregion-->

<!--#region CalendarItemsStyle-->
<Style x:Key="CalendarItemsStyle" TargetType="{x:Type CalendarItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type CalendarItem}">
<ControlTemplate.Resources>
<!-- 头部星期样式 -->
<DataTemplate x:Key="{x:Static CalendarItem.DayTitleTemplateResourceKey}">
<TextBlock
Margin="0,6,0,6"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="{StaticResource HeaderFontSize}"
FontWeight="Bold"
Foreground="{StaticResource PressedForeground}"
Opacity="0.8"
Text="{Binding}" />
</DataTemplate>
</ControlTemplate.Resources>
<Grid x:Name="PART_Root">
<Border
Margin="{TemplateBinding Margin}"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="1">
<Grid Margin="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!-- Header -->
<Grid
Grid.Row="0"
HorizontalAlignment="Stretch"
Background="Transparent">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button
x:Name="PART_PreviousButton"
Grid.Column="0"
Content="&#xe601;"
Focusable="False"
Style="{StaticResource FButton_Transparency}" />
<Button
x:Name="PART_HeaderButton"
Grid.Column="1"
Focusable="False"
Style="{StaticResource FButton_Transparency}" />

<Button
x:Name="PART_NextButton"
Grid.Column="2"
Content="&#xe600;"
Focusable="False"
Style="{StaticResource FButton_Transparency}" />
</Grid>

<!-- PART_MonthView -->
<Grid
x:Name="PART_MonthView"
Grid.Row="1"
Margin="6,1,6,6"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Visibility="Visible">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
</Grid>

<!-- PART_YearView -->
<Grid
x:Name="PART_YearView"
Grid.Row="1"
Margin="6,10,6,10"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Visibility="Hidden">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
</Grid>
</Grid>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="PART_Root" Property="Opacity" Value="{StaticResource DisableOpacity}" />
</Trigger>
<DataTrigger Binding="{Binding DisplayMode, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Calendar}}}" Value="Year">
<Setter TargetName="PART_MonthView" Property="Visibility" Value="Hidden" />
<Setter TargetName="PART_YearView" Property="Visibility" Value="Visible" />
</DataTrigger>
<!-- Decade 美 ['dɛked] n. 十年,十年期;十 -->
<DataTrigger Binding="{Binding DisplayMode, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Calendar}}}" Value="Decade">
<Setter TargetName="PART_MonthView" Property="Visibility" Value="Hidden" />
<Setter TargetName="PART_YearView" Property="Visibility" Value="Visible" />
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!--#endregion-->

<!--#region DropDownButtonStyle-->
<!-- 显示日历的按钮的模板 -->
<Style x:Key="DropDownButtonStyle" TargetType="Button">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<TextBlock
x:Name="DropDownText"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontFamily="../Fonts/#iconfont"
FontSize="16"
Foreground="#3aa7f3"
Text="&#xe6ab;" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="DropDownText" Property="FontSize" Value="18" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="DropDownText" Property="Foreground" Value="#cd8624" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!--#endregion-->

<!--#region DatePickerTextBox样式-->
<Style x:Key="DatePickerTextBoxStyle" TargetType="DatePickerTextBox">
<Setter Property="Background" Value="Transparent" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="VerticalContentAlignment" Value="Stretch" />
<Setter Property="Focusable" Value="False" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<TextBlock
x:Name="tb"
FontSize="{TemplateBinding FontSize}"
Foreground="{TemplateBinding Foreground}"
Text="{TemplateBinding Text}" />
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding Text, RelativeSource={RelativeSource Mode=Self}}" Value="">
<Setter TargetName="tb" Property="Visibility" Value="Visible" />
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!--#endregion-->

<!--#region PickerStyle-->
<Style x:Key="PickerStyle" TargetType="{x:Type DatePicker}">
<Setter Property="Foreground" Value="#00c2f4" />
<Setter Property="IsTodayHighlighted" Value="True" />
<Setter Property="SelectedDateFormat" Value="Short" />
<Setter Property="Padding" Value="2" />
<Setter Property="BorderThickness" Value="2" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<!-- Set CalendarStyle to DatePickerCalendarStyle. -->
<Setter Property="CalendarStyle" Value="{DynamicResource DatePickerCalendarStyle}" />
<Setter Property="Width" Value="200" />
<Setter Property="FontSize" Value="12" />
<!--<Setter Property="Height" Value="30" />-->
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DatePicker}">
<Border
x:Name="br"
Padding="{TemplateBinding Padding}"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Grid
x:Name="PART_Root"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Button
x:Name="PART_Button"
Grid.Column="1"
Height="20"
Margin="3,0,3,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Background="Transparent"
Focusable="False"
Foreground="{TemplateBinding Foreground}"
Style="{StaticResource DropDownButtonStyle}" />
<DatePickerTextBox
x:Name="PART_TextBox"
Grid.Column="0"
Margin="5,0,0,0"
VerticalAlignment="Center"
Foreground="{TemplateBinding Foreground}"
Style="{StaticResource DatePickerTextBoxStyle}"
Text="{TemplateBinding Text}" />
<Grid
x:Name="PART_DisabledVisual"
Grid.Row="0"
Grid.Column="0"
Grid.ColumnSpan="2"
IsHitTestVisible="False"
Opacity="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Rectangle
Grid.Row="0"
Grid.Column="0"
Fill="#A5FFFFFF"
RadiusX="1"
RadiusY="1" />
<Rectangle
Grid.Row="0"
Grid.Column="1"
Width="19"
Height="18"
Margin="3,0,3,0"
Fill="#A5FFFFFF"
RadiusX="1"
RadiusY="1" />
<Popup
x:Name="PART_Popup"
AllowsTransparency="True"
Placement="Bottom"
PlacementTarget="{Binding ElementName=br}"
PopupAnimation="Slide"
StaysOpen="False" />
</Grid>
</Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal" />
<VisualState x:Name="Disabled">
<Storyboard>
<DoubleAnimation
Storyboard.TargetName="PART_DisabledVisual"
Storyboard.TargetProperty="Opacity"
To="1"
Duration="0" />
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="br" Property="BorderBrush" Value="#3aa7f3" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!--#endregion-->

<!--#region Control colors.-->
<Color x:Key="WindowColor">#FFE8EDF9</Color>
<Color x:Key="ContentAreaColorLight">#FFC5CBF9</Color>
<Color x:Key="ContentAreaColorDark">#FF7381F9</Color>

<Color x:Key="DisabledControlLightColor">#FFE8EDF9</Color>
<Color x:Key="DisabledControlDarkColor">#FFC5CBF9</Color>
<Color x:Key="DisabledForegroundColor">#FF888888</Color>

<Color x:Key="SelectedBackgroundColor">#FFC5CBF9</Color>
<Color x:Key="SelectedUnfocusedColor">#FFDDDDDD</Color>

<Color x:Key="ControlLightColor">White</Color>
<Color x:Key="ControlMediumColor">#FF7381F9</Color>
<Color x:Key="ControlDarkColor">#FF211AA9</Color>

<Color x:Key="ControlMouseOverColor">#FF3843C4</Color>
<Color x:Key="ControlPressedColor">#FF211AA9</Color>


<Color x:Key="GlyphColor">#FF444444</Color>
<Color x:Key="GlyphMouseOver">sc#1, 0.004391443, 0.002428215, 0.242281124</Color>
<!--#endregion-->

<!--#region Border colors-->
<Color x:Key="BorderLightColor">#FFCCCCCC</Color>
<Color x:Key="BorderMediumColor">#FF888888</Color>
<Color x:Key="BorderDarkColor">#FF444444</Color>

<Color x:Key="PressedBorderLightColor">#FF888888</Color>
<Color x:Key="PressedBorderDarkColor">#FF444444</Color>

<Color x:Key="DisabledBorderLightColor">#FFAAAAAA</Color>
<Color x:Key="DisabledBorderDarkColor">#FF888888</Color>

<Color x:Key="DefaultBorderBrushDarkColor">Black</Color>
<!--#endregion-->

<!--#region 特定于控制的资源-->
<Color x:Key="HeaderTopColor">#FFC5CBF9</Color>
<Color x:Key="DatagridCurrentCellBorderColor">Black</Color>
<Color x:Key="SliderTrackDarkColor">#FFC5CBF9</Color>

<Color x:Key="NavButtonFrameColor">#FF3843C4</Color>

<LinearGradientBrush x:Key="MenuPopupBrush" StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Offset="0" Color="{DynamicResource ControlLightColor}" />
<GradientStop Offset="0.5" Color="{DynamicResource ControlMediumColor}" />
<GradientStop Offset="1" Color="{DynamicResource ControlLightColor}" />
</LinearGradientBrush>

<LinearGradientBrush x:Key="ProgressBarIndicatorAnimatedFill" StartPoint="0,0" EndPoint="1,0">
<LinearGradientBrush.GradientStops>
<GradientStopCollection>
<GradientStop Offset="0" Color="#000000FF" />
<GradientStop Offset="0.4" Color="#600000FF" />
<GradientStop Offset="0.6" Color="#600000FF" />
<GradientStop Offset="1" Color="#000000FF" />
</GradientStopCollection>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>

<!--#endregion-->

</ResourceDictionary>

+ 8
- 4
BPASmartClient.CustomResource/Themes/GenricStyle.xaml Просмотреть файл

@@ -1192,6 +1192,8 @@
<Setter Property="Background">
<Setter.Value>
<ImageBrush ImageSource="/BPASmartClient.CustomResource;component/Image/表格标题背景2.png" Opacity="0.2" />
<!--<ImageBrush ImageSource="/BPASmartClient.CustomResource;component/Image/窗体样式/datagrid/data_标题栏背景.png" Opacity="0.3"/>-->

</Setter.Value>
</Setter>
<Setter Property="BorderThickness" Value="0" />
@@ -1218,8 +1220,9 @@
BorderBrush="#FFBD2A2A" />
<Thumb
x:Name="PART_RightHeaderGripper"
Width="2"
HorizontalAlignment="Right"
Background="#FF175C86"
Background="#FF1D9B9E"
Style="{StaticResource ColumnHeaderGripperStyle}" />
</Grid>
</ControlTemplate>
@@ -1233,7 +1236,7 @@
<Setter Property="Height" Value="30" />
<Setter Property="Background">
<Setter.Value>
<ImageBrush ImageSource="/BPASmartClient.CustomResource;component/Image/表头背景.png" />
<ImageBrush ImageSource="/BPASmartClient.CustomResource;component/Image/窗体样式/datagrid/data_标题栏背景.png" />
</Setter.Value>
</Setter>
<Setter Property="BorderThickness" Value="0" />
@@ -1270,6 +1273,7 @@
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="SnapsToDevicePixels" Value="true" />
<Setter Property="Foreground" Value="#abf4ff" />
<Setter Property="BorderBrush" Value="#abf4ff"></Setter>
<Setter Property="FontSize" Value="10" />
<Setter Property="Template">
<Setter.Value>
@@ -1341,8 +1345,8 @@

<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderBrush" Value="#FF31879E" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">


+ 5
- 6
BPASmartClient.CustomResource/Themes/MyStyle.xaml Просмотреть файл

@@ -957,7 +957,7 @@
</Setter>
</Style.Setters>
</Style>
<Style TargetType="Button">
<Style.Setters>
<Setter Property="VerticalContentAlignment" Value="Center" />
@@ -968,16 +968,15 @@
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="BD" Cursor="Hand">
<StackPanel
HorizontalAlignment="Center"
Orientation="Horizontal">
<StackPanel HorizontalAlignment="Center" Orientation="Horizontal">
<!--<Border Width="16" Margin="5">
<Border.Background>
<ImageBrush ImageSource="/BPASmartClient.CustomResource;component/Image/顶部切图/返回按钮图标.png" />
</Border.Background>
</Border>-->
<TextBlock Margin="10,0,10,0"
<TextBlock
x:Name="textBlock"
Margin="10,0,10,0"
VerticalAlignment="Center"
FontSize="14"
Foreground="#4fade8"
@@ -1016,7 +1015,7 @@
</Setter>
</Style.Setters>
</Style>
<Style x:Key="CommonBtn_返回" TargetType="Button">
<Style.Setters>
<Setter Property="VerticalContentAlignment" Value="Center" />


+ 329
- 103
BPASmartClient.CustomResource/UserControls/UserKeyBoard.xaml Просмотреть файл

@@ -1,81 +1,100 @@
<UserControl x:Class="BPASmartClient.CustomResource.UserControls.UserKeyBoard"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BPASmartClient.CustomResource.UserControls"
mc:Ignorable="d"
d:DesignHeight="180" d:DesignWidth="500"
x:Name="Keyboard" Background="Transparent" >
<UserControl
x:Class="BPASmartClient.CustomResource.UserControls.UserKeyBoard"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BPASmartClient.CustomResource.UserControls"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Name="Keyboard"
d:DesignHeight="180"
d:DesignWidth="500"
Background="Transparent"
mc:Ignorable="d">
<UserControl.Resources>
<Style x:Key="btnNum" TargetType="{x:Type Button}">
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Cursor" Value="Hand"></Setter>
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="border" BorderBrush="#FF474747" BorderThickness="1" CornerRadius="6">
<Border
x:Name="border"
BorderBrush="#FF474747"
BorderThickness="1"
CornerRadius="6">
<Border.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#002A5F"/>
<GradientStop Color="#6495ED" Offset="1"/>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Color="#002A5F" />
<GradientStop Offset="1" Color="#6495ED" />
</LinearGradientBrush>
</Border.Background>
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" TextElement.Foreground="#4fade8" TextElement.FontSize="16" />
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center"
TextElement.FontSize="16"
TextElement.Foreground="#4fade8" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" TargetName="border" >
<Setter TargetName="border" Property="Background">
<Setter.Value>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFFF7500"/>
<GradientStop Color="#FFFFC547" Offset="1"/>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Color="#FFFF7500" />
<GradientStop Offset="1" Color="#FFFFC547" />
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsPressed" Value="False">
<Setter Property="Background" TargetName="border" >
<Setter TargetName="border" Property="Background">
<Setter.Value>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#002A5F"/>
<GradientStop Color="#6495ED" Offset="1"/>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Color="#002A5F" />
<GradientStop Offset="1" Color="#6495ED" />
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="btnFunc" TargetType="{x:Type Button}">
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Cursor" Value="Hand"></Setter>
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<!--<Setter Property="Padding" Value="1"/>-->
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="border" BorderBrush="#FF565656" BorderThickness="1" CornerRadius="6">
<Border
x:Name="border"
BorderBrush="#FF565656"
BorderThickness="1"
CornerRadius="6">
<Border.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#002A5F"/>
<GradientStop Color="#6495ED" Offset="1"/>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Color="#002A5F" />
<GradientStop Offset="1" Color="#6495ED" />
</LinearGradientBrush>
</Border.Background>
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" TextElement.Foreground="White" TextElement.FontSize="18"/>
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center"
TextElement.FontSize="18"
TextElement.Foreground="White" />

</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" TargetName="border">
<Setter TargetName="border" Property="Background">
<Setter.Value>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Gray" Offset="1"/>
<GradientStop Color="#FF2D2D2D" Offset="0"/>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Offset="1" Color="Gray" />
<GradientStop Offset="0" Color="#FF2D2D2D" />
</LinearGradientBrush>
</Setter.Value>
</Setter>
@@ -87,88 +106,295 @@
</Style>
</UserControl.Resources>
<UserControl.Triggers>
<EventTrigger SourceName="Keyboard" RoutedEvent="UserControl.Loaded">
<EventTrigger RoutedEvent="UserControl.Loaded" SourceName="Keyboard">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="Keyboard" Storyboard.TargetProperty="Opacity"
From="0" To="1" Duration="0:0:0.2">
</DoubleAnimation>
<DoubleAnimation
Storyboard.TargetName="Keyboard"
Storyboard.TargetProperty="Opacity"
From="0"
To="1"
Duration="0:0:0.2" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</UserControl.Triggers>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="10" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="10" />
</Grid.ColumnDefinitions>
<Grid x:Name="ButtonGrid" Grid.Row="1" Grid.Column="1" ButtonBase.Click="ButtonGrid_Click">
<Grid
x:Name="ButtonGrid"
Grid.Row="1"
Grid.Column="1"
ButtonBase.Click="ButtonGrid_Click">
<Grid.RowDefinitions>
<RowDefinition Height="80*"/>
<RowDefinition Height="80*"/>
<RowDefinition Height="80*"/>
<RowDefinition Height="80*"/>
<RowDefinition Height="80*" />
<RowDefinition Height="80*" />
<RowDefinition Height="80*" />
<RowDefinition Height="80*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120*"/>
<ColumnDefinition Width="120*"/>
<ColumnDefinition Width="120*"/>
<ColumnDefinition Width="120*"/>
<ColumnDefinition Width="120*"/>
<ColumnDefinition Width="120*"/>
<ColumnDefinition Width="120*"/>
<ColumnDefinition Width="120*"/>
<ColumnDefinition Width="120*"/>
<ColumnDefinition Width="120*"/>
<ColumnDefinition Width="120*" />
<ColumnDefinition Width="120*" />
<ColumnDefinition Width="120*" />
<ColumnDefinition Width="120*" />
<ColumnDefinition Width="120*" />
<ColumnDefinition Width="120*" />
<ColumnDefinition Width="120*" />
<ColumnDefinition Width="120*" />
<ColumnDefinition Width="120*" />
<ColumnDefinition Width="120*" />
</Grid.ColumnDefinitions>
<Button Margin="2" Grid.Column="0" Grid.Row="0" Content="1" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="1" Grid.Row="0" Content="2" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="2" Grid.Row="0" Content="3" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="3" Grid.Row="0" Content="4" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="4" Grid.Row="0" Content="5" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="5" Grid.Row="0" Content="6" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="6" Grid.Row="0" Content="7" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="7" Grid.Row="0" Content="8" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="8" Grid.Row="0" Content="9" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="9" Grid.Row="0" Content="0" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="0" Grid.Row="1" Content="Q" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="1" Grid.Row="1" Content="W" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="2" Grid.Row="1" Content="E" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="3" Grid.Row="1" Content="R" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="4" Grid.Row="1" Content="T" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="5" Grid.Row="1" Content="Y" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="6" Grid.Row="1" Content="U" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="7" Grid.Row="1" Content="I" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="8" Grid.Row="1" Content="O" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="9" Grid.Row="1" Content="P" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="0" Grid.Row="2" Content="A" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="1" Grid.Row="2" Content="S" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="2" Grid.Row="2" Content="D" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="3" Grid.Row="2" Content="F" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="4" Grid.Row="2" Content="G" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="5" Grid.Row="2" Content="H" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="6" Grid.Row="2" Content="J" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="7" Grid.Row="2" Content="K" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="8" Grid.Row="2" Content="L" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="0" Grid.Row="3" Content="Z" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="1" Grid.Row="3" Content="X" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="2" Grid.Row="3" Content="C" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="3" Grid.Row="3" Content="V" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="4" Grid.Row="3" Content="B" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="5" Grid.Row="3" Content="N" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="6" Grid.Row="3" Content="M" Style="{StaticResource btnNum}"/>
<Button Margin="2" Grid.Column="9" Grid.Row="2" Content="A/a" Style="{StaticResource btnFunc}"/>
<Button Margin="2" Grid.Column="7" Grid.Row="3" Content="DEL" Style="{StaticResource btnFunc}"/>
<Button Margin="2" Grid.Column="8" Grid.Row="3" Content="AC" Style="{StaticResource btnFunc}"/>
<Button Margin="2" Grid.Column="9" Grid.Row="3" Content="确认" Style="{StaticResource btnFunc}"/>
<Button
Grid.Row="0"
Grid.Column="0"
Margin="2"
Content="1"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="0"
Grid.Column="1"
Margin="2"
Content="2"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="0"
Grid.Column="2"
Margin="2"
Content="3"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="0"
Grid.Column="3"
Margin="2"
Content="4"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="0"
Grid.Column="4"
Margin="2"
Content="5"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="0"
Grid.Column="5"
Margin="2"
Content="6"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="0"
Grid.Column="6"
Margin="2"
Content="7"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="0"
Grid.Column="7"
Margin="2"
Content="8"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="0"
Grid.Column="8"
Margin="2"
Content="9"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="0"
Grid.Column="9"
Margin="2"
Content="0"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="1"
Grid.Column="0"
Margin="2"
Content="Q"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="1"
Grid.Column="1"
Margin="2"
Content="W"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="1"
Grid.Column="2"
Margin="2"
Content="E"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="1"
Grid.Column="3"
Margin="2"
Content="R"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="1"
Grid.Column="4"
Margin="2"
Content="T"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="1"
Grid.Column="5"
Margin="2"
Content="Y"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="1"
Grid.Column="6"
Margin="2"
Content="U"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="1"
Grid.Column="7"
Margin="2"
Content="I"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="1"
Grid.Column="8"
Margin="2"
Content="O"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="1"
Grid.Column="9"
Margin="2"
Content="P"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="2"
Grid.Column="0"
Margin="2"
Content="A"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="2"
Grid.Column="1"
Margin="2"
Content="S"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="2"
Grid.Column="2"
Margin="2"
Content="D"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="2"
Grid.Column="3"
Margin="2"
Content="F"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="2"
Grid.Column="4"
Margin="2"
Content="G"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="2"
Grid.Column="5"
Margin="2"
Content="H"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="2"
Grid.Column="6"
Margin="2"
Content="J"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="2"
Grid.Column="7"
Margin="2"
Content="K"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="2"
Grid.Column="8"
Margin="2"
Content="L"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="3"
Grid.Column="0"
Margin="2"
Content="Z"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="3"
Grid.Column="1"
Margin="2"
Content="X"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="3"
Grid.Column="2"
Margin="2"
Content="C"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="3"
Grid.Column="3"
Margin="2"
Content="V"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="3"
Grid.Column="4"
Margin="2"
Content="B"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="3"
Grid.Column="5"
Margin="2"
Content="N"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="3"
Grid.Column="6"
Margin="2"
Content="M"
Style="{StaticResource btnNum}" />
<Button
Grid.Row="2"
Grid.Column="9"
Margin="2"
Content="A/a"
Style="{StaticResource btnFunc}" />
<Button
Grid.Row="3"
Grid.Column="7"
Margin="2"
Content="DEL"
Style="{StaticResource btnFunc}" />
<Button
Grid.Row="3"
Grid.Column="8"
Margin="2"
Content="AC"
Style="{StaticResource btnFunc}" />
<Button
Grid.Row="3"
Grid.Column="9"
Margin="2"
Content="确认"
Style="{StaticResource btnFunc}" />

</Grid>
</Grid>


+ 0
- 1
BPASmartClient.DRCoffee/BPASmartClient.DRCoffee.csproj Просмотреть файл

@@ -5,7 +5,6 @@
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\BPASmartClient.Model\BPASmartClient.Model.csproj" />
<ProjectReference Include="..\BPASmartClient.Peripheral\BPASmartClient.Peripheral.csproj" />
<ProjectReference Include="..\BPASmartClient.SerialPort\BPASmartClient.SerialPort.csproj" />
</ItemGroup>


+ 1
- 1
BPASmartClient.DRCoffee/CoffeeMachine.cs Просмотреть файл

@@ -171,7 +171,7 @@ namespace BPASmartClient.DRCoffee
{
status["Status"] = DrCoffeeStatus.Wait;
status["AppStatus"] = DrCoffeeAppStatus.应用无状态;
status["Warning"] = DrCoffeeWarning.冲泡器未安装到位;
status["Warning"] = DrCoffeeWarning.无警告;
status["Fault"] = DrCoffeeFault.无故障;
}



+ 57
- 56
BPASmartClient.Device/Alarm.cs Просмотреть файл

@@ -1,56 +1,57 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BPASmartClient.Device
{
public class Alarm
{
/// <summary>
/// ID
/// </summary>
[Key]
public int Id { get { return _mId; } set { _mId = value; } }
private int _mId;

/// <summary>
/// 编号ID
/// </summary>
public int NumId { get { return _mNumId; } set { _mNumId = value; } }
private int _mNumId;


/// <summary>
/// 日期
/// </summary>
public string Date { get { return _mDate; } set { _mDate = value; } }
private string _mDate;

/// <summary>
/// 时间
/// </summary>
public string Time { get { return _mTime; } set { _mTime = value; } }
private string _mTime;

/// <summary>
/// 报警信息
/// </summary>
public string Info { get { return _mInfo; } set { _mInfo = value; } }
private string _mInfo;

/// <summary>
/// 报警值
/// </summary>
public string Value { get { return _mValue; } set { _mValue = value; } }
private string _mValue;

/// <summary>
/// 报警等级
/// </summary>
public string Grade { get { return _mGrade; } set { _mGrade = value; } }
private string _mGrade;
}
}
//using System;
//using System.Collections.Generic;
//using System.ComponentModel.DataAnnotations;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;


//namespace BPASmartClient.Device
//{
// public class Alarm
// {
// /// <summary>
// /// ID
// /// </summary>
// [Key]
// public int Id { get { return _mId; } set { _mId = value; } }
// private int _mId;

// /// <summary>
// /// 编号ID
// /// </summary>
// public int NumId { get { return _mNumId; } set { _mNumId = value; } }
// private int _mNumId;


// /// <summary>
// /// 日期
// /// </summary>
// public string Date { get { return _mDate; } set { _mDate = value; } }
// private string _mDate;

// /// <summary>
// /// 时间
// /// </summary>
// public string Time { get { return _mTime; } set { _mTime = value; } }
// private string _mTime;

// /// <summary>
// /// 报警信息
// /// </summary>
// public string Info { get { return _mInfo; } set { _mInfo = value; } }
// private string _mInfo;

// /// <summary>
// /// 报警值
// /// </summary>
// public string Value { get { return _mValue; } set { _mValue = value; } }
// private string _mValue;

// /// <summary>
// /// 报警等级
// /// </summary>
// public string Grade { get { return _mGrade; } set { _mGrade = value; } }
// private string _mGrade;
// }
//}

+ 13
- 20
BPASmartClient.Device/AlarmHelper.cs Просмотреть файл

@@ -1,4 +1,7 @@
using System;
using BPASmartClient.Helper;
using BPASmartClient.Message;
using BPASmartClient.Model;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
@@ -48,7 +51,7 @@ namespace BPASmartClient.Device
{
Alarm tempAlarm = new Alarm()
{
NumId = Alarms.Count,
NumId = Alarms.Count + 1,
Date = DateTime.Now.ToString("yyyy/MM/dd"),
Grade = alarmLevel.ToString(),
Info = AlarmInfo,
@@ -56,22 +59,16 @@ namespace BPASmartClient.Device
Time = DateTime.Now.ToString("HH:mm:ss"),
};

//tempAlarm.Id = IotReport.GetInstance.HttpAddAlarm(new BPA.Message.API请求.AlarmTable
//{
// AlarmTime=DateTime.Now,
// AlarmType= tempAlarm.Grade,
// AlarmMessage= tempAlarm.Info,
// AlarmVla= tempAlarm.Value,
// ClientId= InternetInfo.ClientId.ToString()
//});

//Sqlite<Alarm>.GetInstance.Base.Add(tempAlarm);
var res = Sqlite<Alarm>.GetInstance.Base.Add(tempAlarm);
Sqlite<Alarm>.GetInstance.Save();

if (Alarms.FirstOrDefault(p => p.Info == AlarmInfo) == null)
{
Alarms.Add(tempAlarm);
if (AddAction != null) AddAction(AlarmInfo);//添加报警通知
if (ChangeAction != null) ChangeAction();//更改报警通知
Alarms.Insert(0, tempAlarm);
for (int i = 0; i < Alarms.Count; i++) { Alarms.ElementAt(i).NumId = i + 1; }
AddAction?.Invoke(AlarmInfo);//添加报警通知
ChangeAction?.Invoke();//更改报警通知
MessageLog.GetInstance.AddDeviceAlarmLogShow(tempAlarm.Info, Guid.NewGuid().ToString());
}
}

@@ -85,11 +82,7 @@ namespace BPASmartClient.Device
if (result != null)
{
Alarms.Remove(result);
//IotReport.GetInstance.HttpDeleteAlarm(result.Id);
for (int i = 0; i < Alarms.Count; i++)
{
Alarms.ElementAt(i).NumId = i + 1;
}
for (int i = 0; i < Alarms.Count; i++) { Alarms.ElementAt(i).NumId = i + 1; }
if (RemoveAction != null) RemoveAction(AlarmInfo);
if (ChangeAction != null) ChangeAction();
}


+ 1
- 0
BPASmartClient.Device/BPASmartClient.Device.csproj Просмотреть файл

@@ -12,6 +12,7 @@

<ItemGroup>
<ProjectReference Include="..\BPASmartClient.Helper\BPASmartClient.Helper.csproj" />
<ProjectReference Include="..\BPASmartClient.Model\BPASmartClient.Model.csproj" />
<ProjectReference Include="..\BPASmartClient.Peripheral\BPASmartClient.Peripheral.csproj" />
</ItemGroup>



+ 25
- 25
BPASmartClient.Device/BaseDevice.cs Просмотреть файл

@@ -2,6 +2,7 @@
using BPA.Message.Enum;
using BPASmartClient.Helper;
using BPASmartClient.Message;
using BPASmartClient.Model;
using BPASmartClient.Peripheral;
using System;
using System.Collections.Concurrent;
@@ -27,12 +28,12 @@ namespace BPASmartClient.Device
/// <summary>
/// 订单物料信息
/// </summary>
protected OrderMaterialDelivery orderMaterialDelivery { get; set; } = new OrderMaterialDelivery();
public OrderMaterialDelivery orderMaterialDelivery { get; set; } = new OrderMaterialDelivery();

/// <summary>
/// 配方数据信息
/// </summary>
protected RecipeBoms recipeBoms { get; set; } = new RecipeBoms();
public RecipeBoms recipeBoms { get; set; } = new RecipeBoms();

/// <summary>
/// 设备ID
@@ -99,8 +100,11 @@ namespace BPASmartClient.Device
/// </summary>
private List<IPeripheral> peripherals;

public Action<int,object> AddErrorAction { get; set; }
public Action<int, object> AddErrorAction { get; set; }
public Action<int, object> DeleteErrorAction { get; set; }
public List<Alarm> alarms { get; set; } = new List<Alarm>();
public IAlarm InterfaceAlarm { get; set; }
public AlarmHelper alarmHelper { get; set; } = new AlarmHelper();

#endregion

@@ -110,9 +114,9 @@ namespace BPASmartClient.Device
/// <param name="info"></param>
public void DeviceProcessLogShow(string info)
{
Log.Insert(0,new { Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Type = "流程", Text = info });
Log.Insert(0, new { Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Type = "流程", Text = info });
MessageLog.GetInstance.DeviceProcessLogShow(DeviceId.ToString(), info);
if (Log.Count > 100) { Log.RemoveAt(Log.Count - 1);}
if (Log.Count > 100) { Log.RemoveAt(Log.Count - 1); }
}

public void Initliaze()
@@ -131,9 +135,6 @@ namespace BPASmartClient.Device

public virtual void StartMain()
{
#region 测试添加几个日志与告警
#endregion

ThreadManage.GetInstance().StartLong(new Action(() =>
{
foreach (var peripheral in peripherals)
@@ -144,7 +145,7 @@ namespace BPASmartClient.Device
foreach (var key in peripheral.GetAllStatus().Keys)
{
peripheralStatus[key] = peripheral.GetAllStatus()[key];
if (TypeName != "PLC.MorksMachine")
if (TypeName != "PLC.PLCMachine")
{
Status.Update($"{TypeName}.{key}", peripheral.GetAllStatus()[key]);
}
@@ -169,7 +170,7 @@ namespace BPASmartClient.Device
Text = item.Ms
};
Error.Add(obj);
AddErrorAction?.Invoke(DeviceId,obj);
AddErrorAction?.Invoke(DeviceId, obj);
}
}
else
@@ -178,7 +179,7 @@ namespace BPASmartClient.Device
if (res != null)
{
Error.Remove(res);
DeleteErrorAction?.Invoke(DeviceId,res);
DeleteErrorAction?.Invoke(DeviceId, res);
}
}
}
@@ -216,9 +217,10 @@ namespace BPASmartClient.Device
}
else if (faces.Name == "IAlarm")
{
IAlarm alarm = item.GetValue(this) as IAlarm;
AlarmHelper alarmHelper = new AlarmHelper();
alarmHelper.AddAction = new Action<string>((s) =>
InterfaceAlarm = item.GetValue(this) as IAlarm;
//IAlarm alarm = item.GetValue(this) as IAlarm;
//AlarmHelper alarmHelper = new AlarmHelper();
alarmHelper.AddAction += new Action<string>((s) =>
{
var res = alarmHelper.Alarms.FirstOrDefault(p => p.Info == s);
if (res != null)
@@ -229,11 +231,11 @@ namespace BPASmartClient.Device
Type = res.Grade,
Text = res.Info
};
Error.Insert(0,obj);
Error.Insert(0, obj);
AddErrorAction?.Invoke(DeviceId, obj);
}
});
alarmHelper.RemoveAction = new Action<string>((s) =>
alarmHelper.RemoveAction += new Action<string>((s) =>
{
var res = Error.FirstOrDefault(p => p.GetType().GetProperty("Text").GetValue(p).ToString() == s);
if (res != null && Error.Contains(res))
@@ -244,7 +246,7 @@ namespace BPASmartClient.Device
});
ThreadManage.GetInstance().StartLong(new Action(() =>
{
AlarmMonitoring(alarm, alarmHelper);
AlarmMonitoring();
Thread.Sleep(500);
}), $"报警检测监控:{DeviceId}");
}
@@ -253,24 +255,22 @@ namespace BPASmartClient.Device
});
}



/// <summary>
/// 报警监控
/// </summary>
/// <param name="alarm"></param>
/// <param name="alarmHelper"></param>
private void AlarmMonitoring(IAlarm alarm, AlarmHelper alarmHelper)
private void AlarmMonitoring()
{
if (alarm == null) return;
foreach (var item in alarm.GetType().GetProperties())
if (InterfaceAlarm == null) return;
foreach (var item in InterfaceAlarm.GetType().GetProperties())
{
var res = item.GetValue(alarm);
var res = item.GetValue(InterfaceAlarm);
if (res != null && res is bool blen)
{
if (item.CustomAttributes.Count() > 0 && item.CustomAttributes.ElementAt(0)?.ConstructorArguments.Count() > 0)
{
var info = item.CustomAttributes.ElementAt(0)?.ConstructorArguments.ElementAt(0).Value;
var info = item.GetCustomAttribute<AlarmAttribute>().AlarmInfo;
if (info != null) alarmHelper.EdgeAlarm(blen, info.ToString());
}
}
@@ -319,7 +319,7 @@ namespace BPASmartClient.Device
}

/// <summary>
/// 获取流程信息
/// 获取监控信息
/// </summary>
private void GetMonitorData(IStatus status)
{


+ 10
- 10
BPASmartClient.Device/DeviceStatus.cs Просмотреть файл

@@ -42,7 +42,7 @@ namespace BPASmartClient.Device


};
public ConcurrentDictionary<string, object> status = new ConcurrentDictionary<string, object>();

public void Update(string key, object value)
@@ -68,7 +68,7 @@ namespace BPASmartClient.Device
{
sta = item.Key.Split('.')[0];
string sop = item.Key.Split('.')[item.Key.Split('.').Length - 1]; name = sop;
string value = item.Value.ToString();
string value = item.Value?.ToString();
if (keyValues.ContainsKey(sta)) sta = keyValues[sta];
if (keyValues.ContainsKey(sop)) sop = keyValues[sop];
if (keyValues.ContainsKey(value)) value = keyValues[value];
@@ -89,21 +89,21 @@ namespace BPASmartClient.Device
{
string name = item.Key;
string Ms = string.Empty;
string id=string.Empty;
string sta=string.Empty;
string id = string.Empty;
string sta = string.Empty;
if (item.Key.Contains("."))
{
sta = item.Key.Split('.')[0];
string sop = item.Key.Split('.')[item.Key.Split('.').Length - 1]; name = sop;
string value = item.Value.ToString();
string value = item.Value?.ToString();
if (keyValues.ContainsKey(sta)) sta = keyValues[sta];
if (keyValues.ContainsKey(sop)) sop = keyValues[sop];
if (keyValues.ContainsKey(value)) value = keyValues[value];

Ms = $"[{sta}]-[{sop}]-[{value}]";
id= $"[{sta}]-[{sop}]";
id = $"[{sta}]-[{sop}]";
}
StatusALL.Add(new DevStatus {id= id, Name = name,type=sta, Status = item.Value.ToString(), Ms = Ms });
StatusALL.Add(new DevStatus { id = id, Name = name, type = sta, Status = item.Value.ToString(), Ms = Ms });
}
StatusALL = StatusALL?.OrderBy(x => x.type).ToList();
return StatusALL;
@@ -125,9 +125,9 @@ namespace BPASmartClient.Device
if (_status == "False" || _status == "True")
{
if (_status == "True")
StatusColor = new { r = 51, g = 232, b = 34, a = 1 };
StatusColor = new { r = 51, g = 232, b = 34, a = 1 };
else
StatusColor = new { r = 255, g = 0, b = 0, a = 1 };
StatusColor = new { r = 255, g = 0, b = 0, a = 1 };
}
}
}
@@ -135,7 +135,7 @@ namespace BPASmartClient.Device
public object StatusColor { get; set; }
public DevStatus()
{
StatusColor = new { r = 51, g = 232, b = 34, a = 1 };
StatusColor = new { r = 51, g = 232, b = 34, a = 1 };
}
}
}

+ 29
- 1
BPASmartClient.Device/IDevice.cs Просмотреть файл

@@ -1,4 +1,6 @@
using BPA.Message.Enum;
using BPA.Message;
using BPA.Message.Enum;
using BPASmartClient.Model;
using BPASmartClient.Peripheral;
using System;
using System.Collections.Concurrent;
@@ -26,6 +28,17 @@ namespace BPASmartClient.Device
/// 设备类型
/// </summary>
DeviceClientType DeviceType { get; }

/// <summary>
/// 订单物料信息
/// </summary>
OrderMaterialDelivery orderMaterialDelivery { get; set; }

/// <summary>
/// 配方数据信息
/// </summary>
RecipeBoms recipeBoms { get; set; }

/// <summary>
/// 设备所有状态
/// </summary>
@@ -43,6 +56,21 @@ namespace BPASmartClient.Device
/// </summary>
List<VariableMonitor> variableMonitors { get; set; }

/// <summary>
/// 设备报警信息集合
/// </summary>
List<Alarm> alarms { get; set; }

/// <summary>
/// 接口报警对象
/// </summary>
IAlarm InterfaceAlarm { get; set; }

/// <summary>
/// 报警实体
/// </summary>
AlarmHelper alarmHelper { get; set; }

/// <summary>
/// 是否忙碌
/// </summary>


+ 0
- 1
BPASmartClient.GSIceCream/BPASmartClient.GSIceCream.csproj Просмотреть файл

@@ -5,7 +5,6 @@
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\BPASmartClient.Model\BPASmartClient.Model.csproj" />
<ProjectReference Include="..\BPASmartClient.Peripheral\BPASmartClient.Peripheral.csproj" />
<ProjectReference Include="..\BPASmartClient.SerialPort\BPASmartClient.SerialPort.csproj" />
</ItemGroup>


+ 2
- 1
BPASmartClient.Helper/BPASmartClient.Helper.csproj Просмотреть файл

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
@@ -18,6 +18,7 @@

<ItemGroup>
<PackageReference Include="log4net" Version="2.0.14" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.5" />
<PackageReference Include="Microsoft.Win32.Registry" Version="5.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>


+ 49
- 0
BPASmartClient.Helper/Sqlite.cs Просмотреть файл

@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Sqlite;

namespace BPASmartClient.Helper
{
public class Sqlite<T> : DbContext where T : class, new()
{

private volatile static Sqlite<T> _Instance;
public static Sqlite<T> GetInstance => _Instance ?? (_Instance = new Sqlite<T>());
private Sqlite() { }

public DbSet<T> Base { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite($"FileName={path}");
}

static string path
{
get
{
Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"AccessFile\\DB"));
return $"{AppDomain.CurrentDomain.BaseDirectory}AccessFile\\DB\\{typeof(T).Name}.db";
}
}


public void Save()
{
Database.EnsureCreated();
var a = SaveChanges();
}

public List<T> GetData()
{
Database.EnsureCreated();
return Base.ToList();
}

}
}

+ 13
- 12
BPASmartClient.IoT/BPASmartClient.IoT.csproj Просмотреть файл

@@ -1,18 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="M2Mqtt" Version="4.3.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Aliyun.OSS.SDK" Version="2.13.0" />
<PackageReference Include="M2Mqtt" Version="4.3.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="6.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\BPASmartClient.Business\BPASmartClient.Business.csproj" />
<ProjectReference Include="..\BPASmartClient.Helper\BPASmartClient.Helper.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BPASmartClient.Business\BPASmartClient.Business.csproj" />
<ProjectReference Include="..\BPASmartClient.Helper\BPASmartClient.Helper.csproj" />
</ItemGroup>

</Project>

+ 70
- 21
BPASmartClient.IoT/DataVClient.cs Просмотреть файл

@@ -4,6 +4,7 @@ using BPA.Message.IOT;
using BPASmartClient.Business;
using BPASmartClient.Device;
using BPASmartClient.Helper;
using BPASmartClient.IoT.Model;
using BPASmartClient.Message;
using BPASmartDatavDeviceClient.IoT;
using System;
@@ -39,7 +40,7 @@ namespace BPASmartClient.IoT
ProductKey = System.Configuration.ConfigurationManager.AppSettings["ProductKey"].ToString();
DeviceSecret = System.Configuration.ConfigurationManager.AppSettings["DeviceSecret"].ToString();
StartupMode = System.Configuration.ConfigurationManager.AppSettings["StartupMode"].ToString();
BroadcastPubTopic= System.Configuration.ConfigurationManager.AppSettings["BroadcastPubTopic"].ToString();
BroadcastPubTopic = System.Configuration.ConfigurationManager.AppSettings["BroadcastPubTopic"].ToString();
}
#endregion

@@ -65,16 +66,10 @@ namespace BPASmartClient.IoT
/// 大屏上报Model
/// </summary>
public DataVAPI.Tool.IOT.IOTDevSXModel iOTDevSXModel = new DataVAPI.Tool.IOT.IOTDevSXModel() { };
/// <summary>
/// 广播
/// </summary>
//public string PubTopic = "/broadcast/" + "grgpECHSL7q" + "/" + "Transit_SetDevice";
//public string PubTopic = "/broadcast/" + "grgpECHSL7q" + "/" + "Transit_Test_SetDevice";

/// <summary>
/// key值
/// </summary>
public Dictionary<string,string> keyValues = new Dictionary<string, string>();
public Dictionary<string, string> keyValues = new Dictionary<string, string>();
#endregion

#region API调用
@@ -111,7 +106,7 @@ namespace BPASmartClient.IoT
string id = string.Empty;
try
{
if (DeviceDataV != null && DeviceDataV.GetIsConnected() && DeviceDataV.deviceTable!=null)
if (DeviceDataV != null && DeviceDataV.GetIsConnected() && DeviceDataV.deviceTable != null)
{
logTable.ClientId = ClientId;
logTable.devicename = DeviceDataV.deviceTable.devicename;
@@ -150,10 +145,11 @@ namespace BPASmartClient.IoT
DeviceSecret = DeviceDataV.deviceTable.devicesecret;
DeviceDataV.DataVMessageAction += DevIOTActionHandler;
MessageLog.GetInstance.Show($"客户端:【{ClientId}】,设备名称{DeviceName}阿里云连接成功");
UpDataFile();
}
else
{
MessageLog.GetInstance.ShowEx(message);
MessageLog.GetInstance.ShowEx(message);
}
}
else
@@ -161,13 +157,14 @@ namespace BPASmartClient.IoT
if (DeviceDataV.InitializeNo(ProductKey, DeviceName, DeviceSecret, ref message))
{
MessageLog.GetInstance.Show($"客户端:【{ClientId}】,设备名称{DeviceName}阿里云连接成功");
UpDataFile();
}
else
MessageLog.GetInstance.ShowEx(message);
}
Plugin.GetInstance()?.GetPlugin<DeviceMgr>()?.GetDevices()?.ForEach(device =>
{
device.AddErrorAction+= AddErrorAction;
device.AddErrorAction += AddErrorAction;
device.DeleteErrorAction += DeleteErrorAction;
});
}
@@ -179,8 +176,9 @@ namespace BPASmartClient.IoT
{
ThreadManage.GetInstance().StartLong(new Action(() =>
{
if (DeviceDataV != null && DeviceDataV.GetIsConnected() && DeviceDataV.deviceTable != null)
if (DeviceDataV != null && DeviceDataV.GetIsConnected() && DeviceDataV.deviceTable != null)
{
iOTDevSXModel.Device1=String.Empty;iOTDevSXModel.Device2=String.Empty;iOTDevSXModel.Device3 = String.Empty;
List<object> dataVNode = new List<object>();
Plugin.GetInstance()?.GetPlugin<DeviceMgr>()?.GetDevices()?.ForEach(device =>
{
@@ -200,6 +198,10 @@ namespace BPASmartClient.IoT
VariableMonitor = device.GetVariableMonitor(),
};
dataVNode.Add(obj);

if (string.IsNullOrEmpty(iOTDevSXModel.Device1)) iOTDevSXModel.Device1 = $"[{device.Name}]:{(device.IsBusy ? "忙碌" : "空闲")}-{(device.IsHealth ? "健康" : "故障")}";
else if (string.IsNullOrEmpty(iOTDevSXModel.Device2)) iOTDevSXModel.Device2 = $"[{device.Name}]:{(device.IsBusy ? "忙碌" : "空闲")}-{(device.IsHealth ? "健康" : "故障")}";
else if (string.IsNullOrEmpty(iOTDevSXModel.Device3)) iOTDevSXModel.Device3 = $"[{device.Name}]:{(device.IsBusy ? "忙碌" : "空闲")}-{(device.IsHealth ? "健康" : "故障")}";
});
if (dataVNode.Count > 0)
{
@@ -210,10 +212,27 @@ namespace BPASmartClient.IoT
Thread.Sleep(3000);
}), "DataV数据上报", true);
}

/// <summary>
/// 文件上传请求
/// </summary>
public void UpDataFile()
{
try
{
if (DeviceDataV != null && DeviceDataV.GetIsConnected() && DeviceDataV.deviceTable != null)
{
FileUpload.FileRequest(DeviceDataV);
}
}
catch (Exception ex)
{
MessageLog.GetInstance.Show(ex.Message);
}
}
#endregion

#region 私有

/// <summary>
/// 增加告警
/// </summary>
@@ -221,7 +240,7 @@ namespace BPASmartClient.IoT
private void AddErrorAction(int Devid, object obj)
{
string id = Guid.NewGuid().ToString();
HttpAddAlarm(new AlarmTable
HttpAddAlarm(new AlarmTable
{
AlarmTime = GetPropertyValue(obj, "Time").ToString(),
AlarmType = GetPropertyValue(obj, "Type").ToString(),
@@ -230,8 +249,8 @@ namespace BPASmartClient.IoT
DeviceId = Devid.ToString(),
KeyID = id,
});
keyValues[GetPropertyValue(obj, "Time").ToString() + GetPropertyValue(obj, "Type").ToString() + GetPropertyValue(obj, "Text").ToString()] =id ;
MessageLog.GetInstance.AddDeviceAlarmLogShow(GetPropertyValue(obj, "Time").ToString() + GetPropertyValue(obj, "Type").ToString() + GetPropertyValue(obj, "Text").ToString(),id);
keyValues[GetPropertyValue(obj, "Time").ToString() + GetPropertyValue(obj, "Type").ToString() + GetPropertyValue(obj, "Text").ToString()] = id;
//MessageLog.GetInstance.AddDeviceAlarmLogShow(GetPropertyValue(obj, "Time").ToString() + GetPropertyValue(obj, "Type").ToString() + GetPropertyValue(obj, "Text").ToString(),id);

}

@@ -250,11 +269,11 @@ namespace BPASmartClient.IoT
AlarmType = GetPropertyValue(obj, "Type").ToString(),
AlarmMessage = GetPropertyValue(obj, "Text").ToString(),
AlarmVla = "告警",
DeviceId= Devid.ToString(),
DeviceId = Devid.ToString(),
KeyID = keyValues[message],
State="n"
State = "n"
});
MessageLog.GetInstance.DeleteDeviceAlarmLogShow(message, keyValues[message]);
//MessageLog.GetInstance.DeleteDeviceAlarmLogShow(message, keyValues[message]);

}
}
@@ -272,6 +291,38 @@ namespace BPASmartClient.IoT
if (iOTCommand.deviceName == DeviceDataV.deviceTable.devicename)
ActionManage.GetInstance.Send("IotBroadcast", iOTCommand);
}
else if (DeviceDataV.FileUpLoadReplyTopic == topic)//文件请求上传响应Topic
{
FileUploadModelResult result = Tools.JsonToObjectTools<FileUploadModelResult>(message);
if (result.code == 200)
{
string FileName = result.data?.fileName;
string uploadId = result.data?.uploadId;
FileUpload.SetUploadData(result.id,uploadId);
FileUpload.FileSend(DeviceDataV, uploadId);
MessageLog.GetInstance.Show($"请求上传【阿里云】成功,准备上传日志文件【HBL.LogDir{DateTime.Now.ToString("yyyy_M_d")}.log】");
}
else
MessageLog.GetInstance.Show($"【HBL.LogDir{DateTime.Now.ToString("yyyy_M_d")}.log】请求上传【阿里云】失败,{result.message}");

}
else if (DeviceDataV.FileUpLoadSendReplyTopic == topic)//文件上传Topic
{
FileUploadModelResult result = Tools.JsonToObjectTools<FileUploadModelResult>(message);
if (result.code == 200)
{
MessageLog.GetInstance.Show($"今日日志文件“HBL.LogDir{DateTime.Now.ToString("yyyy_M_d")}.log”更新上传【阿里云】成功");
bool complete = result.data.complete;
string uploadId = result.data?.uploadId;
}else
MessageLog.GetInstance.Show($"今日日志文件“HBL.LogDir{DateTime.Now.ToString("yyyy_M_d")}.log”更新上传【阿里云】失败,{result.message}");

}
else if (DeviceDataV.CancelFileUpLoadSendReplyTopic == topic)//取消文件上传Topic
{
FileUploadModelResult result = Tools.JsonToObjectTools<FileUploadModelResult>(message);
}
}

/// <summary>
@@ -287,8 +338,6 @@ namespace BPASmartClient.IoT
return property.First().GetValue(info, null);
}
#endregion


}

//命令实体类


+ 247
- 0
BPASmartClient.IoT/Model/CRC.cs Просмотреть файл

@@ -0,0 +1,247 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BPASmartClient.IoT.Model
{
/// <summary>
/// CRC校验
/// </summary>
public class CRC
{

#region CRC16
public static byte[] CRC16(byte[] data)
{
int len = data.Length;
if (len > 0)
{
ushort crc = 0xFFFF;

for (int i = 0; i < len; i++)
{
crc = (ushort)(crc ^ (data[i]));
for (int j = 0; j < 8; j++)
{
crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1);
}
}
byte hi = (byte)((crc & 0xFF00) >> 8); //高位置
byte lo = (byte)(crc & 0x00FF); //低位置

return new byte[] { hi, lo };
}
return new byte[] { 0, 0 };
}

public static byte[] CRC16_L(byte[] data)
{
int len = data.Length;
if (len > 0)
{
ushort crc = 0xFFFF;

for (int i = 0; i < len; i++)
{
crc = (ushort)(crc ^ (data[i]));
for (int j = 0; j < 8; j++)
{
crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1);
}
}
byte hi = (byte)((crc & 0xFF00) >> 8); //高位置
byte lo = (byte)(crc & 0x00FF); //低位置

return new byte[] { lo,hi };
}
return new byte[] { 0, 0 };
}
#endregion

#region ToCRC16
public static string ToCRC16(string content)
{
return ToCRC16(content, Encoding.UTF8);
}

public static string ToCRC16(string content, bool isReverse)
{
return ToCRC16(content, Encoding.UTF8, isReverse);
}

public static string ToCRC16(string content, Encoding encoding)
{
return ByteToString(CRC16(encoding.GetBytes(content)), true);
}

public static string ToCRC16(string content, Encoding encoding, bool isReverse)
{
return ByteToString(CRC16(encoding.GetBytes(content)), isReverse);
}

public static string ToCRC16(byte[] data)
{
return ByteToString(CRC16(data), true);
}

public static string ToCRC16(byte[] data, bool isReverse)
{
return ByteToString(CRC16(data), isReverse);
}
#endregion

#region ToModbusCRC16
public static string ToModbusCRC16(string s)
{
return ToModbusCRC16(s, true);
}

public static string ToModbusCRC16(string s, bool isReverse)
{
return ByteToString(CRC16(StringToHexByte(s)), isReverse);
}

public static string ToModbusCRC16(byte[] data)
{
return ToModbusCRC16(data, true);
}

public static string ToModbusCRC16(byte[] data, bool isReverse)
{
return ByteToString(CRC16(data), isReverse);
}
#endregion

#region ByteToString
public static string ByteToString(byte[] arr, bool isReverse)
{
try
{
byte hi = arr[0], lo = arr[1];
return Convert.ToString(isReverse ? hi + lo * 0x100 : hi * 0x100 + lo, 16).ToUpper().PadLeft(4, '0');
}
catch (Exception ex) { throw (ex); }
}

public static string ByteToString(byte[] arr)
{
try
{
return ByteToString(arr, true);
}
catch (Exception ex) { throw (ex); }
}
#endregion

#region StringToHexString
public static string StringToHexString(string str)
{
StringBuilder s = new StringBuilder();
foreach (short c in str.ToCharArray())
{
s.Append(c.ToString("X4"));
}
return s.ToString();
}
#endregion

#region StringToHexByte
private static string ConvertChinese(string str)
{
StringBuilder s = new StringBuilder();
foreach (short c in str.ToCharArray())
{
if (c <= 0 || c >= 127)
{
s.Append(c.ToString("X4"));
}
else
{
s.Append((char)c);
}
}
return s.ToString();
}

private static string FilterChinese(string str)
{
StringBuilder s = new StringBuilder();
foreach (short c in str.ToCharArray())
{
if (c > 0 && c < 127)
{
s.Append((char)c);
}
}
return s.ToString();
}

/// <summary>
/// 字符串转16进制字符数组
/// </summary>
/// <param name="hex"></param>
/// <returns></returns>
public static byte[] StringToHexByte(string str)
{
return StringToHexByte(str, false);
}

/// <summary>
/// 字符串转16进制字符数组
/// </summary>
/// <param name="str"></param>
/// <param name="isFilterChinese">是否过滤掉中文字符</param>
/// <returns></returns>
public static byte[] StringToHexByte(string str, bool isFilterChinese)
{
string hex = isFilterChinese ? FilterChinese(str) : ConvertChinese(str);

//清除所有空格
hex = hex.Replace(" ", "");
//若字符个数为奇数,补一个0
hex += hex.Length % 2 != 0 ? "0" : "";

byte[] result = new byte[hex.Length / 2];
for (int i = 0, c = result.Length; i < c; i++)
{
result[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return result;
}
#endregion

}

class CRC16Standard
{
private static int[] table = { 0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, 0xC601, 0x06C0, 0x0780, 0xC741,
0x0500, 0xC5C1, 0xC481, 0x0440, 0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40, 0x0A00, 0xCAC1, 0xCB81, 0x0B40,
0xC901, 0x09C0, 0x0880, 0xC841, 0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40, 0x1E00, 0xDEC1, 0xDF81, 0x1F40,
0xDD01, 0x1DC0, 0x1C80, 0xDC41, 0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641, 0xD201, 0x12C0, 0x1380, 0xD341,
0x1100, 0xD1C1, 0xD081, 0x1040, 0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240, 0x3600, 0xF6C1, 0xF781, 0x3740,
0xF501, 0x35C0, 0x3480, 0xF441, 0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41, 0xFA01, 0x3AC0, 0x3B80, 0xFB41,
0x3900, 0xF9C1, 0xF881, 0x3840, 0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41, 0xEE01, 0x2EC0, 0x2F80, 0xEF41,
0x2D00, 0xEDC1, 0xEC81, 0x2C40, 0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640, 0x2200, 0xE2C1, 0xE381, 0x2340,
0xE101, 0x21C0, 0x2080, 0xE041, 0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240, 0x6600, 0xA6C1, 0xA781, 0x6740,
0xA501, 0x65C0, 0x6480, 0xA441, 0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41, 0xAA01, 0x6AC0, 0x6B80, 0xAB41,
0x6900, 0xA9C1, 0xA881, 0x6840, 0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41, 0xBE01, 0x7EC0, 0x7F80, 0xBF41,
0x7D00, 0xBDC1, 0xBC81, 0x7C40, 0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640, 0x7200, 0xB2C1, 0xB381, 0x7340,
0xB101, 0x71C0, 0x7080, 0xB041, 0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241, 0x9601, 0x56C0, 0x5780, 0x9741,
0x5500, 0x95C1, 0x9481, 0x5440, 0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40, 0x5A00, 0x9AC1, 0x9B81, 0x5B40,
0x9901, 0x59C0, 0x5880, 0x9841, 0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40, 0x4E00, 0x8EC1, 0x8F81, 0x4F40,
0x8D01, 0x4DC0, 0x4C80, 0x8C41, 0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641, 0x8201, 0x42C0, 0x4380, 0x8341,
0x4100, 0x81C1, 0x8081, 0x4040, };

public static byte[] getCRCBytes(byte[] data)
{
int crc = 0x0000;
foreach (byte b in data)
{
crc = (crc >> 8) ^ table[(crc ^ b) & 0xff];
}
return new byte[] { (byte)(0xff & crc), (byte)((0xff00 & crc) >> 8) };
}
}
}

+ 66
- 12
BPASmartClient.IoT/Model/DataVReport.cs Просмотреть файл

@@ -1,6 +1,7 @@
using BPA.Message.IOT;
using BPASmartClient.Helper;
using BPASmartClient.IoT;
using BPASmartClient.IoT.Model;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -22,16 +23,20 @@ namespace BPASmartDatavDeviceClient.IoT
/// <summary>
/// 初始化IOT连接
/// </summary>
public bool Initialize(string url,string _clientId,string _deviceId,ref string message)
public bool Initialize(string url, string _clientId, string _deviceId, ref string message)
{
if(string.IsNullOrEmpty(url))return false;
if (string.IsNullOrEmpty(url)) return false;
deviceId = _deviceId;
if (!CreateLinks(url, _clientId,out deviceTable, _deviceId))
if (!CreateLinks(url, _clientId, out deviceTable, _deviceId))
{
message += $"客户端{_clientId}设备{_deviceId}阿里云上没有该设备。";
return false;
}
IOT_Subscribe(BroadcastTopic);//订阅广播主题
IOT_Subscribe(FileUpLoadReplyTopic);
IOT_Subscribe(FileUpLoadSendReplyTopic);
IOT_Subscribe(CancelFileUpLoadSendTopic);

if (!DatavDeviceClient.IsConnected) message += $"客户端:【{_clientId}】,设备名称{deviceTable.devicename}阿里云连接失败.不能上报业务信息";
return DatavDeviceClient.IsConnected;
}
@@ -113,6 +118,11 @@ namespace BPASmartDatavDeviceClient.IoT
var id = DatavDeviceClient.Publish(topic, Encoding.UTF8.GetBytes(message));
}

public void IOT_Publish(string topic, byte[] message)
{
var id = DatavDeviceClient.Publish(topic, message);
}

/// <summary>
/// 订阅主题
/// </summary>
@@ -125,8 +135,20 @@ namespace BPASmartDatavDeviceClient.IoT
}
DatavDeviceClient.Subscribe(new string[] { topic }, new byte[] { 0 });
}

public void Chkin_Up()
{
OSS_Helper ss = new OSS_Helper();

string objectName = "Project/aa.bak";
string downloadFilename = @"\\aa.bak";
//记录进度的文件路径
string checkpointDir = @"D:\checkin\";
//ss.Multipar_tUp(objectName, downloadFilename);
ss.chkin_Up(objectName, downloadFilename, checkpointDir);
}
#endregion
#region 私有函数
/// <summary>
/// 设置变量
@@ -151,18 +173,24 @@ namespace BPASmartDatavDeviceClient.IoT
HeartbeatSubTopic = "/" + ProductKey + "/" + DeviceName + "/user/HeartbeatAndState";
TargetStatusSubTopic = "/" + ProductKey + "/" + DeviceName + "/user/TargetStatus";
ScreenShowPubTopic = "/" + ProductKey + "/" + DeviceName + "/user/ScreenShow";
FileUpLoadTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/init";
FileUpLoadReplyTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/init_reply";
FileUpLoadSendTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/send";
FileUpLoadSendReplyTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/send_reply";
CancelFileUpLoadSendTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/cancel";
CancelFileUpLoadSendReplyTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/cancel_reply";
}

/// <summary>
/// 创建连接
/// </summary>
private bool CreateLinks(string url, string clientId, out DeviceTable device ,string deviceId = "")
private bool CreateLinks(string url, string clientId, out DeviceTable device, string deviceId = "")
{
try
{
string json = string.Empty;
if (string.IsNullOrEmpty(deviceId))
json = HttpRequestHelper.HttpGetRequest($"{url}/api/Device/Query?clientId={clientId}",1000);
json = HttpRequestHelper.HttpGetRequest($"{url}/api/Device/Query?clientId={clientId}", 1000);
else
json = HttpRequestHelper.HttpGetRequest($"{url}/api/Device/Query?clientId={clientId}&deviceId={deviceId}");
JsonMsg<List<DeviceTable>> jsonMsg = Tools.JsonToObjectTools<JsonMsg<List<DeviceTable>>>(json);
@@ -224,7 +252,7 @@ namespace BPASmartDatavDeviceClient.IoT
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Client_ConnectionClosed(object sender, EventArgs e)
private void Client_ConnectionClosed(object sender, EventArgs e)
{
// 尝试重连
_TryContinueConnect();
@@ -235,7 +263,7 @@ namespace BPASmartDatavDeviceClient.IoT
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
private void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
string topic = e.Topic;
string message = Encoding.UTF8.GetString(e.Message);
@@ -248,7 +276,7 @@ namespace BPASmartDatavDeviceClient.IoT
/// <summary>
/// 自动重连主体
/// </summary>
private void _TryContinueConnect()
private void _TryContinueConnect()
{
Thread retryThread = new Thread(new ThreadStart(delegate
{
@@ -265,7 +293,7 @@ namespace BPASmartDatavDeviceClient.IoT
DatavDeviceClient.ConnectionClosed += Client_ConnectionClosed;
if (DatavDeviceClient.IsConnected)
{
SubTopicList?.ForEach(par =>{DatavDeviceClient.Subscribe(new string[] { par }, new byte[] { 0 }); });
SubTopicList?.ForEach(par => { DatavDeviceClient.Subscribe(new string[] { par }, new byte[] { 0 }); });
}
Thread.Sleep(3000);
continue;
@@ -312,7 +340,7 @@ namespace BPASmartDatavDeviceClient.IoT
/// <summary>
/// 设备消息数据回调
/// </summary>
public Action<string,string, string> DataVMessageAction { get; set; }
public Action<string, string, string> DataVMessageAction { get; set; }
/// <summary>
/// 重连事件
/// </summary>
@@ -324,7 +352,7 @@ namespace BPASmartDatavDeviceClient.IoT
/// <summary>
/// 当前设备
/// </summary>
public DeviceTable deviceTable =new DeviceTable();
public DeviceTable deviceTable = new DeviceTable();
#endregion

#region 发布或订阅主题或URL地址
@@ -369,6 +397,30 @@ namespace BPASmartDatavDeviceClient.IoT
/// </summary>
public string BroadcastTopic = "/broadcast/" + "grgpECHSL7q" + "/" + DeviceName + "_SetDevice";
/// <summary>
/// 文件上传请求Topic
/// </summary>
public string FileUpLoadTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/init";
/// <summary>
/// 文件上传请求响应Topic
/// </summary>
public string FileUpLoadReplyTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/init_reply";
/// <summary>
/// 文件发送Topic
/// </summary>
public string FileUpLoadSendTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/send";
/// <summary>
/// 文件发送响应Topic
/// </summary>
public string FileUpLoadSendReplyTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/send_reply";
/// <summary>
/// 取消文件发送Topic
/// </summary>
public string CancelFileUpLoadSendTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/cancel";
/// <summary>
/// 取消文件发送响应Topic
/// </summary>
public string CancelFileUpLoadSendReplyTopic = $"/sys/{ProductKey}/{DeviceName}/thing/file/upload/mqtt/cancel_reply";
/// <summary>
/// 订阅主题集合
/// </summary>
public static List<string> SubTopicList = new List<string>();
@@ -405,4 +457,6 @@ namespace BPASmartDatavDeviceClient.IoT
return signBuilder.ToString();
}
}


}

+ 373
- 0
BPASmartClient.IoT/Model/FileUpload.cs Просмотреть файл

@@ -0,0 +1,373 @@
using BPASmartClient.Helper;
using BPASmartDatavDeviceClient.IoT;
using DataVAPI.Tool.IOT;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BPASmartClient.IoT.Model
{
/// <summary>
/// 阿里云文件上传
/// </summary>
public class FileUpload
{
public static Dictionary<string, string> UploadData = new Dictionary<string, string>();
public static string FileName = $"HBL.LogDir{DateTime.Now.ToString("yyyy_M_d")}";
public static string path = $"{System.AppDomain.CurrentDomain.BaseDirectory}LogDir\\{FileName}.log";
public static void SetUploadData(string key, string value)
{
UploadData[key] = value;
}
public static string GetUploadData(string key)
{
return UploadData.ContainsKey(key) ? UploadData[key] : string.Empty;
}
public static long length = 0;
public static byte[] FileBlock;
/// <summary>
/// 文件请求上传
/// </summary>
public static void FileRequest(DataVReport dataV)
{
FileBlock = FileContent(path);
length = FileBlock.Count();
FileUploadModel fileUpload = new FileUploadModel();
fileUpload.@params.fileName = FileName;
fileUpload.@params.fileSize = length;
fileUpload.@params.conflictStrategy = "overwrite";//覆盖模式
//fileUpload.@params.ficMode = "crc64";
//fileUpload.@params.ficValue = CRC.ToCRC16(FileBlock);
fileUpload.@params.initUid = $"ab{RandomHelper.GenerateRandomCode()}";

//上传到阿里云物联网平台的OSS存储空间中
fileUpload.@params.extraParams.ossOwnerType = "iot-platform";

//表示上传到设备所属用户自己的OSS存储空间中
//{ossbucket}/aliyun-iot-device-file/${instanceId}/${productKey}/${serviceId}/${deviceName}/${fileName}
//fileUpload.@params.extraParams.ossOwnerType = "device-user";
//fileUpload.@params.extraParams.serviceId = "black";
//fileUpload.@params.extraParams.fileTag = new Dictionary<string, string> { {"Time", DateTime.Now.ToString("yyyy_M_d") },{"Name", "HBL.LogDir" } };

dataV.IOT_Publish(dataV.FileUpLoadTopic, Tools.JsonConvertTools(fileUpload));
}

/// <summary>
/// 文件上传
/// </summary>
public static void FileSend(DataVReport dataV, string uploadId)
{
FileSendModel fileSend = new FileSendModel();
fileSend.@params.uploadId = uploadId;
fileSend.@params.offset = 0;
fileSend.@params.bSize = length;
//结构如下图
//Header.length(高 低) + Header(字节数组UTF-8) + 文件分片的字节数组 + "分片校验值CrC16 低 高"
byte[] Header = Encoding.UTF8.GetBytes(Tools.JsonConvertTools(fileSend));
byte HeaderLen_L = (byte)(Header.Length);
byte HeaderLen_H = (byte)(Header.Length >> 8);
byte[] CRC16 = CRC16Standard.getCRCBytes(FileBlock);//CRC.CRC16(FileBlock);
List<byte> message = new List<byte>() { HeaderLen_H, HeaderLen_L };
message.AddRange(Header);
message.AddRange(FileBlock);
message.AddRange(CRC16);
dataV.IOT_Publish(dataV.FileUpLoadSendTopic, message.ToArray());
}

/// <summary>
/// 取消文件上传
/// </summary>
public static void FileCancelSend(DataVReport dataV, string uploadId)
{
CancelSend cancel = new CancelSend(uploadId);
dataV.IOT_Publish(dataV.CancelFileUpLoadSendTopic, Tools.JsonConvertTools(cancel));
}


/// <summary>
/// 读取文件
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
private static byte[] FileContent(string fileName)
{
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
try
{
byte[] buffur = new byte[fs.Length];
fs.Read(buffur, 0, (int)fs.Length);
return buffur;
}
catch (Exception ex)
{
return new byte[0];
}
}
}
/// <summary>
/// 读取文件字节
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static byte[] ReadFile(string path)
{
//创建d:\file.txt的FileStream对象
FileStream fstream = new FileStream($@"{path}", FileMode.OpenOrCreate);
byte[] bData = new byte[fstream.Length];
//设置流当前位置为文件开始位置
fstream.Seek(0, SeekOrigin.Begin);

//将文件的内容存到字节数组中(缓存)
fstream.Read(bData, 0, bData.Length);
string result = Encoding.UTF8.GetString(bData);
Console.WriteLine(result);
if (fstream != null)
{
//清除此流的缓冲区,使得所有缓冲的数据都写入到文件中
fstream.Flush();
fstream.Close();
}
return bData;
}
}

#region 请求上传文件
/// <summary>
/// 请求上传文件
/// </summary>
public class FileUploadModel
{
/// <summary>
/// 消息ID号
/// 0~4294967295
/// </summary>
public string id { get; set; }
/// <summary>
/// 请求业务参数
/// </summary>
public BusinessParameters @params { get; set; }

public FileUploadModel()
{
id = RandomHelper.GenerateRandomCode();
@params = new BusinessParameters();
}
}

/// <summary>
/// 业务参数
/// </summary>
public class BusinessParameters
{
/// <summary>
/// 设备上传文件的名称
/// </summary>
public string fileName { get; set; }
/// <summary>
/// 上传文件大小,单位字节。单个文件大小不超过16 MB。
/// 取值为-1时,表示文件大小未知。文件上传完成时,需在上传文件分片的消息中,指定参数isComplete
/// </summary>
public long fileSize { get; set; }
/// <summary>
/// 物联网平台对设备上传同名文件的处理策略,默认为overwrite
/// overwrite:覆盖模式 append:文件追加模式 reject:拒绝模式
/// </summary>
public string conflictStrategy { get; set; } = "overwrite";
/// <summary>
/// 文件的完整性校验模式,目前可取值crc64
/// 若不传入,在文件上传完成后不校验文件完整性
/// </summary>
public string ficMode { get; set; }
/// <summary>
/// 文件的完整性校验值,是16位的Hex格式编码的字符串
/// </summary>
public string ficValue { get; set; }
/// <summary>
/// 自定义的设备请求上传文件的任务唯一ID,同一上传任务请求必须对应相同的唯一ID
/// 不传入:物联网平台的云端识别当前请求为新的文件上传请求
/// </summary>
public string initUid { get; set; }
/// <summary>
/// 设备上传文件至OSS存储空间的配置参数
/// </summary>
public ConfigureParameters extraParams { get; set; } = new ConfigureParameters();
}
/// <summary>
/// 配置参数
/// </summary>
public class ConfigureParameters
{
/// <summary>
/// 设备上传文件的目标OSS所有者类型
/// iot-platform:表示上传到阿里云物联网平台的OSS存储空间中
/// device-user:表示上传到设备所属用户自己的OSS存储空间中
/// </summary>
public string ossOwnerType { get; set; } = "device-user";
/// <summary>
/// 文件上传相关的业务ID
/// </summary>
public string serviceId { get; set; }
/// <summary>
/// 标签
/// </summary>
public Dictionary<string, string> fileTag { get; set; }
public ConfigureParameters()
{

}
}
#endregion

#region 请求上传文件响应
/// <summary>
/// 请求响应
/// </summary>
public class FileUploadModelResult
{
/// <summary>
/// 消息ID号
/// 0~4294967295
/// </summary>
public string id { get; set; }
/// <summary>
/// 结果码。返回200表示成功
/// </summary>
public int code { get; set; }
/// <summary>
/// 请求失败时,返回的错误信息
/// </summary>
public string message { get; set; }
/// <summary>
/// 返回设备端的数据。
/// </summary>
public ResultData data { get; set; }

}
/// <summary>
/// 请求响应数据
/// </summary>
public class ResultData
{
/// <summary>
/// 设备上传文件的名称
/// </summary>
public string fileName { get; set; }
/// <summary>
/// 本次上传文件任务的标识ID。后续上传文件分片时,需要传递该文件标识ID。
/// </summary>
public string uploadId { get; set; }
/// <summary>
/// 仅当请求参数conflictStrategy为append,且物联网平台云端存在未完成上传的文件时,返回的已上传文件的大小,单位为字节。
/// </summary>
public long offset { get; set; }
/// <summary>
/// 当前上传文件分片的大小
/// </summary>
public long bSize { get; set; }
/// <summary>
/// 当上传了最后一个分片数据后,文件上传完成
/// </summary>
public bool complete { get; set; }
/// <summary>
/// 文件的完整性校验模式。若请求上传文件时传入了该参数,对应的值仅支持为crc64
/// </summary>
public string ficMode { get; set; }
/// <summary>
/// 文件上传完成,返回设备请求上传文件时的
/// </summary>
public string ficValueClient { get; set; }
/// <summary>
/// 文件上传完成,返回物联网平台云端计算的文件完整性校验值。该值与ficValueClient值相同,表示文件上传完整。
/// </summary>
public string ficValueServer { get; set; }
}
#endregion

#region 上传文件
public class FileSendModel
{
/// <summary>
/// 消息ID号
/// 0~4294967295
/// </summary>
public string id { get; set; }
/// <summary>
/// 上传业务参数
/// </summary>
public SendBusinessParameters @params { get; set; } = new SendBusinessParameters();
public FileSendModel()
{
id = RandomHelper.GenerateRandomCode();
}
}
/// <summary>
/// 上传业务参数
/// </summary>
public class SendBusinessParameters
{
/// <summary>
/// 设备请求上传文件时返回的文件上传任务标识ID。
/// </summary>
public string uploadId { get; set; }
/// <summary>
/// 已上传文件分片的总大小,单位为字节。
/// </summary>
public long offset { get; set; }
/// <summary>
/// 当前上传文件分片的大小,单位为字节
/// </summary>
public long bSize { get; set; }
/// <summary>
/// 仅当设备请求上传文件中fileSize为-1,即文件大小未知时,该参数有效,表示当前分片是否是文件的最后一个分片
/// </summary>
public bool isComplete { get; set; } = true;
}
#endregion

#region 取消文件上传
/// <summary>
/// 取消上传
/// </summary>
public class CancelSend
{
/// <summary>
/// 消息ID号
/// 0~4294967295
/// </summary>
public string id { get; set; }
/// <summary>
/// 请求业务参数
/// </summary>
public object @params { get; set; }

public CancelSend(string uploadId)
{
id = RandomHelper.GenerateRandomCode();
@params = new { uploadId = uploadId };
}
}
#endregion

public class RandomHelper
{
/// <summary>
///生成制定位数的随机码(数字)
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
public static string GenerateRandomCode(int length = 10)
{
var result = new StringBuilder();
for (var i = 0; i < length; i++)
{
var r = new Random(Guid.NewGuid().GetHashCode());
result.Append(r.Next(0, 10));
}
return result.ToString();
}
}
}

+ 95
- 95
BPASmartClient.IoT/Model/IOT/IOTDevModel.cs Просмотреть файл

@@ -67,29 +67,29 @@ namespace DataVAPI.Tool.IOT
public class IOTDevSXModel
{
/// <summary>
/// 硬件状态
/// 设备一状态
/// </summary>
public string HardwareStatus { get; set; }
public string Device1 { get; set; }
/// <summary>
/// 扩展属性
/// 设备二状态
/// </summary>
public string KZSX { get; set; }
public string Device2 { get; set; }
/// <summary>
/// 基本属性
/// 设备三状态
/// </summary>
public string JBSX { get; set; }
public string Device3 { get; set; }
/// <summary>
/// 节点状态
/// </summary>
public string NodeStatus { get; set; }
/// <summary>
/// 运行日志
/// </summary>
public string SZXX { get; set; }
/// <summary>
/// 运行告警
/// </summary>
public string GJXX { get; set; }
///// <summary>
///// 运行日志
///// </summary>
//public string SZXX { get; set; }
///// <summary>
///// 运行告警
///// </summary>
//public string GJXX { get; set; }
/// <summary>
/// Model
/// </summary>
@@ -114,87 +114,87 @@ namespace DataVAPI.Tool.IOT
return string.Empty;
}
}
/// <summary>
/// 设置基本属性
/// </summary>
/// <param name="devSX"></param>
/// <returns></returns>
public void SetJBSX(DevSX devSX)
{
try
{
JBSX = Tools.JsonConvertTools(devSX);
}
catch (Exception ex)
{
JBSX = string.Empty;
}
}
/// <summary>
/// 设置基本属性状态
/// </summary>
/// <param name="devSX"></param>
/// <returns></returns>
public void SetJBSXStatus(DevSXBase sXBase, bool Status)
{
try
{
if (sXBase == null) return;
DevSX dev = Tools.JsonToObjectTools<DevSX>(JBSX);
dev.data?.ForEach(x =>
{
if (x.SXMC == sXBase.SXMC && x.SXLX == sXBase.SXLX)
{
x.SXStatus = Status;
}
});
JBSX = Tools.JsonConvertTools(dev);
}
catch (Exception ex)
{
JBSX = string.Empty;
}
}
/// <summary>
/// 设置扩展属性
/// </summary>
/// <param name="devSX"></param>
public void SetKZSX(DevSX devSX)
{
try
{
KZSX = Tools.JsonConvertTools(devSX);
}
catch (Exception ex)
{
KZSX = string.Empty;
}
}
/// <summary>
/// 设置扩展属性状态
/// </summary>
/// <param name="devSX"></param>
/// <returns></returns>
public void SetKZSXStatus(DevSXBase sXBase, bool Status)
{
try
{
if (sXBase == null) return;
DevSX dev = Tools.JsonToObjectTools<DevSX>(KZSX);
dev.data?.ForEach(x =>
{
if (x.SXMC == sXBase.SXMC && x.SXLX == sXBase.SXLX)
{
x.SXStatus = Status;
}
});
KZSX = Tools.JsonConvertTools(dev);
}
catch (Exception ex)
{
KZSX = string.Empty;
}
}
///// <summary>
///// 设置基本属性
///// </summary>
///// <param name="devSX"></param>
///// <returns></returns>
//public void SetJBSX(DevSX devSX)
//{
// try
// {
// JBSX = Tools.JsonConvertTools(devSX);
// }
// catch (Exception ex)
// {
// JBSX = string.Empty;
// }
//}
///// <summary>
///// 设置基本属性状态
///// </summary>
///// <param name="devSX"></param>
///// <returns></returns>
//public void SetJBSXStatus(DevSXBase sXBase, bool Status)
//{
// try
// {
// if (sXBase == null) return;
// DevSX dev = Tools.JsonToObjectTools<DevSX>(JBSX);
// dev.data?.ForEach(x =>
// {
// if (x.SXMC == sXBase.SXMC && x.SXLX == sXBase.SXLX)
// {
// x.SXStatus = Status;
// }
// });
// JBSX = Tools.JsonConvertTools(dev);
// }
// catch (Exception ex)
// {
// JBSX = string.Empty;
// }
//}
///// <summary>
///// 设置扩展属性
///// </summary>
///// <param name="devSX"></param>
//public void SetKZSX(DevSX devSX)
//{
// try
// {
// KZSX = Tools.JsonConvertTools(devSX);
// }
// catch (Exception ex)
// {
// KZSX = string.Empty;
// }
//}
///// <summary>
///// 设置扩展属性状态
///// </summary>
///// <param name="devSX"></param>
///// <returns></returns>
//public void SetKZSXStatus(DevSXBase sXBase, bool Status)
//{
// try
// {
// if (sXBase == null) return;
// DevSX dev = Tools.JsonToObjectTools<DevSX>(KZSX);
// dev.data?.ForEach(x =>
// {
// if (x.SXMC == sXBase.SXMC && x.SXLX == sXBase.SXLX)
// {
// x.SXStatus = Status;
// }
// });
// KZSX = Tools.JsonConvertTools(dev);
// }
// catch (Exception ex)
// {
// KZSX = string.Empty;
// }
//}
}
/// <summary>
/// 告警消息


+ 26
- 0
BPASmartClient.IoT/Model/IOT/IOTDevServer.cs Просмотреть файл

@@ -5,6 +5,7 @@ using BPASmartClient.IoT;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
@@ -461,6 +462,31 @@ namespace DataVAPI.Tool.IOT
}
return "192.168.1.124";
}

/// <summary>
/// Http下载文件
/// </summary>
public static string HttpDownloadFile(string url, string path)
{
// 设置参数
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream responseStream = response.GetResponseStream();
//创建本地文件写入流
Stream stream = new FileStream(path, FileMode.Create);
byte[] bArr = new byte[1024];
int size = responseStream.Read(bArr, 0, (int)bArr.Length);
while (size > 0)
{
stream.Write(bArr, 0, size);
size = responseStream.Read(bArr, 0, (int)bArr.Length);
}
stream.Close();
responseStream.Close();
return path;
}
}




+ 269
- 0
BPASmartClient.IoT/Model/OSS_Helper.cs Просмотреть файл

@@ -0,0 +1,269 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Aliyun.OSS;
using Aliyun.OSS.Common;

namespace BPASmartClient.IoT.Model
{
public class OSS_Helper
{
const string accessKeyId = "xxx";
const string accessKeySecret = "xxx";
const string endpoint = "http://oss-cn-shanghai.aliyuncs.com";
const string bucketName = "xxx";
OssClient client = null;

public OSS_Helper()
{
// 由用户指定的OSS访问地址、阿里云颁发的AccessKeyId/AccessKeySecret构造一个新的OssClient实例。
client = new OssClient(endpoint, accessKeyId, accessKeySecret);
}

/*简单上传:文件最大不能超过5GB。
追加上传:文件最大不能超过5GB。
断点续传上传:支持并发、断点续传、自定义分片大小。大文件上传推荐使用断点续传。最大不能超过48.8TB。
分片上传:当文件较大时,可以使用分片上传,最大不能超过48.8TB。*/
/// <summary>
///
/// </summary>
/// <param name="objectName"></param>
/// <param name="localFilename"></param>
public void Simple_Up(string objectName, string localFilename)
{

//var objectName = "Project/222.jpg";
//var localFilename = @"C:\tiger.jpg";
// 创建OssClient实例。
try
{
// 上传文件。
client.PutObject(bucketName, objectName, localFilename);
Console.WriteLine("Put object succeeded");
}
catch (Exception ex)
{
Console.WriteLine("Put object failed, {0}", ex.Message);
}
}
/// <summary>
/// 分片上传
/// </summary>
/// <param name="objectName"></param>
/// <param name="localFilename"></param>
public void Multipar_tUp(string objectName, string localFilename)
{
var uploadId = "";
try
{
// 定义上传文件的名字和所属存储空间。在InitiateMultipartUploadRequest中,可以设置ObjectMeta,但不必指定其中的ContentLength。
var request = new InitiateMultipartUploadRequest(bucketName, objectName);
var result = client.InitiateMultipartUpload(request);
uploadId = result.UploadId;
// 打印UploadId。
Console.WriteLine("Init multi part upload succeeded");
Console.WriteLine("Upload Id:{0}", result.UploadId);
}
catch (Exception ex)
{
throw ex;
}
// 计算分片总数。
var partSize = 1024 * 1024;
var fi = new FileInfo(localFilename);
var fileSize = fi.Length;
var partCount = fileSize / partSize;
if (fileSize % partSize != 0)
{
partCount++;
}
// 开始分片上传。partETags是保存partETag的列表,OSS收到用户提交的分片列表后,会逐一验证每个分片数据的有效性。 当所有的数据分片通过验证后,OSS会将这些分片组合成一个完整的文件。
var partETags = new List<PartETag>();
try
{
using (var fs = File.Open(localFilename, FileMode.Open))
{
for (var i = 0; i < partCount; i++)
{
var skipBytes = (long)partSize * i;
// 定位到本次上传起始位置。
fs.Seek(skipBytes, 0);
// 计算本次上传的片大小,最后一片为剩余的数据大小。
var size = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes);
var request = new UploadPartRequest(bucketName, objectName, uploadId)
{
InputStream = fs,
PartSize = size,
PartNumber = i + 1
};
// 调用UploadPart接口执行上传功能,返回结果中包含了这个数据片的ETag值。
var result = client.UploadPart(request);
partETags.Add(result.PartETag);
Console.WriteLine("finish {0}/{1}", partETags.Count, partCount);
}
Console.WriteLine("Put multi part upload succeeded");
}
}
catch (Exception ex)
{
throw ex;
}
// 列举已上传的分片。
try
{
var listPartsRequest = new ListPartsRequest(bucketName, objectName, uploadId);
var listPartsResult = client.ListParts(listPartsRequest);
Console.WriteLine("List parts succeeded");
// 遍历所有分片。
var parts = listPartsResult.Parts;
foreach (var part in parts)
{
Console.WriteLine("partNumber: {0}, ETag: {1}, Size: {2}", part.PartNumber, part.ETag, part.Size);
}
}
catch (Exception ex)
{
throw ex;
}
// 完成分片上传。
try
{
var completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucketName, objectName, uploadId);
foreach (var partETag in partETags)
{
completeMultipartUploadRequest.PartETags.Add(partETag);
}
var result = client.CompleteMultipartUpload(completeMultipartUploadRequest);
Console.WriteLine("complete multi part succeeded");
}
catch (Exception ex)
{
throw ex;
}

}
/// <summary>
/// 上传
/// </summary>
/// <param name="objectName"></param>
/// <param name="localFilename"></param>
/// <param name="checkpointDir"></param>
public void chkin_Up(string objectName, string localFilename, string checkpointDir)
{
try
{
// 通过UploadFileRequest设置多个参数。
UploadObjectRequest request = new UploadObjectRequest(bucketName, objectName, localFilename)
{
// 指定上传的分片大小。
PartSize = 1024 * 1024,
// 指定并发线程数。
ParallelThreadCount = 10,
// checkpointDir保存断点续传的中间状态,用于失败后继续上传。如果checkpointDir为null,断点续传功能不会生效,每次失败后都会重新上传。
CheckpointDir = checkpointDir,
};
// 断点续传上传。
client.ResumableUploadObject(request);
Console.WriteLine("Resumable upload object:{0} succeeded", objectName);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}

}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="objectName"></param>
/// <param name="downloadFilename"></param>
public void Stream_Down(string objectName, string downloadFilename)
{
// objectName 表示您在下载文件时需要指定的文件名称,如abc/efg/123.jpg。
//var objectName = "Project/cc.jpg";
//var downloadFilename = @"D:\GG.jpg";
// 创建OssClient实例。
//var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
// 下载文件到流。OssObject 包含了文件的各种信息,如文件所在的存储空间、文件名、元信息以及一个输入流。
var obj = client.GetObject(bucketName, objectName);
using (var requestStream = obj.Content)
{
byte[] buf = new byte[1024];
var fs = File.Open(downloadFilename, FileMode.OpenOrCreate);
var len = 0;
// 通过输入流将文件的内容读取到文件或者内存中。
while ((len = requestStream.Read(buf, 0, 1024)) != 0)
{
fs.Write(buf, 0, len);
}
fs.Close();
}
Console.WriteLine("Get object succeeded");
}
catch (Exception ex)
{
Console.WriteLine("Get object failed. {0}", ex.Message);
}
}

public void DownPBar()
{

}

public static void GetObjectProgress()
{
var endpoint = "<yourEndpoint>";
var accessKeyId = "<yourAccessKeyId>";
var accessKeySecret = "<yourAccessKeySecret>";
var bucketName = "<yourBucketName>";
var objectName = "<yourObjectName>";
// 创建OssClient实例。
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
var getObjectRequest = new GetObjectRequest(bucketName, objectName);
getObjectRequest.StreamTransferProgress += streamProgressCallback;
// 下载文件。
var ossObject = client.GetObject(getObjectRequest);
using (var stream = ossObject.Content)
{
var buffer = new byte[1024 * 1024];
var bytesRead = 0;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
// 处理读取的数据(此处代码省略)。
}
}
Console.WriteLine("Get object:{0} succeeded", objectName);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}
}

private static void streamProgressCallback(object sender, StreamTransferProgressArgs args)
{
System.Console.WriteLine("ProgressCallback - Progress: {0}%, TotalBytes:{1}, TransferredBytes:{2} ",
args.TransferredBytes * 100 / args.TotalBytes, args.TotalBytes, args.TransferredBytes);
}

}
}

+ 0
- 1
BPASmartClient.KLMCoffee/BPASmartClient.KLMCoffee.csproj Просмотреть файл

@@ -5,7 +5,6 @@
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\BPASmartClient.Model\BPASmartClient.Model.csproj" />
<ProjectReference Include="..\BPASmartClient.Peripheral\BPASmartClient.Peripheral.csproj" />
<ProjectReference Include="..\BPASmartClient.SerialPort\BPASmartClient.SerialPort.csproj" />
</ItemGroup>


+ 0
- 1
BPASmartClient.Lebai/BPASmartClient.Lebai.csproj Просмотреть файл

@@ -11,7 +11,6 @@
<ProjectReference Include="..\BPASmartClient.Helper\BPASmartClient.Helper.csproj" />
<ProjectReference Include="..\BPASmartClient.LebaiRobot\BPASmartClient.LebaiRobot.csproj" />
<ProjectReference Include="..\BPASmartClient.Message\BPASmartClient.Message.csproj" />
<ProjectReference Include="..\BPASmartClient.Model\BPASmartClient.Model.csproj" />
<ProjectReference Include="..\BPASmartClient.Peripheral\BPASmartClient.Peripheral.csproj" />
<ProjectReference Include="..\Lebai.SDK\Lebai.SDK.csproj" />
</ItemGroup>


+ 0
- 1
BPASmartClient.MORKSM.BK.PLC/BPASmartClient.PLC.csproj Просмотреть файл

@@ -11,7 +11,6 @@
<ProjectReference Include="..\BPASmartClient.Helper\BPASmartClient.Helper.csproj" />
<ProjectReference Include="..\BPASmartClient.Message\BPASmartClient.Message.csproj" />
<ProjectReference Include="..\BPASmartClient.Modbus\BPASmartClient.Modbus.csproj" />
<ProjectReference Include="..\BPASmartClient.Model\BPASmartClient.Model.csproj" />
<ProjectReference Include="..\BPASmartClient.Peripheral\BPASmartClient.Peripheral.csproj" />
</ItemGroup>



+ 74
- 42
BPASmartClient.MORKSM.BK.PLC/PLCMachine.cs Просмотреть файл

@@ -12,17 +12,17 @@ namespace BPASmartClient.PLC
public class PLCMachine : BasePeripheral
{
ModbusTcp modbusTcp = new ModbusTcp();
public string IpAddress { get; set; }
public int Port { get; set; }
public string PLCReadAddress { get; set; }
//public string IpAddress { get; set; }
//public int Port { get; set; }
//public string PLCReadAddress { get; set; }

private List<PLCReadParameter> plcReadParameters;
//private List<PLCReadParameter> plcReadParameters;

public override void Init()
{
plcReadParameters = PLCReadParameter.DeSerialize(PLCReadAddress);
//plcReadParameters = PLCReadParameter.DeSerialize(PLCReadAddress);

Task.Run(new Action(() => { modbusTcp.ModbusTcpConnect(IpAddress, Port); })); //PLC 设备连接
Task.Run(new Action(() => { modbusTcp.ModbusTcpConnect(communicationPar.IPAddress, communicationPar.IPPort); })); //PLC 设备连接

ThreadManage.GetInstance().StartLong(new Action(() =>
{
@@ -31,59 +31,91 @@ namespace BPASmartClient.PLC
while (IsConnected)
{
IsWork = true;
foreach (var par in plcReadParameters)
foreach (var par in variables)
{
ushort address = (ushort)modbusTcp.GetAddress(par?.Address);
object readData = new object();
switch (par.CmdType)
if (par?.Address.Length > 0)
{
case CommandType.Coils:
modbusTcp.Readbool(address, par.Length, new Action<bool[]>((s) => { readData = s; }));
break;
case CommandType.HoldingRegisters:
readData = modbusTcp.Read(address, CommandType.HoldingRegisters, par.Length);
break;
var res = modbusTcp.READD(par.Address, (ushort)par.ReadLeng);
if (status.ContainsKey(par.Address))
{
status[par.Address] = res;
}
else
{
status.TryAdd(par.Address, res);
}
}
status[par.Address] = readData;

//ushort address = (ushort)modbusTcp.GetAddress(par?.Address);
//object readData = new object();
//switch (par.CmdType)
//{
// case CommandType.Coils:
// modbusTcp.Readbool(address, par.Length, new Action<bool[]>((s) => { readData = s; }));
// break;
// case CommandType.HoldingRegisters:
// readData = modbusTcp.Read(address, CommandType.HoldingRegisters, par.Length);
// break;
//}
//status[par.Address] = readData;
}


//foreach (var par in plcReadParameters)
//{
// ushort address = (ushort)modbusTcp.GetAddress(par?.Address);
// object readData = new object();
// switch (par.CmdType)
// {
// case CommandType.Coils:
// modbusTcp.Readbool(address, par.Length, new Action<bool[]>((s) => { readData = s; }));
// break;
// case CommandType.HoldingRegisters:
// readData = modbusTcp.Read(address, CommandType.HoldingRegisters, par.Length);
// break;
// }
// status[par.Address] = readData;
//}

Thread.Sleep(500);
}
Thread.Sleep(1000);
}), $"设备[{DeviceId}]PLC读取线程", true);

//读取数据
EventBus.EventBus.GetInstance().Subscribe<ReadModel>(DeviceId, delegate (IEvent @event, EventCallBackHandle callBack)
{
if (@event == null) return;
var par = @event as ReadModel;
ushort address = (ushort)modbusTcp.GetAddress(par?.Address);
object readData = new object();
if (par.Address.ToUpper().Contains("M"))
{
modbusTcp.Readbool(address, par.Length, new Action<bool[]>((s) => { readData = s; }));
}
else if (par.Address.ToUpper().Contains("VW"))
{
readData = modbusTcp.Read(address, CommandType.HoldingRegisters, par.Length);
}
callBack?.Invoke(readData);
});
// EventBus.EventBus.GetInstance().Subscribe<ReadModel>(DeviceId, delegate (IEvent @event, EventCallBackHandle callBack)
//{
// if (@event == null) return;
// var par = @event as ReadModel;
// ushort address = (ushort)modbusTcp.GetAddress(par?.Address);
// object readData = new object();
// if (par.Address.ToUpper().Contains("M"))
// {
// modbusTcp.Readbool(address, par.Length, new Action<bool[]>((s) => { readData = s; }));
// }
// else if (par.Address.ToUpper().Contains("VW"))
// {
// readData = modbusTcp.Read(address, CommandType.HoldingRegisters, par.Length);
// }
// callBack?.Invoke(readData);
//});

//写入数据
EventBus.EventBus.GetInstance().Subscribe<WriteModel>(DeviceId, delegate (IEvent @event, EventCallBackHandle callBack)
{
if (@event == null) return;
var par = @event as WriteModel;
ushort address = (ushort)modbusTcp.GetAddress(par?.Address);
if (par.Address.ToUpper().Contains("M"))
{
modbusTcp.Write(address, CommandType.Coils, par.Value);
}
else if (par.Address.ToUpper().Contains("VW"))
{
modbusTcp.Write(address, CommandType.HoldingRegisters, par.Value);
}

modbusTcp.WRITEE(par?.Address, par?.Value);
//ushort address = (ushort)modbusTcp.GetAddress(par?.Address);
//if (par.Address.ToUpper().Contains("M"))
//{
// modbusTcp.Write(address, CommandType.Coils, par.Value);
//}
//else if (par.Address.ToUpper().Contains("VW"))
//{
// modbusTcp.Write(address, CommandType.HoldingRegisters, par.Value);
//}
});
}



+ 0
- 4
BPASmartClient.Message/BPASmartClient.Message.csproj Просмотреть файл

@@ -4,8 +4,4 @@
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\BPASmartClient.Peripheral\BPASmartClient.Peripheral.csproj" />
</ItemGroup>

</Project>

+ 22
- 25
BPASmartClient.Message/MessageLog.cs Просмотреть файл

@@ -1,4 +1,4 @@
using BPASmartClient.Peripheral;
//using BPASmartClient.Peripheral;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -84,10 +84,7 @@ namespace BPASmartClient.Message
else
DPLogInfo[id] = $"{DateTime.Now.ToString("HH:mm:ss")}:{info} \n\r {DPLogInfo[id]}";
Debug.WriteLine($"{DateTime.Now.ToString("HH:mm:ss")}:{info}");
if (DeviceProcessLogNotify != null) DeviceProcessLogNotify(id, info);
//Debug.WriteLine($"{DateTime.Now.ToString("HH:mm:ss")}:{info}");
// //ExLogInfo = $"{DateTime.Now.ToString("HH:mm:ss")}:{info} \n\r {ExLogInfo}";
// if (DeviceProcessLogNotify != null) DeviceProcessLogNotify(id,info);
DeviceProcessLogNotify?.Invoke(id, info);
}

#endregion
@@ -138,26 +135,26 @@ namespace BPASmartClient.Message
public object ReturnDeviceID()
{
object DeviceId = null;
StackTrace trace = new StackTrace();
for (int i = 1; i < 10; i++)
{
Type type = trace.GetFrame(i).GetMethod().ReflectedType;
try
{
object obj = Activator.CreateInstance(type);
if (obj is IPeripheral)
{
IPeripheral peripheral = obj as IPeripheral;
DeviceId = type?.GetProperty("DeviceId")?.GetValue(peripheral, null);
}
if (DeviceId != null) break;
}
catch (Exception ex)
{
}
}
//StackTrace trace = new StackTrace();
//for (int i = 1; i < 10; i++)
//{
// Type type = trace.GetFrame(i).GetMethod().ReflectedType;
// try
// {
// object obj = Activator.CreateInstance(type);
// if (obj is IPeripheral)
// {
// IPeripheral peripheral = obj as IPeripheral;
// DeviceId = type?.GetProperty("DeviceId")?.GetValue(peripheral, null);
// }
// if (DeviceId != null) break;
// }
// catch (Exception ex)
// {
// }
//}

return DeviceId;
}


+ 198
- 131
BPASmartClient.Modbus/ModbusTcp.cs Просмотреть файл

@@ -107,179 +107,246 @@ namespace BPASmartClient.Modbus
return -1;
}

public int GetBoolAddress(string address)
//public void Readbool(ushort startAddress, ushort len, Action<bool[]> action)
//{
// object result;
// result = Read(startAddress, CommandType.Coils, len);
// if (result != null)
// {
// if (result is bool[] bools)
// {
// if (bools.Length == len)
// {
// action(bools);
// }
// }
// else if (result is bool bl)
// {
// List<bool> boolLists = new List<bool>();
// boolLists.Add(bl);
// action(boolLists.ToArray());
// }
// }
//}

public object READD(string address, ushort len = 1, byte slaveAddress = 1)
{
if (address != null && address.Length >= 4)
{
var res = address.Substring(1).Split('.');
if (res != null && res.Length == 2)
{
if (int.TryParse(res[0], out int firstAddress) && int.TryParse(res[1], out int ExitAddress))
{
if (ExitAddress >= 0 && ExitAddress <= 7)
{
return (firstAddress * 8) + 320 + ExitAddress;
}
}
}
}
return -1;
}

public int GetWordAddress(string address)
{
if (address != null && address.Length > 3)
{
var res = address.Substring(2);
if (res != null && int.TryParse(res, out int tempAddress))
{
return (tempAddress / 2) + 100;
}
}
return -1;
}

public void Readbool(ushort startAddress, ushort len, Action<bool[]> action)
{
object result;
result = Read(startAddress, CommandType.Coils, len);
if (result != null)
{
if (result is bool[] bools)
{
if (bools.Length == len)
{
action(bools);
}
}
else if (result is bool bl)
{
List<bool> boolLists = new List<bool>();
boolLists.Add(bl);
action(boolLists.ToArray());
}
}
}

public object Read(ushort startAddress, CommandType readType, ushort num = 1, byte slaveAddress = 1)
{
object result = new object();
if (tcpClient == null) return result;
if (num <= 0) return result;
if (address == null || tcpClient == null) return default(object);
ushort startAddress = (ushort)GetAddress(address);
CommandType commandType = CommandType.Coils;
try
{
switch (readType)
if (address.ToUpper().Contains("M"))
{
case CommandType.Coils:
result = master.ReadCoils(slaveAddress, startAddress, num);
break;
case CommandType.Inputs:
result = master.ReadInputs(slaveAddress, startAddress, num);
break;
case CommandType.HoldingRegisters:
result = master.ReadHoldingRegisters(slaveAddress, startAddress, num);
break;
case CommandType.InputRegisters:
result = master.ReadInputRegisters(slaveAddress, startAddress, num);
break;
default:
break;
commandType = CommandType.Coils;
return master.ReadCoils(slaveAddress, startAddress, len);
}
if (result == null) return new object();
if (result is bool[] bools)
else if (address.ToUpper().Contains("VW"))
{
if (bools.Length == 1)
return bools[0];
else
return bools;
commandType = CommandType.HoldingRegisters;
return master.ReadHoldingRegisters(slaveAddress, startAddress, len);
}
if (result is ushort[] ushorts)
else if (address.ToUpper().Contains("I"))
{
if (ushorts.Length == 1)
return ushorts[0];
else
return ushorts;
commandType = CommandType.Inputs;
return master.ReadInputs(slaveAddress, startAddress, len);
}
}
catch (Exception ex)
{
MessageLog.GetInstance.ShowEx($"读取地址:【{startAddress}】,读取类型:【{readType}】出错,{ex.ToString()}");
MessageLog.GetInstance.ShowEx($"读取地址:【{address}:= {startAddress}】,读取类型:【{commandType.ToString()}】出错,{ex.ToString()}");
if (ex.InnerException is SocketException)
{
tcpClient = null;
Connect();
}
}
return result;
return default(object);
}

public bool Write(ushort startAddress, CommandType writeType, object InputValue, byte slaveAddress = 1)
public void WRITEE<T>(string address, T value, byte slaveAddress = 1)
{
bool result = false;
if (tcpClient == null) return result;
if (!(InputValue is bool || InputValue is bool[] || InputValue is ushort || InputValue is ushort[])) return result;
if (address == null || tcpClient == null) return;
ushort startAddress = (ushort)GetAddress(address);
CommandType commandType = CommandType.Coils;
try
{
switch (writeType)
if (address.ToUpper().Contains("M"))
{
case CommandType.Coils:
if (InputValue is bool boolValue)
master.WriteSingleCoil(slaveAddress, startAddress, boolValue);

if (InputValue is bool[] boolsValue)
master.WriteMultipleCoils(slaveAddress, startAddress, boolsValue);
break;
case CommandType.HoldingRegisters:
if (InputValue is ushort ushortValue)
master.WriteSingleRegister(slaveAddress, startAddress, ushortValue);

if (InputValue is ushort[] ushortsValue)
commandType = CommandType.Coils;
if (value is bool boolValue)
master.WriteSingleCoil(slaveAddress, startAddress, boolValue);
else if (value is bool[] boolsValue)
master.WriteMultipleCoils(slaveAddress, startAddress, boolsValue);
}
else if (address.ToUpper().Contains("VW"))
{
commandType = CommandType.HoldingRegisters;
if (value is ushort ushortValue)
master.WriteSingleRegister(slaveAddress, startAddress, ushortValue);
else if (value is ushort[] ushortsValue)
{
int len = 100;
if (ushortsValue.Length > len)
{
int len = 100;
if (ushortsValue.Length > len)
List<ushort[]> ushortLists = new List<ushort[]>();
for (int i = 0; i < ushortsValue.Length / len; i++)
{
List<ushort[]> ushortLists = new List<ushort[]>();
for (int i = 0; i < ushortsValue.Length / len; i++)
{
ushortLists.Add(ushortsValue.Skip(0).Take(len).ToArray());
}
int y = ushortsValue.Length % len;

if (y > 0)
{
ushortLists.Add(ushortsValue.Skip(ushortsValue.Length - y).Take(y).ToArray());
}
foreach (var item in ushortLists)
{
master.WriteMultipleRegisters(slaveAddress, startAddress, item);
startAddress += (ushort)item.Length;
}
ushortLists.Add(ushortsValue.Skip(0).Take(len).ToArray());
}
else
int y = ushortsValue.Length % len;

if (y > 0)
{
master.WriteMultipleRegisters(slaveAddress, startAddress, ushortsValue);
ushortLists.Add(ushortsValue.Skip(ushortsValue.Length - y).Take(y).ToArray());
}
foreach (var item in ushortLists)
{
master.WriteMultipleRegisters(slaveAddress, startAddress, item);
startAddress += (ushort)item.Length;
}

}

break;
default:
break;
else
{
master.WriteMultipleRegisters(slaveAddress, startAddress, ushortsValue);
}
}
}
else if (address.ToUpper().Contains("I"))
{
commandType = CommandType.Inputs;
}
}
catch (Exception ex)
{
MessageLog.GetInstance.ShowEx(ex.ToString());
MessageLog.GetInstance.ShowEx($"读写入地址:【{address}:= {startAddress}】,写入类型:【{commandType.ToString()}】出错,{ex.ToString()}");
if (ex.InnerException is SocketException)
{
tcpClient = null;
Connect();
}
return false;
}
return true;
}

//public object Read(ushort startAddress, CommandType readType, ushort num = 1, byte slaveAddress = 1)
//{
// object result = new object();
// if (tcpClient == null) return result;
// if (num <= 0) return result;
// try
// {
// switch (readType)
// {
// case CommandType.Coils:
// result = master.ReadCoils(slaveAddress, startAddress, num);
// break;
// case CommandType.Inputs:
// result = master.ReadInputs(slaveAddress, startAddress, num);
// break;
// case CommandType.HoldingRegisters:
// result = master.ReadHoldingRegisters(slaveAddress, startAddress, num);
// break;
// case CommandType.InputRegisters:
// result = master.ReadInputRegisters(slaveAddress, startAddress, num);
// break;
// default:
// break;
// }
// if (result == null) return new object();
// if (result is bool[] bools)
// {
// if (bools.Length == 1)
// return bools[0];
// else
// return bools;
// }
// if (result is ushort[] ushorts)
// {
// if (ushorts.Length == 1)
// return ushorts[0];
// else
// return ushorts;
// }
// }
// catch (Exception ex)
// {
// MessageLog.GetInstance.ShowEx($"读取地址:【{startAddress}】,读取类型:【{readType}】出错,{ex.ToString()}");
// if (ex.InnerException is SocketException)
// {
// tcpClient = null;
// Connect();
// }
// }
// return result;
//}

//public bool Write(ushort startAddress, CommandType writeType, object InputValue, byte slaveAddress = 1)
//{
// bool result = false;
// if (tcpClient == null) return result;
// if (!(InputValue is bool || InputValue is bool[] || InputValue is ushort || InputValue is ushort[])) return result;
// try
// {
// switch (writeType)
// {
// case CommandType.Coils:
// if (InputValue is bool boolValue)
// master.WriteSingleCoil(slaveAddress, startAddress, boolValue);

// if (InputValue is bool[] boolsValue)
// master.WriteMultipleCoils(slaveAddress, startAddress, boolsValue);
// break;
// case CommandType.HoldingRegisters:
// if (InputValue is ushort ushortValue)
// master.WriteSingleRegister(slaveAddress, startAddress, ushortValue);

// if (InputValue is ushort[] ushortsValue)
// {
// int len = 100;
// if (ushortsValue.Length > len)
// {
// List<ushort[]> ushortLists = new List<ushort[]>();
// for (int i = 0; i < ushortsValue.Length / len; i++)
// {
// ushortLists.Add(ushortsValue.Skip(0).Take(len).ToArray());
// }
// int y = ushortsValue.Length % len;

// if (y > 0)
// {
// ushortLists.Add(ushortsValue.Skip(ushortsValue.Length - y).Take(y).ToArray());
// }
// foreach (var item in ushortLists)
// {
// master.WriteMultipleRegisters(slaveAddress, startAddress, item);
// startAddress += (ushort)item.Length;
// }
// }
// else
// {
// master.WriteMultipleRegisters(slaveAddress, startAddress, ushortsValue);
// }

// }

// break;
// default:
// break;
// }
// }
// catch (Exception ex)
// {
// MessageLog.GetInstance.ShowEx(ex.ToString());
// if (ex.InnerException is SocketException)
// {
// tcpClient = null;
// Connect();
// }
// return false;
// }
// return true;
//}


#region 批量数据读取
/// <summary>


+ 58
- 0
BPASmartClient.Model/Alarm.cs Просмотреть файл

@@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Toolkit.Mvvm.ComponentModel;

namespace BPASmartClient.Model
{
public class Alarm : ObservableObject
{
/// <summary>
/// ID
/// </summary>
[Key]
public int Id { get { return _mId; } set { _mId = value; OnPropertyChanged(); } }
private int _mId;

/// <summary>
/// 编号ID
/// </summary>
public int NumId { get { return _mNumId; } set { _mNumId = value; OnPropertyChanged(); } }
private int _mNumId;


/// <summary>
/// 日期
/// </summary>
public string Date { get { return _mDate; } set { _mDate = value; OnPropertyChanged(); } }
private string _mDate;

/// <summary>
/// 时间
/// </summary>
public string Time { get { return _mTime; } set { _mTime = value; OnPropertyChanged(); } }
private string _mTime;

/// <summary>
/// 报警信息
/// </summary>
public string Info { get { return _mInfo; } set { _mInfo = value; OnPropertyChanged(); } }
private string _mInfo;

/// <summary>
/// 报警值
/// </summary>
public string Value { get { return _mValue; } set { _mValue = value; OnPropertyChanged(); } }
private string _mValue;

/// <summary>
/// 报警等级
/// </summary>
public string Grade { get { return _mGrade; } set { _mGrade = value; OnPropertyChanged(); } }
private string _mGrade;

}
}

+ 184
- 0
BPASmartClient.Model/DeviceConfigModelJson.cs Просмотреть файл

@@ -0,0 +1,184 @@
using Microsoft.Toolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BPASmartClient.Model
{

/// <summary>
/// 店铺设备
/// </summary>
public class DeviceConfigModelJson : ObservableObject
{
/// <summary>
/// 店铺名称
/// </summary>
public string ShopName { get { return _mShopName; } set { _mShopName = value; OnPropertyChanged(); } }
private string _mShopName = string.Empty;

/// <summary>
/// 店铺ID
/// </summary>
public string ShopId { get { return _mShopId; } set { _mShopId = value; OnPropertyChanged(); } }
private string _mShopId = string.Empty;

/// <summary>
/// 设备集合
/// </summary>
public ObservableCollection<DeviceModel> deviceModels { get; set; } = new ObservableCollection<DeviceModel>();
}

/// <summary>
/// 启动模块
/// </summary>
public class DeviceModel : ObservableObject
{
/// <summary>
/// 设备名称
/// </summary>
public string DeviceName { get { return _mDeviceName; } set { _mDeviceName = value; OnPropertyChanged(); } }
private string _mDeviceName = string.Empty;

/// <summary>
/// 启动设备模块
/// </summary>
public string DeviceModule { get { return _mDeviceModule; } set { _mDeviceModule = value; OnPropertyChanged(); } }
private string _mDeviceModule = string.Empty;

public string DeviceNamespace { get; set; }


public string Id { get { return _mId; } set { _mId = value; OnPropertyChanged(); } }
private string _mId = string.Empty;


/// <summary>
/// 设备ID
/// </summary>
public string DeviceId { get { return _mDeviceId; } set { _mDeviceId = value; OnPropertyChanged(); } }
private string _mDeviceId = string.Empty;

/// <summary>
/// 通讯模块
/// </summary>
public ObservableCollection<CommunicationModel> communicationDevcies { get; set; } = new ObservableCollection<CommunicationModel>();

}

/// <summary>
/// 通讯模块
/// </summary>
public class CommunicationModel : ObservableObject
{
/// <summary>
/// 通讯启动模块
/// </summary>
public string CommunicationModule { get { return _mCommunicationModule; } set { _mCommunicationModule = value; OnPropertyChanged(); } }
private string _mCommunicationModule = string.Empty;

public string CommunicationNamespace { get; set; }

public string CommunicationName { get { return _mCommunicationName; } set { _mCommunicationName = value; OnPropertyChanged(); } }
private string _mCommunicationName = string.Empty;

public string DeviceModelId { get { return _mDeviceModelId; } set { _mDeviceModelId = value; OnPropertyChanged(); } }
private string _mDeviceModelId = string.Empty;

public CommunicationPar communicationPar { get { return _mcommunicationPar; } set { _mcommunicationPar = value; OnPropertyChanged(); } }
private CommunicationPar _mcommunicationPar = new CommunicationPar();

public ObservableCollection<Variable> variables { get; set; } = new ObservableCollection<Variable>();

}

/// <summary>
/// 通讯参数
/// </summary>
public class CommunicationPar : ObservableObject
{
/// <summary>
/// 选择网口通讯
/// </summary>
public bool IsNetworkPort { get { return _mIsNetworkPort; } set { _mIsNetworkPort = value; OnPropertyChanged(); } }
private bool _mIsNetworkPort = false;

/// <summary>
/// 选择串口通讯
/// </summary>
public bool IsSerialPort { get { return _mIsSerialPort; } set { _mIsSerialPort = value; OnPropertyChanged(); } }
private bool _mIsSerialPort = true;

/// <summary>
/// IP地址
/// </summary>
public string IPAddress { get { return _mIPAddress; } set { _mIPAddress = value; OnPropertyChanged(); } }
private string _mIPAddress;

/// <summary>
/// IP 端口号
/// </summary>
public int IPPort { get { return _mIPPort; } set { _mIPPort = value; OnPropertyChanged(); } }
private int _mIPPort;

/// <summary>
/// ip 串口 站号
/// </summary>
public int StationNo { get { return _mStationNo; } set { _mStationNo = value; OnPropertyChanged(); } }
private int _mStationNo;


/// <summary>
/// 串口单口号
/// </summary>
public string SerialPort { get { return _mSerialPort; } set { _mSerialPort = value; OnPropertyChanged(); } }
private string _mSerialPort;

/// <summary>
/// 波特率
/// </summary>
public int BaudRate { get { return _mBaudRate; } set { _mBaudRate = value; OnPropertyChanged(); } }
private int _mBaudRate;

/// <summary>
/// 数据位
/// </summary>
public int DataBits { get { return _mDataBits; } set { _mDataBits = value; OnPropertyChanged(); } }
private int _mDataBits = 8;

/// <summary>
/// 停止位
/// </summary>
public string StopBits { get { return _mStopBits; } set { _mStopBits = value; OnPropertyChanged(); } }
private string _mStopBits = "1";

/// <summary>
/// 校验位
/// </summary>
public string Parity { get { return _mParity; } set { _mParity = value; OnPropertyChanged(); } }
private string _mParity;

//public ObservableCollection<Variable> variables { get; set; } = new ObservableCollection<Variable>();
}

public class Variable : ObservableObject
{
public int Id { get { return _mId; } set { _mId = value; OnPropertyChanged(); } }
private int _mId;


public string Address { get { return _mAddress; } set { _mAddress = value; OnPropertyChanged(); } }
private string _mAddress;


public int ReadLeng { get { return _mReadLeng; } set { _mReadLeng = value; OnPropertyChanged(); } }
private int _mReadLeng;


}
}



+ 0
- 1
BPASmartClient.Model/KeepDataBase.cs Просмотреть файл

@@ -23,7 +23,6 @@ namespace BPASmartClient.Model
public ObservableCollection<OrderData> orderLists { get; set; } = new ObservableCollection<OrderData>();



/// <summary>
/// 参数设置
/// </summary>


+ 87
- 15
BPASmartClient.MorkS/Alarm.cs Просмотреть файл

@@ -11,7 +11,7 @@ namespace BPASmartClient.MorkS
{
/// <summary>
/// 煮面机左侧低温报警
/// PLC ---> M550.0
/// PLC ---> M230.0
/// ModbusTcp --> 1570
/// </summary>
[Alarm("煮面机左侧低温报警")]
@@ -19,7 +19,7 @@ namespace BPASmartClient.MorkS

/// <summary>
/// 煮面机左侧低温报警
/// PLC ---> M550.1
/// PLC ---> M230.1
/// ModbusTcp --> 1571
/// </summary>
[Alarm("煮面机右侧低温报警")]
@@ -27,7 +27,7 @@ namespace BPASmartClient.MorkS

/// <summary>
/// 供碗1缺碗
/// PLC ---> M550.2
/// PLC ---> 230.2
/// ModbusTcp --> 1572
/// </summary>
[Alarm("供碗1缺碗")]
@@ -35,7 +35,7 @@ namespace BPASmartClient.MorkS

/// <summary>
/// 供碗2缺碗
/// PLC ---> M550.3
/// PLC ---> M230.3
/// ModbusTcp --> 1573
/// </summary>
[Alarm("供碗2缺碗")]
@@ -43,7 +43,7 @@ namespace BPASmartClient.MorkS

/// <summary>
/// 供碗1出碗检测异常
/// PLC ---> M550.4
/// PLC ---> M230.4
/// ModbusTcp --> 1574
/// </summary>
[Alarm("供碗1出碗检测异常")]
@@ -51,7 +51,7 @@ namespace BPASmartClient.MorkS

/// <summary>
/// 供碗2出碗检测异常
/// PLC ---> M550.5
/// PLC ---> M230.5
/// ModbusTcp --> 1575
/// </summary>
[Alarm("供碗2出碗检测异常")]
@@ -59,7 +59,7 @@ namespace BPASmartClient.MorkS

/// <summary>
/// 推碗气缸故障
/// PLC ---> M550.6
/// PLC ---> M230.6
/// ModbusTcp --> 1576
/// </summary>
[Alarm("推碗气缸故障")]
@@ -67,7 +67,7 @@ namespace BPASmartClient.MorkS

/// <summary>
/// 煮面机通讯异常
/// PLC ---> M550.7
/// PLC ---> M230.7
/// ModbusTcp --> 1577
/// </summary>
[Alarm("煮面机通讯异常")]
@@ -75,7 +75,7 @@ namespace BPASmartClient.MorkS

/// <summary>
/// 配料机通讯异常
/// PLC ---> M551.0
/// PLC ---> M231.0
/// ModbusTcp --> 1580
/// </summary>
[Alarm("配料机通讯异常")]
@@ -83,15 +83,23 @@ namespace BPASmartClient.MorkS

/// <summary>
/// 机器人通讯异常
/// PLC ---> M551.1
/// PLC ---> M231.1
/// ModbusTcp --> 1581
/// </summary>
[Alarm("机器人通讯异常")]
public bool RobotMacCommunicateError { get; set; }

/// <summary>
/// 机器人通讯异常
/// PLC ---> M231.2
/// ModbusTcp --> 1581
/// </summary>
[Alarm("设备急停")]
public bool DeviceEstop { get; set; }

/// <summary>
/// 机器人初始化失败
/// PLC ---> M551.3
/// PLC ---> M231.3
/// ModbusTcp --> 1583
/// </summary>
[Alarm("机器人初始化失败")]
@@ -99,7 +107,7 @@ namespace BPASmartClient.MorkS

/// <summary>
/// 机器人急停
/// PLC ---> M551.4
/// PLC ---> M231.4
/// ModbusTcp --> 1584
/// </summary>
[Alarm("机器人急停")]
@@ -107,7 +115,7 @@ namespace BPASmartClient.MorkS

/// <summary>
/// 机器人不在远程模式
/// PLC ---> M551.5
/// PLC ---> M231.5
/// ModbusTcp --> 1585
/// </summary>
[Alarm("机器人不在远程模式")]
@@ -115,7 +123,7 @@ namespace BPASmartClient.MorkS

/// <summary>
/// 机器人伺服未就绪
/// PLC ---> M551.6
/// PLC ---> M231.6
/// ModbusTcp --> 1586
/// </summary>
[Alarm("机器人伺服未就绪")]
@@ -123,10 +131,74 @@ namespace BPASmartClient.MorkS

/// <summary>
/// 机器人本体异常
/// PLC ---> M551.7
/// PLC ---> M231.7
/// ModbusTcp --> 1587
/// </summary>
[Alarm("机器人本体异常")]
public bool RobotSelfInException { get; set; }

/// <summary>
/// 煮面机左侧缺水
/// PLC ---> M232.0
/// ModbusTcp --> 1570
/// </summary>
[Alarm("煮面机左侧缺水报警")]
public bool LeftLackWater { get; set; }

/// <summary>
/// 煮面机右侧缺水
/// PLC ---> M232.1
/// ModbusTcp --> 1571
/// </summary>
[Alarm("煮面机右侧缺水报警")]
public bool RightLackWater { get; set; }

/// <summary>
/// 丝杆初始化失败
/// PLC ---> M232.2
/// ModbusTcp --> 1571
/// </summary>
[Alarm("丝杆初始化失败")]
public bool SvrewInitFail { get; set; }

/// <summary>
/// 转盘初始化失败
/// PLC ---> M232.3
/// ModbusTcp --> 1571
/// </summary>
[Alarm("转盘初始化失败")]
public bool TurntableInitFail { get; set; }

/// <summary>
/// 机器人初始化失败
/// PLC ---> M232.4
/// ModbusTcp --> 1571
/// </summary>
[Alarm("机器人初始化失败")]
public bool RobotInitFail { get; set; }

/// <summary>
/// 煮面机初始化失败
/// PLC ---> M232.5
/// ModbusTcp --> 1571
/// </summary>
[Alarm("煮面机初始化失败")]
public bool NoodleCookerInitFail { get; set; }

/// <summary>
/// 推碗1步进推杆初始化失败
/// PLC ---> M232.6
/// ModbusTcp --> 1571
/// </summary>
[Alarm("推碗1步进推杆初始化失败")]
public bool PushBowlInitFail1 { get; set; }

/// <summary>
/// 推碗2步进推杆初始化失败
/// PLC ---> M232.7
/// ModbusTcp --> 1571
/// </summary>
[Alarm("推碗2步进推杆初始化失败")]
public bool PushBowlInitFail2 { get; set; }
}
}

+ 89
- 33
BPASmartClient.MorkS/Control_Morks.cs Просмотреть файл

@@ -67,7 +67,10 @@ namespace BPASmartClient.MorkS

private void OrderChange(string subid, ORDER_STATUS oRDER_STATUS)
{
EventBus.EventBus.GetInstance().Publish(new OrderStatusChangedEvent() { Status = oRDER_STATUS, SubOrderId = subid, deviceClientType = DeviceType });
var res = mORKS.doOrderEvents.FirstOrDefault(p => p.MorkOrder.SuborderId == subid);
string goodName = string.Empty;
if (res != null) goodName = res.MorkOrder.GoodsName;
EventBus.EventBus.GetInstance().Publish(new OrderStatusChangedEvent() { GoodName = goodName, Status = oRDER_STATUS, SubOrderId = subid, deviceClientType = DeviceType });
}

private void ReadData(string address, ushort len = 1, Action<bool[]> action = null)
@@ -85,13 +88,17 @@ namespace BPASmartClient.MorkS
{
if (peripheralStatus.ContainsKey(key))
{
action((bool[])peripheralStatus[key]);
if (peripheralStatus[key] is bool[] bools)
{
action?.Invoke(bools);
}
//action((bool[])peripheralStatus[key]);
}
}

public override void ReadData()
{
GetStatus("M550.0", new Action<bool[]>((bools) =>
GetStatus("M230.0", new Action<bool[]>((bools) =>
{
alarm.MachineLeftLowTemperature = bools[0];
alarm.MachineRightLowTemperature = bools[1];
@@ -103,11 +110,20 @@ namespace BPASmartClient.MorkS
alarm.NoodleMacCommunicateError = bools[7];
alarm.DosingMacCommunicateError = bools[8];
alarm.RobotMacCommunicateError = bools[9];
alarm.DeviceEstop = bools[10];
alarm.RobotInitError = bools[11];
alarm.RobotUrgentStop = bools[12];
alarm.RobotNotInRemoteMode = bools[13];
alarm.RobotNotInReady = bools[14];
alarm.RobotSelfInException = bools[15];
alarm.LeftLackWater = bools[16];
alarm.RightLackWater = bools[17];
alarm.SvrewInitFail = bools[18];
alarm.TurntableInitFail = bools[19];
alarm.RobotInitFail = bools[20];
alarm.NoodleCookerInitFail = bools[21];
alarm.PushBowlInitFail1 = bools[22];
alarm.PushBowlInitFail2 = bools[23];
}));

GetStatus("M0.3", new Action<bool[]>((bools) =>
@@ -179,6 +195,7 @@ namespace BPASmartClient.MorkS
if (@event == null) return;
if (@event is DoOrderEvent order)
{
mORKS.doOrderEvents.Add(order);
if (order.MorkOrder.GoodBatchings == null) return;
OrderCount++;
DeviceProcessLogShow($"接收到{OrderCount}次订单");
@@ -192,7 +209,7 @@ namespace BPASmartClient.MorkS
if (loc >= 1 && loc <= 5)
{
if (mORKS.RBTakeNoodleTask.FirstOrDefault(p => p.SuborderId == order.MorkOrder.SuborderId) == null)
mORKS.RBTakeNoodleTask.Enqueue(new OrderLocInfo() { Loc = ushort.Parse(res.BatchingLoc), SuborderId = order.MorkOrder.SuborderId, BatchingId = res.BatchingId });
mORKS.RBTakeNoodleTask.Enqueue(new OrderLocInfo() { GoodName = order.MorkOrder.GoodsName, Loc = ushort.Parse(res.BatchingLoc), SuborderId = order.MorkOrder.SuborderId, BatchingId = res.BatchingId });
}
else if (loc >= 10 && loc <= 11)
{
@@ -205,6 +222,8 @@ namespace BPASmartClient.MorkS
if (mORKS.TakeBowlTask.FirstOrDefault(p => p.SuborderId == order.MorkOrder.SuborderId) == null)
mORKS.TakeBowlTask.Enqueue(new OrderLocInfo()
{
BatchingId = res.BatchingId,
GoodName = order.MorkOrder.GoodsName,
Loc = ushort.Parse(res.BatchingLoc),
SuborderId = order.MorkOrder.SuborderId,
RecipeNumber = (index >= 1 && index <= 10) ? (ushort)index : (ushort)0
@@ -221,8 +240,8 @@ namespace BPASmartClient.MorkS
public override void MainTask()
{
mORKS.AllowRun = mORKS.InitComplete;
//IsHealth = mORKS.Error && mORKS.InitComplete;
IsHealth = true;
IsHealth = mORKS.Error && mORKS.InitComplete;
//IsHealth = true;

if (mORKS.AllowRun)
{
@@ -238,6 +257,18 @@ namespace BPASmartClient.MorkS
}
}

private void BowlControl(OrderLocInfo orderLocInfo)
{
if (orderLocInfo.Loc >= 10 && orderLocInfo.Loc <= 11)
{
mORKS.TakeBowlId = orderLocInfo.SuborderId;
TakeBowlControl(orderLocInfo.Loc);
SetRecipeNumber(orderLocInfo.RecipeNumber);
OrderChange(mORKS.TakeBowlId, ORDER_STATUS.COOKING);
DeviceProcessLogShow($"订单【{ mORKS.TakeBowlId}】执行取碗控制,位置:[{orderLocInfo.Loc}]");
mORKS.TakeBowlInterlock = true;
}
}

/// <summary>
/// 取碗控制
@@ -246,43 +277,60 @@ namespace BPASmartClient.MorkS
{
if (mORKS.AllowRun && mORKS.TakeBowlTask.Count > 0 && !mORKS.TakeBowlIdle && !mORKS.TakeBowlInterlock)
{
if (mORKS.TakeBowlTask.TryDequeue(out OrderLocInfo orderLocInfo))
//if (mORKS.TakeBowlTask.TryDequeue(out OrderLocInfo orderLocInfo))
//{
ushort BowLoc = 0;
var res = orderMaterialDelivery?.BatchingInfo?.Where(p => p.BatchingId == mORKS.TakeBowlTask.ElementAt(0).BatchingId).ToList();
if (res == null || res?.Count == 0)
{
ushort BowLoc = 0;
var res = orderMaterialDelivery?.BatchingInfo?.Where(p => p.BatchingId == orderLocInfo.BatchingId).ToList();
if (res != null)
if (mORKS.TakeBowlTask.TryDequeue(out OrderLocInfo orderLocInfo)) BowlControl(orderLocInfo);
}
else
{
foreach (var item in res)
{
foreach (var item in res)
if (ushort.TryParse(item.BatchingLoc, out ushort loc))
{
if (ushort.TryParse(item.BatchingLoc, out ushort loc))
DeviceProcessLogShow($"位置:={loc},检测开关1:{alarm.Supply1_LossBowl},检测开关1:{alarm.Supply2_LossBowl}");
if (loc == 10 && !alarm.Supply1_LossBowl)
{
if (loc == 10 && alarm.Supply1_LossBowl)
{
BowLoc = loc;
break;
}
else if (loc == 11 && alarm.Supply2_LossBowl)
{
BowLoc = loc;
break;
}
BowLoc = loc;
break;
}
else if (loc == 11 && !alarm.Supply2_LossBowl)
{
BowLoc = loc;
break;
}

}
}

if (BowLoc >= 10 && BowLoc <= 11)
if (mORKS.TakeBowlTask.TryDequeue(out OrderLocInfo orderLocInfo))
{
mORKS.TakeBowlId = orderLocInfo.SuborderId;
//TakeBowlControl(orderLocInfo.Loc);
TakeBowlControl(BowLoc);
SetRecipeNumber(orderLocInfo.RecipeNumber);
OrderChange(mORKS.TakeBowlId, ORDER_STATUS.COOKING);
DeviceProcessLogShow($"订单【{ mORKS.TakeBowlId}】执行取碗控制,位置:[{orderLocInfo.Loc}]");
orderLocInfo.Loc = BowLoc;
BowlControl(orderLocInfo);
}

}
mORKS.TakeBowlInterlock = true;

//if (BowLoc >= 10 && BowLoc <= 11)
//{
// mORKS.TakeBowlInterlock = true;
// mORKS.TakeBowlId = orderLocInfo.SuborderId;
// TakeBowlControl(BowLoc);
// SetRecipeNumber(orderLocInfo.RecipeNumber);
// OrderChange(mORKS.TakeBowlId, ORDER_STATUS.COOKING);
// DeviceProcessLogShow($"订单【{ mORKS.TakeBowlId}】执行取碗控制,位置:[{orderLocInfo.Loc}]");
//}


//之前版本
//mORKS.TakeBowlId = orderLocInfo.SuborderId;
//TakeBowlControl(orderLocInfo.Loc);
//SetRecipeNumber(orderLocInfo.RecipeNumber);
//OrderChange(mORKS.TakeBowlId, ORDER_STATUS.COOKING);
//DeviceProcessLogShow($"订单【{ mORKS.TakeBowlId}】执行取碗控制,位置:[{orderLocInfo.Loc}]");
//mORKS.TakeBowlInterlock = true;
//}

}
}

@@ -345,6 +393,13 @@ namespace BPASmartClient.MorkS
}
}

//补料中检测
if (RTrig.GetInstance("mORKS.Feeding").Start(mORKS.Feeding))
{
mORKS.AllowTakeNoodle = false;
mORKS.TakeNoodleInterlock = false;
}

//转台到位检测
if (RTrig.GetInstance("TurntableInPlace").Start(mORKS.TurntableMoveInPlace && mORKS.CurrentLoc == mORKS.TurntableFeedbackloc))
{
@@ -496,6 +551,7 @@ namespace BPASmartClient.MorkS
{
//配方数据地址范围:VW2000 - VW2278
WriteData("VW2000", recipeBoms.ToArray());
DeviceProcessLogShow("写配方成功");
}
else { DeviceProcessLogShow("配方数据为空"); }
}


+ 3
- 0
BPASmartClient.MorkS/GVL_MORKS.cs Просмотреть файл

@@ -1,4 +1,5 @@
using BPASmartClient.Device;
using BPASmartClient.Model;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
@@ -303,6 +304,8 @@ namespace BPASmartClient.MorkS
//[Circuit("取碗控制", "有取碗队列数量")]
public ConcurrentQueue<OrderLocInfo> TakeBowlTask { get; set; } = new ConcurrentQueue<OrderLocInfo>();

public List<DoOrderEvent> doOrderEvents { get; set; } = new List<DoOrderEvent>();

/// <summary>
/// 是否有面条
/// </summary>


+ 1
- 0
BPASmartClient.MorkS/OrderLocInfo.cs Просмотреть файл

@@ -12,5 +12,6 @@ namespace BPASmartClient.MorkS
public ushort Loc { get; set; }
public ushort RecipeNumber { get; set; }
public int BatchingId { get; set; }
public string GoodName { get; set; }
}
}

+ 4
- 0
BPASmartClient.Peripheral/BPASmartClient.Peripheral.csproj Просмотреть файл

@@ -6,4 +6,8 @@
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\BPASmartClient.Model\BPASmartClient.Model.csproj" />
</ItemGroup>

</Project>

+ 7
- 2
BPASmartClient.Peripheral/BasePeripheral.cs Просмотреть файл

@@ -1,6 +1,8 @@
using System;
using BPASmartClient.Model;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -24,11 +26,14 @@ namespace BPASmartClient.Peripheral
/// 归属设备Id
/// </summary>
public int DeviceId { get; set; }
public CommunicationPar communicationPar { get; set; } = new CommunicationPar();
public ConcurrentDictionary<string, object> status { get; set; } = new ConcurrentDictionary<string, object>();
public ObservableCollection<Variable> variables { get; set; } = new ObservableCollection<Variable>();

/// <summary>
/// 外设状态集合
/// </summary>
protected ConcurrentDictionary<string, object> status = new ConcurrentDictionary<string, object>();
//protected ConcurrentDictionary<string, object> status = new ConcurrentDictionary<string, object>();

/// <summary>
/// 初始化外设状态


+ 19
- 1
BPASmartClient.Peripheral/IPeripheral.cs Просмотреть файл

@@ -1,6 +1,8 @@
using System;
using BPASmartClient.Model;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -35,6 +37,22 @@ namespace BPASmartClient.Peripheral
/// </summary>
/// <returns>状态值</returns>
ConcurrentDictionary<string, object> GetAllStatus();

/// <summary>
/// 设备变量数据
/// </summary>
ObservableCollection<Variable> variables { get; set; }

/// <summary>
/// 通讯参数
/// </summary>
CommunicationPar communicationPar { get; set; }

/// <summary>
/// 设备数据,key:地址,value:数据
/// </summary>
ConcurrentDictionary<string, object> status { get; set; }

/// <summary>
/// 初始化
/// </summary>


+ 0
- 1
BPASmartClient.SCChip/BPASmartClient.SCChip.csproj Просмотреть файл

@@ -5,7 +5,6 @@
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\BPASmartClient.Model\BPASmartClient.Model.csproj" />
<ProjectReference Include="..\BPASmartClient.Peripheral\BPASmartClient.Peripheral.csproj" />
<ProjectReference Include="..\BPASmartClient.SerialPort\BPASmartClient.SerialPort.csproj" />
</ItemGroup>


+ 158
- 0
BPASmartClient.ViewModel/AlarmViewModel.cs Просмотреть файл

@@ -0,0 +1,158 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Toolkit.Mvvm.Input;
using System.Collections.ObjectModel;
using System.Windows;
using System.Threading;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using BPASmartClient.Device;
using BPASmartClient.Helper;
using BPASmartClient.Business;
using BPASmartClient.Model;

namespace BPASmartClient.ViewModel
{
public class AlarmViewModel : ObservableObject
{
public AlarmViewModel()
{
ControlCommand = new RelayCommand(() =>
{
if (ControlButText == "报警复位")
{
return;
}
if (ControlButText == "开始查询")
{
var lists = Sqlite<Alarm>.GetInstance.GetData();
var res = lists.Where(p => Convert.ToDateTime(p.Date) >= StartDateTime && Convert.ToDateTime(p.Date) <= EndDateTime).ToList();
if (res != null)
{
HistoryAlarm.Clear();
foreach (var item in res)
{
HistoryAlarm.Add(item);
}
}
}

});

SwitchCommand = new RelayCommand(() =>
{
if (ButContent == "历史报警")
{
GetHistoryAlarm();
CurrentDataVis = Visibility.Hidden;
HistoryDataVis = Visibility.Visible;
IsVisibility = Visibility.Visible;
ControlButText = "开始查询";
ButContent = "实时报警";
return;
}

if (ButContent == "实时报警")
{
HistoryDataVis = Visibility.Hidden;
CurrentDataVis = Visibility.Visible;
IsVisibility = Visibility.Hidden;
ControlButText = "报警复位";
ButContent = "历史报警";
return;
}
});
AlarmMonitoring();
}


public void AlarmMonitoring()
{
AlarmInfos.Clear();
Plugin.GetInstance()?.GetPlugin<DeviceMgr>()?.GetDevices()?.ForEach(device =>
{
device.alarmHelper.Alarms.ForEach((item) => { AlarmInfos.Add(item); });
device.alarmHelper.AddAction += new Action<string>((s) =>
{
var res = device.alarmHelper.Alarms.FirstOrDefault(p => p.Info == s);
if (res != null) Application.Current.Dispatcher.Invoke(new Action(() => { AlarmInfos.Insert(0, res); }));
});

device.alarmHelper.RemoveAction += new Action<string>((s) =>
{
var res = AlarmInfos.FirstOrDefault(p => p.Info == s);
if (res != null) Application.Current.Dispatcher.Invoke(new Action(() => { AlarmInfos.Remove(res); }));
});
});
}

private void GetHistoryAlarm()
{
var data = Sqlite<Alarm>.GetInstance.GetData();
if (data != null)
{
HistoryAlarm.Clear();
foreach (var item in data)
{
int day = DateTime.Now.Subtract(Convert.ToDateTime(item.Date)).Days;
if (day == 0)
{
HistoryAlarm.Add(item);
}
}
}
}

public RelayCommand SwitchCommand { get; set; }

public RelayCommand ControlCommand { get; set; }


public Visibility CurrentDataVis { get { return _mCurrentDataVis; } set { _mCurrentDataVis = value; OnPropertyChanged(); } }
private Visibility _mCurrentDataVis = Visibility.Visible;


public Visibility HistoryDataVis { get { return _mHistoryDataVis; } set { _mHistoryDataVis = value; OnPropertyChanged(); } }
private Visibility _mHistoryDataVis = Visibility.Hidden;


/// <summary>
/// 是否显示
/// </summary>
public Visibility IsVisibility { get { return _mIsVisibility; } set { _mIsVisibility = value; OnPropertyChanged(); } }
private Visibility _mIsVisibility = Visibility.Hidden;

/// <summary>
/// 文字显示
/// </summary>
public string ButContent { get { return _mButContent; } set { _mButContent = value; OnPropertyChanged(); } }
private string _mButContent = "历史报警";

/// <summary>
/// 控制按钮文本显示
/// </summary>
public string ControlButText { get { return _mControlButText; } set { _mControlButText = value; OnPropertyChanged(); } }
private string _mControlButText = "报警复位";


/// <summary>
/// 开始时间
/// </summary>
public DateTime StartDateTime { get { return _mStartDateTime; } set { _mStartDateTime = value; OnPropertyChanged(); } }
private DateTime _mStartDateTime = DateTime.Now;

/// <summary>
/// 结束时间
/// </summary>
public DateTime EndDateTime { get { return _mEndDateTime; } set { _mEndDateTime = value; OnPropertyChanged(); } }
private DateTime _mEndDateTime = DateTime.Now;


public ObservableCollection<Alarm> AlarmInfos { get; set; } = new ObservableCollection<Alarm>();

public ObservableCollection<Alarm> HistoryAlarm { get; set; } = new ObservableCollection<Alarm>();

}
}

+ 117
- 0
BPASmartClient.ViewModel/LogOrAlarmIOTViewModel.cs Просмотреть файл

@@ -0,0 +1,117 @@
using BPASmartClient.CustomResource.UserControls;
using BPASmartClient.CustomResource.UserControls.MessageShow;
using BPASmartClient.Helper;
using BPASmartClient.IoT;
using DataVAPI.Tool.IOT;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;

namespace BPASmartClient.ViewModel
{
public class LogOrAlarmIOTViewModel : ObservableObject
{

#region 单一变量
private volatile static LogOrAlarmIOTViewModel _Instance;
public static LogOrAlarmIOTViewModel GetInstance() => _Instance ?? (_Instance = new LogOrAlarmIOTViewModel());
private LogOrAlarmIOTViewModel()
{
Init();
}
#endregion
#region 变量
public string api = "https://bpa.black-pa.com:21527/datav/api/Log/QueryLogFile?DeviceName=";
public string DataVApiAddress { set; get; }
private ObservableCollection<FileModel> _LogModels; public ObservableCollection<FileModel> LogDataFile
{
get
{
return _LogModels;
}
set
{
if (_LogModels == value)
return;
_LogModels = value;
OnPropertyChanged("LogDataFile");
}
}
#endregion
#region Command
public RelayCommand QueryCommand { get; set; }
#endregion

#region 函数
public void Init()
{
DataVApiAddress = System.Configuration.ConfigurationManager.AppSettings["DataVServiceUri"].ToString();

LogDataFile = new ObservableCollection<FileModel>();
//查询
QueryCommand = new RelayCommand(() =>
{
Res();
});
}

public void Res()
{
if (DataVClient.GetInstance().DeviceDataV != null && DataVClient.GetInstance().DeviceDataV.deviceTable != null)
{
try
{
LogDataFile.Clear();
api = $"{DataVApiAddress}/api/Log/QueryLogFile?DeviceName={DataVClient.GetInstance().DeviceDataV.deviceTable.devicename}"; ;
string json = HttpRequestHelper.HttpGetRequest(api, 1000);
JsonMsg<List<FileModel>> jsonMsg = Tools.JsonToObjectTools<JsonMsg<List<FileModel>>>(json);
jsonMsg.obj?.data?.ForEach(file =>
{
LogDataFile.Add(file);
});
NoticeDemoViewModel.OpenMsg(EnumPromptType.Info, MainViewModel.GetInstance().window, "提示", $"查询成功,文件数{LogDataFile.Count}!");
}
catch (Exception ex)
{
NoticeDemoViewModel.OpenMsg(EnumPromptType.Error, MainViewModel.GetInstance().window, "提示", $"查询失败!");
}

}
}
#endregion
}

public class FileModel : ObservableObject
{
public string downloadUrl { get; set; }
public string fileId { get; set; }
public string name { get; set; }
public string size { get; set; }
public string utcCreatedOn { get; set; }
private Brush _foreground;
public Brush foreground
{
get
{
return _foreground;
}
set
{
if (_foreground == value)
return;
_foreground = value;
OnPropertyChanged("foreground");
}
}
public FileModel()
{
foreground = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#21bb2e"));
}
}
}

+ 0
- 10
BPASmartClient.ViewModel/LogOrAlarmViewModel.cs Просмотреть файл

@@ -186,16 +186,6 @@ namespace BPASmartClient.ViewModel
});
}

/// <summary>
/// 查询告警或日志
/// </summary>
/// <param name="time"></param>
/// <param name="info"></param>
public void QueryLogOrAlarm(DateTime time, string info)
{

}

/// <summary>
/// 读取文件
/// </summary>


+ 10
- 0
BPASmartClient.ViewModel/LogViewModel.cs Просмотреть файл

@@ -26,6 +26,9 @@ namespace BPASmartClient.ViewModel
public class LogViewModel : ObservableObject
{
#region 变量
//定时上报文件到阿里云
public DispatcherTimer UpDataFileTimer;
//定时清除界面日志
public DispatcherTimer dispatcherTimer;
public string ClientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"].ToString();
public ObservableCollection<LogModel> LogDataGridData { get; set; }
@@ -231,6 +234,13 @@ namespace BPASmartClient.ViewModel
};
dispatcherTimer.Interval = TimeSpan.FromSeconds(10);
dispatcherTimer.Start();
UpDataFileTimer = new DispatcherTimer();
UpDataFileTimer.Tick += delegate
{
DataVClient.GetInstance().UpDataFile();
};
UpDataFileTimer.Interval = TimeSpan.FromHours(0.5);
UpDataFileTimer.Start();
}
/// <summary>
/// 增加日志


+ 181
- 191
BPASmartClient.ViewModel/Model/DeviceConfigModel.cs Просмотреть файл

@@ -1,191 +1,181 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using System.Collections.ObjectModel;
using Microsoft.Toolkit.Mvvm.Input;
using System.Windows;

namespace BPASmartClient.ViewModel.Model
{
/// <summary>
/// 店铺设备
/// </summary>
public class DeviceConfigModel : ObservableObject
{

/// <summary>
/// 店铺名称
/// </summary>
public string ShopName { get { return _mShopName; } set { _mShopName = value; OnPropertyChanged(); } }
private string _mShopName = string.Empty;

/// <summary>
/// 店铺ID
/// </summary>
public string ShopId { get { return _mShopId; } set { _mShopId = value; OnPropertyChanged(); } }
private string _mShopId = string.Empty;

/// <summary>
/// 设备集合
/// </summary>
public ObservableCollection<DeviceModel> deviceModels { get; set; } = new ObservableCollection<DeviceModel>();
}

/// <summary>
/// 启动模块
/// </summary>
public class DeviceModel : ObservableObject
{
/// <summary>
/// 设备名称
/// </summary>
public string DeviceName { get { return _mDeviceName; } set { _mDeviceName = value; OnPropertyChanged(); } }
private string _mDeviceName = string.Empty;

/// <summary>
/// 启动设备模块
/// </summary>
public string DeviceModule { get { return _mDeviceModule; } set { _mDeviceModule = value; OnPropertyChanged(); } }
private string _mDeviceModule = string.Empty;


public string Id { get { return _mId; } set { _mId = value; OnPropertyChanged(); } }
private string _mId = string.Empty;


/// <summary>
/// 设备ID
/// </summary>
public string DeviceId { get { return _mDeviceId; } set { _mDeviceId = value; OnPropertyChanged(); } }
private string _mDeviceId = string.Empty;

/// <summary>
/// 通讯模块
/// </summary>
public ObservableCollection<CommunicationModel> communicationDevcies { get; set; } = new ObservableCollection<CommunicationModel>();

}

/// <summary>
/// 通讯模块
/// </summary>
public class CommunicationModel : ObservableObject
{
/// <summary>
/// 通讯启动模块
/// </summary>
public string CommunicationModule { get { return _mCommunicationModule; } set { _mCommunicationModule = value; OnPropertyChanged(); } }
private string _mCommunicationModule = string.Empty;

public string CommunicationName { get { return _mCommunicationName; } set { _mCommunicationName = value; OnPropertyChanged(); } }
private string _mCommunicationName = string.Empty;

public string DeviceModelId { get { return _mDeviceModelId; } set { _mDeviceModelId = value; OnPropertyChanged(); } }
private string _mDeviceModelId = string.Empty;

public CommunicationPar communicationPar { get { return _mcommunicationPar; } set { _mcommunicationPar = value; OnPropertyChanged(); } }
private CommunicationPar _mcommunicationPar = new CommunicationPar();


}

/// <summary>
/// 通讯参数
/// </summary>
public class CommunicationPar : ObservableObject
{
///// <summary>
///// 通讯类型,false:串口,true:网口
///// </summary>
//public bool CommunicationType { get { return _mCommunicationType; } set { _mCommunicationType = value; OnPropertyChanged(); } }
//private bool _mCommunicationType;

/// <summary>
/// 选择网口通讯
/// </summary>
public bool IsNetworkPort { get { return _mIsNetworkPort; } set { _mIsNetworkPort = value; OnPropertyChanged(); } }
private bool _mIsNetworkPort = false;

/// <summary>
/// 选择串口通讯
/// </summary>
public bool IsSerialPort { get { return _mIsSerialPort; } set { _mIsSerialPort = value; OnPropertyChanged(); } }
private bool _mIsSerialPort = true;

//public Visibility NetworkVisibility { get { return _mNetworkVisibility; } set { _mNetworkVisibility = value; OnPropertyChanged(); } }
//private Visibility _mNetworkVisibility = Visibility.Collapsed;

//public Visibility SerialVisibility { get { return _mSerialVisibility; } set { _mSerialVisibility = value; OnPropertyChanged(); } }
//private Visibility _mSerialVisibility = Visibility.Visible;

/// <summary>
/// IP地址
/// </summary>
public string IPAddress { get { return _mIPAddress; } set { _mIPAddress = value; OnPropertyChanged(); } }
private string _mIPAddress;

/// <summary>
/// IP 端口号
/// </summary>
public int IPPort { get { return _mIPPort; } set { _mIPPort = value; OnPropertyChanged(); } }
private int _mIPPort;

/// <summary>
/// ip 串口 站号
/// </summary>
public int StationNo { get { return _mStationNo; } set { _mStationNo = value; OnPropertyChanged(); } }
private int _mStationNo;


/// <summary>
/// 串口单口号
/// </summary>
public string SerialPort { get { return _mSerialPort; } set { _mSerialPort = value; OnPropertyChanged(); } }
private string _mSerialPort;

/// <summary>
/// 波特率
/// </summary>
public int BaudRate { get { return _mBaudRate; } set { _mBaudRate = value; OnPropertyChanged(); } }
private int _mBaudRate;

/// <summary>
/// 数据位
/// </summary>
public int DataBits { get { return _mDataBits; } set { _mDataBits = value; OnPropertyChanged(); } }
private int _mDataBits = 8;

/// <summary>
/// 停止位
/// </summary>
public string StopBits { get { return _mStopBits; } set { _mStopBits = value; OnPropertyChanged(); } }
private string _mStopBits = "1";

/// <summary>
/// 校验位
/// </summary>
public string Parity { get { return _mParity; } set { _mParity = value; OnPropertyChanged(); } }
private string _mParity;

public ObservableCollection<Variable> variables { get; set; } = new ObservableCollection<Variable>();
}

public class Variable : ObservableObject
{
public int Id { get { return _mId; } set { _mId = value; OnPropertyChanged(); } }
private int _mId;


public string Address { get { return _mAddress; } set { _mAddress = value; OnPropertyChanged(); } }
private string _mAddress;


public int ReadLeng { get { return _mReadLeng; } set { _mReadLeng = value; OnPropertyChanged(); } }
private int _mReadLeng;


}
}
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
//using Microsoft.Toolkit.Mvvm.ComponentModel;
//using System.Collections.ObjectModel;
//using Microsoft.Toolkit.Mvvm.Input;
//using System.Windows;

//namespace BPASmartClient.ViewModel.Model
//{
// /// <summary>
// /// 店铺设备
// /// </summary>
// public class DeviceConfigModel : ObservableObject
// {
// /// <summary>
// /// 店铺名称
// /// </summary>
// public string ShopName { get { return _mShopName; } set { _mShopName = value; OnPropertyChanged(); } }
// private string _mShopName = string.Empty;

// /// <summary>
// /// 店铺ID
// /// </summary>
// public string ShopId { get { return _mShopId; } set { _mShopId = value; OnPropertyChanged(); } }
// private string _mShopId = string.Empty;

// /// <summary>
// /// 设备集合
// /// </summary>
// public ObservableCollection<DeviceModel> deviceModels { get; set; } = new ObservableCollection<DeviceModel>();
// }

// /// <summary>
// /// 启动模块
// /// </summary>
// public class DeviceModel : ObservableObject
// {
// /// <summary>
// /// 设备名称
// /// </summary>
// public string DeviceName { get { return _mDeviceName; } set { _mDeviceName = value; OnPropertyChanged(); } }
// private string _mDeviceName = string.Empty;

// /// <summary>
// /// 启动设备模块
// /// </summary>
// public string DeviceModule { get { return _mDeviceModule; } set { _mDeviceModule = value; OnPropertyChanged(); } }
// private string _mDeviceModule = string.Empty;

// public string DeviceNamespace { get; set; }


// public string Id { get { return _mId; } set { _mId = value; OnPropertyChanged(); } }
// private string _mId = string.Empty;


// /// <summary>
// /// 设备ID
// /// </summary>
// public string DeviceId { get { return _mDeviceId; } set { _mDeviceId = value; OnPropertyChanged(); } }
// private string _mDeviceId = string.Empty;

// /// <summary>
// /// 通讯模块
// /// </summary>
// public ObservableCollection<CommunicationModel> communicationDevcies { get; set; } = new ObservableCollection<CommunicationModel>();

// }

// /// <summary>
// /// 通讯模块
// /// </summary>
// public class CommunicationModel : ObservableObject
// {
// /// <summary>
// /// 通讯启动模块
// /// </summary>
// public string CommunicationModule { get { return _mCommunicationModule; } set { _mCommunicationModule = value; OnPropertyChanged(); } }
// private string _mCommunicationModule = string.Empty;

// public string CommunicationNamespace { get; set; }

// public string CommunicationName { get { return _mCommunicationName; } set { _mCommunicationName = value; OnPropertyChanged(); } }
// private string _mCommunicationName = string.Empty;

// public string DeviceModelId { get { return _mDeviceModelId; } set { _mDeviceModelId = value; OnPropertyChanged(); } }
// private string _mDeviceModelId = string.Empty;

// public CommunicationPar communicationPar { get { return _mcommunicationPar; } set { _mcommunicationPar = value; OnPropertyChanged(); } }
// private CommunicationPar _mcommunicationPar = new CommunicationPar();

// }

// /// <summary>
// /// 通讯参数
// /// </summary>
// public class CommunicationPar : ObservableObject
// {
// /// <summary>
// /// 选择网口通讯
// /// </summary>
// public bool IsNetworkPort { get { return _mIsNetworkPort; } set { _mIsNetworkPort = value; OnPropertyChanged(); } }
// private bool _mIsNetworkPort = false;

// /// <summary>
// /// 选择串口通讯
// /// </summary>
// public bool IsSerialPort { get { return _mIsSerialPort; } set { _mIsSerialPort = value; OnPropertyChanged(); } }
// private bool _mIsSerialPort = true;

// /// <summary>
// /// IP地址
// /// </summary>
// public string IPAddress { get { return _mIPAddress; } set { _mIPAddress = value; OnPropertyChanged(); } }
// private string _mIPAddress;

// /// <summary>
// /// IP 端口号
// /// </summary>
// public int IPPort { get { return _mIPPort; } set { _mIPPort = value; OnPropertyChanged(); } }
// private int _mIPPort;

// /// <summary>
// /// ip 串口 站号
// /// </summary>
// public int StationNo { get { return _mStationNo; } set { _mStationNo = value; OnPropertyChanged(); } }
// private int _mStationNo;


// /// <summary>
// /// 串口单口号
// /// </summary>
// public string SerialPort { get { return _mSerialPort; } set { _mSerialPort = value; OnPropertyChanged(); } }
// private string _mSerialPort;

// /// <summary>
// /// 波特率
// /// </summary>
// public int BaudRate { get { return _mBaudRate; } set { _mBaudRate = value; OnPropertyChanged(); } }
// private int _mBaudRate;

// /// <summary>
// /// 数据位
// /// </summary>
// public int DataBits { get { return _mDataBits; } set { _mDataBits = value; OnPropertyChanged(); } }
// private int _mDataBits = 8;

// /// <summary>
// /// 停止位
// /// </summary>
// public string StopBits { get { return _mStopBits; } set { _mStopBits = value; OnPropertyChanged(); } }
// private string _mStopBits = "1";

// /// <summary>
// /// 校验位
// /// </summary>
// public string Parity { get { return _mParity; } set { _mParity = value; OnPropertyChanged(); } }
// private string _mParity;

// public ObservableCollection<Variable> variables { get; set; } = new ObservableCollection<Variable>();
// }

// public class Variable : ObservableObject
// {
// public int Id { get { return _mId; } set { _mId = value; OnPropertyChanged(); } }
// private int _mId;


// public string Address { get { return _mAddress; } set { _mAddress = value; OnPropertyChanged(); } }
// private string _mAddress;


// public int ReadLeng { get { return _mReadLeng; } set { _mReadLeng = value; OnPropertyChanged(); } }
// private int _mReadLeng;


// }
//}

+ 32
- 13
BPASmartClient.ViewModel/ShopDeviceConfigViewModel.cs Просмотреть файл

@@ -6,7 +6,6 @@ using System.Threading.Tasks;
using BPASmartClient.Helper;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input;
using BPASmartClient.ViewModel.Model;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
@@ -14,14 +13,16 @@ using System.Windows;
using System.IO.Ports;
using System.IO;
using Newtonsoft.Json;
using BPASmartClient.Model;

namespace BPASmartClient.ViewModel
{
public class ShopDeviceConfigViewModel : ObservableObject
{
private DeviceConfigModel configModel = new DeviceConfigModel();
private DeviceConfigModelJson configModel = new DeviceConfigModelJson();
string FileName => deviceConfig.Count > 0 ? deviceConfig[0].ShopName : string.Empty;

public static List<string> IDevices = new List<string>();
public static List<string> IPeripherals = new List<string>();
public ShopDeviceConfigViewModel()
{
ActionManage.GetInstance.Register(new Action<object[]>((o) =>
@@ -49,6 +50,17 @@ namespace BPASmartClient.ViewModel
{
if (deviceConfig.Count > 0)
{
for (int i = 0; i < deviceConfig.ElementAt(0).deviceModels.Count; i++)
{
string name = deviceConfig.ElementAt(0).deviceModels.ElementAt(i).DeviceModule;
deviceConfig.ElementAt(0).deviceModels.ElementAt(i).DeviceNamespace = IDevices.FirstOrDefault(p => p.Contains(name));

for (int m = 0; m < deviceConfig.ElementAt(0).deviceModels.ElementAt(i).communicationDevcies.Count; m++)
{
string comName = deviceConfig.ElementAt(0).deviceModels.ElementAt(i).communicationDevcies.ElementAt(m).CommunicationModule;
deviceConfig.ElementAt(0).deviceModels.ElementAt(i).communicationDevcies.ElementAt(m).CommunicationNamespace = IPeripherals.FirstOrDefault(p => p.Contains(comName));
}
}
File.WriteAllText($"{LocaPath.GetInstance().GetDeviceConfigPath}{FileName}.json", JsonConvert.SerializeObject(deviceConfig));
}
});
@@ -166,7 +178,7 @@ namespace BPASmartClient.ViewModel
/// <summary>
/// 设备信息列表
/// </summary>
public static ObservableCollection<DeviceConfigModel> deviceConfig { get; set; } = new ObservableCollection<DeviceConfigModel>();
public static ObservableCollection<DeviceConfigModelJson> deviceConfig { get; set; } = new ObservableCollection<DeviceConfigModelJson>();

/// <summary>
/// 端口号列表
@@ -211,17 +223,24 @@ namespace BPASmartClient.ViewModel
Enum.GetNames(typeof(Parity)).ToList().ForEach((item) => { Paritys.Add(item); });

DeviceModels.Clear();
DeviceModels.Add("Morks");
DeviceModels.Add("Morkt");
DeviceModels.Add("Morkic");
DeviceModels.Add("Morkjc");
IDevices.ForEach((item) =>
{
var strs = item.Split(".");
if (strs != null && strs.Length == 3)
{
DeviceModels.Add(strs[1]);
}
});

CommunicationModel.Clear();
CommunicationModel.Add("乐百");
CommunicationModel.Add("节卡");
CommunicationModel.Add("单片机");
CommunicationModel.Add("咖啡机");
CommunicationModel.Add("冰淇淋机");
IPeripherals.ForEach((item) =>
{
var strs = item.Split(".");
if (strs != null && strs.Length == 3)
{
CommunicationModel.Add(strs[1]);
}
});

Shops.Clear();
DirectoryInfo directoryInfo = new DirectoryInfo(LocaPath.GetInstance().GetDeviceConfigPath);


+ 46
- 0
BPASmartClient.ViewModel/SystemSetViewModel.cs Просмотреть файл

@@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BPASmartClient.Helper;
using BPASmartClient.Model;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input;

namespace BPASmartClient.ViewModel
{
public class SystemSetViewModel : ObservableObject
{
public SystemSetViewModel()
{
if (SaveInfoCommand == null)
{
SaveInfoCommand = new Action(() =>
{
List<ushort> values = new List<ushort>();
values.Clear();

List<bool> bools = new List<bool>();
bools.Clear();

for (int i = 0; i < Json<KeepDataBase>.Data.parSets.Count; i++)
{
values.Clear();
values.Add(Json<KeepDataBase>.Data.parSets[i].Minute);
values.Add(Json<KeepDataBase>.Data.parSets[i].Second);
bools.Add(Json<KeepDataBase>.Data.parSets[i].IsShield);
//ModbusTcpHelper.GetInstance.Write((ushort)ModbusTcpHelper.GetInstance.GetWordAddress($"VW{116 + (i * 6)}"), WriteType.HoldingRegisters, values.ToArray());
}
//ModbusTcpHelper.GetInstance.Write((ushort)ModbusTcpHelper.GetInstance.GetBoolAddress("M260.0"), WriteType.Coils, bools.ToArray());

});
}
}

public ObservableCollection<ParSet> parSets { get; set; } = Json<KeepDataBase>.Data.parSets;
public Action SaveInfoCommand { get; set; }

}
}

+ 3
- 4
BPASmartClient/App.config Просмотреть файл

@@ -12,7 +12,7 @@
<!--<add key="ClientId" value="2"/>-->

<!--开发环境-->
<add key="apollouri" value="http://10.2.1.21:28080"/>
<!--<add key="apollouri" value="http://10.2.1.21:28080"/>
<add key="orderserviceuri" value="https://bpa.black-pa.com:21527/order/"/>
<add key="stockserviceuri" value="https://bpa.black-pa.com:21527/stock/"/>
<add key="datavserviceuri" value="https://bpa.black-pa.com:21527/datav"/>
@@ -20,7 +20,7 @@
<add key="broadcastpubtopic" value="/broadcast/grgpechsl7q/transit_test_setdevice"/>
<add key="AppId" value="dev1_common"/>
<add key ="Namespaces" value="DEV.Config"/>
<add key="IsEnableTest" value="False"/>
<add key="IsEnableTest" value="False"/>-->


<!--测试环境-->
@@ -34,7 +34,6 @@
<add key ="Namespaces" value="DEV.test1.Config"/>-->

<!--正式环境-->
<!--
<add key="ApolloUri" value="http://47.108.65.220:28080"/>
<add key="OrderServiceUri" value="https://witt.black-pa.com/order/"/>
<add key="StockServiceUri" value="https://witt.black-pa.com/stock/"/>
@@ -43,7 +42,7 @@
<add key="BroadcastPubTopic" value="/broadcast/grgpECHSL7q/Transit_SetDevice"/>
<add key="AppId" value="order"/>
<add key ="Namespaces" value="TEST1.Config"/>
<add key="IsEnableTest" value="False"/>-->
<add key="IsEnableTest" value="false"/>

<!--阿里云上报启动方式:API 或者 LOCAL-->
<!--API :通过客户端ID,调用接口查询“设备连接信息”-->


+ 1
- 0
BPASmartClient/App.xaml Просмотреть файл

@@ -15,6 +15,7 @@
<ResourceDictionary Source="/BPASmartClient.CustomResource;component/RecDictionarys/RecIcoButtonStyle.xaml" />
<ResourceDictionary Source="/BPASmartClient.CustomResource;component/RecDictionarys/RecToggleButton.xaml" />
<ResourceDictionary Source="/BPASmartClient.CustomResource;component/RecDictionarys/BeveledRadioButtonStyle.xaml" />
<ResourceDictionary Source="/BPASmartClient.CustomResource;component/RecDictionarys/DatePickeerDictionary.xaml" />
<!--<ResourceDictionary Source="/BPASmartClient.CustomResource;component/Themes/GenricStyle.xaml"/>
<ResourceDictionary Source="/BPASmartClient.CustomResource;component/Themes/MyStyle.xaml"/>-->



+ 2
- 0
BPASmartClient/App.xaml.cs Просмотреть файл

@@ -114,6 +114,7 @@ namespace BPASmartClient
private void DataSave()
{
Json<KeepDataBase>.Save();
//Sqlite<Alarm>.GetInstance.Save();
}

/// <summary>
@@ -122,6 +123,7 @@ namespace BPASmartClient
private void DataRead()
{
Json<KeepDataBase>.Read();
Task.Run(new Action(() => { Sqlite<Alarm>.GetInstance.GetData(); }));
}




+ 37
- 29
BPASmartClient/Control/AdminstratorsView.xaml Просмотреть файл

@@ -1,50 +1,53 @@
<UserControl x:Class="BPASmartClient.Control.AdminstratorsView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BPASmartClient.Control"
xmlns:uc="clr-namespace:BPASmartClient.CustomResource.UserControls;assembly=BPASmartClient.CustomResource"
xmlns:helper ="clr-namespace:BPASmartClient.Control.Helper"
xmlns:vm ="clr-namespace:BPASmartClient.ViewModel;assembly=BPASmartClient.ViewModel"
mc:Ignorable="d"
d:DesignHeight="600" d:DesignWidth="800" Loaded="UserControl_Loaded">
<UserControl
x:Class="BPASmartClient.Control.AdminstratorsView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:helper="clr-namespace:BPASmartClient.Control.Helper"
xmlns:local="clr-namespace:BPASmartClient.Control"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:uc="clr-namespace:BPASmartClient.CustomResource.UserControls;assembly=BPASmartClient.CustomResource"
xmlns:vm="clr-namespace:BPASmartClient.ViewModel;assembly=BPASmartClient.ViewModel"
d:DesignHeight="600"
d:DesignWidth="800"
Loaded="UserControl_Loaded"
mc:Ignorable="d">
<UserControl.DataContext>
<vm:AdminstratorsViewModel/>
<vm:AdminstratorsViewModel />
</UserControl.DataContext>
<UserControl.Resources>
<Style x:Key="TxLogin" TargetType="TextBlock" >
<Setter Property="FontSize" Value="20"/>
<Setter Property="Foreground" Value="#ddd"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Style x:Key="TxLogin" TargetType="TextBlock">
<Setter Property="FontSize" Value="20" />
<Setter Property="Foreground" Value="#ddd" />
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</UserControl.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="7*"/>
<ColumnDefinition Width="10*"/>
<ColumnDefinition Width="7*" />
<ColumnDefinition Width="10*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="10*"/>
<RowDefinition Height="5*"/>
<RowDefinition Height="4*"/>
<RowDefinition Height="8*"/>
<RowDefinition Height="20*"/>
<RowDefinition Height="10*" />
<RowDefinition Height="5*" />
<RowDefinition Height="4*" />
<RowDefinition Height="8*" />
<RowDefinition Height="20*" />
</Grid.RowDefinitions>
<TextBlock Text="账号:"
VerticalAlignment="Bottom" HorizontalAlignment="Right"
Margin="20"
Margin="20" Foreground="#feffff"
Style="{StaticResource TxLogin}"
/>
<TextBlock Text="密码:" Grid.Row="1"
VerticalAlignment="Top" HorizontalAlignment="Right"
Margin="20"
Margin="20" Foreground="#feffff"
Style="{StaticResource TxLogin}"/>
<TextBox x:Name="tbx_admin" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2"
Text="{Binding Admin, Mode=TwoWay}"
Foreground="#F8F8FF" FontSize="20"
Width="180" Height="28"
Width="180" Height="28"
VerticalAlignment="Bottom" HorizontalAlignment="Center"
VerticalContentAlignment="Top" HorizontalContentAlignment="Center"
Margin="20"
@@ -78,7 +81,12 @@
Content="登 录"
Command="{Binding AdminLoginCommand}" IsDefault="True"/>

<uc:UserKeyBoard x:Name="myKeyboard" Grid.Row="4" Grid.ColumnSpan="2" Margin="100,10,100,50" Focusable="False"/>
<uc:UserKeyBoard
x:Name="myKeyboard"
Grid.Row="4"
Grid.ColumnSpan="2"
Margin="100,10,100,50"
Focusable="False" />
</Grid>
</UserControl>

+ 378
- 0
BPASmartClient/Control/AlarmView.xaml Просмотреть файл

@@ -0,0 +1,378 @@
<UserControl
x:Class="BPASmartClient.Control.AlarmView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BPASmartClient.Control"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:BPASmartClient.ViewModel;assembly=BPASmartClient.ViewModel"
d:DesignHeight="450"
d:DesignWidth="800"
mc:Ignorable="d">

<UserControl.DataContext>
<vm:AlarmViewModel />
</UserControl.DataContext>

<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary>
<!--<convert:TextDisplayConvert x:Key="textDisplayConvert" />
<convert:IsEnableConvert x:Key="isEnableConvert" />
<convert:AnalogAlarmConvert x:Key="analogAlarmConvert" />
<convert:DiscreteAlarmConvert x:Key="discreteAlarmConvert" />
<convert:AlarmTypeTextConvert x:Key="alarmTypeTextConvert" />-->
<SolidColorBrush x:Key="BorderSolid" Color="#5523CACA" />
<SolidColorBrush x:Key="FontColor" Color="#FF2AB2E7" />
<SolidColorBrush x:Key="TitleFontColor" Color="#ddd" />
<SolidColorBrush x:Key="CursorColor" Color="Aqua" />
<SolidColorBrush x:Key="TitleBorderColor" Color="#FF2AB2E7" />

<Style x:Key="TextBlockStyle" TargetType="TextBlock">
<Setter Property="FontFamily" Value="楷体" />
<Setter Property="FontSize" Value="18" />
<Setter Property="Foreground" Value="{StaticResource TextBlockForeground}" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>

<Style x:Key="TextBoxStyle" TargetType="TextBox">
<Setter Property="FontFamily" Value="楷体" />
<Setter Property="FontSize" Value="22" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="{StaticResource TextBlockForeground}" />
<Setter Property="BorderBrush" Value="#FF23CACA" />
<Setter Property="CaretBrush" Value="Aqua" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>

<Style x:Key="DataTextBlockStyle" TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="Red" />
<Setter Property="FontSize" Value="14" />
</Style>

<ControlTemplate x:Key="ButTemplate" TargetType="Button">
<Border
x:Name="br"
Background="Transparent"
BorderBrush="#FF19B7EC"
BorderThickness="2">
<StackPanel
HorizontalAlignment="Center"
VerticalAlignment="Center"
Orientation="Horizontal">
<ContentControl
HorizontalAlignment="Center"
VerticalAlignment="Center"
Content="{TemplateBinding Content}"
Foreground="{TemplateBinding Foreground}" />
</StackPanel>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="br" Property="Background" Value="#2219B7EC" />
</Trigger>

<Trigger Property="IsPressed" Value="true">
<Setter TargetName="br" Property="Background" Value="#2219B7EC" />
</Trigger>

</ControlTemplate.Triggers>
</ControlTemplate>

</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>

<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="30" />
<RowDefinition />
</Grid.RowDefinitions>
<StackPanel
Margin="0,8"
HorizontalAlignment="Right"
Orientation="Horizontal">

<DatePicker
Background="Transparent"
BorderBrush="#aa3aa7f3"
BorderThickness="2"
SelectedDate="{Binding StartDateTime}"
Style="{StaticResource PickerStyle}"
Text="请输入开始时间"
Visibility="{Binding IsVisibility}" />

<DatePicker
Margin="20,0,20,0"
Background="Transparent"
BorderBrush="#aa3aa7f3"
BorderThickness="2"
SelectedDate="{Binding EndDateTime}"
Style="{StaticResource PickerStyle}"
Text="请输入结束时间"
Visibility="{Binding IsVisibility}" />

<Button
Width="140"
Height="30"
Background="#FF19B7EC"
Command="{Binding ControlCommand}"
Content="{Binding ControlButText}"
FontFamily="楷体"
FontSize="18"
Template="{StaticResource ButTemplate}">
<Button.Foreground>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Color="#FFBB662A" />
<GradientStop Offset="1" Color="White" />
</LinearGradientBrush>
</Button.Foreground>
</Button>

<Button
Width="140"
Height="30"
Margin="20,0,0,0"
Background="#FF19B7EC"
Command="{Binding SwitchCommand}"
Content="{Binding ButContent}"
FontFamily="楷体"
FontSize="18"
Template="{StaticResource ButTemplate}">
<Button.Foreground>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Color="#FFBB662A" />
<GradientStop Offset="1" Color="White" />
</LinearGradientBrush>
</Button.Foreground>
</Button>

</StackPanel>

<!--#region 表格标题栏设置-->
<Grid Grid.Row="1" Background="#dd2AB2E7">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.3*" />
<ColumnDefinition Width="0.7*" />
<ColumnDefinition Width="0.7*" />
<ColumnDefinition />
<ColumnDefinition Width="0.7*" />
<ColumnDefinition Width="0.5*" />
</Grid.ColumnDefinitions>
<TextBlock
Grid.Column="0"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="16"
Foreground="{StaticResource TitleFontColor}"
Text="ID" />

<Grid Grid.Column="1">
<TextBlock
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="16"
Foreground="{StaticResource TitleFontColor}"
Text="报警日期" />
<Border
BorderBrush="{StaticResource TitleBorderColor}"
BorderThickness="1,0,1,0"
Cursor="SizeWE" />
</Grid>

<TextBlock
Grid.Column="2"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="16"
Foreground="{StaticResource TitleFontColor}"
Text="报警时间" />

<Grid Grid.Column="3">
<TextBlock
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="16"
Foreground="{StaticResource TitleFontColor}"
Text="报警信息" />
<Border
BorderBrush="{StaticResource TitleBorderColor}"
BorderThickness="1,0,1,0"
Cursor="SizeWE" />
</Grid>

<TextBlock
Grid.Column="4"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="16"
Foreground="{StaticResource TitleFontColor}"
Text="报警值" />

<Grid Grid.Column="5">
<TextBlock
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="16"
Foreground="{StaticResource TitleFontColor}"
Text="报警等级" />
<Border
BorderBrush="{StaticResource TitleBorderColor}"
BorderThickness="1,0,1,0"
Cursor="SizeWE" />
</Grid>
</Grid>
<!--#endregion-->

<!--#region 表格数据显示-->
<ScrollViewer
Grid.Row="2"
HorizontalScrollBarVisibility="Hidden"
VerticalScrollBarVisibility="Hidden">

<Grid>
<!--#region 实时报警信息-->
<ItemsControl ItemsSource="{Binding AlarmInfos}" Visibility="{Binding CurrentDataVis}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid x:Name="gr" Height="30">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.3*" />
<ColumnDefinition Width="0.7*" />
<ColumnDefinition Width="0.7*" />
<ColumnDefinition />
<ColumnDefinition Width="0.7*" />
<ColumnDefinition Width="0.5*" />
</Grid.ColumnDefinitions>

<TextBlock
Grid.Column="0"
Style="{StaticResource DataTextBlockStyle}"
Text="{Binding NumId}" />

<Grid Grid.Column="1">
<TextBlock Style="{StaticResource DataTextBlockStyle}" Text="{Binding Date}" />
<Border BorderBrush="{StaticResource BorderSolid}" BorderThickness="1,0,1,0" />
</Grid>

<TextBlock
Grid.Column="2"
Style="{StaticResource DataTextBlockStyle}"
Text="{Binding Time}" />

<Grid Grid.Column="3">
<TextBlock
Margin="10,0,0,0"
HorizontalAlignment="Left"
Style="{StaticResource DataTextBlockStyle}"
Text="{Binding Info}" />
<Border BorderBrush="{StaticResource BorderSolid}" BorderThickness="1,0,1,0" />
</Grid>

<TextBlock
Grid.Column="4"
Style="{StaticResource DataTextBlockStyle}"
Text="{Binding Value}" />

<Grid Grid.Column="5">
<TextBlock Style="{StaticResource DataTextBlockStyle}" Text="{Binding Grade}" />
<Border BorderBrush="{StaticResource BorderSolid}" BorderThickness="1,0,1,0" />
</Grid>

<Border
Grid.ColumnSpan="6"
BorderBrush="{StaticResource BorderSolid}"
BorderThickness="1" />

</Grid>

<DataTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter TargetName="gr" Property="Background" Value="#112AB2E7" />
</Trigger>
</DataTemplate.Triggers>

</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<!--#endregion-->

<!--#region 历史报警信息-->
<ItemsControl ItemsSource="{Binding HistoryAlarm}" Visibility="{Binding HistoryDataVis}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid x:Name="gr" Height="30">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.3*" />
<ColumnDefinition Width="0.7*" />
<ColumnDefinition Width="0.7*" />
<ColumnDefinition />
<ColumnDefinition Width="0.7*" />
<ColumnDefinition Width="0.5*" />
</Grid.ColumnDefinitions>

<TextBlock
Grid.Column="0"
Style="{StaticResource DataTextBlockStyle}"
Text="{Binding Id}" />

<Grid Grid.Column="1">
<TextBlock Style="{StaticResource DataTextBlockStyle}" Text="{Binding Date}" />
<Border BorderBrush="{StaticResource BorderSolid}" BorderThickness="1,0,1,0" />
</Grid>

<TextBlock
Grid.Column="2"
Style="{StaticResource DataTextBlockStyle}"
Text="{Binding Time}" />

<Grid Grid.Column="3">
<TextBlock
Margin="10,0,0,0"
HorizontalAlignment="Left"
Style="{StaticResource DataTextBlockStyle}"
Text="{Binding Info}" />
<Border BorderBrush="{StaticResource BorderSolid}" BorderThickness="1,0,1,0" />
</Grid>

<TextBlock
Grid.Column="4"
Style="{StaticResource DataTextBlockStyle}"
Text="{Binding Value}" />

<Grid Grid.Column="5">
<TextBlock Style="{StaticResource DataTextBlockStyle}" Text="{Binding Grade}" />
<Border BorderBrush="{StaticResource BorderSolid}" BorderThickness="1,0,1,0" />
</Grid>

<Border
Grid.ColumnSpan="6"
BorderBrush="{StaticResource BorderSolid}"
BorderThickness="1" />

</Grid>

<DataTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter TargetName="gr" Property="Background" Value="#112AB2E7" />
</Trigger>
</DataTemplate.Triggers>

</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<!--#endregion-->
</Grid>
</ScrollViewer>
<!--#endregion-->


</Grid>
</UserControl>

+ 28
- 0
BPASmartClient/Control/AlarmView.xaml.cs Просмотреть файл

@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BPASmartClient.Control
{
/// <summary>
/// AlarmView.xaml 的交互逻辑
/// </summary>
public partial class AlarmView : UserControl
{
public AlarmView()
{
InitializeComponent();
}
}
}

+ 74
- 0
BPASmartClient/Control/LogOrAlarmIOTView.xaml Просмотреть файл

@@ -0,0 +1,74 @@
<UserControl x:Class="BPASmartClient.Control.LogOrAlarmIOTView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BPASmartClient.Control"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/BPASmartClient.CustomResource;component/Themes/GenricStyle.xaml" />
<ResourceDictionary Source="/BPASmartClient.CustomResource;component/Themes/MyStyle.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="45" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>

<!-- 查询按钮栏 -->
<StackPanel Margin="10,0,50,0" Orientation="Horizontal" HorizontalAlignment="Right">
<Button Margin="10,0,0,0" Cursor="Hand" Command="{Binding QueryCommand}" >查询数据</Button>
</StackPanel>
<!-- 表格栏 -->
<Grid Grid.Row="1">
<DataGrid Margin="10" ItemsSource="{Binding LogDataFile, UpdateSourceTrigger=PropertyChanged}" Grid.Row="2">
<DataGrid.Columns>
<DataGridTemplateColumn Header="文件名称" Width="250">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" FontSize="14" Foreground="{Binding foreground, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

<DataGridTemplateColumn Header="上传时间" Width="250">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding utcCreatedOn, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" FontSize="14" Foreground="{Binding foreground, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

<DataGridTemplateColumn Header="文件大小" Width="100">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding size, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" FontSize="14" Foreground="{Binding foreground, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="文件ID" Width="300">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{Binding fileId, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" FontSize="14" Foreground="{Binding foreground, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

<DataGridTemplateColumn Header=" " Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Tag="{Binding downloadUrl, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" ToolTip="{Binding name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="10,5,0,5" Click="Button_Click">文件下载</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>

</Grid>
</Grid>
</UserControl>

+ 70
- 0
BPASmartClient/Control/LogOrAlarmIOTView.xaml.cs Просмотреть файл

@@ -0,0 +1,70 @@
using BPASmartClient.CustomResource.UserControls;
using BPASmartClient.CustomResource.UserControls.MessageShow;
using BPASmartClient.Helper;
using BPASmartClient.ViewModel;
using DataVAPI.Tool.IOT;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BPASmartClient.Control
{
/// <summary>
/// LogOrAlarmIOTView.xaml 的交互逻辑
/// </summary>
public partial class LogOrAlarmIOTView : UserControl
{
public LogOrAlarmIOTView()
{
InitializeComponent();
this.DataContext = LogOrAlarmIOTViewModel.GetInstance();
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
Button button = (Button)sender;
if (button.Tag != null)
{
string url=button.Tag.ToString();
SaveFileDialog openfile = new SaveFileDialog();
openfile.Filter = "log文件(*.log)|*.log";
openfile.FileName = button.ToolTip.ToString();
if (openfile.ShowDialog() == false)
{
return;
}
string path = openfile.FileName;
Tools.HttpDownloadFile(url,path);
NoticeDemoViewModel.OpenMsg(EnumPromptType.Info, MainViewModel.GetInstance().window, "提示", $"下载成功!");
string msg = string.Format("下载成功,是否打开!");
if (System.Windows.MessageBox.Show(msg, "提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
{
logHelper.GetLogConfigInstance().OpenFile(openfile.FileName);
}
}
}
catch (Exception ex)
{
NoticeDemoViewModel.OpenMsg(EnumPromptType.Error, MainViewModel.GetInstance().window, "提示", $"下载失败!");
}
}
}
}

+ 0
- 10
BPASmartClient/Control/LogOrAlarmView.xaml.cs Просмотреть файл

@@ -26,15 +26,5 @@ namespace BPASmartClient.Control
InitializeComponent();
this.DataContext = LogOrAlarmViewModel.GetInstance();
}

private void CheckBox_Checked(object sender, RoutedEventArgs e)
{

}

private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
{

}
}
}

+ 7
- 7
BPASmartClient/Control/OrderStatusView.xaml Просмотреть файл

@@ -36,7 +36,7 @@
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<!--<RowDefinition />-->
<RowDefinition />
</Grid.RowDefinitions>

<!--#region 制作中的订单列表-->
@@ -118,8 +118,8 @@
<!--#region 表格数据显示-->
<ScrollViewer
Grid.Row="1"
HorizontalScrollBarVisibility="Visible"
VerticalScrollBarVisibility="Visible">
HorizontalScrollBarVisibility="Hidden"
VerticalScrollBarVisibility="Hidden">
<ItemsControl ItemsSource="{Binding orderStatusLists}">
<ItemsControl.ItemTemplate>
<DataTemplate>
@@ -206,7 +206,7 @@

<!--#region 表格标题栏设置-->

<!--<Grid Background="#dd2AB2E7">
<Grid Background="#dd2AB2E7">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.3*" />
<ColumnDefinition />
@@ -271,13 +271,13 @@
Foreground="{StaticResource TitleFontColor}"
Text="完成时间" />

</Grid>-->
</Grid>

<!--#endregion-->

<!--#region 表格数据显示-->

<!--<ScrollViewer
<ScrollViewer
Grid.Row="1"
HorizontalScrollBarVisibility="Hidden"
VerticalScrollBarVisibility="Hidden">
@@ -352,7 +352,7 @@
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>-->
</ScrollViewer>

<!--#endregion-->



+ 3
- 3
BPASmartClient/Control/ShopDeviceConfigView.xaml Просмотреть файл

@@ -7,7 +7,7 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:pry="clr-namespace:BPASmartClient.CustomResource.UserControls;assembly=BPASmartClient.CustomResource"
xmlns:vm="clr-namespace:BPASmartClient.ViewModel;assembly=BPASmartClient.ViewModel"
xmlns:vmm="clr-namespace:BPASmartClient.ViewModel.Model;assembly=BPASmartClient.ViewModel"
xmlns:vmm="clr-namespace:BPASmartClient.Model;assembly=BPASmartClient.Model"
d:DesignHeight="900"
d:DesignWidth="1200"
mc:Ignorable="d">
@@ -425,7 +425,7 @@
<TreeView.Resources>

<!-- 店铺信息 -->
<HierarchicalDataTemplate DataType="{x:Type vmm:DeviceConfigModel}" ItemsSource="{Binding deviceModels}">
<HierarchicalDataTemplate DataType="{x:Type vmm:DeviceConfigModelJson}" ItemsSource="{Binding deviceModels}">
<StackPanel>
<TextBlock Style="{StaticResource TextBlockStyle}" Text="{Binding ShopName}">
<TextBlock.ContextMenu>
@@ -924,7 +924,7 @@
Grid.Row="1"
HorizontalScrollBarVisibility="Hidden"
VerticalScrollBarVisibility="Hidden">
<ItemsControl ItemsSource="{Binding SelectedValue.communicationPar.variables, ElementName=tv, Mode=TwoWay}">
<ItemsControl ItemsSource="{Binding SelectedValue.variables, ElementName=tv, Mode=TwoWay}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Height="30">


+ 5
- 5
BPASmartClient/Control/ShopDeviceConfigView.xaml.cs Просмотреть файл

@@ -16,8 +16,8 @@ using System.Windows.Navigation;
using System.Windows.Shapes;
using BPASmartClient.DialogWindow;
using BPASmartClient.Helper;
using BPASmartClient.Model;
using BPASmartClient.ViewModel;
using BPASmartClient.ViewModel.Model;
using Newtonsoft.Json;

namespace BPASmartClient.Control
@@ -81,13 +81,13 @@ namespace BPASmartClient.Control
int commIndex = Array.FindIndex(ShopDeviceConfigViewModel.deviceConfig.ElementAt(0).deviceModels.ElementAt(index).communicationDevcies.ToArray(), p => p.DeviceModelId == communicationModel.DeviceModelId);
if (commIndex >= 0 && commIndex < ShopDeviceConfigViewModel.deviceConfig.ElementAt(0).deviceModels.ElementAt(index).communicationDevcies.Count)
{
if (ShopDeviceConfigViewModel.deviceConfig.ElementAt(0).deviceModels.ElementAt(index).communicationDevcies.ElementAt(commIndex).communicationPar.variables.Count <= 0)
if (ShopDeviceConfigViewModel.deviceConfig.ElementAt(0).deviceModels.ElementAt(index).communicationDevcies.ElementAt(commIndex).variables.Count <= 0)
{
for (int i = 0; i < 20; i++)
{
ShopDeviceConfigViewModel.deviceConfig.ElementAt(0).deviceModels.ElementAt(index).communicationDevcies.ElementAt(commIndex).communicationPar.variables.Add(new Variable()
ShopDeviceConfigViewModel.deviceConfig.ElementAt(0).deviceModels.ElementAt(index).communicationDevcies.ElementAt(commIndex).variables.Add(new Variable()
{
Id = ShopDeviceConfigViewModel.deviceConfig.ElementAt(0).deviceModels.ElementAt(index).communicationDevcies.ElementAt(commIndex).communicationPar.variables.Count,
Id = ShopDeviceConfigViewModel.deviceConfig.ElementAt(0).deviceModels.ElementAt(index).communicationDevcies.ElementAt(commIndex).variables.Count,
Address = string.Empty,
ReadLeng = 0
});
@@ -140,7 +140,7 @@ namespace BPASmartClient.Control
if (file != null && File.Exists(file.FullName))
{
string JsonString = File.ReadAllText(file.FullName);
var result = JsonConvert.DeserializeObject<ObservableCollection<DeviceConfigModel>>(JsonString);
var result = JsonConvert.DeserializeObject<ObservableCollection<DeviceConfigModelJson>>(JsonString);
if (result != null)
{
ShopDeviceConfigViewModel.deviceConfig.Clear();


+ 142
- 10
BPASmartClient/Control/SystemSetView.xaml Просмотреть файл

@@ -1,12 +1,144 @@
<UserControl x:Class="BPASmartClient.Control.SystemSetView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BPASmartClient.Control"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Label FontSize="100" >系统参数设置界面</Label>
<UserControl
x:Class="BPASmartClient.Control.SystemSetView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BPASmartClient.Control"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:pry="clr-namespace:BPASmartClient.CustomResource.UserControls;assembly=BPASmartClient.CustomResource"
xmlns:vm="clr-namespace:BPASmartClient.ViewModel;assembly=BPASmartClient.ViewModel"
d:DesignHeight="450"
d:DesignWidth="800"
mc:Ignorable="d">

<UserControl.DataContext>
<vm:SystemSetViewModel />
</UserControl.DataContext>

<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary>
<Style x:Key="TextBlockStyle" TargetType="TextBlock">
<Setter Property="FontFamily" Value="楷体" />
<Setter Property="FontSize" Value="18" />
<Setter Property="Foreground" Value="{StaticResource TextBlockForeground}" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>

<Style x:Key="TextBoxStyle" TargetType="TextBox">
<Setter Property="FontFamily" Value="楷体" />
<Setter Property="FontSize" Value="22" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="{StaticResource TextBlockForeground}" />
<Setter Property="BorderBrush" Value="#FF23CACA" />
<Setter Property="CaretBrush" Value="Aqua" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>

</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

</UserControl.Resources>

<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="40" />
<RowDefinition Height="35" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>

<CheckBox
Grid.Row="0"
Grid.Column="2"
Height="20"
Margin="10"
VerticalAlignment="Top"
Background="#FF2AB2E7"
Content="开机启动"
FontSize="14"
Foreground="#00c2f4"
IsChecked="{Binding IsSelected}"
Template="{StaticResource CbTemplate}" />

<StackPanel
Grid.Row="1"
HorizontalAlignment="Right"
Orientation="Horizontal">

<TextBlock Style="{StaticResource TextBlockStyle}" Text="请点击按钮保存参数:" />

<pry:IcoButton
Grid.Column="5"
Width="140"
HorizontalAlignment="Left"
Command="{Binding SaveInfoCommand}"
Content="保存配置"
FontSize="16"
IcoText="&#xe936;"
Style="{StaticResource NewButtonStyle}">
<pry:IcoButton.Foreground>
<LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Color="#FFBB662A" />
<GradientStop Offset="1" Color="White" />
</LinearGradientBrush>
</pry:IcoButton.Foreground>
</pry:IcoButton>


</StackPanel>

<!-- 参数放置面板 -->
<Grid Grid.Row="2">
<ItemsControl ItemsSource="{Binding parSets}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Style="{StaticResource TextBlockStyle}" Text="{Binding TextBlockContext}" />
<TextBox
Width="100"
Margin="10,0,0,0"
VerticalAlignment="Center"
Background="Transparent"
BorderBrush="#FF23CACA"
CaretBrush="Aqua"
FontFamily="楷体"
FontSize="21"
Foreground="#ff34f7f7"
Text="{Binding Minute}" />
<TextBlock Style="{StaticResource TextBlockStyle}" Text="(分)" />
<TextBox
Width="100"
Margin="0,10"
VerticalAlignment="Center"
Background="Transparent"
BorderBrush="#FF23CACA"
CaretBrush="Aqua"
FontFamily="楷体"
FontSize="21"
Foreground="#ff34f7f7"
Text="{Binding Second}" />
<TextBlock Style="{StaticResource TextBlockStyle}" Text="(秒)" />

<CheckBox
Height="20"
Margin="10"
VerticalAlignment="Center"
Background="#FF2AB2E7"
Content="{Binding CheckBoxContext}"
FontSize="14"
Foreground="#00c2f4"
IsChecked="{Binding IsShield}"
Template="{StaticResource CbTemplate}" />

</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

</Grid>

</Grid>
</UserControl>

+ 9
- 7
BPASmartClient/DeviceInfo.xml Просмотреть файл

@@ -35,6 +35,7 @@
<!--<IpAddress>192.168.6.1</IpAddress>
<Port>502</Port>
<PLCReadAddress>M,M0.1,1;M,M1.0,8;M,M2.0,9;M,M8.0,4;M,M13.5,1;M,M16.0,7;</PLCReadAddress>-->
<!--
</Parameters>
</Peripheral>
<Peripheral Module="BPASmartClient.GSIceCream.IceCreamMachine">
@@ -57,7 +58,7 @@
</Parameters>
</Peripheral>-->
</Peripherals>
</Device>
</Device>-->


<!--<Device Name="MorkF" Module="BPASmartClient.MorkF.Control_MorkF" DeviceId="2">
@@ -70,18 +71,19 @@
</Parameters>
</Peripheral>
</Peripherals>
</Device>
</Device>-->

<Device Name="Morks" Module="BPASmartClient.MorkS.Control_Morks" DeviceId="28">
<Device Name="Morks" Module="BPASmartClient.MorkS.Control_Morks" DeviceId="100">
<Peripherals>
<Peripheral Module="BPASmartClient.PLC.PLCMachine">
<Parameters>
<IpAddress>192.168.1.11</IpAddress>
<Port>508</Port>
<PLCReadAddress>M,M550.0,16;M,M0.3,3;M,M100.0,16;M,M235.0,1;M,M102.0,7;M,M103.0,6;VW,VW372,1</PLCReadAddress>
<IpAddress>127.0.0.1</IpAddress>
<Port>502</Port>
<PLCReadAddress>M,M230.0,24;M,M0.3,3;M,M100.0,16;M,M235.0,1;M,M102.0,7;M,M103.0,6;VW,VW372,1</PLCReadAddress>
<!--<PLCReadAddress>M,M230.0,24</PLCReadAddress>-->
</Parameters>
</Peripheral>
</Peripherals>
</Device>-->
</Device>

</BPADevices>

+ 35
- 50
BPASmartClient/MainWindow.xaml Просмотреть файл

@@ -26,7 +26,6 @@
</ResourceDictionary>
</Window.Resources>


<Border x:Name="br" Style="{DynamicResource border主窗体背景}">
<Grid>
<Grid.RowDefinitions>
@@ -108,6 +107,12 @@
Header="设备监视"
Tag="DeviceMonitorView" />
<Separator />
<MenuItem
Click="MenuItem_Click"
FontSize="12"
Header="报警监视"
Tag="AlarmView" />
<Separator />
<MenuItem
Click="MenuItem_Click"
FontSize="12"
@@ -119,14 +124,14 @@
<MenuItem
Click="MenuItem_Click"
FontSize="12"
Header="日志/告警查询"
Header="本地日志查询"
Tag="LogOrAlarmView" />
<Separator />
<MenuItem
Click="MenuItem_Click"
FontSize="12"
Header="维护查询"
Tag="LogOrAlarmView" />
Header="云端日志下载"
Tag="LogOrAlarmIOTView" />
</MenuItem>
<MenuItem Header="参数配置">
<MenuItem
@@ -214,64 +219,46 @@
Grid.Row="0"
Grid.RowSpan="2"
Style="{DynamicResource border右下}" />
<Border
Grid.Row="0"
Grid.RowSpan="2"
Style="{DynamicResource border左下}" />
<Border
Grid.Row="0"
Grid.RowSpan="2"
Style="{DynamicResource border右上}" />
<Border
Grid.Row="0"
Grid.RowSpan="2"
Style="{DynamicResource border左上}" />
<Grid Margin="10">
<Border Width="600" Style="{DynamicResource borderFromTitle}" />
<Button
Grid.Row="0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Click="Button_Click"
Content="测试"
Cursor="Hand" />
<Button
Grid.Row="0"
Width="100"
Margin="100,0,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Click="Button_Click_1"
Content="测试消息弹窗"
Cursor="Hand"/>

<!--<Button
Name="save"
Grid.Row="0"
Width="100"
Margin="230,0,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Click="Button_Click_2"
Content="保存订单数据"
Cursor="Hand"
Style="{DynamicResource CommonBtn_返回}" />-->

<Button
Name="init"
<StackPanel Orientation="Horizontal" >
<CheckBox
Content="开机启动" Margin="5,0,5,0"
IsChecked="{Binding AutoStart}" />
<Button
Name="init" Margin="5,0,5,0"
Grid.Row="0"
Width="90"
Margin="230,0,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Click="init_Click"
Content="初始化设备"
Cursor="Hand"/>

<CheckBox
Margin="350,0,0,0"
Content="开机启动"
IsChecked="{Binding AutoStart}" />
Cursor="Hand" />
<Button
Grid.Row="0" Margin="5,0,5,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Click="Button_Click"
Content="测试"
Cursor="Hand" />
</StackPanel>

<TextBlock
x:Name="Title"
@@ -280,11 +267,12 @@
Foreground="#feffff">
日志监控界面
</TextBlock>
<Button
Name="login"
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Button
Name="login" Margin="5,0,5,0"
Grid.Row="0"
Width="45"
Margin="0,0,60,0"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Click="Button_Login"
@@ -294,20 +282,17 @@
Name="logout"
Grid.Row="0"
Width="45"
Margin="350,0,0,0"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Click="Button_LogOut"
Command="{Binding LogoutCommand}"
Content="注销"
Cursor="Hand" />
</Grid>
<!--#region 底部窗体栏-->

<ContentControl x:Name="contentRegion" Grid.Row="1" />
<!--#endregion-->
<!--<Button Grid.Row="2" Content="返回" Style="{DynamicResource CommonBtn_返回}" HorizontalAlignment="Left" VerticalAlignment="Top" Click="Button_Click"/>

<Button Grid.Row="2" Visibility="Collapsed" Content="测试" HorizontalAlignment="Left" Margin="153,123,0,0" VerticalAlignment="Top" Click="Button_Click"/>-->
</Grid>




+ 135
- 52
BPASmartClient/MainWindow.xaml.cs Просмотреть файл

@@ -11,9 +11,11 @@ using BPASmartClient.Message;
using BPASmartClient.Model;
using BPASmartClient.Model.冰淇淋.Enum;
using BPASmartClient.Model.咖啡机.Enum;
using BPASmartClient.Peripheral;
using BPASmartClient.ViewModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
@@ -35,6 +37,7 @@ namespace BPASmartClient
/// </summary>
public partial class MainWindow : Window
{
public MainConsole mainConsole;
public MainWindow()
{
InitializeComponent();
@@ -70,7 +73,9 @@ namespace BPASmartClient

ThreadManage.GetInstance().Start(new Action(() =>
{
new MainConsole().Start();
mainConsole = new MainConsole();
mainConsole.Start();
GetDevices();
}), "启动主控制台", false);

ThreadManage.GetInstance().Start(new Action(() =>
@@ -84,10 +89,114 @@ namespace BPASmartClient
{
MessageLog.GetInstance.ShowEx(ex.ToString());
}

}), "启动主IoT", false);

ActionManage.GetInstance.Register(new Action<object>((o) =>
{
App.Current.Dispatcher.Invoke(new Action(() =>
{
if (o is IOTCommandModel iot)
{
switch (iot.CommandName)
{
case 0://控制类
if (iot.CommandValue != null && iot.CommandValue.Count>0)
{
switch (iot.CommandValue.Keys.ToList()[0])
{
case "程序启动":
//mainConsole.Start();
break;
//mainConsole.Stop();
case "程序停止":
break;
case "程序复位":
//mainConsole.Stop();
//mainConsole.Start();
break;
default:
break;
}
NoticeDemoViewModel.OpenMsg(EnumPromptType.Info, MainViewModel.GetInstance().window, "大屏控制", iot.CommandValue.Keys.ToList()[0]);
}
break;
case 1://设置类
break;
case 2://通知类
if (iot.CommandValue != null && iot.CommandValue.ContainsKey("text"))
{
NoticeDemoViewModel.OpenMsg(EnumPromptType.Info, MainViewModel.GetInstance().window, "大屏通知", iot.CommandValue["text"]);
}
break;
default:
break;
}
}
}));
}), "IotBroadcast");
}
/// <summary>
/// 获取设备集合
/// </summary>
private void GetDevices()
{
//List<string> IDevices = new List<string>();
//List<string> IPeripherals = new List<string>();

DirectoryInfo directoryInfo = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
var files = directoryInfo.GetFiles().Where(p => p.FullName.Contains("BPASmartClient.") && p.FullName.Contains("dll")).ToList();
List<string> fileList = new List<string>();

var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var dlls = assemblies?.Where(p => p.FullName.Contains("BPASmartClient.")).ToList();
List<string> dllList = new List<string>();

if (files != null)
{
foreach (var item in files)
{
var res = System.IO.Path.GetFileNameWithoutExtension(item.FullName);
if (res != null && res.Length > 0 && res.Contains(".") && !res.Contains("dll")) fileList.Add(res);
}
}

if (dlls != null)
{
dlls.ForEach((item) =>
{
item.GetTypes().ToList().ForEach((type) =>
{
if (type.GetInterfaces().Contains(typeof(IDevice)))
{
if (!type.FullName.Contains("BaseDevice")) ShopDeviceConfigViewModel.IDevices.Add(type.FullName);
}
else if (type.GetInterfaces().Contains(typeof(IPeripheral)))
{
if (!type.FullName.Contains("BasePeripheral")) ShopDeviceConfigViewModel.IPeripherals.Add(type.FullName);
}
});

dllList.Add(System.IO.Path.GetFileNameWithoutExtension(item.EscapedCodeBase));
});
}

dllList.ForEach((item) => { if (fileList.Contains(item)) fileList.Remove(item); });

fileList.ForEach((item) =>
{
Assembly.Load(item).GetTypes().ToList().ForEach((type) =>
{
if (type.GetInterfaces().Contains(typeof(IDevice)))
{
if (!type.FullName.Contains("BaseDevice")) ShopDeviceConfigViewModel.IDevices.Add(type.FullName);
}
else if (type.GetInterfaces().Contains(typeof(IPeripheral)))
{
if (!type.FullName.Contains("BasePeripheral")) ShopDeviceConfigViewModel.IPeripherals.Add(type.FullName);
}
});
});

}
#endregion

@@ -141,8 +250,12 @@ namespace BPASmartClient
}
#endregion


#region 临时测试代码
/// <summary>
/// 测试按钮
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Click(object sender, RoutedEventArgs e)
{
//new Demo_MakeCoffeeEvent() { Id = 1 }.Publish();
@@ -153,56 +266,20 @@ namespace BPASmartClient
var temp = BPAPackage.Make(morkOrderPush, 12, BPA.Message.Enum.DeviceClientType.MORKS);
Plugin.GetInstance().GetPlugin<MQTTMgr>().Publish("DOWN/MORKS/ORDER/12", temp.Serialize());
}

private void Button_Click_1(object sender, RoutedEventArgs e)
{
NoticeDemoViewModel.OpenMsg(EnumPromptType.Info, this, "我是标题", "我是消息内容!我是消息内容!我是消息内容!我是消息内容!");
NoticeDemoViewModel.OpenMsg(EnumPromptType.Error, this, "我是标题", "我是消息内容!我是消息内容!我是消息内容!我是消息内容!");
NoticeDemoViewModel.OpenMsg(EnumPromptType.Warn, this, "我是标题", "我是消息内容!我是消息内容!我是消息内容!我是消息内容!");
NoticeDemoViewModel.OpenMsg(EnumPromptType.Success, this, "我是标题", "我是消息内容!我是消息内容!我是消息内容!我是消息内容!");
}

#endregion

private void Button_Click_2(object sender, RoutedEventArgs e)
{
//this.save.IsEnabled = false;
Task.Run(new Action(() =>
{
var res = Json<KeepDataBase>.Data.orderLists.FirstOrDefault(p => p.DeviceId == "2")?.morkOrderPushes;
if (res != null)
{
string info = string.Empty;
int count = 0;
foreach (var item in res)
{
info = $"SuborderId:= {item.OrderPush.SuborderId},SortNum:= {item.OrderPush.SortNum},GoodsName:= {item.OrderPush.GoodsName} \r\n {info}";
count++;
if (count >= 1000)
{
TextHelper.GetInstance.WriteTextInfo(info, $"订单信息-{DateTime.Now.ToString("HH-mm-ss")}-{count}", "Morks");
info = string.Empty;
count = 0;
}
}
if (info != string.Empty)
{
TextHelper.GetInstance.WriteTextInfo(info, $"订单信息-{DateTime.Now.ToString("HH-mm-ss")}-{count}", "Morks");
info = string.Empty;
count = 0;
}
}
//App.Current.Dispatcher.Invoke(new Action(() => { this.save.IsEnabled = true; }));
}));


}

/// <summary>
/// 初始化
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void init_Click(object sender, RoutedEventArgs e)
{
ActionManage.GetInstance.Send("InitDevice");
}

/// <summary>
/// 登录
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Login(object sender, RoutedEventArgs e)
{
try
@@ -218,12 +295,18 @@ namespace BPASmartClient

MessageLog.GetInstance.ShowEx($"BPASmartClient 中引发错误,MainWindow.xaml.cs 类MenuItem_Click(),描述:[{ex.Message}]");
}
}

}
/// <summary>
/// 注销
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_LogOut(object sender, RoutedEventArgs e)
{
myMenu.Visibility = Visibility.Hidden;
}
#endregion

}
}

Загрузка…
Отмена
Сохранить