Commit aac03067 张东亮

init

0 个父辈
正在显示 116 个修改的文件 包含 4862 行增加0 行删除
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
project.fragment.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
#*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
\ No newline at end of file

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30523.141
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common", "source\Common\Common.csproj", "{43CDD09E-FCF3-4960-A01D-3BBFE9933122}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DeviceLibrary", "source\DeviceLibrary\DeviceLibrary.csproj", "{513BC1C9-800D-43A6-9499-3700BAEC3554}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UserFromControl", "source\UserFromControl\UserFromControl.csproj", "{F018462A-D9BC-4365-97F2-F6D71751641E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LoadCSVLibrary", "source\LoadCVSLibrary\LoadCSVLibrary.csproj", "{064BEBF5-8FAA-4EA2-A5F3-A06E6E7D9251}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VMILineClient", "source\VMILineClient\VMILineClient.csproj", "{0D2542F5-DD62-4352-82D0-383D9A045E74}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{43CDD09E-FCF3-4960-A01D-3BBFE9933122}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{43CDD09E-FCF3-4960-A01D-3BBFE9933122}.Debug|Any CPU.Build.0 = Debug|Any CPU
{43CDD09E-FCF3-4960-A01D-3BBFE9933122}.Release|Any CPU.ActiveCfg = Release|Any CPU
{43CDD09E-FCF3-4960-A01D-3BBFE9933122}.Release|Any CPU.Build.0 = Release|Any CPU
{513BC1C9-800D-43A6-9499-3700BAEC3554}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{513BC1C9-800D-43A6-9499-3700BAEC3554}.Debug|Any CPU.Build.0 = Debug|Any CPU
{513BC1C9-800D-43A6-9499-3700BAEC3554}.Release|Any CPU.ActiveCfg = Release|Any CPU
{513BC1C9-800D-43A6-9499-3700BAEC3554}.Release|Any CPU.Build.0 = Release|Any CPU
{F018462A-D9BC-4365-97F2-F6D71751641E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F018462A-D9BC-4365-97F2-F6D71751641E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F018462A-D9BC-4365-97F2-F6D71751641E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F018462A-D9BC-4365-97F2-F6D71751641E}.Release|Any CPU.Build.0 = Release|Any CPU
{064BEBF5-8FAA-4EA2-A5F3-A06E6E7D9251}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{064BEBF5-8FAA-4EA2-A5F3-A06E6E7D9251}.Debug|Any CPU.Build.0 = Debug|Any CPU
{064BEBF5-8FAA-4EA2-A5F3-A06E6E7D9251}.Release|Any CPU.ActiveCfg = Release|Any CPU
{064BEBF5-8FAA-4EA2-A5F3-A06E6E7D9251}.Release|Any CPU.Build.0 = Release|Any CPU
{0D2542F5-DD62-4352-82D0-383D9A045E74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0D2542F5-DD62-4352-82D0-383D9A045E74}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0D2542F5-DD62-4352-82D0-383D9A045E74}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0D2542F5-DD62-4352-82D0-383D9A045E74}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {5459501E-8250-488F-B563-3C6777AEFCBA}
EndGlobalSection
EndGlobal
文件属性发生变化
此文件类型无法预览
此文件类型无法预览
此文件类型无法预览
此文件的差异被折叠, 点击展开。
此文件类型无法预览
此文件类型无法预览
此文件类型无法预览
此文件类型无法预览
文件属性发生变化
文件属性发生变化
此文件类型无法预览
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{43CDD09E-FCF3-4960-A01D-3BBFE9933122}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>OnlineStore.Common</RootNamespace>
<AssemblyName>Common</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="log4net, Version=1.2.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\dll\log4net.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json">
<HintPath>..\..\dll\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="bean\Bean.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Setting_Init.cs" />
<Compile Include="util\ConfigAppSettings.cs" />
<Compile Include="util\FormUtil.cs" />
<Compile Include="util\HttpHelper.cs" />
<Compile Include="util\JsonHelper.cs" />
<Compile Include="util\LogUtil.cs" />
<Compile Include="util\MyWebClient.cs">
<SubType>Component</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<WCFMetadata Include="Service References\" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Common")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Common")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("f8eab140-5f98-4df7-842c-0d866e759c9a")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
[assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyVersion("1.0.0.0")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OnlineStore.Common
{
/// <summary>
/// 记录配置的key
/// </summary>
public class Setting_Init
{
public static string Server_Log_Open = "Server_Log_Open";
/// <summary>
/// 系统启动时自动启动VMI流水线,=1时自动启动,并隐藏窗口,=0时不需要
/// </summary>
public static string App_AutoRun = "App_AutoRun";
/// <summary>
/// 系统主界面标题
/// </summary>
public static string App_Title = "App_Title";
public static string http_server = "http.server";
public static string Line_Config = "Line_Config";
public static string UseAIOBOX = "UseAIOBOX";
/// <summary>
/// 是否调试状态
/// </summary>
public static string IsInDebug = "IsInDebug";
public static string AgvServerIp = "AgvServerIp";
public static string Agv_Log_Open = "Agv_Log_Open";
public static string RfidServer_Port = "RfidServer_Port";
}
}
文件属性发生变化
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OnlineStore.Common
{
/// <summary>
/// 与服务器通信用对象
/// </summary>
public class Operation
{
/// <summary>
/// VMI流水线唯一标识
/// </summary>
private string _cid = "";
public string cid
{
get { return _cid; }
set { _cid = value; }
}
/// <summary>
/// 请求序列号
/// </summary>
public int seq { get; set; }
/// <summary>
/// 操作码(0无操作(发送VMI流水线状态给服务器),
/// 1扫码入库(扫码成功后发送给服务器),
/// 2 出库(服务器发送),3表示错误信息 )
/// 4,发送给服务表示二维码扫码入库,收到开始扫码
/// </summary>
public int op { get; set; }
/// <summary>
/// 操作相关数据,
/// op=1时,客户端发送 code 二维码给服务器,服务器返回时有:posId库位编号,plateW:料盘宽度,plateH:料盘高度
/// 如果需要更新温湿度的报警值,服务器会发送alarmTemperature,alarmHumidity给客户端,客户端缓存,如果没有发送,不处理
/// op=3时,data发送BoxID和AlarmCode
/// =4时扫码入库
/// =5时服务器发送预警温度
/// </summary>
private Dictionary<string, string> _data = new Dictionary<string, string>();
public Dictionary<string, string> data
{
get { return _data; }
set { _data = value; }
}
/// <summary>
/// 整体VMI流水线状态
/// 1=正常运行中
/// 2=急停中
/// 3=故障(气压检测不到等,用msg发送详细故障说明)
/// 4=警告(用msg发送提醒,如出库到达工位但是没有工人操作)
/// </summary>
public int status { get; set; }
/// <summary>
/// 提示消息
/// 出入库错误: BOX正在调试中,不能出入库
/// 出入库错误: 急停了不能出入库
/// 入库错误:料盘过大,放不到指定的位置中去
/// 故障:气压信号检测不到
/// 警告:出库盘到达工位但是没有工人操作
/// </summary>
public string msg { get; set; }
/// <summary>
/// 包含的多个 BOX 的状态信息
/// </summary>
public Dictionary<int, BoxStatus> boxStatus = new Dictionary<int, BoxStatus>();
/// <summary>
/// 报警集合
/// </summary>
public List<AlarmInfo> alarmList = new List<AlarmInfo>();
}
/// <summary>
/// 单台VMI流水线状态(包含流水线)
/// </summary>
public class BoxStatus
{
/// <summary>
/// Box编号,从1开始
/// </summary>
public int boxId { get; set; }
/// <summary>
/// 单台BOX状态
/// 急停,故障,调试中,就绪状态(正常待机)
/// 入库执行中,入库完成,入库失败
/// 出库执行中,出库完成,出库失败
/// </summary>
public int status { get; set; }
/// <summary>
/// 单台BOX的消息
/// 正在调试中,不能出入库
/// 入库失败原因:
/// 出库失败原因:
/// </summary>
public string msg { get; set; }
/// <summary>
/// 温度
/// </summary>
public string temperature { get; set; }
/// <summary>
/// 湿度
/// </summary>
public string humidity { get; set; }
/// <summary>
/// 操作相关数据,
/// 出库完成后发送posId库位编号给服务器
/// </summary>
private Dictionary<string, string> _data = new Dictionary<string, string>();
public Dictionary<string, string> data
{
get { return _data; }
set { _data = value; }
}
}
public class AlarmInfo
{
public AlarmInfo(int StoreID, int aType, string alarmDetial, string WarnMsg, int inoutStatus)
{
// TODO: Complete member initialization
this.boxId = StoreID;
this.alarmType = aType;
this.alarmDetail = alarmDetial;
this.alarmMsg = WarnMsg;
this.inOutStatus = inoutStatus;
}
public AlarmInfo()
{
// TODO: Complete member initialization
}
/// <summary>
/// VMI流水线ID,0表示流水线
/// </summary>
public int boxId { get; set; }
/// <summary>
/// 报警类型,
/// </summary>
public int alarmType { get; set; }
/// <summary>
/// 报警详情
///AlarmType= 0 消息 "1=原点返回
//AlarmType= 0 消息 2=复位"
//AlarmType=1 总体错误 "1=急停
//AlarmType=1 总体错误 2=没有气压信号
//AlarmType=1 总体错误,3=盘错乱"
//AlarmType=2 运动轴错误 1=第一轴(旋转)
//AlarmType=2 运动轴错误 2=第二轴(上下轴)
//AlarmType=2 运动轴错误 3=第三轴(前进轴)
//AlarmType=2 运动轴错误 4=第四轴(压紧轴)"
//AlarmType=2 电钢报警 5=上下电钢
//AlarmType=3 IO报警,信号超时 io电器定义(电器定义)
/// </summary>
public string alarmDetail { get; set; }
/// <summary>
/// 报警消息
/// </summary>
public string alarmMsg { get; set; }
/// <summary>
/// 0,1=入库,2=出库
/// </summary>
public int inOutStatus { get; set; }
}
public class ParamDefine
{
/// <summary>
/// 库位 ID
/// </summary>
public static string posId = "posId";
/// <summary>
/// 料盘宽
/// </summary>
public static string plateW = "plateW";
/// <summary>
/// 料盘高
/// </summary>
public static string plateH = "plateH";
/// <summary>
/// VMI流水线ID
/// </summary>
public static string storeId = "storeId";
/// <summary>
/// 报警码
/// </summary>
public static string alarmCode = "alarmCode";
/// <summary>
/// 报警详情或参数
/// </summary>
public static string alarmDetial = "alarmDetial";
/// <summary>
/// 湿度报警值
/// </summary>
public static string maxHumidity = "humi";
/// <summary>
/// 温度报警值
/// </summary>
public static string maxTemperature = "temp";
/// <summary>
/// urgentReel: true 表示紧急料,需要出到料串上
/// </summary>
public static string urgentReel = "urgentReel";
/// <summary>
/// cutReel: true 表示分盘料,需要出到料串上
/// </summary>
public static string cutReel = "cutReel";
/// <summary>
/// smallReel: true 小料(7x8),放置到小料架上
/// </summary>
public static string smallReel = "smallReel";
/// <summary>
/// rfid: 分配的料架RFID
/// </summary>
public static string rfid = "rfid";
/// <summary>
/// rfidLoc: 料架的架位,值为 - 1时,可以自由分配皮带线, 小料时,架位为1 - 46优先走1 / 2号皮带线,47 - 92优先走3 / 4号皮带线,
/// 70,71,72时只能分配到3 / 4号皮带线; 大料时,架位1 - 6优先走1 / 2号皮带线, 7 - 12优先走3 / 4号皮带线
/// </summary>
public static string rfidLoc = "rfidLoc";
public static string barcode = "barcode";
}
}
文件属性发生变化
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Threading;
using System.Xml;
using System.Windows.Forms;
using log4net;
namespace OnlineStore.Common
{
public class ConfigAppSettings
{
public static readonly ILog LOGGER = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private static int seq = 1;
public static int nextSeq()
{
if (seq.Equals(Int32.MaxValue))
{
LOGGER.Info("seq当前值:" + seq + ",重置seq=0");
seq = 0;
}
Interlocked.Increment(ref seq);
return seq;
}
public static string GetValue(string keyStr, string storeStr)
{
string key = keyStr + storeStr;
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] == null)
{
return GetValue(keyStr);
}
else
{
return config.AppSettings.Settings[key].Value;
}
}
public static decimal GetNumValue(string keyStr, string storeStr)
{
string key = keyStr + storeStr;
decimal a = 0;
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] == null)
{
return GetNumValue(keyStr);
}
else
{
Decimal.TryParse(config.AppSettings.Settings[key].Value, out a);
}
return a;
}
public static int GetIntValue(string keyStr, string storeStr)
{
string key = keyStr + storeStr;
int a = 0;
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] == null)
{
return GetIntValue(keyStr);
}
else
{
Int32.TryParse(config.AppSettings.Settings[key].Value, out a);
}
return a;
}
public static string GetValue(string key)
{
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] == null)
{
LOGGER.Error("未找到配置:" + key + ",请检查配置是否完整!");
return "";
}
else
{
return config.AppSettings.Settings[key].Value;
}
}
public static decimal GetNumValue(string key)
{
decimal a = 0;
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] == null)
{
LOGGER.Error("未找到配置:" + key + ",请检查配置是否完整!");
return a;
}
else
{
Decimal.TryParse(config.AppSettings.Settings[key].Value, out a);
}
return a;
}
public static int GetIntValue(string key)
{
int a = 0;
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] == null)
{
LOGGER.Error("未找到配置:" + key + ",请检查配置是否完整!");
return a;
}
else
{
Int32.TryParse(config.AppSettings.Settings[key].Value, out a);
}
return a;
}
public static void SaveValue(string key, int value)
{
SaveValue(key, value.ToString());
}
public static void SaveValue(string key, string value)
{
try
{
if (key.Equals("") || value.Equals(""))
{
//return;
}
//增加的内容写在appSettings段下 <add key="RegCode" value="0"/>
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] == null)
{
SetValue(key, value);
}
else
{
UpdateConfig(key, value);
}
}
catch (Exception ex)
{
LogUtil.error(LOGGER, "SaveValue保存配置出错:AppKey=" + key + ",AppValue=" + value + "," + ex.StackTrace);
}
}
/// <summary>
/// 更新配置文件信息
/// </summary>
/// <param name="name">配置文件字段名称</param>
/// <param name="Xvalue">值</param>
private static void UpdateConfig(string name, string Xvalue)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(Application.ExecutablePath + ".config");
XmlNode node = doc.SelectSingleNode(@"//add[@key='" + name + "']");
XmlElement ele = (XmlElement)node;
ele.SetAttribute("value", Xvalue);
doc.Save(Application.ExecutablePath + ".config");
}
catch (Exception ex)
{
LogUtil.error(LOGGER, "UpdateConfig保存配置出错:name=" + name + ",Xvalue=" + Xvalue + "," + ex.StackTrace);
}
}
///<summary>
///向.config文件的appKey结写入信息AppValue 保存设置
///</summary>
///<param name="AppKey">节点名</param>
///<param name="AppValue">值</param>
private static void SetValue(String AppKey, String AppValue)
{
try
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
XmlNode xNode;
XmlElement xElem1;
XmlElement xElem2;
xNode = xDoc.SelectSingleNode("//appSettings");
xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
if (xElem1 != null)
xElem1.SetAttribute("value", AppValue);
else
{
xElem2 = xDoc.CreateElement("add");
xElem2.SetAttribute("key", AppKey);
xElem2.SetAttribute("value", AppValue);
xNode.AppendChild(xElem2);
}
xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
}
catch (Exception ex)
{
LogUtil.error(LOGGER, "SetValue保存配置出错:AppKey=" + AppKey + ",AppValue=" + AppValue + "," + ex.StackTrace);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace OnlineStore.Common
{
public class FormUtil
{
public static int GetIntValue(TextBox txt)
{
int value = 0;
try
{
value = int.Parse(txt.Text);
}
catch (Exception ex)
{
value = 0;
}
return value;
}
public static short GetShortValue(TextBox txt)
{
short value = 0;
try
{
value = short.Parse(txt.Text);
}
catch (Exception ex)
{
value = 0;
}
return value;
}
public static double getDoubleValue(TextBox txt)
{
double value = 0;
try
{
value = double.Parse(txt.Text);
}
catch (Exception ex)
{
value = 0;
}
return value;
}
public static short get16ShortValue(TextBox txt)
{
short value = 0;
try
{
value = System.Convert.ToInt16(txt.Text,16);
}
catch
{
value = 0;
}
return value;
}
public static string GetShowStr(double value)
{
string wStr = "";
if (value == (int)value)
{
wStr = string.Format("{0:d}", (int)value);
}
else
{
wStr = string.Format("{0:f}", value);
}
return wStr;
}
public static string GetSpanStr(TimeSpan span)
{
//return Convert.ToDateTime(span.ToString()).ToString("HH:mm:ss");
string seconds = Math.Round(span.TotalSeconds % 60, 1).ToString();
if (seconds.IndexOf(".") >= 0)
{
seconds = seconds.ToString().PadLeft(4, '0');
}
else
{
seconds = seconds.ToString().PadLeft(2, '0');
}
return span.Hours.ToString().PadLeft(2, '0') + ":" + span.Minutes.ToString().PadLeft(2, '0') + ":" + seconds;
}
public static bool GetBoolData(Dictionary<string, string> data, string key, bool defaultValue=false)
{
if (data.ContainsKey(key))
{
try
{
return Convert.ToBoolean(data[key]);
}
catch (Exception ex)
{
}
}
return defaultValue;
}
public static int GetIntData(Dictionary<string, string> data, string key, int defaultValue = 0)
{
if (data.ContainsKey(key))
{
try
{
return Convert.ToInt32(data[key]);
}
catch (Exception ex)
{
}
}
return defaultValue;
}
}
}
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Collections;
using System.Net;
using System.Net.Security;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Reflection;
using log4net;
namespace OnlineStore.Common
{
public class HttpHelper
{
public static string Post(string url, string paramData)
{
return Post(url, paramData, Encoding.UTF8);
}
public static Operation Post(string url, Operation operation, bool simulate)
{
try
{
if (simulate)
{//模拟服务器返回
operation.status = 200;
operation.data.Clear();
operation.data.Add("posId", "A001");
string pos = "D100-111#D102-222#D104-333";
operation.data.Add("pos", pos);
if (operation.op == 1 || operation.op == 2)
{//入库或出库
string json = JsonHelper.SerializeObject(operation);
LogUtil.error( "模拟HTTP服务器返回出库入库信息:" + json);
return operation;
}
}
else
{
string json = "";
try
{
json = JsonHelper.SerializeObject(operation);
}
catch (Exception ex)
{
LogUtil.error("JsonHelper.SerializeObject(operation) 出错【operation.op=" + operation.op + "】" + ex);
}
string result = Post(url, json);
if (!string.IsNullOrEmpty(result))
{
try
{
return JsonHelper.DeserializeJsonToObject<Operation>(result);
}
catch (Exception ex)
{
LogUtil.error("JsonHelper.DeserializeJsonToObject 出错【result=" + result + "】" + ex);
}
}
}
}
catch (Exception ex)
{
LogUtil.error("Post 出错【operation.op=" + operation.op + "】:" + ex);
}
return null;
}
private static int isLog = ConfigAppSettings.GetIntValue(Setting_Init.Server_Log_Open);
public static string Post(string url, string paramData, Encoding encoding)
{
if (isLog == 1)
{
LogUtil.info("给服务器发送数据【" + paramData + "】 ");
}
if (paramData != "null" && paramData != null)
{
// LogUtil.debug( "HTTP POST to " + url + " \n\t >> " + paramData);
}
string result = "";
if (url.ToLower().IndexOf("https", System.StringComparison.Ordinal) > -1)
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback((sender, certificate, chain, errors) => { return true; });
}
try
{
var wc = new MyWebClient(5000);
if (string.IsNullOrEmpty(wc.Headers["Content-Type"]))
wc.Headers.Add("Content-Type", "application/json;charset=UTF-8");
wc.Encoding = encoding;
result = wc.UploadString(url, "POST", paramData);
//LogUtil.info(result);
}
catch (Exception e)
{
LogUtil.error( "POST ERROR:" + e.ToString(), 1);
}
if (!result.Contains("null") && result.Length != 0)
{
//LogUtil.debug( "receive << " + result);
}
if (isLog == 1)
{
LogUtil.info("收到服务器数据【" + result + "】");
}
return result;
}
public static string Get(string url)
{
return Get(url, Encoding.UTF8);
}
public static string Get(string url, Encoding encoding)
{
try
{
LogUtil.info( "HTTP GET FROM: " + url);
var wc = new WebClient { Encoding = encoding };
var readStream = wc.OpenRead(url);
using (var sr = new StreamReader(readStream, encoding))
{
var result = sr.ReadToEnd();
LogUtil.info( "receive << " + result);
return result;
}
}
catch (Exception e)
{
LogUtil.error( "HTTP GET ERROR:" + e.Message, 2);
}
return "";
}
}
}
\ No newline at end of file
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
namespace OnlineStore.Common
{
/// <summary>
/// Json帮助类
/// </summary>
public class JsonHelper
{
/// <summary>
/// 将对象序列化为JSON格式
/// </summary>
/// <param name="o">对象</param>
/// <returns>json字符串</returns>
public static string SerializeObject(object o)
{
string json = JsonConvert.SerializeObject(o);
return json;
}
/// <summary>
/// 解析JSON字符串生成对象实体
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="json">json字符串(eg.{"ID":"112","Name":"石子儿"})</param>
/// <returns>对象实体</returns>
public static T DeserializeJsonToObject<T>(string json) where T : class
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(json);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
T t = o as T;
return t;
}
/// <summary>
/// 解析JSON数组生成对象实体集合
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="json">json数组字符串(eg.[{"ID":"112","Name":"石子儿"}])</param>
/// <returns>对象实体集合</returns>
public static List<T> DeserializeJsonToList<T>(string json) where T : class
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(json);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
List<T> list = o as List<T>;
return list;
}
/// <summary>
/// 反序列化JSON到给定的匿名对象.
/// </summary>
/// <typeparam name="T">匿名对象类型</typeparam>
/// <param name="json">json字符串</param>
/// <param name="anonymousTypeObject">匿名对象</param>
/// <returns>匿名对象</returns>
public static T DeserializeAnonymousType<T>(string json, T anonymousTypeObject)
{
T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
return t;
}
}
///// <summary>
///// 与服务器通信用对象
///// </summary>
//public class Operation
//{
// private string _cid = "";
// public string cid
// {
// get { return _cid; }
// set { _cid = value; }
// }
// public int seq { get; set; }
// public int op { get; set; }
// public int status { get; set; }
// private string _error = "";
// public string error
// {
// get { return _error; }
// set { _error = value; }
// }
// private Dictionary<string, string> _data = new Dictionary<string,string>();
// public Dictionary<string, string> data {
// get { return _data; }
// set { _data = value; }
// }
//}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using System.Reflection;
using System.Drawing;
namespace OnlineStore.Common
{
public class LogUtil
{
public static readonly ILog AIOLog = LogManager.GetLogger("AIOBOXLog");
private static LogUtil instance = new LogUtil();
public delegate void ShowLog(string msg, Color color);
public static readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static Dictionary<int, DateTime> lastErrorLogTime = new Dictionary<int, DateTime>();
public static System.Windows.Forms.RichTextBox logBox = null;
public static int showCount = 20;
public static bool debug_opened = false;
public static void info(ILog log, string msg)
{
if (log == null)
{
return;
}
log.Info(msg);
AddToBox(msg, Color.Black);
//clear();
}
public static void info(ILog log, string msg, Color color)
{
log.Info(msg);
AddToBox(msg, color);
}
public static void debug(ILog log, string msg, Color color)
{
log.Debug(msg);
if (debug_opened)
{
AddToBox(msg, color);
}
}
public static void debug(ILog log, string msg)
{
log.Debug(msg);
if (debug_opened)
{
AddToBox(msg, Color.Gray);
}
}
public static void error(string errorMsg, int type)
{
if (lastErrorLogTime.ContainsKey(type))
{
TimeSpan span = DateTime.Now - lastErrorLogTime[type];
if (span.TotalSeconds > 10)
{
lastErrorLogTime.Remove(type);
lastErrorLogTime.Add(type, DateTime.Now);
error(LOGGER, errorMsg);
}
}
else
{
lastErrorLogTime.Add(type, DateTime.Now);
error(LOGGER, errorMsg);
}
}
public static void error(ILog log, string errorMsg, Exception ex = null)
{
if (errorMsg.Trim().Equals(""))
{
return;
}
if (ex == null)
{
log.Error(errorMsg);
}
else
{
log.Error(errorMsg, ex);
}
AddToBox(errorMsg, Color.Red);
}
private static void AddToBox(string msg, Color color)
{
try
{
ShowLogPro(msg, color);
}
catch (Exception ex)
{
LOGGER.Error("出错:", ex);
}
}
private static List<string> logList = new List<string>();
public static string LastText = "";
private static void ShowLogPro(string msg, Color color)
{
try
{
if (logList.Count > 0)
{
// logList.RemoveAt(0);
}
if (logList.Count >= showCount)
{
logList.RemoveAt(0);
}
string text = "";
foreach (string str in logList)
{
text += str;
}
System.DateTime now = System.DateTime.Now;
logList.Add(now.ToLongTimeString() + " " + msg + Environment.NewLine);
if (logBox == null)
{
return;
}
LastText = text;
if (logBox.Visible)
{
logBox.Text = text;
// logBox.Focus(); //使文本框获取焦点
logBox.AppendText(now.ToLongTimeString() + " " + msg + Environment.NewLine); //增加文本
TimeSpan span = DateTime.Now - lastTime;
if (span.TotalSeconds > 3000000)
{
lastTime = DateTime.Now;
logBox.Select(logBox.Text.Length, 0); //设置光标的位置到文本尾
logBox.ScrollToCaret(); //滚动到控件光标处
}
}
}
catch (Exception ex)
{
LOGGER.Error("出错:" + ex.ToString());
}
}
private static DateTime lastTime = DateTime.Now;
public static void UpdateLogbox()
{
if (logBox != null && logBox.Visible)
{
logBox.Text = LastText;
TimeSpan span = DateTime.Now - lastTime;
if (span.TotalSeconds > 3000000)
{
lastTime = DateTime.Now;
logBox.Select(logBox.Text.Length, 0); //设置光标的位置到文本尾
logBox.ScrollToCaret(); //滚动到控件光标处
}
}
}
public static void ClearLog()
{
if (logBox != null)
{
LastText = "";
logList.Clear();
logBox.Text = "";
}
}
public static void debug(string msg)
{
debug(LOGGER, msg);
}
public static void error(string errorMsg, Exception ex = null)
{
error(LOGGER, errorMsg, ex);
}
public static void info(string msg)
{
info(LOGGER, msg);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
namespace OnlineStore.Common
{
public class MyWebClient:WebClient
{
private int _timeout;
/// <summary>
/// 超时时间(毫秒)
/// </summary>
public int Timeout
{
get
{
return _timeout;
}
set
{
_timeout = value;
}
}
public MyWebClient()
{
this._timeout = 60000;
}
public MyWebClient(int timeout)
{
this._timeout = timeout;
}
protected override WebRequest GetWebRequest(Uri address)
{
var result = base.GetWebRequest(address);
result.Timeout = this._timeout;
return result;
}
}
}
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace OnlineStore.Common
{
/// <summary>
/// 扫码枪连接类
/// </summary>
public class ScanSocket
{
private readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public event ScanRevice OnScanRevice;
public delegate void ScanRevice(string message);
/// <summary>
/// 扫码枪链接
/// </summary>
private TcpClient scannerSocket;
/// <summary>
/// 扫描枪 是否开始运行
/// </summary>
public bool isScannerRun = false;
/// <summary>
/// 连接扫码枪
/// </summary>
/// <param name="serverIp">扫码枪Ip</param>
/// <param name="port">扫码枪端口号</param>
/// <returns>是否连接成功</returns>
public bool ConnectScanner(string serverIp, int port)
{
return StartScanner(serverIp, port, false);
}
/// <summary>
/// 停止扫码枪
/// </summary>
public void StopScanner()
{
try
{
scannerSocket.close();
isScannerRun = false;
}
catch (Exception ex)
{
LogUtil.error(LOGGER, "出错:" + ex);
}
}
/// <summary>
/// 发送扫码命令开始扫码
/// </summary>
public void BeginScannering()
{
string str = ConfigAppSettings.GetValue(Setting_Init.scanner_start_command);
if (str.Equals(""))
{
str = "S";
}
scannerSocket.send(str);
//onCodeReceived("AAAA");
}
/// <summary>
/// 开启扫码枪
/// </summary>
private bool StartScanner(string serverIp, int port, bool isMustCon)
{
bool result = true;
try
{
if (!isScannerRun || isMustCon)
{
if (scannerSocket == null)
{
scannerSocket = new TcpClient();
}
result = scannerSocket.connect(serverIp, port, new TcpClient.HandleMessage(onCodeReceived));
if (result)
{
isScannerRun = true;
}
}
}
catch (Exception ex)
{
LogUtil.error(LOGGER, "出错:" + ex);
}
return result;
}
/// <summary>
/// 扫码枪数据接收
/// </summary>
/// <param name="message"></param>
private void onCodeReceived(string message)
{
try
{
message = ScanCodeManager.ReplaceCode(message);
if (OnScanRevice != null)
{
OnScanRevice.Invoke(message);
}
}
catch (Exception ex)
{
LogUtil.error(LOGGER, "出错:" + ex.ToString());
}
}
}
}
文件属性发生变化
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{513BC1C9-800D-43A6-9499-3700BAEC3554}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>OnlineStore.DeviceLibrary</RootNamespace>
<AssemblyName>DeviceLibrary</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<PlatformTarget>AnyCPU</PlatformTarget>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="Asa.IOModule.AIOBOX">
<HintPath>..\..\dll\Asa.IOModule.AIOBOX.dll</HintPath>
</Reference>
<Reference Include="Asa.RFID">
<HintPath>..\..\dll\Asa.RFID.dll</HintPath>
</Reference>
<Reference Include="Client">
<HintPath>..\..\dll\Client.dll</HintPath>
</Reference>
<Reference Include="CodeLibrary">
<HintPath>..\..\..\RC32-SZBOSCH-ACSingleStore\dll\CodeLibrary.dll</HintPath>
</Reference>
<Reference Include="halcondotnet">
<HintPath>..\..\..\RC32-SZBOSCH-ACSingleStore\dll\halcondotnet.dll</HintPath>
</Reference>
<Reference Include="HFReader9CSharp, Version=1.0.0.0, Culture=neutral, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\dll\RFID\HFReader9CSharp.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=1.2.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\dll\log4net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Web" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="acVmiLine\VMILineBean.cs" />
<Compile Include="acVmiLine\VMILineBean_Partial.cs" />
<Compile Include="acVmiLine\LineManager.cs" />
<Compile Include="acVmiLine\WaitUtil.cs" />
<Compile Include="agvClient\AgvClient.cs" />
<Compile Include="bean\StoreMoveInfo.cs" />
<Compile Include="IO\AIOBOX\AIOBOXManager.cs" />
<Compile Include="IO\IOManager.cs" />
<Compile Include="IO\KangNaiDe\KNDManager.cs" />
<Compile Include="IO\KangNaiDe\MasterTcpClient.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="bean\StoreStep.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="RFIDManager.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Common\Common.csproj">
<Project>{43cdd09e-fcf3-4960-a01d-3bbfe9933122}</Project>
<Name>Common</Name>
</ProjectReference>
<ProjectReference Include="..\LoadCVSLibrary\LoadCSVLibrary.csproj">
<Project>{064bebf5-8faa-4ea2-a5f3-a06e6e7d9251}</Project>
<Name>LoadCSVLibrary</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup />
<ItemGroup>
<None Include="LineConfig\VMILineConfig.csv">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace OnlineStore.DeviceLibrary
{
public abstract class IOManager
{
public static IOManager instance = null;
public abstract void ConnectionIOList(List<string> dIODeviceNameList);
#region KNDIO
public static void IOMove(string ioType, IO_VALUE ioValue)
{
if (LineManager.Config.StoreDOList.ContainsKey(ioType))
{
ConfigIO configIo = LineManager.Config.StoreDOList[ioType];
instance.WriteSingleDO(configIo.IO_IP, configIo.SlaveID, configIo.GetIOAddr(), ioValue);
Thread.Sleep(60);
}
else
{
LogUtil.error("没有DO=" + ioType);
}
}
public static void CIOMove(string ioType,IO_VALUE ioValue)
{
if (!IOValue(ioType).Equals(ioValue))
{
IOMove(ioType, ioValue);
}
}
public static IO_VALUE IOValue(string ioType)
{
IO_VALUE ioValue = IO_VALUE.LOW;
if (LineManager.Config.StoreDIList.ContainsKey(ioType))
{
ConfigIO configIo = LineManager.Config.StoreDIList[ioType];
ioValue = instance.GetDIValue(configIo.IO_IP, configIo.SlaveID, configIo.GetIOAddr());
//UpdateDoValue(ioType, ioValue);
}
else if (LineManager.Config.StoreDOList.ContainsKey(ioType))
{
ConfigIO configIo = LineManager.Config.StoreDOList[ioType];
ioValue = instance.GetDOValue(configIo.IO_IP, configIo.SlaveID, configIo.GetIOAddr());
}
else
{
LogUtil.error("没有DO=" + ioType);
}
return ioValue;
}
public static IO_VALUE DOValue(string ioType)
{
IO_VALUE ioValue = IO_VALUE.LOW;
if (LineManager.Config.StoreDOList.ContainsKey(ioType))
{
ConfigIO configIo = LineManager.Config.StoreDOList[ioType];
ioValue = instance.GetDOValue(configIo.IO_IP, configIo.SlaveID, configIo.GetIOAddr());
}
else
{
LogUtil.error("没有DO=" + ioType);
}
return ioValue;
}
#endregion
public static void Init()
{
bool isAIOBox = ConfigAppSettings.GetIntValue(Setting_Init.UseAIOBOX).Equals(1);
if (isAIOBox)
{
instance = new AIOBOXManager();
}
else
{
instance = new KNDManager();
}
}
public abstract void ReadAllDI(string deviceName, byte slaveId);
public abstract void ReadAllDO(string deviceName, byte slaveId);
public abstract void WriteSingleDO(string deviceName, byte slaveId, ushort index, IO_VALUE value, int time);
public abstract void WriteSingleDO(string deviceName, byte slaveId, ushort index, IO_VALUE value);
public abstract IO_VALUE GetDIValue(string deviceName, byte slaveID, ushort v);
public abstract IO_VALUE GetDOValue(string deviceName, byte slaveID, ushort v);
public abstract IO_VALUE GetIOValue(ConfigIO configIO);
public abstract void CloseAllDO();
public abstract void CloseAllConnection();
}
}
类型,说明,名称,属性值,设备名称,默认值,描述,电器定义,代码定义,SlaveID,
PRO,IO模块对应的DI数量,IO_DILength,10.85.162.17#16,,,,,,,
PRO,模块对应的DO数量,IO_DOLength,10.85.162.17#16,,,,,,,
PRO,IO模块IP,PRO_AOI_IP_1,10.85.162.17,,,,,,,
,,,,,,,,,,
DI,急停,SuddenStop_BTN,0,PRO_AOI_IP_1,0,急停,X01,DI-01,0,
DI,进料线入口检测,L1_InCheck,1,PRO_AOI_IP_1,0,进料线入口检测,X02,DI-02,0,
DI,进料线阻挡检测,L1_StopCheck,2,PRO_AOI_IP_1,0,进料线阻挡检测,X03,DI-03,0,
DI,进料线出口检测,L1_OutCheck,3,PRO_AOI_IP_1,0,进料线出口检测,X04,DO-04,0,
DI,出料线入口检测,L2_InCheck,4,PRO_AOI_IP_1,0,出料线入口检测,X05,DI-05,0,
DI,出料线阻挡检测,L2_StopCheck1,5,PRO_AOI_IP_1,0,出料线阻挡检测,X06,DI-06,0
DI,出料线出口检测,L2_OutCheck,6,PRO_AOI_IP_1,0,出料线出口检测,X07,DI-07,0,
DI,进料线人工取料信号,L1_ManualRecSig,7,PRO_AOI_IP_1,0,进料线人工取料信号,X08,DI-08,0,
DI,进料线体横移上升端,L1_UpDown_Up_Sig,8,PRO_AOI_IP_1,0,进料线体横移上升端,X09,DI-09,0,
DI,进料线体横移下降端,L1_UpDown_Down_Sig,9,PRO_AOI_IP_1,0,进料线体横移下降端,X10,DI-10,0,
DI,出料线体横移上升端,L2_UpDown_Up_Sig,10,PRO_AOI_IP_1,0,出料线体横移上升端,X11,DI-11,0,
DI,出料线体横移下降端,L2_UpDown_Down_Sig,11,PRO_AOI_IP_1,0,出料线体横移下降端,X12,DI-12,0,
DI,复位,Reset_BTN,12,PRO_AOI_IP_1,0,复位,X13,DI-13,0,
,料串切换气缸前进端(未用),Switch_Forward_Sig,13,PRO_AOI_IP_1,0,料串切换气缸前进端(未用),X14,DI-14,0,
,料串切换气缸后退端(未用),Switch_Back_Sig,14,PRO_AOI_IP_1,0,料串切换气缸后退端(未用),X15,DI-15,0,
,包装料架检测信号(未用),PackingShelf_Sig,15,PRO_AOI_IP_1,0,包装料架检测信号(未用),X16,DI-16,0,
DO,进料线驱动电机运转,L1_Run,0,PRO_AOI_IP_1,0,进料线驱动电机运转,Y01,DO-01,0,
DO,出料线驱动电机运转,L2_Run,1,PRO_AOI_IP_1,0,出料线驱动电机运转,Y02,DI-02,0,
DO,进料线阻挡下降,L1_StopDown,2,PRO_AOI_IP_1,0,进料线阻挡下降,Y03,DI-03,0,
DO,进料线出口阻挡下降,L1_OutStopDown,3,PRO_AOI_IP_1,0,进料线出口阻挡下降,Y04,DI-04,0,
DO,出料线阻挡下降,L2_StopDown,4,PRO_AOI_IP_1,0,出料线阻挡下降,Y05,DO-05,0,
DO,出料线出口阻挡下降,L2_OutStopDown,5,PRO_AOI_IP_1,0,出料线出口阻挡下降,Y06,DI-06,0,
DO,横移电机运转,Traverse1_Run,6,PRO_AOI_IP_1,0,横移电机运转,Y07,DO-07,0,
DO,横移机构上升SOL,Traverse_Up_SOL,7,PRO_AOI_IP_1,0,横移机构上升SOL,Y08,DO-08,0,
DO,横移机构下降SOL,Traverse_Down_SOL,8,PRO_AOI_IP_1,0,横移机构下降SOL,Y09,DO-09,0,
DO,运行状态指示灯,AutoRun_HddLed,9,PRO_AOI_IP_1,0,运行状态指示灯,Y10,DO-10,0,
,横移电机2运转(未用),Traverse2_Run,10,PRO_AOI_IP_1,0,横移电机2运转,Y11,DO-11,0,
,料串切换气缸前进(未用),Switch_Forward,11,PRO_AOI_IP_1,0,料串切换气缸前进,Y12,DO-12,0,
,料串切换气缸后退(未用),Switch_Back,12,PRO_AOI_IP_1,0,料串切换气缸后退,Y13,DO-13,0,
,故障状态指示灯(未用),Alarm_HddLed,13,PRO_AOI_IP_1,0,故障状态指示灯(未用),Y14,DI-14,0,
PRO,IO信号超时时间(毫秒),IOSingle_TimerOut,10000,,,,,,,
PRO,L1线AGV节点名称,L1_AgvName,A2,,,,,,,
PRO,L2线AGV节点名称,L2_AgvName,A1,,,,,,,
PRO,L2线入口RFIDIP,L2_In_RFIDIP,192.168.103.108,,,,,, ,
PRO,L2线出口RFIDIP,L2_Out_RFIDIP,192.168.103.107,,,,,, ,
PRO,休眠秒数(秒),SleepSeconds,40,,,,,,,
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("DeviceLibrary")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DeviceLibrary")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("10193426-c259-4528-930a-9bdd47a6c8be")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
[assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyVersion("1.0.0.0")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
using log4net;
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static Asa.RFID.RFIDAuto;
namespace Asa.RFID
{
public class RFIDAutoReader
{
public static readonly ILog LOGGER = LogManager.GetLogger("TheRFID");
private static Dictionary<string, RFIDAuto> rfidMap = new Dictionary<string, RFIDAuto>();
public static Dictionary<string, int> rfidErrorMap = new Dictionary<string, int>();
/// <summary>
/// 打开所有
/// </summary>
/// <param name="ipArr"></param>
/// <param name="OnReceive"></param>
/// <param name="ip"></param>
public static void Open(Received_Event OnReceive, params string[] ipArr)
{
rfidErrorMap = new Dictionary<string, int>();
foreach (var ip in ipArr)
{
int code = 0;
if (rfidMap.ContainsKey(ip))
{
code = rfidMap[ip].StartAutoScan(OnReceive);
}
else
{
RFIDAuto rfid = new RFIDAuto(ip);
code = rfid.StartAutoScan(OnReceive);
rfidMap.Add(ip, rfid);
}
if (rfidErrorMap.ContainsKey(ip))
{
rfidErrorMap.Remove(ip);
}
rfidErrorMap.Add(ip, code);
if (code.Equals(0).Equals(false))
{
LogUtil.error("连接RFID【" + ip + "】ErrorCode=" + code);
}
}
}
public static void ReOpen(string ip)
{
LogUtil.error("ReOpen【" + ip + "】");
int code = 0;
if (rfidMap.ContainsKey(ip))
{
rfidMap[ip].StopAutoScan();
Thread.Sleep(200);
code = rfidMap[ip].StartAutoScan(null);
}
else
{
RFIDAuto rfid = new RFIDAuto(ip);
code = rfid.StartAutoScan(null);
rfidMap.Add(ip, rfid);
}
if (rfidErrorMap.ContainsKey(ip))
{
rfidErrorMap.Remove(ip);
}
rfidErrorMap.Add(ip, code);
if (code.Equals(0).Equals(false))
{
LogUtil.error("连接RFID【" + ip + "】ErrorCode=" + code);
}
}
/// <summary>
/// 获取最后读到的标签并清理
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static byte[] ReadAndClear(string ip)
{
if (rfidMap.ContainsKey(ip))
{
return rfidMap[ip].ReadAndClear();
}
return null;
}
/// <summary>
/// 获取最后读到的标签
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static byte[] Read(string ip)
{
if (rfidMap.ContainsKey(ip))
{
return rfidMap[ip].Read();
}
return null;
}
/// <summary>
/// 关闭所有
/// </summary>
public static void CloseAll()
{
foreach (var rfid in rfidMap.Values)
{
rfid.StopAutoScan();
}
rfidMap = new Dictionary<string, RFIDAuto>();
}
}
}

using Asa.RFID;
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace OnlineStore.DeviceLibrary
{
public class RFIDManager
{
public static void Open(string[] iparray)
{
try
{
RFIDAutoReader.Open( null,iparray);
}catch(Exception ex)
{
LogUtil.error("Open 出错:" + ex.ToString());
}
}
public static RFIDData ReadRFID(string ip, bool isClear = false)
{
try
{
if (String.IsNullOrEmpty(ip).Equals(false))
{
byte[] bdata = null;
if (isClear)
{
bdata = RFIDAutoReader.ReadAndClear(ip);
}
else
{
bdata = RFIDAutoReader.Read(ip);
}
if (bdata == null)
{
LogUtil.error("RFID [ " + ip + " ] 读到数据=null");
}
RFIDData data = new RFIDData(bdata);
return data;
}
}
catch (Exception ex)
{
//LogUtil.error("ReadRFID["+ip+"]出错:" + ex.ToString());
}
return new RFIDData(0, 0);
}
public static void Close()
{
try
{
RFIDAutoReader.CloseAll();
}
catch (Exception ex)
{
LogUtil.error("关闭RFID出错:" + ex.ToString());
}
}
}
public class RFIDData
{
/// <summary>
/// RFID类型,区分是料架还是托盘,托盘E=69,包装料料架A=65,料串=B
/// </summary>
public char RFType = '0';
public int Num = 0;
public RFIDData(int num, int t)
{
if (t < 65)
{
RFType = '0';
}
else
{
this.RFType = (char)t;
}
this.Num = num;
}
public RFIDData(byte[] data)
{
try
{
if (data != null && data.Length > 2)
{
if (data[1] < 65)
{
RFType = '0';
}
else
{
RFType = (char)data[1];
}
Num = (int)(data[2]);
}
}
catch (Exception ex)
{
LogUtil.error("RFIP 数据【" + data + "】 获取编码失败");
}
}
public byte[] ToData()
{
return new byte[] { (byte)RFType, (byte)Num };
}
public string NumStr()
{
return "" + RFType + "" + Num.ToString() + "";
}
}
}
using Asa.RFID;
using OnlineStore.Common;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OnlineStore.DeviceLibrary
{
public class RFIDManager
{
private static ReadAll readAll =new ReadAll ("TheRFID");
private static bool IsOpen = false;
// private static ConcurrentDictionary<string, string> LastRfidMap = new ConcurrentDictionary<string, string>();
public static void Open(string[] iparray)
{
if (IsOpen)
{
return;
}
try
{
int port = ConfigAppSettings.GetIntValue(Setting_Init.RfidServer_Port);
if (port <= 0)
{
port = 13001;
}
// readAll.Received += ReadAll_Received;
// readAll.Log += ReadAll_Log;
LogUtil.info("RFID Server Open,port=" + port);
readAll.Start(port);
IsOpen = true;
}
catch (Exception ex)
{
LogUtil.error("Open 出错:" + ex.ToString());
}
}
private static string lastStr = "";
private static void ReadAll_Log(string ip, string log)
{
string str = "RFID : [" + ip + "] " + log;
if (lastStr.Equals(str))
{
return;
}
LogUtil.info(str);
lastStr = str;
}
public static RFIDData ReadRFID(string ip, bool isClear = false)
{
try
{
if (String.IsNullOrEmpty(ip).Equals(false))
{
string outValue = readAll.Read(ip);
if (isClear)
{
readAll.Clear(ip);
}
RFIDData data = new RFIDData(outValue);
return data;
}
}
catch (Exception ex)
{
LogUtil.error("ReadRFID[" + ip + "] [" + isClear + "] 出错:" + ex.ToString());
}
return new RFIDData();
}
public static void Close()
{
try
{
readAll.Stop();
}
catch (Exception ex)
{
LogUtil.error("关闭RFID出错:" + ex.ToString());
}
}
}
public class RFIDData
{
public string StrData = "";
public RFIDData(string data = "00")
{
if (String.IsNullOrEmpty(data))
{
data = "00";
}
this.StrData = data;
}
public string NumStr()
{
return StrData;
}
internal static bool IsRealRfid(string shelfRfid)
{
//判断料架号是否是真实的料架号
if (shelfRfid.StartsWith("C") || shelfRfid.StartsWith("D"))
{
int num = -1;
try
{
num = Convert.ToInt32(shelfRfid.Substring(1, shelfRfid.Length - 1));
}
catch (Exception ex)
{
}
if (num > 0)
{
return true;
}
}
return false;
}
}
}
文件属性发生变化
using log4net;
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace OnlineStore.DeviceLibrary
{
public class LineManager
{
public static readonly ILog LOGGER = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public static VMILineBean VMILine = null;
public static VMLLineConfig Config = null;
private static bool isInit = false;
public static bool IsConnectServer = !ConfigAppSettings.GetValue(Setting_Init.http_server).Equals("");
public LineManager()
{
}
public static void CheckEnum(Type type)
{
if (type.IsEnum)
{
List<int> valueList = new List<int>();
foreach (int item in Enum.GetValues(type))
{
if (valueList.Contains(item))
{
LogUtil.error(LOGGER, type.Name + "枚举值:" + item + "重复存在,请检查代码!");
Application.Exit();
break;
}
valueList.Add(item);
}
}
}
public static VMILineBean InitStore()
{
try
{
RobotConfig.ProIOIpMap = new Dictionary<string, string>();
if (!isInit)
{
string server = ConfigAppSettings.GetValue(Setting_Init.http_server);
if (server.Equals(""))
{
IsConnectServer = false;
}
CheckEnum(typeof(MoveStep));
CheckEnum(typeof(RunStatus));
isInit = true;
string appPath = Application.StartupPath;
string linefilePath = appPath + ConfigAppSettings.GetValue(Setting_Init.Line_Config);
LogUtil.info(LOGGER, " 开始加载VMI流水线配置:" + linefilePath);
RobotConfig storeConfig = CSVConfigReader.LoadConfig(linefilePath);
Config = (VMLLineConfig)storeConfig;
VMILine = new VMILineBean(Config);
LogUtil.info(LOGGER, "加载VMI流水线完成!");
return VMILine;
}
}
catch (Exception ex)
{
LOGGER.Error("出错:", ex);
MessageBox.Show(ex.ToString(), "加载配置错误(请检查配置)");
Application.Exit();
}
return VMILine;
}
public static bool checkWatch(Stopwatch watch, int targetMs, bool isStop = true)
{
if (!watch.IsRunning)
{
watch.Restart();
return false;
}
else if (watch.ElapsedMilliseconds >= targetMs)
{
watch.Stop();
return true;
}
return false;
}
public static string GetRunStr(RunStatus runs)
{
string sta = "运行中";
switch (runs)
{
case RunStatus.Busy:
sta = "忙碌";
break;
case RunStatus.HomeMoving:
sta = "原点返回";
break;
case RunStatus.Reset:
sta = "重置";
break;
case RunStatus.Runing:
sta = "运行中";
break;
case RunStatus.Wait:
sta = "等待启动";
break;
}
return sta;
}
}
}
using Asa;
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace OnlineStore.DeviceLibrary
{
partial class VMILineBean
{
#region CheckWait处理
private DateTime preCheckAxisTime = DateTime.Now;
protected DateTime preRWTime = DateTime.Now;
internal void CheckWait(LineMoveInfo moveInfo)
{
try
{
List<WaitResultInfo> list = moveInfo.WaitList;
if (list.Count <= 0)
{
moveInfo.EndStepWait();
return;
}
//当等待超过一分钟时,需要打印提示
TimeSpan span = DateTime.Now - moveInfo.LastSetpTime;
string NotOkMsg = "";
bool isOk = true;
if (moveInfo.OneWaitCanEndStep)
{
isOk = false;
}
foreach (WaitResultInfo wait in list)
{
if (wait.IsEnd)
{
continue;
}
NotOkMsg = " [" + wait.ToStr() + "] ";
if (wait.WaitType.Equals(WaitEnum.W001_AxisMove))
{
}
else if (wait.WaitType.Equals(WaitEnum.W002_IOValue))
{
wait.IsEnd = IOManager.IOValue(wait.IoType).Equals(wait.IoValue);
}
else if (wait.WaitType.Equals(WaitEnum.W003_Time))
{
wait.IsEnd = (span.TotalMilliseconds >= wait.TimeMSeconds);
}
if (wait.IsEnd && moveInfo.OneWaitCanEndStep)
{
isOk = true;
break;
}
else if (!moveInfo.OneWaitCanEndStep)
{
isOk = false;
break;
}
}
if (isOk)
{
moveInfo.EndStepWait();
}
else if (span.TotalSeconds > moveInfo.TimeOutSeconds)
{
WarnMsg = Name + "[" + moveInfo.MoveType + "][" + moveInfo.MoveStep + "]等待" + NotOkMsg
+ "超时[" + Math.Round(span.TotalSeconds, 1) + "]秒";
LogUtil.error(WarnMsg);
Alarm(AlarmType.IoSingleTimeOut);
}
}
catch (Exception ex)
{
LogUtil.error(Name + " [" + moveInfo.MoveStep + "] CheckWait 出错:", ex);
}
}
public void StopIOMove(string ioType, int ms = 1000)
{
Task.Factory.StartNew(delegate
{
IOManager.IOMove(ioType, IO_VALUE.HIGH);
Thread.Sleep(ms);
IOManager.IOMove(ioType, IO_VALUE.LOW);
});
}
public void SetWarnMsg(string msg = "")
{
if (String.IsNullOrEmpty(msg).Equals(false))
{
if (WarnMsg.Equals(msg))
{
if (msg.StartsWith(Name))
{
LogUtil.error(msg, 105);
}
else
{
LogUtil.error(Name + msg, 105);
}
}
else
{
if (msg.StartsWith(Name))
{
LogUtil.error(msg);
}
else
{
LogUtil.error(Name + msg);
}
}
}
WarnMsg = msg;
}
public string GetRunInfo()
{
return "进料线入口" + Config.L1_AgvName + ":" + AgvClient.GetAction(Config.L1_AgvName) + ",料架: " + LastInShelfId + "\r\n" +
"出料线出口" + Config.L2_AgvName + ":" + AgvClient.GetAction(Config.L2_AgvName) + ",料架: " + LastOutShelfId + "\r\n";
}
#endregion
#region 休眠处理
public bool IsSleep = false;
private DateTime LastBusyTime = DateTime.Now;
private Dictionary<string, IO_VALUE> lastDIValue = new Dictionary<string, IO_VALUE>();
private List<string> needCheckList = new List<string>();
private int GetDIV(string type)
{
if (lastDIValue.ContainsKey(type))
{
return (int)lastDIValue[type];
}
return -1;
}
private void SleepTimerProcess()
{
if (needCheckList.Count <= 0)
{
needCheckList.Add(IO_Type.L1_InCheck);
needCheckList.Add(IO_Type.L1_StopCheck);
needCheckList.Add(IO_Type.L1_OutCheck);
needCheckList.Add(IO_Type.L2_InCheck);
needCheckList.Add(IO_Type.L2_StopCheck1);
needCheckList.Add(IO_Type.L2_OutCheck);
needCheckList.Add(IO_Type.L2_StopDown);
needCheckList.Add(IO_Type.L1_StopDown);
}
bool agvBusy = false;
ClientAction currA = AgvClient.GetAction(Config.L1_AgvName);
if (currA.Equals(ClientAction.None) || currA.Equals(ClientAction.NeedLeave) || currA.Equals(ClientAction.NeedEnter) )
{
ClientAction currB = AgvClient.GetAction(Config.L2_AgvName);
if (currB.Equals(ClientAction.None) || currB.Equals(ClientAction.NeedLeave) || currB.Equals(ClientAction.NeedEnter))
{
agvBusy = false;
}
else
{
LastBusyTime = DateTime.Now;
agvBusy = true;
}
}
else
{
LastBusyTime = DateTime.Now;
agvBusy = true;
}
if (agvBusy && IsSleep)
{
UpdateSleep(false);
return;
}
bool diIsBusy = false;
foreach (string type in needCheckList)
{
IO_VALUE currValue = IOManager.IOValue(type);
int lastValue = GetDIV(type);
if (((int)currValue).Equals(lastValue))
{
diIsBusy = false ;
}
else
{
if (lastDIValue.ContainsKey(type))
{
lastDIValue[type]=currValue;
}
else
{
lastDIValue.Add(type, currValue);
}
LastBusyTime = DateTime.Now;
diIsBusy = true;
UpdateSleep(false);
return;
}
}
if (diIsBusy.Equals(false) && agvBusy.Equals(false) && IsSleep.Equals(false))
{
TimeSpan time = DateTime.Now-LastBusyTime;
if (time.TotalSeconds > Config.SleepSeconds)
{
LogUtil.info(Name + "已经空闲【"+Math.Abs(time.TotalSeconds)+"】秒,开始休眠");
UpdateSleep(true);
}
}
}
public void UpdateSleep(bool needSleep)
{
if (needSleep)
{
IsSleep = true;
IOManager.IOMove(IO_Type.L1_Run, IO_VALUE.LOW);
IOManager.IOMove(IO_Type.L2_Run, IO_VALUE.LOW);
}
else
{
IsSleep = false;
LastBusyTime = DateTime.Now;
IOManager.IOMove(IO_Type.L1_Run, IO_VALUE.HIGH);
IOManager.IOMove(IO_Type.L2_Run, IO_VALUE.HIGH);
};
}
#endregion
}
}
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace OnlineStore.DeviceLibrary
{
public class WaitUtil
{
public delegate bool IsOk();
/// <summary>
/// 使用异步委托检测超时,防止isOk方法不返回结果导致卡死的问题
/// </summary>
/// <param name="waitName"></param>
/// <param name="timeout"></param>
/// <param name="isOk"></param>
public static bool Wait(int timeout, IsOk isOk, string waitName = "")
{
DateTime startTime = System.DateTime.Now;
TimeSpan timoutSpan = TimeSpan.FromMilliseconds(timeout);
TimeSpan waitSpan = TimeSpan.FromMilliseconds(0);
int sleepTime = 10;
while (true)
{
TimeSpan remainTimes = timoutSpan.Subtract(waitSpan);
if (remainTimes.TotalMilliseconds < 0)
{
//已经超时
throw new TimeoutException(waitName + "超时");
}
try
{
IAsyncResult re = isOk.BeginInvoke(null, null);
var waitResult = re.AsyncWaitHandle.WaitOne(remainTimes);
if (waitResult)
{
bool okResult = isOk.EndInvoke(re);
if (okResult)
{
return true;
}
}
}
catch (Exception ex)
{
LogUtil.error("同步等待出现异常:", ex);
}
Thread.Sleep(sleepTime);
waitSpan = System.DateTime.Now.Subtract(startTime);
}
}
}
}

using Asa;
using Asa.RFID;
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OnlineStore.DeviceLibrary
{
public class AgvClient
{
private static string ServerIp = ConfigAppSettings.GetValue(Setting_Init.AgvServerIp);
private static Asa.Client agvClient;
public static Dictionary<string, string> actionMap = new Dictionary<string, string>();
public static List<string> NodeList = new List<string>();
private static bool isInit = false;
public static void Init()
{
try
{
if (!isInit)
{
isInit = true;
agvClient = new Asa.Client(ServerIp);
agvClient.Log += AgvClient_Log;
agvClient.Arrive += AgvClient_Arrive;
agvClient.CanEnter += AgvClient_CanEnter;
agvClient.Ready += AgvClient_Ready;
}
lastNeedLeave = "";
lastNeedEnter = "";
actionMap = new Dictionary<string, string>();
foreach (string key in NodeList)
{
actionMap.Add(key, AGVAction.None);
}
agvClient.Connect(NodeList.ToArray());
}
catch (Exception ex)
{
LogUtil.error("初始化agvClient " + ServerIp + " 出错:", ex);
}
}
private static void AgvClient_Ready(string id, byte[] content)
{
UpdateAction(id, AGVAction.Ready);
RFIDData data = new RFIDData(content);
LogUtil.info("收到 AgvClient_Ready [" + id + "] [" + data.ToData() + "] ");
if (id.Equals(LineManager.Config.OutL_AgvName))
{
// MayEnter("C2");
if (IOManager.IOValue(IO_Type.OutL_InCheck).Equals(IO_VALUE.LOW))
{
agvClient.MayEnter(id);
LogUtil.info("收到 AgvClient_Ready [" + id + "] [" + data.ToData() + "] 调用 MayEnter ");
}
}
else if (id.Equals(LineManager.Config.InL_AgvName))
{
if (IOManager.IOValue(IO_Type.InL_OutStopCheck).Equals(IO_VALUE.HIGH))
{
LineManager.VMILine.StopIOMove(IO_Type.InL_OutStopDown);
agvClient.MayLeave(id);
LogUtil.info("收到 AgvClient_Ready [" + id + "] [" + data.ToData() + "] ,下降 InL_OutStopDown 600ms,调用 MayLeave ");
}
}
}
private static void AgvClient_CanEnter(string id, byte[] content)
{
UpdateAction(id, AGVAction.CanEnter);
RFIDData data = new RFIDData(content);
LogUtil.info("收到 AgvClient_CanEnter [" + id + "] [" + data.ToData() + "] ");
if (id.Equals(LineManager.Config.OutL_AgvName))
{
bool result = IOManager.IOValue(IO_Type.OutL_InCheck).Equals(IO_VALUE.LOW);
if (IOManager.IOValue(IO_Type.OutL_InCheck).Equals(IO_VALUE.LOW))
{
agvClient.IsEnter(id);
}
}
else if (id.Equals(LineManager.Config.InL_AgvName))
{
}
}
private static void AgvClient_Arrive(string id, byte[] content)
{
UpdateAction(id, AGVAction.Arrive);
RFIDData data = new RFIDData(content);
LogUtil.info("收到 AgvClient_Arrive [" + id + "] [" + data.ToData() + "] ");
}
public static bool ISConnected()
{
if (agvClient == null)
{
return false;
}
return agvClient.IsConn;
}
public static void SendRFID(string NodeName, string rfid)
{
agvClient.SendRFID(NodeName, rfid);
}
private static string lastNeedEnter = "";
public static void NeedEnter(string NodeName, string shelfID, bool NeedClearLast = false)
{
if (NeedClearLast)
{
lastNeedEnter = "";
}
if (lastNeedEnter.Equals(NodeName + shelfID))
{
//return;
}
bool result = agvClient.NeedEnter(NodeName);
if (result)
{
lastNeedEnter = NodeName + shelfID;
LogUtil.info(" agvClient 料架需要进入:NeedEnter[" + NodeName + shelfID + "],呼叫成功");
}
else
{
LogUtil.info(" agvClient 料架需要进入:NeedEnter[" + NodeName + shelfID + "],呼叫失败,等待重新呼叫");
}
}
private static string lastNeedLeave = "";
public static void NeedLeave(string NodeName, string shelfID, bool NeedClearLast = false)
{
if (NeedClearLast)
{
lastNeedLeave = "";
}
if (lastNeedLeave.Equals(NodeName + shelfID))
{
// return;
}
bool result = agvClient.NeedLeave(NodeName);
if (result)
{
lastNeedLeave = NodeName + shelfID;
LogUtil.info(" agvClient 料架需要离开:NeedLeave[" + NodeName + shelfID + "],呼叫成功");
}
else
{
LogUtil.info(" agvClient 料架需要离开:NeedLeave[" + NodeName + shelfID + "],呼叫失败,等待重新呼叫");
}
}
public static void MayEnter(string NodeName)
{
agvClient.MayEnter(NodeName);
}
public static void FinishEnter(string NodeName)
{
agvClient.FinishEnter(NodeName);
}
public static void MayLeave(string NodeName)
{
agvClient.MayLeave(NodeName);
}
public static void IsEnter(string NodeName, bool result)
{
if (result)
{
agvClient.IsEnter(NodeName);
}
}
private static void AgvClient_Log(string s)
{
try
{
bool isLog = ConfigAppSettings.GetIntValue(Setting_Init.Agv_Log_Open).Equals(1);
if (isLog)
{
LogUtil.info(" AGV " + ServerIp + " Log : " + s);
}
}
catch (Exception ex)
{
LogUtil.error("AgvClient_Log 出错:" + ex.ToString());
}
}
public static string GetAction(string NodeName)
{
if (actionMap.ContainsKey(NodeName))
{
return actionMap[NodeName];
}
return AGVAction.None;
}
public static void UpdateAction(string name, string action)
{
if (actionMap.ContainsKey(name))
{
actionMap[name] = action;
}
else
{
actionMap.Add(name, action);
}
}
public static void Dispose()
{
try
{
lastNeedLeave = "";
lastNeedEnter = "";
if (agvClient != null)
{
agvClient.Close();
}
}
catch (Exception ex)
{
LogUtil.error("agvClient.Close " + ServerIp + " 出错:", ex);
}
}
}
public class AGVAction
{
public static string None = "None";
public static string Arrive = "Arrive";
public static string CanEnter = "CanEnter";
public static string GetRFID = "GetRFID";
public static string Ready = "Ready";
}
}

using Asa;
using Asa.RFID;
using OnlineStore.Common;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace OnlineStore.DeviceLibrary
{
public class AgvClient
{
private static string ServerIp = ConfigAppSettings.GetValue(Setting_Init.AgvServerIp);
private static Asa.AgvClient agvClient;
public static Dictionary<string, Asa.ClientAction> actionMap = new Dictionary<string, Asa.ClientAction>();
public static List<string> NodeList = new List<string>();
private static bool isInit = false;
public static void Init()
{
try
{
if (!isInit)
{
isInit = true;
agvClient = new Asa.AgvClient(ServerIp);
agvClient.CancelState = true;
agvClient.Log += AgvClient_Log;
agvClient.Arrive += AgvClient_Arrive;
agvClient.Ready += AgvClient_Ready;
agvClient.CloseDoor += AgvClient_CloseDoor;
}
actionMap = new Dictionary<string, Asa.ClientAction>();
//foreach (string key in NodeList)
//{
// actionMap.Add(key, Asa.ClientAction.None);
//}
agvClient.Connect();
foreach (string str in NodeList)
{
SetStatus(str);
LogUtil.info("agv init ,SetStatus[" + str + "]=none ");
}
}
catch (Exception ex)
{
LogUtil.error("初始化agvClient " + ServerIp + " 出错:", ex);
}
}
public static void SetCancelState(bool isCancel)
{
agvClient.CancelState = isCancel;
}
private static void AgvClient_CloseDoor(string id, string rfid)
{
//RFIDData data = new RFIDData(content);
LogUtil.info("收到 AgvClient_CloseDoor [" + id + "] [" + rfid + "] ");
}
public static void SetStatus(string id, string shelfId = "", ClientAction action = ClientAction.None, ClientLevel level = ClientLevel.Low)
{
// ClientAction currA = GetAction(id);
if (actionMap.ContainsKey(id))
{
ClientAction currA = actionMap[id]; //相同状态就设置一次
if (currA.Equals(action))
{
return;
}
}
agvClient.SetStatus(id, "",shelfId, action, level);
UpdateAction(id, action);
}
private static void AgvClient_Ready(string id, string rfid)
{
// RFIDData data = new RFIDData(content);
string logName = "收到 AgvClient_Ready [" + id + "] [" + rfid + "] ";
LogUtil.info(logName);
UpdateAction(id, Asa.ClientAction.Ready);
if (id.Equals(LineManager.Config.L1_AgvName))
{
LineManager.VMILine.UpdateSleep(false);
if (IOManager.IOValue(IO_Type.L1_InCheck).Equals(IO_VALUE.LOW))
{
Task.Factory.StartNew(delegate
{
SetStatus(id, "", ClientAction.MayEnter);
LogUtil.info(logName + " ,等待L1_InCheck");
try
{
WaitUtil.Wait(60000, delegate
{
return IOManager.IOValue(IO_Type.L1_InCheck).Equals(IO_VALUE.HIGH);
}, "等待L1_InCheck=HIGH");
}
catch (Exception ex)
{
LogUtil.error(logName + ":" + ex.ToString());
}
//两秒后改为离开状态
Thread.Sleep(3000);
LogUtil.info(logName + " ,调用 FinishEnter ");
SetStatus(id, "", ClientAction.FinishEnter);
Thread.Sleep(5000);
LogUtil.info(logName + " ,处理结束 更新状态为None ");
SetStatus(id, "", ClientAction.None);
});
}
else
{
LogUtil.error(logName + " L1_InCheck 检测到有料架,AGV的料架无法进入");
SetStatus(id, "", ClientAction.None, ClientLevel.High);
}
}
else if (id.Equals(LineManager.Config.L2_AgvName))
{
string shefId = LineManager.VMILine.LastOutShelfId;
if (IOManager.IOValue(IO_Type.L2_OutCheck).Equals(IO_VALUE.HIGH))
{
SetStatus(id, shefId, ClientAction.MayLeave);
LineManager.VMILine.UpdateSleep(false);
LineManager.VMILine.StopIOMove(IO_Type.L2_OutStopDown, 1500);
//agvClient.MayLeave(id);
LogUtil.info(logName + "下降 L2_OutStopDown , " + shefId);
Task.Factory.StartNew(delegate
{
//两秒后改为离开状态
Thread.Sleep(5000);
LogUtil.info(logName + " ,调用 FinishLeave " + shefId);
SetStatus(id, shefId, ClientAction.FinishLeave);
Thread.Sleep(5000);
LogUtil.info(logName + " ,处理结束 更新状态为None ");
SetStatus(id, "", ClientAction.None);
});
}
else
{
LogUtil.error(logName + " L2_OutCheck 未检测到料架,无法将料架进入AGV");
SetStatus(id, "", ClientAction.None, ClientLevel.High);
}
}
}
private static void AgvClient_Arrive(string id, string rfid)
{
UpdateAction(id, Asa.ClientAction.Arrive);
// RFIDData data = new RFIDData(content);
LogUtil.info("收到 AgvClient_Arrive [" + id + "] [" +rfid + "] ");
}
public static bool SetToNone(string id, string shelfId = "")
{
ClientAction currA = GetAction(id);
if (currA.Equals(ClientAction.None) || currA.Equals(ClientAction.NeedLeave) || currA.Equals(ClientAction.NeedEnter))
{
SetStatus(id, shelfId, ClientAction.None);
return true;
}
return false;
}
public static bool NeedEnter(string id, string shelfId)
{
ClientAction currA = GetAction(id);
if (currA.Equals(ClientAction.None) || currA.Equals(ClientAction.NeedLeave) || currA.Equals(ClientAction.NeedEnter))
{
SetStatus(id, shelfId, ClientAction.NeedEnter);
return true;
}
return false;
}
public static bool NeedLeave(string id, string shelfId)
{
ClientAction currA = GetAction(id);
if (currA.Equals(ClientAction.None) || currA.Equals(ClientAction.NeedLeave) || currA.Equals(ClientAction.NeedEnter))
{
SetStatus(id, shelfId, ClientAction.NeedLeave);
return true;
}
return false;
}
public static bool ISConnected()
{
if (agvClient == null)
{
return false;
}
return agvClient.IsConn;
}
//public static void SendRFID(string NodeName, string rfid)
//{
// agvClient.SendRFID(NodeName, rfid);
//}
private static void AgvClient_Log(string s)
{
try
{
bool isLog = ConfigAppSettings.GetIntValue(Setting_Init.Agv_Log_Open).Equals(1);
if (isLog)
{
LogUtil.info(" AGV " + ServerIp + " Log : " + s);
}
}
catch (Exception ex)
{
LogUtil.error("AgvClient_Log 出错:" + ex.ToString());
}
}
public static Asa.ClientAction GetAction(string NodeName)
{
if (actionMap.ContainsKey(NodeName))
{
return actionMap[NodeName];
}
return Asa.ClientAction.None;
}
public static void UpdateAction(string name, Asa.ClientAction action)
{
if (actionMap.ContainsKey(name))
{
actionMap[name] = action;
}
else
{
actionMap.Add(name, action);
}
}
public static void Dispose()
{
try
{
if (agvClient != null)
{
agvClient.Close();
}
}
catch (Exception ex)
{
LogUtil.error("agvClient.Close " + ServerIp + " 出错:", ex);
}
}
}
}
using OnlineStore.Common;
using OnlineStore.DeviceLibrary;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OnlineStore.DeviceLibrary
{
/// <summary>
/// VMI流水线当前运动信息类(出入库状态,步骤记录)
/// </summary>
public class LineMoveInfo
{
/// <summary>
/// 超时时间
/// </summary>
public int TimeOutSeconds = 60;
public LineMoveInfo( )
{
moveType = LineMoveType.None;
this.moveStep = MoveStep.Wait;
IsInWait = false;
}
public DateTime LastSetpTime { get; set; }
/// <summary>
/// =true表示满足一个等待条件,就可以完成此步骤的等待
/// </summary>
public bool OneWaitCanEndStep = false;
/// <summary>
/// 操作类型
/// </summary>
private LineMoveType moveType = LineMoveType.None;
public LineMoveType MoveType
{
get { return moveType; }
}
/// <summary>
/// 是否再当前步骤等待中
/// </summary>
public bool IsInWait { get; set; }
/// <summary>
/// 上一个执行步骤
/// </summary>
public MoveStep PreMoveStep { get; set; }
/// <summary>
/// 当前执行到的步骤
/// </summary>
private MoveStep moveStep;
/// <summary>
/// 可以循环运动的次数(轴卡运动才需要)
/// </summary>
public int CanWhileCount = 0;
/// <summary>
/// VMI流水线运动步骤记录
/// </summary>
public MoveStep MoveStep
{
get { return moveStep; }
}
public void NextMoveStep(MoveStep step)
{
PreMoveStep = moveStep;
moveStep = step;
LastSetpTime = DateTime.Now;
IsInWait = true;
WaitList = new List<WaitResultInfo>();
OneWaitCanEndStep = false;
CanWhileCount = 5;
TimeOutSeconds = 60;
}
/// <summary>
/// 当前步骤执行完成
/// </summary>
public void EndStepWait()
{
IsInWait = false;
WaitList = new List<WaitResultInfo>();
}
public void NewMove(LineMoveType type )
{
moveStep = MoveStep.Wait;
this.moveType = type;
LastSetpTime = DateTime.Now;
WaitList = new List<WaitResultInfo>();
}
public void EndMove()
{
this.moveType = LineMoveType.None;
// this.MoveParam = null;
moveStep = MoveStep.Wait;
LastSetpTime = DateTime.Now;
IsInWait = false;
WaitList = new List<WaitResultInfo>();
CanWhileCount = 0;
}
public LineMoveInfo clone()
{
return (LineMoveInfo)this.MemberwiseClone();
}
public List<WaitResultInfo> WaitList = new List<WaitResultInfo>();
/// <summary>
/// 重置之后继续出入库时,退回上一个步骤执行
/// </summary>
public void BackStep()
{
moveStep = PreMoveStep;
IsInWait = false;
}
}
public class WaitResultInfo
{
private WaitResultInfo()
{
}
public static WaitResultInfo WaitIO(string ioType, IO_VALUE ioValue)
{
WaitResultInfo wait = new WaitResultInfo();
wait.CanWhileMoveCount = 0;
wait.WaitType = 2;
wait.IoType = ioType;
wait.IoValue = ioValue;
wait.IsEnd = false;
return wait;
}
public static WaitResultInfo WaitTime(int MScends)
{
WaitResultInfo wait = new WaitResultInfo();
wait.CanWhileMoveCount = 0;
wait.WaitType = 3;
wait.TimeMSeconds = MScends;
wait.IsEnd = false;
return wait;
}
public string ToStr()
{
if (WaitType == 1)
{
}
else if (WaitType == 2)
{
return "IO信号等待,IO类型【" + IoType + "】,等待值【" + IoValue + "】";
}
else if (WaitType == 3)
{
return "时间等待:【" + TimeMSeconds + "】毫秒";
}
else
{
return "Wait位置类型:WaitType=【" + WaitType + "】";
}
return "";
}
/// <summary>
/// 当未结束时可以重复运动的次数
/// </summary>
public int CanWhileMoveCount { get; set; }
/// <summary>
/// 等待结果,1=轴运动,2=IO运动,3=时间,4=电钢,5=硕科电机,6=等待轴原点信号
/// </summary>
public int WaitType { get; set; }
/// <summary>
/// IO类型
/// </summary>
public String IoType { get; set; }
/// <summary>
/// IO值
/// </summary>
public IO_VALUE IoValue { get; set; }
/// <summary>
/// 等待的毫秒
/// </summary>
public int TimeMSeconds { get; set; }
/// <summary>
/// 是否已经结束
/// </summary>
public bool IsEnd{ get; set; }
}
internal class WaitEnum
{
/// <summary>
/// 伺服运动
/// </summary>
internal static int W001_AxisMove = 1;
/// <summary>
/// 信号到达
/// </summary>
internal static int W002_IOValue = 2;
/// <summary>
/// 时间等待
/// </summary>
internal static int W003_Time = 3;
/// <summary>
/// 电钢运动
/// </summary>
internal static int W004_StellMove = 4;
/// <summary>
/// 硕科电机
/// </summary>
internal static int W005_ShuoKe = 5;
/// <summary>
/// 轴原点信号
/// </summary>
internal static int W006_AxisOrg = 6;
}
public enum LineMoveType
{
/// <summary>
/// 没有任何操作
/// </summary>
None = 0,
/// <summary>
/// 入库
/// </summary>
InStore = 1,
/// <summary>
/// 出库
/// </summary>
OutStore = 2,
/// <summary>
/// 原点返回
/// </summary>
ReturnHome = 3,
/// <summary>
/// 重置
/// </summary>
StoreReset = 4,
}
}
using log4net;
using OnlineStore.Common;
using OnlineStore.DeviceLibrary;
using OnlineStore.LoadCSVLibrary;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace OnlineStore.DeviceLibrary
{
/// <summary>
/// 等待启动/已经停止,初始化完成, 正常运行中,可以进行新的处理,忙碌,重置
/// </summary>
public enum RunStatus
{
/// <summary>
/// 等待启动/已经停止
/// </summary>
Wait = 0,
/// <summary>
/// 初始化 ,原点返回状态中
/// </summary>
HomeMoving = 1,
/// <summary>
/// 设备正在重置中,请稍后
/// </summary>
Reset = 2,
/// <summary>
/// 正常运行中,可以进行新的处理
/// </summary>
Runing = 3,
/// <summary>
/// 正在忙碌中,请稍后
/// </summary>
Busy = 4,
}
public enum MoveStep
{
/// <summary>
/// 无操作,等待状态
/// </summary>
Wait = 0,
#region VMI流水线原点返回和重置步骤
/// <summary>
/// VMI流水线复位:所有阻挡上升
/// </summary>
VMI_H_StopUp=010,
/// <summary>
/// VMI流水线复位:线体开始转动
/// </summary>
VMI_H_LineRun = 011,
#endregion
}
public enum AlarmType
{
/// <summary>
/// 没有报警
/// </summary>
None = 0,
///// <summary>
///// 轴报警
///// </summary>
//AxisAlarm = 1,
/// <summary>
/// 收到急停
/// </summary>
SuddenStop = 10,
///// <summary>
///// 没有气压信号
///// </summary>
//NoAirCheck = 11,
///// <summary>
///// 轴运动错误,没有达到指定脉冲,但是io判断已停止运动
///// </summary>
//AxisMoveError = 20,
/// <summary>
/// io信号超时未收到
/// </summary>
IoSingleTimeOut = 30,
///// <summary>
///// 电钢报警
///// </summary>
//StellAlarm=50,
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OnlineStore.LoadCSVLibrary
{
//这里利用AttributeUsage 来设置我们的自定义属性的应用范围,这里定义的可以用于类,结构和方法的声明
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class CSVAttribute : Attribute
{
public CSVAttribute(string fieldName)
{
FieldName = fieldName;
}
private string fieldName;
public string FieldName
{
get { return fieldName; }
set { fieldName = value; }
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OnlineStore.LoadCSVLibrary
{
public class CVSFieldNotMatchingExection : ApplicationException
{
public CVSFieldNotMatchingExection(string message)
: base(message)
{
}
public override string Message
{
get
{
return base.Message;
}
}
}
public class PositionAlreadyExistingExection : ApplicationException
{
public PositionAlreadyExistingExection(string message)
: base(message)
{
}
public override string Message
{
get
{
return base.Message;
}
}
}
}
using log4net;
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace OnlineStore.LoadCSVLibrary
{
public class CSVReaderBase
{
public static char Spilt_Char = ',';
public static readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// 获取一个类所有的《字段,AttributeName列名》集合
/// </summary>
public static Dictionary<string, string> getProAttributeMap(Type type)
{
Dictionary<string, string> proCsvMap = new Dictionary<string, string>();
PropertyInfo[] props = type.GetProperties();
foreach (PropertyInfo prop in props)
{
object[] array = prop.GetCustomAttributes(false);
if (array.Length > 0)
{
CSVAttribute att = (CSVAttribute)array[0];
if (att != null)
{
string csvName = att.FieldName;
proCsvMap.Add(prop.Name, csvName);
}
}
}
return proCsvMap;
}
/// <summary>
/// 获取一个类所有的《字段,AttributeName列名》集合
/// </summary>
public static Dictionary<string, string> getConfigProAttributeMap(Type type)
{
Dictionary<string, string> proCsvMap = new Dictionary<string, string>();
PropertyInfo[] props = type.GetProperties();
foreach (PropertyInfo prop in props)
{
object[] array = prop.GetCustomAttributes( false);
if (array.Length > 0)
{
ConfigProAttribute att = (ConfigProAttribute)array[0];
if (att != null)
{
string csvName = att.FieldName;
if (proCsvMap.ContainsKey(csvName))
{
}
else
{
proCsvMap.Add(csvName, prop.Name);
}
}
}
}
return proCsvMap;
}
/// <summary>
/// 读取一个csv文件的所有内容
/// </summary>
protected static string[] ReadCSVFile(string filePath)
{
if (!File.Exists(filePath))
{
throw new FileNotFoundException("未找到文件:" + filePath);
}
string[] lines = File.ReadAllLines(filePath, Encoding.GetEncoding("gbk"));
return lines;
}
/// <summary>
/// 把数据写入csv中
/// </summary>
protected static bool WriteCSVFile(string filePath, string[] lines)
{
try
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
File.WriteAllLines(filePath, lines, Encoding.GetEncoding("gbk"));
//备份保存
try
{
FileInfo file = new FileInfo(filePath);
string date = DateTime.Now.ToString("yyyy-MM-dd");
string targetBackPath = @"C:\configBack\" + date + @"\";
if (!Directory.Exists(targetBackPath))
{
Directory.CreateDirectory(targetBackPath);
}
string fileName = file.Name;
string backFile = targetBackPath + fileName;
if (File.Exists(backFile))
{
File.Delete(backFile);
}
File.WriteAllLines(backFile, lines, Encoding.GetEncoding("gbk"));
}
catch (Exception e)
{
LOGGER.Error("出错:", e);
}
}
catch (Exception ex)
{
LOGGER.Error(ex.ToString());
return false;
}
return true;
}
protected static Dictionary<string, int> GetAllTitleIndex(string lineValue)
{
Dictionary<string, int> titleIndex = new Dictionary<string, int>();
var array = lineValue.Split(',');
//验证列
for (int i = 0; i < array.Length; i++)
{
string title = array[i];
titleIndex.Add(title, i);
}
return titleIndex;
}
protected static Dictionary<string, int> GetTitleIndex(string lineValue, List<string> cvsTitleList)
{
Dictionary<string, int> titleIndex = new Dictionary<string, int>();
var array = lineValue.Split(',');
//验证列
for (int i = 0; i < array.Length; i++)
{
string title = array[i];
if (cvsTitleList.Contains(title))
{
titleIndex.Add(title, i);
}
}
if (titleIndex.Count < cvsTitleList.Count)
{
foreach (string str in cvsTitleList)
{
if (!titleIndex.ContainsKey(str))
{
LOGGER.Error("未找到必须列:" + str + ",加载数据失败!");
throw new CVSFieldNotMatchingExection("未找到必须列:" + str + ",加载数据失败!");
}
}
}
return titleIndex;
}
protected static void BackConfig(string filePath, string[] lines)
{
////备份保存
//try
//{
// FileInfo file = new FileInfo(filePath);
// string date = DateTime.Now.ToString("yyyy-MM-dd");
// string targetBackPath = @"C:\configBack\" + date + @"\";
// if (!Directory.Exists(targetBackPath))
// {
// Directory.CreateDirectory(targetBackPath);
// }
// string fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "." + file.Name;
// string backFile = targetBackPath + fileName;
// if (File.Exists(backFile))
// {
// File.Delete(backFile);
// }
// File.WriteAllLines(backFile, lines, Encoding.GetEncoding("gbk"));
//}
//catch (Exception e)
//{
// LogUtil.error("备份【" + filePath + "】到C:configBack出错:" + e.ToString());
//}
//备份保存
try
{
FileInfo file = new FileInfo(filePath);
string date = DateTime.Now.ToString("yyyy-MM-dd");
string targetBackPath = @"D:\configBack\" + date + @"\";
if (!Directory.Exists(targetBackPath))
{
Directory.CreateDirectory(targetBackPath);
}
string fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "." + file.Name;
string backFile = targetBackPath + fileName;
if (File.Exists(backFile))
{
File.Delete(backFile);
}
File.WriteAllLines(backFile, lines, Encoding.GetEncoding("gbk"));
}
catch (Exception e)
{
LogUtil.error("备份【" + filePath + "】到D:configBack出错:" + e.ToString());
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace OnlineStore.LoadCSVLibrary
{
public class CSVConfigReader : CSVReaderBase
{
private static Dictionary<Type, Dictionary<string, string>> allItemProTitleMap = null;
/// <summary>
/// 获取一个类所有的《字段,AttributeName列名》集合
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private static Dictionary<string, string> GetProMapByType(Type type)
{
if (allItemProTitleMap == null)
{
allItemProTitleMap = new Dictionary<Type, Dictionary<string, string>>();
}
if (!allItemProTitleMap.ContainsKey(type))
{
allItemProTitleMap.Add(type, getProAttributeMap(type));
}
return allItemProTitleMap[type];
}
public static List<ConfigBase> ReadConfig(string filePath)
{
List<ConfigBase> configList = new List<ConfigBase>();
string[] lines = ReadCSVFile(filePath);
int index = 0;
Dictionary<string, int> allTitleIndex = new Dictionary<string, int>();
int typeIndex = -1;
foreach (var line in lines)
{
if (index == 0)
{
//根据配置表来读取数据
allTitleIndex = GetAllTitleIndex(line);
//必须有列【类型】
if (allTitleIndex.Count < 0 || !allTitleIndex.ContainsKey("类型"))
{
LOGGER.Error("未找到必须列:类型,加载数据失败!");
throw new CVSFieldNotMatchingExection("未找到必须列:类型,加载数据失败!");
}
typeIndex = allTitleIndex["类型"];
}
else
{
var array = line.Split(',');
//每一列必须有类型字段
string typeValue = array[typeIndex];
if (typeValue.Equals(""))
{
continue;
}
Type type = typeof(ConfigBase);
if (typeValue.Equals(ConfigItemType.DI) || typeValue.Equals(ConfigItemType.DO))
{
type = typeof(ConfigIO);
}
else if (typeValue.Equals(ConfigItemType.AXIS))
{
type = typeof(ConfigMoveAxis);
}
Dictionary<string, string> proTitleMap = getProAttributeMap(type);
ConfigBase bllIns = (ConfigBase)type.Assembly.CreateInstance(type.FullName);
//取得属性集合
PropertyInfo[] props = type.GetProperties();
int listIndex = 0;
List<string> proNameList = new List<string>(proTitleMap.Keys);
List<string> cvsTitleList = new List<string>(proTitleMap.Values);
List<string> checkFiledList = new List<string>(proNameList);
Dictionary<string, int> proIndexMap = new Dictionary<string, int>();
for (int i = 0; i<cvsTitleList.Count; i++)
{
proIndexMap.Add(cvsTitleList[i], i);
}
foreach (string key in cvsTitleList)
{
try
{
if (allTitleIndex.ContainsKey(key))
{
try
{
int titIndex = allTitleIndex[key];
string value = array[titIndex];
//string proName = proNameList[listIndex];
string proName = proNameList[proIndexMap[key]];
checkFiledList.Remove(proName);
PropertyInfo prop = props.First(c => c.Name == proName);//获取同名属性
if (prop != null && !value.Equals(""))
{
if (value.Equals("") && prop.PropertyType.Name.ToLower().Contains("int"))
{
prop.SetValue(bllIns, Convert.ChangeType(-1, prop.PropertyType), null);//赋值****在这里需要考虑类型问题
}
else if (value.Equals("") && prop.PropertyType.Name.ToLower().Contains("byte"))
{
prop.SetValue(bllIns, Convert.ChangeType(0, prop.PropertyType), null);//赋值****在这里需要考虑类型问题
}
else
{
prop.SetValue(bllIns, Convert.ChangeType(value, prop.PropertyType), null);//赋值****在这里需要考虑类型问题
}
}
}
catch (Exception ex)
{
LOGGER.Error("filepath=" + filePath + ",index=" + index + ",key=" + key + "出错:" + ex.ToString());
}
listIndex++;
}
}
catch (Exception ex)
{
LOGGER.Error("filepath=" + filePath + ",index=" + index + ",key=" + key + "出错:" + ex.ToString());
}
}
bllIns.CheckField();
configList.Add(bllIns);
}
index++;
}
return configList;
}
public static VMLLineConfig LoadConfig(string filePath)
{
VMLLineConfig config = null;
config = new VMLLineConfig(filePath);
return LoadConfig(config);
}
public static VMLLineConfig LoadConfig(VMLLineConfig config)
{
LOGGER.Info("开始读取文件:" + config.ConfigFilePath);
if (config == null || config.ConfigFilePath.Equals(""))
{
return null;
}
List<ConfigBase> configList = ReadConfig(config.ConfigFilePath);
config.LoadConfig(configList);
return config;
}
public static bool SaveBoxPosition<T>(string filePath, T newConfig)
{
Type type = typeof(T);
//取得属性集合
PropertyInfo[] props = type.GetProperties();
string[] lines = ReadCSVFile(filePath);
BackConfig(filePath, lines);
int index = 0;
Dictionary<string, int> titleIndex = new Dictionary<string, int>();
string[] newLines = new string[lines.Length] ;
// 获取一个类所有的《字段,AttributeName列名》集合
Dictionary<string, string> proMap = GetProMapByType(typeof(ConfigBase));
List<string> proNameList = new List<string>(proMap.Keys);
List<string> csvNameList = new List<string>(proMap.Values);
Dictionary<string, int> allTitleIndex = new Dictionary<string, int>();
foreach (var line in lines)
{
newLines[index] = line;
var array = line.Split(',');
if (index == 0)
{
allTitleIndex = GetAllTitleIndex(line);
newLines[index] = line;
}
else
{
if (array.Length > 0 && array[0].ToString().Equals(ConfigItemType.PRO))
{
string[] newArray = array;
string proName = array[2];
string proValue = array[3];
try
{
PropertyInfo prop = props.First(c => c.Name == proName);//获取同名属性
if (prop != null)
{
string newValue = prop.GetValue(newConfig, null).ToString();
newArray[3] = newValue;
}
}
catch (Exception e) {
LOGGER.Error("出错:" + e.ToString());
}
string newLine = "";
foreach (string s in newArray)
{
newLine = newLine + s + ",";
}
newLines[index] = newLine;
}
}
index++;
}
return WriteCSVFile(filePath, newLines);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OnlineStore.LoadCSVLibrary
{
//这里利用AttributeUsage 来设置我们的自定义属性的应用范围,这里定义的可以用于类,结构和方法的声明
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class ConfigProAttribute : Attribute
{
public ConfigProAttribute(string fieldName)
{
FieldName = fieldName;
IsMust = true;
}
public ConfigProAttribute(string fieldName,bool ismust)
{
FieldName = fieldName;
IsMust = ismust;
}
private string fieldName;
public string FieldName
{
get { return fieldName; }
set { fieldName = value; }
}
/// <summary>
/// 是否必须的
/// </summary>
public bool IsMust { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace OnlineStore.LoadCSVLibrary
{
public class IO_Type
{
private static List<string> TypeList = null;
public static List<string> GetTypeList()
{
if (TypeList == null)
{
TypeList = new List<string>();
var p = typeof(IO_Type).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static);
foreach (var item in p)
{
TypeList.Add(item.Name);
}
}
return TypeList;
}
/// <summary>
/// DI,急停,SuddenStop_BTN,0,PRO_AOI_IP_1,0,急停,X721,DI-01,0,
/// </summary>
public static string SuddenStop_BTN = "SuddenStop_BTN";
/// <summary>
/// DI,复位,Reset_BTN,1,PRO_AOI_IP_1,0,复位,X722,DI-02,0,
/// </summary>
public static string Reset_BTN = "Reset_BTN";
/// <summary>
/// DI,出料线入口检测,L2_InCheck,2,PRO_AOI_IP_1,0,出料线入口检测,X723,DI-03,0,
/// </summary>
public static string L2_InCheck = "L2_InCheck";
/// <summary>
/// DI,出料线检测1,L2_StopCheck1,3,PRO_AOI_IP_1,0,出料线检测1,X724,DI-04,0,
/// </summary>
public static string L2_StopCheck1 = "L2_StopCheck1";
/// <summary>
/// DI,料串切换气缸前进端,Switch_Forward_Sig,4,PRO_AOI_IP_1,0,料串切换气缸前进端,X725,DI-05,0,
/// </summary>
//public static string Switch_Forward_Sig = "Switch_Forward_Sig";
/// <summary>
///DI,出料线出口检测,L2_OutCheck,5,PRO_AOI_IP_1,0,出料线出口检测,X726,DI-06,0,
/// </summary>
public static string L2_OutCheck = "L2_OutCheck";
/// <summary>
/// DI,入料线入口检测,L1_InCheck,6,PRO_AOI_IP_1,0,入料线入口检测,X727,DI-07,0,
/// </summary>
public static string L1_InCheck = "L1_InCheck";
/// <summary>
///DI,入料线阻挡检测,L1_StopCheck,7,PRO_AOI_IP_1,0,入料线阻挡检测,X728,DI-08,0,
/// </summary>
public static string L1_StopCheck = "L1_StopCheck";
/// <summary>
/// DI,料串切换气缸后退端,Switch_Back_Sig,8,PRO_AOI_IP_1,0,料串切换气缸后退端,X729,DO-01,0,
/// </summary>
//public static string Switch_Back_Sig = "Switch_Back_Sig";
/// <summary>
///DI,入料线出口检测,L1_OutCheck,9,PRO_AOI_IP_1,0,入料线出口检测,X730,DO-02,0,
/// </summary>
public static string L1_OutCheck = "L1_OutCheck";
/// <summary>
/// DI,出料线人工取料信号,L1_ManualRecSig,10,PRO_AOI_IP_1,0,出料线人工取料信号,X731,DO-03,0,
/// </summary>
public static string L1_ManualRecSig = "L1_ManualRecSig";
/// <summary>
/// DI,进料线体横移上升端,L1_UpDown_Up_Sig,11,PRO_AOI_IP_1,0,进料线体横移上升端,X732,DO-04,0,
/// </summary>
public static string L1_UpDown_Up_Sig = "L1_UpDown_Up_Sig";
/// <summary>
/// DI,进料线体横移下降端,L1_UpDown_Down_Sig,12,PRO_AOI_IP_1,0,进料线体横移下降端,X733,DO-05,0,
/// </summary>
public static string L1_UpDown_Down_Sig = "L1_UpDown_Down_Sig";
/// <summary>
///DI,出料线体横移上升端,L2_UpDown_Up_Sig,13,PRO_AOI_IP_1,0,出料线体横移上升端,X734,DO-06,0,
/// </summary>
public static string L2_UpDown_Up_Sig = "L2_UpDown_Up_Sig";
/// <summary>
/// DI,出料线体横移下降端,L2_UpDown_Down_Sig,14,PRO_AOI_IP_1,0,出料线体横移下降端,X735,DO-07,0,
/// </summary>
public static string L2_UpDown_Down_Sig = "L2_UpDown_Down_Sig";
/// <summary>
/// DI,包装料架检测信号,PackingShelf_Sig,15,PRO_AOI_IP_1,0,包装料架检测信号,X736,DO-08,0,
/// </summary>
//public static string PackingShelf_Sig = "PackingShelf_Sig";
/// <summary>
/// DO,运行状态(指示灯),AutoRun_HddLed,0,PRO_AOI_IP_1,0,运行状态(指示灯),Y721,DI-01,0,
/// </summary>
public static string AutoRun_HddLed = "AutoRun_HddLed";
/// <summary>
///DO,故障状态(指示灯),Alarm_HddLed,1,PRO_AOI_IP_1,0,故障状态(指示灯),Y722,DI-02,0,
/// </summary>
//public static string Alarm_HddLed = "Alarm_HddLed";
/// <summary>
///DO,进料线驱动电机运转,L1_Run,2,PRO_AOI_IP_1,0,进料线驱动电机运转,Y723,DI-03,0,
/// </summary>
public static string L1_Run = "L1_Run";
/// <summary>
/// DO,出料线驱动电机运转,L2_Run,3,PRO_AOI_IP_1,0,出料线驱动电机运转,Y724,DI-04,0,
/// </summary>
public static string L2_Run = "L2_Run";
/// <summary>
/// DO,进料线阻挡1下降,L1_StopDown,4,PRO_AOI_IP_1,0,进料线阻挡1下降,Y725,DI-05,0,
/// </summary>
public static string L1_StopDown = "L1_StopDown";
/// <summary>
/// DO,进料线阻挡2下降,L1_StopDown2,5,PRO_AOI_IP_1,0,进料线阻挡2下降,Y726,DI-06,0,
/// </summary>
//public static string L1_StopDown2 = "L1_StopDown2";
/// <summary>
/// DO,进料线出口阻挡下降,L1_OutStopDown,6,PRO_AOI_IP_1,0,进料线出口阻挡下降,Y727,DI-07,0,
/// </summary>
public static string L1_OutStopDown = "L1_OutStopDown";
/// <summary>
/// DO,出料线出口阻挡下降,L2_OutStopDown,7,PRO_AOI_IP_1,0,出料线阻挡1下降,Y728,DI-08,0,
/// </summary>
public static string L2_OutStopDown = "L2_OutStopDown";
/// <summary>
/// DO,出料线阻挡2下降,L2_OutStopDown2,8,PRO_AOI_IP_1,0,出料线阻挡2下降,Y729,DO-01,0,
/// </summary>
//public static string L2_StopDown2 = "L2_StopDown2";
/// <summary>
/// DO,出料线出口阻挡下降,L2_StopDown,9,PRO_AOI_IP_1,0,出料线出口阻挡下降,Y730,DO-02,0,
/// </summary>
public static string L2_StopDown = "L2_StopDown";
/// <summary>
/// DO,横移机构上升SOL,Traverse_Up_SOL,10,PRO_AOI_IP_1,0,横移机构上升SOL,Y731,DO-03,0,
/// </summary>
public static string Traverse_Up_SOL = "Traverse_Up_SOL";
/// <summary>
/// DO,横移机构下降SOL,Traverse_Down_SOL,11,PRO_AOI_IP_1,0,横移机构下降SOL,Y732,DO-04,0,
/// </summary>
public static string Traverse_Down_SOL = "Traverse_Down_SOL";
/// <summary>
/// DO,横移电机1运转,Traverse1_Run,12,PRO_AOI_IP_1,0,横移电机1运转,Y733,DO-05,0,
/// </summary>
public static string Traverse1_Run = "Traverse1_Run";
/// <summary>
/// DO,横移电机2运转,Traverse2_Run,13,PRO_AOI_IP_1,0,横移电机2运转,Y734,DO-06,0,
/// </summary>
// public static string Traverse2_Run = "Traverse2_Run";
/// <summary>
/// DO,料串切换气缸前进,Switch_Forward,14,PRO_AOI_IP_1,0,料串切换气缸前进,Y735,DO-07,0,
/// </summary>
//public static string Switch_Forward = "Switch_Forward";
/// <summary>
/// DO,料串切换气缸后退,Switch_Back,15,PRO_AOI_IP_1,0,料串切换气缸后退,Y736,DO-08,0,
/// </summary>
//public static string Switch_Back = "Switch_Back";
}
public enum IO_VALUE
{
/// <summary>
/// 低位
/// </summary>
LOW = 0,
/// <summary>
/// 高位
/// </summary>
HIGH = 1,
}
}
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace OnlineStore.LoadCSVLibrary
{
public class RobotConfig
{
public static Dictionary<string, string> ProIOIpMap = null;
public const string IOIP_Str = "PRO_AOI_IP";
public static readonly ILog LOGGER = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// ID
/// </summary>
public int Id { get; set; }
/// <summary>
/// 编号,与服务器通信的唯一标识
/// </summary>
public string CID { get; set; }
/// <summary>
/// 料层类型
/// </summary>
public string StoreType { get; set; }
/// <summary>
/// 配置文件路径
/// </summary>
public string ConfigFilePath { get; set; }
/// <summary>
/// 输入IO配置
/// 手动VMI流水线输入Io列表,key=对应的坐标位置的positionNum
/// </summary>
public Dictionary<String, ConfigIO> StoreDIList { get; set; }
/// <summary>
/// 输出IO配置
/// 手动VMI流水线输出Io列表,key=对应的坐标位置的positionNum
/// </summary>
public Dictionary<String, ConfigIO> StoreDOList { get; set; }
/// <summary>
/// VMI流水线所有用到的IO卡名称
/// </summary>
public List<string> DIODeviceNameList { get; set; }
/// <summary>
/// VMI流水线所有用到的运动卡名称
/// </summary>
public List<string> SMCDeviceNameList { get; set; }
/// <summary>
/// 必须拥有的DI列表
/// </summary>
protected List<string> MustHaveDIList { get; set; }
/// <summary>
/// 必须拥有的DO列表
/// </summary>
protected List<string> MustHaveDOList { get; set; }
protected virtual void initMustHavePro()
{
MustHaveDIList = new List<string>();
MustHaveDOList = new List<string>();
}
public RobotConfig()
{
initMustHavePro();
}
public RobotConfig(int id, string cid, string type, string filepath)
{
initMustHavePro();
MustHaveDIList = new List<string>();
MustHaveDOList = new List<string>();
this.Id = id;
this.CID = cid;
this.StoreType = type;
this.ConfigFilePath = filepath;
}
public virtual void LoadConfig(List<ConfigBase> configList)
{
StoreDIList = new Dictionary<string, ConfigIO>();
StoreDOList = new Dictionary<string, ConfigIO>();
DIODeviceNameList = new List<string>();
SMCDeviceNameList = new List<string>();
//取得属性集合
PropertyInfo[] props = GetType().GetProperties();
Dictionary<string, string> proMap = CSVReaderBase.getConfigProAttributeMap(GetType());
List<string> checkProList = new List<string>(proMap.Keys);//用来检测attribute属性都应该要配置值
foreach (ConfigBase con in configList)
{
if (con.ProType == ConfigItemType.AXIS || con.ProType == ConfigItemType.PRO)
{
if (proMap.ContainsKey(con.ProName))
{
string proName = proMap[con.ProName];
checkProList.Remove(con.ProName);
PropertyInfo prop = props.First(c => c.Name == proName);//获取同名属性
if (prop != null)
{
if (con.ProType == ConfigItemType.AXIS)
{
//如果属性存在
prop.SetValue(this, Convert.ChangeType(con, prop.PropertyType), null);//赋值****在这里需要考虑类型问题
ConfigMoveAxis axis = (ConfigMoveAxis)con;
if (!SMCDeviceNameList.Contains(axis.DeviceName) && axis.GetAxisValue() >= 0)
{
SMCDeviceNameList.Add(axis.DeviceName);
}
}
else if (con.ProType == ConfigItemType.PRO)
{
prop.SetValue(this, Convert.ChangeType(con.ProValue, prop.PropertyType), null);//赋值
}
}
else
{
LOGGER.Error("配置文件:" + this.ConfigFilePath + ",属性名=" + con.ProName + "的属性未找到匹配字段!");
}
}
else if (!ProIOIpMap.ContainsKey(con.ProName) && con.ProName.ToUpper().Contains(IOIP_Str))
{
ProIOIpMap.Add(con.ProName, con.ProValue);
if (!DIODeviceNameList.Contains(con.ProValue))
{
DIODeviceNameList.Add(con.ProValue);
}
}
else
{
LOGGER.Error("配置文件:" + this.ConfigFilePath + ",属性名=" + con.ProName + "的属性未找到匹配字段!");
}
}
else if (con.ProType == ConfigItemType.DI)
{
if (IO_Type.GetTypeList().Contains(con.ProName))
{
ConfigIO io = (ConfigIO)con;
if (!DIODeviceNameList.Contains(io.DeviceName) && (io.GetIOAddr() >= 0 || io.GetIOAddr() >= 0)&&io.DeviceName.Contains(IOIP_Str).Equals(false))
{
DIODeviceNameList.Add(io.DeviceName);
}
this.StoreDIList.Add(con.ProName, io);
}
else
{
LOGGER.Error("配置文件:" + this.ConfigFilePath + ",属性名=" + con.ProName + "的属性未找到匹配字段!");
}
}
else if (con.ProType == ConfigItemType.DO)
{
if (IO_Type.GetTypeList().Contains(con.ProName))
{
ConfigIO io = (ConfigIO)con;
if (!DIODeviceNameList.Contains(io.DeviceName) && io.GetIOAddr() >= 0 && io.DeviceName.Contains(IOIP_Str).Equals(false))
{
DIODeviceNameList.Add(io.DeviceName);
}
this.StoreDOList.Add(con.ProName, io);
}
else
{
LOGGER.Error("配置文件:" + this.ConfigFilePath + ",属性名=" + con.ProName + "的属性未找到匹配字段!");
}
}
}
if (checkProList.Count >= 0)
{
//常规属性检测
foreach (string str in checkProList)
{
PropertyInfo prop = props.First(c => c.Name == str);//获取同名属性
//判断是否必须要配置
object[] array = prop.GetCustomAttributes(false);
if (array.Length > 0)
{
ConfigProAttribute att = (ConfigProAttribute)array[0];
if (att != null)
{
if (att.IsMust)
{
throw new CVSFieldNotMatchingExection(this.ToString() + "的属性" + str + "必须配置值!");
}
else
{
if (prop.PropertyType.Equals(typeof(int)))
{
prop.SetValue(this, Convert.ChangeType(0, prop.PropertyType), null);//赋值****在这里需要考虑类型问题
}
else
{
prop.SetValue(this, Convert.ChangeType("", prop.PropertyType), null);//赋值****在这里需要考虑类型问题
}
}
}
}
}
//DI检测
foreach (string di in MustHaveDIList)
{
if (!StoreDIList.ContainsKey(di))
{
throw new CVSFieldNotMatchingExection(this.ToString() + "的DI属性" + di + "必须配置值!");
}
}
//DO检测
foreach (string io in MustHaveDOList)
{
if (!this.StoreDOList.ContainsKey(io))
{
throw new CVSFieldNotMatchingExection(this.ToString() + "的DO属性" + io + "必须配置值!");
}
}
}
}
public ConfigIO getWaitIO(string ioType)
{
if (StoreDIList.ContainsKey(ioType))
{
return StoreDIList[ioType];
}
else if (StoreDOList.ContainsKey(ioType))
{
return StoreDOList[ioType];
}
return null;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OnlineStore.LoadCSVLibrary
{
public class VMLLineConfig : RobotConfig
{
public VMLLineConfig()
: base()
{
}
public VMLLineConfig( string filepath)
: base(1, "", "", filepath)
{
}
/// <summary>
/// PRO,休眠秒数(秒),SleepSeconds,180,,,,,,,
/// </summary>
[ConfigProAttribute("SleepSeconds", false)]
public int SleepSeconds { get; set; }
/// <summary>
/// PRO IO信号超时时间(毫秒) IOSingle_TimerOut 5000
/// </summary>
[ConfigProAttribute("IOSingle_TimerOut", false)]
public int IOSingle_TimerOut { get; set; }
/// <summary>
/// PRO IO模块对应的DI数量 IO_DILength 192.168.200.10#16;192.168.200.11#4
/// </summary>
[ConfigProAttribute("IO_DILength")]
public string IO_DILength { get; set; }
/// <summary>
/// PRO 模块对应的DO数量 IO_DOLength 192.168.200.10#16;192.168.200.11#4
/// </summary>
[ConfigProAttribute("IO_DOLength")]
public string IO_DOLength { get; set; }
/// <summary>
///PRO,L1线AGV节点名称,L1_AgvName,A2,,,,,,,
/// </summary>
[ConfigProAttribute("L1_AgvName")]
public string L1_AgvName { get; set; }
/// <summary>
/// PRO,L2线AGV节点名称,L2_AgvName,A1,,,,,,,
/// </summary>
[ConfigProAttribute("L2_AgvName")]
public string L2_AgvName { get; set; }
public double AirCheckSeconds = 60;
/// <summary>
///PRO,L2线入口RFIDIP,L2_In_RFIDIP,192.168.103.108,,,,,, ,
/// </summary>
[ConfigProAttribute("L2_In_RFIDIP", false)]
public string L2_In_RFIDIP { get; set; }
/// <summary>
/// PRO,L2线出口RFIDIP,L2_Out_RFIDIP,192.168.103.107,,,,,, ,
/// </summary>
[ConfigProAttribute("L2_Out_RFIDIP", false)]
public string L2_Out_RFIDIP { get; set; }
protected override void initMustHavePro()
{
MustHaveDIList = new List<string>();
MustHaveDOList = new List<string>();
MustHaveDIList.Add(IO_Type.SuddenStop_BTN);
MustHaveDIList.Add(IO_Type.Reset_BTN);
MustHaveDOList.Add(IO_Type.AutoRun_HddLed);
//MustHaveDOList.Add(IO_Type.Alarm_HddLed);
}
private Dictionary<string, ushort> DILengthMap = null;
private Dictionary<string, ushort> DOLengthMap = null;
public ushort GetDILength(string ip)
{
try
{
if (DILengthMap == null)
{
DILengthMap = new Dictionary<string, ushort>();
string[] arrayList = IO_DILength.Split(';');
foreach (string str in arrayList)
{
string[] arrStr = str.Split('#');
if (arrStr.Length == 2)
{
string ioip = arrStr[0];
ushort length = Convert.ToUInt16(arrStr[1]);
DILengthMap.Add(ioip, length);
}
}
}
}
catch (Exception ex)
{
}
if (DILengthMap.ContainsKey(ip))
{
return DILengthMap[ip];
}
return 16;
}
public ushort GetDOLength(string ip)
{
try
{
if (DOLengthMap == null)
{
DOLengthMap = new Dictionary<string, ushort>();
string[] arrayList = IO_DOLength.Split(';');
foreach (string str in arrayList)
{
string[] arrStr = str.Split('#');
if (arrStr.Length == 2)
{
string ioip = arrStr[0];
ushort length = Convert.ToUInt16(arrStr[1]);
DOLengthMap.Add(ioip, length);
}
}
}
}
catch (Exception ex)
{
}
if (DOLengthMap.ContainsKey(ip))
{
return DOLengthMap[ip];
}
return 16;
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{064BEBF5-8FAA-4EA2-A5F3-A06E6E7D9251}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>OnlineStore.LoadCSVLibrary</RootNamespace>
<AssemblyName>LoadCSVLibrary</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="log4net, Version=1.2.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\dll\log4net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CSVExection.cs" />
<Compile Include="Config\ConfigItemBase.cs" />
<Compile Include="Config\ConfigProAttribute.cs" />
<Compile Include="Config\bean\VMLLineConfig.cs" />
<Compile Include="Config\bean\IO_Type.cs" />
<Compile Include="CSVAttribute.cs" />
<Compile Include="Config\CSVConfigReader.cs" />
<Compile Include="CSVReaderBase.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Config\bean\RobotConfig.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Common\Common.csproj">
<Project>{43cdd09e-fcf3-4960-a01d-3bbfe9933122}</Project>
<Name>Common</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("LoadCVSLibrary")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LoadCVSLibrary")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("f9998ad1-83a5-4191-8109-7e255e71744e")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
[assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyVersion("1.0.0.0")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
namespace UserFromControl
{
partial class IOTextControl
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 组件设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
this.SuspendLayout();
//
// label1
//
this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(30, 4);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(53, 12);
this.label1.TabIndex = 0;
this.label1.Text = "测试一下";
//
// pictureBox1
//
this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.pictureBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
this.pictureBox1.Location = new System.Drawing.Point(0, 0);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(25, 27);
this.pictureBox1.TabIndex = 1;
this.pictureBox1.TabStop = false;
this.pictureBox1.Click += new System.EventHandler(this.pictureBox1_Click);
//
// pictureBox2
//
this.pictureBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.pictureBox2.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
this.pictureBox2.Location = new System.Drawing.Point(0, 0);
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.Size = new System.Drawing.Size(25, 27);
this.pictureBox2.TabIndex = 2;
this.pictureBox2.TabStop = false;
this.pictureBox2.Click += new System.EventHandler(this.pictureBox2_Click);
//
// IOTextControl
//
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
this.Controls.Add(this.pictureBox2);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.label1);
this.Name = "IOTextControl";
this.Size = new System.Drawing.Size(202, 27);
this.Load += new System.EventHandler(this.IOStatusControl_Load);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.PictureBox pictureBox2;
}
}
此文件类型无法预览
此文件类型无法预览
此文件的差异太大,无法显示。
此文件的差异太大,无法显示。
此文件类型无法预览
此文件的差异被折叠, 点击展开。
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!