Commit eddb5fd6 张东亮

init

0 个父辈
正在显示 181 个修改的文件 包含 4985 行增加0 行删除
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain
## 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
*.DS_Store

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27130.2024
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}") = "ABBRobotTest", "source\ABBRobotTest\ABBRobotTest.csproj", "{C147236C-D1E7-4CD1-9344-79C948110F8F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DoubleLineClient", "source\DoubleLineClient_3D\DoubleLineClient.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
{C147236C-D1E7-4CD1-9344-79C948110F8F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C147236C-D1E7-4CD1-9344-79C948110F8F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C147236C-D1E7-4CD1-9344-79C948110F8F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C147236C-D1E7-4CD1-9344-79C948110F8F}.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
文件属性发生变化
此文件类型无法预览
此文件类型无法预览
文件属性发生变化
此文件类型无法预览
此文件类型无法预览
此文件类型无法预览
此文件类型无法预览
此文件的差异被折叠, 点击展开。
此文件类型无法预览
此文件类型无法预览
此文件类型无法预览
文件属性发生变化
此文件类型无法预览
此文件的差异太大,无法显示。
文件属性发生变化
此文件类型无法预览
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ABBRobotTest
{
public class ABBRobotServer
{
private static TcpServer tcpserver = null;
public static bool IsStart = false;
private static int ABBServerPort = ConfigAppSettings.GetIntValue(Setting_Init.ABBServerPort );
public static string ErrorInfo = "";
internal static string Cmd_movep = "movep";
internal static string Cmd_moveget = "moveget";
internal static string Cmd_moveput = "moveput";
internal static string Cmd_validateP = "validateP";
public static Dictionary<string, Client> ClientMap = new Dictionary<string, Client>();
//最后一次软件控制移动到的位置
public static string LastSendPoint = "";
public delegate void OpEnd(string result);
private static event OpEnd OnCmdEnd;
private static object LockObj = new object();
public static void StartServer( )
{
try
{
if (ABBServerPort <= 0)
{
ABBServerPort = 21;
}
if (!IsStart)
{
ClientMap = new Dictionary<string, Client>();
if (tcpserver == null)
{
tcpserver = new TcpServer();
}
IsStart = true;
tcpserver.Start(ABBServerPort);
tcpserver.AcceptClientEvent += Tcpserver_AcceptClientEvent;
LogUtil.info("ABBRobotServer在端口[" + ABBServerPort + "]监听!");
tcpserver.ReviceMsgEvent += tcp_ReviceMsgEvent;
}
}catch(Exception ex)
{
LogUtil.error("ABBRobotServer启动[" + ABBServerPort + "]监听错误:" + ex.ToString());
}
}
private static void Tcpserver_AcceptClientEvent(Client client)
{
SaveRobotClient(client);
}
private static object MapLock = "";
private static void SaveRobotClient( Client client)
{
lock (MapLock)
{
IPEndPoint clientipe = (IPEndPoint)client.ClientSocket.RemoteEndPoint;
string ip = clientipe.Address.ToString();
if (ClientMap.ContainsKey(ip))
{
ClientMap.Remove(ip);
}
ClientMap.Add(ip, client);
}
}
public static void StopServer()
{
try
{
if (IsStart)
{
IsStart = false;
tcpserver.Stop();
}
}
catch (Exception ex)
{
LogUtil.error("关闭 监听出错:" + ex.ToString());
}
}
private static void tcp_ReviceMsgEvent(Client client, string msg)
{
try
{
if (String.IsNullOrEmpty(msg))
{
return;
}
ProcessMsg(client, msg);
}
catch (Exception ex)
{
LogUtil.error("处理ABB消息【" + msg + "】出错:" + ex.ToString());
}
}
private static bool ProcessMsg(Client client, string msg)
{
IPEndPoint clientipe = (IPEndPoint)client.ClientSocket.RemoteEndPoint;
string add = clientipe.Address.ToString();
// string[] msgArray = msg.Split(cmd_spilt);
msg = msg.Replace("\r", "") ;
LogUtil.info("Revice[" + add + "]:[" + msg + "]");
msg = msg.Replace(";", "");
string OkStr = "OK";
if (msg.Contains("ERROR"))
{
ErrorInfo = msg;
}
else if(msg.Contains(Cmd_movep)&& msg.Contains(OkStr))
{
OnCmdEnd?.Invoke(msg);
}
else if (msg.Contains(Cmd_moveput) && msg.Contains(OkStr))
{
OnCmdEnd?.Invoke(msg);
} else if (msg.Contains(Cmd_moveget) && msg.Contains(OkStr))
{
OnCmdEnd?.Invoke(msg);
}else if (msg.Contains(OkStr))
{
OnCmdEnd?.Invoke(msg);
}
return false;
}
public static bool MoveToP(string robotIp, string PointName, string moveType="L" , double targetSpeed = 100, OpEnd AfterCmd = null)
{
ABBRobotServer.OnCmdEnd = AfterCmd;
return SendMovePoint(robotIp, Cmd_movep, PointName,moveType,targetSpeed.ToString());
}
public static bool MoveToPut(string robotIp, string PointName, string moveType = "L", double targetSpeed = 100, OpEnd AfterCmd = null)
{
ABBRobotServer.OnCmdEnd = AfterCmd;
return SendMovePoint(robotIp, Cmd_moveput, PointName, moveType, targetSpeed.ToString());
}
public static bool MoveToGet(string robotIp, string PointName, string moveType = "L", double targetSpeed = 100, OpEnd AfterCmd = null)
{
ABBRobotServer.OnCmdEnd = AfterCmd;
return SendMovePoint(robotIp, Cmd_moveget, PointName, moveType, targetSpeed.ToString());
}
public static bool SendCmd(string robotIp, string moveCmd,string PointName, string moveType = "L", double targetSpeed = 100, OpEnd AfterCmd = null)
{
ABBRobotServer.OnCmdEnd = AfterCmd;
if (moveCmd.Equals(Cmd_moveget) || moveCmd.Equals(Cmd_movep) || moveCmd.Equals(Cmd_moveput)||moveCmd.Equals(Cmd_validateP))
{
return SendMovePoint(robotIp, moveCmd, PointName, moveType, targetSpeed.ToString());
}
return false;
}
public static bool ValidateP(string robotIp, string pointName, OpEnd AfterCmd = null)
{
ABBRobotServer.OnCmdEnd = AfterCmd;
return SendMovePoint(robotIp, Cmd_validateP, pointName);
}
private static bool SendMovePoint(string robotIp, string param1, string param2, string param3 = "L", string param4 = "10")
{
Client client = null;
lock (LockObj)
{
if (ClientMap.ContainsKey(robotIp))
{
client = ClientMap[robotIp];
}
}
if (client != null)
{
string str = param1 + "," + param2 + "," + param3 + "," + param4 + "";
LastSendPoint = param2;
LogUtil.info("Send [" + robotIp + "] : [" + str + "]");
SendStrToClient(client, str);
return true;
}
return false;
}
private static bool SendStrToClient(Client client, string sendMsg)
{
if (client != null && client.ClientSocket.Connected)
{
byte[] sendBuffer = new byte[1024];
sendBuffer = Encoding.UTF8.GetBytes(sendMsg);
client.ClientSocket.Send(sendBuffer);
return true;
}
return false;
}
internal static bool RobotIsConnect(string ip)
{
if (ClientMap.ContainsKey(ip))
{
return true;
}
return false;
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" 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>{C147236C-D1E7-4CD1-9344-79C948110F8F}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>ABBRobotTest</RootNamespace>
<AssemblyName>ABBRobotTest</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="ABB.Robotics.Controllers.PC">
<HintPath>..\..\dll\ABB\ABB.Robotics.Controllers.PC.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\dll\log4net.dll</HintPath>
</Reference>
<Reference Include="RobotStudio.Services.RobApi">
<HintPath>..\..\dll\ABB\RobotStudio.Services.RobApi.dll</HintPath>
</Reference>
<Reference Include="RobotStudio.Services.RobApi.Desktop">
<HintPath>..\..\dll\ABB\RobotStudio.Services.RobApi.Desktop.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.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="ABBRobotServer.cs" />
<Compile Include="ABBRobotManager.cs" />
<Compile Include="FrmRobotMain.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FrmRobotMain.Designer.cs">
<DependentUpon>FrmRobotMain.cs</DependentUpon>
</Compile>
<Compile Include="FrmRobotTest.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FrmRobotTest.Designer.cs">
<DependentUpon>FrmRobotTest.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="FrmRobotMain.resx">
<DependentUpon>FrmRobotMain.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="FrmRobotTest.resx">
<DependentUpon>FrmRobotTest.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</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" />
</Project>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<appSettings>
<!--是否开机自动启动料仓-->
<add key="App_AutoRun" value="1" />
<add key="App_Title" value="流水线客户端" />
<!--Server address-->
<add key="http.server" value="http://localhost/myproject/service/store/emptyPosForPutin"/>
<!--storeType-->
<add key="Line_moveEquip_count" value="18" />
<add key="Line_feedingEquip_count" value="4" />
<add key="Line_providingEquip_count" value="4" />
<add key ="Line_dischargeLine_count" value ="2"/>
<!--start oneSecondMoveconfig-->
<add key="ConfigPath_Line" value="\LineConfig\Config_Line.csv" />
<add key="ConfigPath_MoveEquip" value="\LineConfig\MoveEquip\Config_MoveEquip.csv" />
<add key="ConfigPath_FeedingEquip" value="\LineConfig\Config_FeedingEquip.csv" />
<add key="ConfigPath_ProvidingEquip" value="\LineConfig\Config_ProvidingEquip.csv" />
<add key ="ConfigPath_DischargeLine" value ="\LineConfig\Config_DischargeLine.csv"/>
<add key="Line_Type" value="RC_LINE" />
<add key="Line_CID" value="rc1250" />
<!--end oneSecondMoveconfig-->
<!--摄像机名称列表配置,用#分割-->
<add key="CameraName" value="GigE:MV-CE100-30GC (00C69898519)#GigE:MV-CE100-30GC (00C95305929)" />
<!--二维码类型列表配置,用#分割,一维码=Barcode 二维码: QR Code#Data Matrix ECC 200#Micro QR Code-->
<add key="CodeType" value="QR Code" />
<!--<add key="CodeType" value="Data Matrix ECC 200"/>-->
<add key="ACBaudRate" value="115200" />
<!--二维码参数文件所在路径,文件名与二维码类型名一样-->
<add key="CodeParamPath" value="\CodeParam\" />
<add key="Config_Pwd" value="123456" />
<!--出库等待料盘拿走的时间,秒-->
<add key="OutStoreWaitSeconds" value="10" />
<add key="UseAIOBOX" value="1" />
<!--流水线监听端口-->
<add key="TCPServerPort" value="5246" />
<add key="ClientSettingsProvider.ServiceUri" value="" />
<add key ="DIMS" value ="120"/>
<add key ="DOMS" value ="300"/>
<add key ="LineRunTest" value ="1"/>
<!--ABB机器人服务器-->
<add key ="ABBServerPort" value ="21"/>
</appSettings>
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logs/Line-RC1250.log" />
<param name="Encoding" value="UTF-8" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyy-MM-dd" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="[%date][%t]%-5p %m%n" />
</layout>
</appender>
<root>
<level value="Info" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
\ No newline at end of file
using ABB.Robotics.Controllers;
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ABBRobotTest
{
public partial class FrmRobotMain : Form
{
public FrmRobotMain()
{
Control.CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
}
private string SelConIp = "";
private void FrmRobotMain_Load(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
LoadCom();
LoadListView();
LoadController();
timer1.Start();
ABBRobotServer.StartServer();
ABBRobotManager.ControllerAddEvent += ABBRobotManager_ControllerAddEvent;
LogUtil.logBox = this.richTextBox1;
}
private void ABBRobotManager_ControllerAddEvent(ControllerInfo controller)
{
int index = listView1.Items.Count;
AddConInfo(controller, index);
}
private void LoadCom()
{
comMoveCmd.Items.Clear();
comMoveCmd.Items.Add(ABBRobotServer.Cmd_movep);
comMoveCmd.Items.Add(ABBRobotServer.Cmd_moveget);
comMoveCmd.Items.Add(ABBRobotServer.Cmd_moveput);
comMoveCmd.Items.Add(ABBRobotServer.Cmd_validateP);
comMoveP.Items.Clear();
for(int i = 1; i <= 30; i++)
{
comMoveP.Items.Add("p" + i);
}
comMoveP.SelectedIndex = 0;
comMoveCmd.SelectedIndex = 0;
radioButton1.Checked = true;
}
private void LoadController()
{
ABBRobotManager.LoadController();
int i = 0;
foreach (ControllerInfo con in ABBRobotManager.controllerInfoMap.Values)
{
AddConInfo(con,i);
i++;
}
}
private void AddConInfo(ControllerInfo con,int i)
{
ListViewItem item = new ListViewItem(con.IPAddress.ToString());
item.SubItems.Add(con.Id.ToString());
item.SubItems.Add(con.Availability.ToString());
item.SubItems.Add(con.IsVirtual.ToString());
item.SubItems.Add(con.SystemName);
item.SubItems.Add(con.Version.ToString());
item.SubItems.Add(con.ControllerName);
item.Tag = con.IPAddress;
string state = ABBRobotManager.GetRobotState(con.IPAddress.ToString());
item.SubItems.Add(state);
this.listView1.Items.Add(item);
this.listView1.Items[i].Selected = true;
SelConIp = con.IPAddress.ToString();
}
private void LoadListView()
{
this.listView1.Columns.Clear();
AddHealder("IPAddress", 150);
AddHealder("ID", 180);
// AddHealder("设备状态", 100);
AddHealder("Availability", 150);
AddHealder("IsVirtual", 150);
AddHealder("SystemName", 150);
AddHealder("Version", 150);
AddHealder("ControllerName", 180);
AddHealder("Statue", 180);
}
private void AddHealder(string name, int widht)
{
ColumnHeader preSendwire = new ColumnHeader();
preSendwire.Text = name; //设置列标题
preSendwire.Width = widht; //设置列宽度
preSendwire.TextAlign = HorizontalAlignment.Left; //设置列的对齐方式
this.listView1.Columns.Add(preSendwire); //将列头添加到ListView控件。
}
private void timer1_Tick(object sender, EventArgs e)
{
int i = 0;
List<string> conList = new List<string>(ABBRobotManager.controllerMap.Keys);
foreach (string con in conList)
{
string result = ABBRobotManager.GetRobotState(con);
listView1.Items[i].SubItems[7].Text = result;
i++;
}
if (ABBRobotServer.RobotIsConnect(SelConIp))
{
groupMove.Enabled = true;
}
else
{
groupMove.Enabled = false;
}
if (String.IsNullOrEmpty(SelConIp))
{
lblState.Text = "";
return;
}
bool isOk = false;
int esValue = ABBRobotManager.GetSingalState(SelConIp);
if (esValue.Equals(1))
{
SetMsg("机器人[" + SelConIp + "]急停中", Color.Red);
}
else
{
lblState.Text = "";
int isRun = ABBRobotManager.GetSingalState(SelConIp, ABBRobotManager.DO_IsRun);
if (isRun.Equals(1))
{
isOk = true;
SetMsg("机器人程序正常运行中", Color.Green);
}
else
{
SetMsg("机器人[" + SelConIp + "]程序未运行", Color.Red);
}
}
if (isOk && ABBRobotServer.RobotIsConnect(SelConIp))
{
if (!groupMove.Enabled)
{
groupMove.Enabled = true;
}
}
else if (groupMove.Enabled)
{
groupMove.Enabled = false;
}
}
private void SetMsg(string msg,Color foreColor)
{
lblState.Text = msg;
lblState.ForeColor = foreColor;
}
private void btnStart_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(SelConIp))
{
return;
}
ABBRobotManager.StartRobotBySingle(SelConIp);
}
private void btnStop_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(SelConIp))
{
return;
}
ABBRobotManager.StopRobotBySingle(SelConIp);
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems != null && listView1.SelectedItems.Count > 0)
{
int index = listView1.SelectedItems[0].Index;
string ip = listView1.Items[index].SubItems[0].Text.ToString();
if (!String.IsNullOrEmpty(ip))
{
SelConIp = ip;
if (ABBRobotServer.RobotIsConnect(SelConIp))
{
groupMove.Enabled = true;
}
else
{
groupMove.Enabled = false;
}
}
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void FrmRobotMain_FormClosing(object sender, FormClosingEventArgs e)
{
ABBRobotManager.DisposeControllers();
ABBRobotServer.StopServer();
LogUtil.logBox = null;
}
private void btnMove_Click(object sender, EventArgs e)
{
string moveCmd = comMoveCmd.Text;
string PPoint = comMoveP.Text;
string MType = "L";
if (radioButton2.Checked)
{
MType = "J";
}
int speed =(int) numSpeed.Value;
if (speed > 500)
{
speed = 100;
}
ABBRobotServer.SendCmd(SelConIp, moveCmd, PPoint, MType, speed, MoveEnd);
}
private void MoveEnd(string msg)
{
LogUtil.info("机器人运动完成:" + msg);
}
private void btnClearLog_Click(object sender, EventArgs e)
{
this.richTextBox1.Clear();
LogUtil.ClearLog();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="timer1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>
\ No newline at end of file
namespace ABBRobotTest
{
partial class FrmRobotTest
{
/// <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 Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.btnStart = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.button4 = new System.Windows.Forms.Button();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.btnStop = new System.Windows.Forms.Button();
this.listView1 = new System.Windows.Forms.ListView();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.SuspendLayout();
//
// btnStart
//
this.btnStart.Location = new System.Drawing.Point(27, 486);
this.btnStart.Name = "btnStart";
this.btnStart.Size = new System.Drawing.Size(108, 46);
this.btnStart.TabIndex = 0;
this.btnStart.Text = "启动";
this.btnStart.UseVisualStyleBackColor = true;
this.btnStart.Visible = false;
this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(160, 155);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(108, 46);
this.button2.TabIndex = 2;
this.button2.Text = "IO set";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button3
//
this.button3.Location = new System.Drawing.Point(272, 155);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(108, 46);
this.button3.TabIndex = 3;
this.button3.Text = "IO reset";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// timer1
//
this.timer1.Interval = 1000;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// button4
//
this.button4.Location = new System.Drawing.Point(591, 155);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(108, 46);
this.button4.TabIndex = 5;
this.button4.Text = "get io List";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// comboBox1
//
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.Font = new System.Drawing.Font("微软雅黑", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Items.AddRange(new object[] {
"di_start",
"di_startatmain",
"di_stop",
"aaa"});
this.comboBox1.Location = new System.Drawing.Point(16, 163);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(121, 28);
this.comboBox1.TabIndex = 6;
//
// btnStop
//
this.btnStop.Location = new System.Drawing.Point(164, 486);
this.btnStop.Name = "btnStop";
this.btnStop.Size = new System.Drawing.Size(108, 46);
this.btnStop.TabIndex = 7;
this.btnStop.Text = "停止";
this.btnStop.UseVisualStyleBackColor = true;
this.btnStop.Visible = false;
this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
//
// listView1
//
this.listView1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.listView1.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.listView1.FullRowSelect = true;
this.listView1.GridLines = true;
this.listView1.HideSelection = false;
this.listView1.Location = new System.Drawing.Point(11, 12);
this.listView1.MultiSelect = false;
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(872, 117);
this.listView1.TabIndex = 192;
this.listView1.UseCompatibleStateImageBehavior = false;
this.listView1.View = System.Windows.Forms.View.Details;
this.listView1.SelectedIndexChanged += new System.EventHandler(this.listView1_SelectedIndexChanged_1);
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(716, 135);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(159, 159);
this.richTextBox1.TabIndex = 193;
this.richTextBox1.Text = "";
//
// FrmRobotTest
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(887, 595);
this.Controls.Add(this.richTextBox1);
this.Controls.Add(this.listView1);
this.Controls.Add(this.btnStop);
this.Controls.Add(this.comboBox1);
this.Controls.Add(this.button4);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.btnStart);
this.Name = "FrmRobotTest";
this.Text = "network scanning";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FrmRobotTest_FormClosing);
this.Load += new System.EventHandler(this.FrmRobotTest_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button btnStart;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.Button btnStop;
private System.Windows.Forms.ListView listView1;
private System.Windows.Forms.RichTextBox richTextBox1;
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="timer1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>
\ No newline at end of file
using log4net.Config;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ABBRobotTest
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
XmlConfigurator.Configure();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FrmRobotMain());
}
}
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("ABBRobotTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ABBRobotTest")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("c147236c-d1e7-4cd1-9344-79c948110f8f")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本: 4.0.30319.42000
//
// 对此文件的更改可能导致不正确的行为,如果
// 重新生成代码,则所做更改将丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace ABBRobotTest.Properties
{
/// <summary>
/// 强类型资源类,用于查找本地化字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或删除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// 返回此类使用的缓存 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ABBRobotTest.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 覆盖当前线程的 CurrentUICulture 属性
/// 使用此强类型的资源类的资源查找。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
\ No newline at end of file
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ABBRobotTest.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
文件属性发生变化
<?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\JsonHelper.cs" />
<Compile Include="util\LogUtil.cs" />
<Compile Include="util\MyWebClient.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="util\TcpServer.cs" />
</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>
/// 系统启动时自动启动双层流水线,=1时自动启动,并隐藏窗口,=0时不需要
/// </summary>
public static string App_AutoRun = "App_AutoRun";
/// <summary>
/// 系统主界面标题
/// </summary>
public static string App_Title = "App_Title";
public static string httpAddr = "httpAddr";
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 ABBServerPort = "ABBServerPort";
public static string BenQ_AGV = "BenQ_AGV";
public static string DefaultSpeed = "DefaultSpeed";
}
}
文件属性发生变化
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OnlineStore.Common
{
/// <summary>
/// 与服务器通信用对象
/// </summary>
public class Operation
{
/// <summary>
/// 双层流水线唯一标识
/// </summary>
private string _cid = "";
public string cid
{
get { return _cid; }
set { _cid = value; }
}
/// <summary>
/// 请求序列号
/// </summary>
public int seq { get; set; }
/// <summary>
/// 操作码(0无操作(发送双层流水线状态给服务器),
/// 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>
/// 整体双层流水线状态
/// 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>
/// 单台双层流水线状态(包含流水线)
/// </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>
/// 双层流水线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>
/// 双层流水线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))
{
LogUtil.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)
{
LogUtil.info("未找到配置:" + 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)
{
LogUtil.info("未找到配置:" + 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)
{
LogUtil.info("未找到配置:" + 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( "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( "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( "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("RollingLogFileAppender");
public static readonly ILog rfidLog = LogManager.GetLogger("RfidLog");
public static Dictionary<int, DateTime> lastErrorLogTime = new Dictionary<int, DateTime>();
public static System.Windows.Forms.RichTextBox logBox = null;
public static int showCount = 25;
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 RfidLog(string msg)
{
rfidLog.Debug(msg);
}
public static void error(string errorMsg, int type, int seconds = 10)
{
if (lastErrorLogTime.ContainsKey(type))
{
TimeSpan span = DateTime.Now - lastErrorLogTime[type];
if (span.TotalSeconds > seconds)
{
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("") && (ex == null))
{
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(System.Windows.Forms.RichTextBox box)
{
logBox = box;
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 log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Security;
using System.Reflection;
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)
{
HttpWebRequest result =(HttpWebRequest ) base.GetWebRequest(address);
result.Timeout = this._timeout;
// result.KeepAlive = false;
result.ServicePoint.Expect100Continue = false;
return result;
}
}
public class HttpHelper
{
public static bool PingURLIP(string url, int ms = 100)
{
string[] urlArray = url.Split('/');
if (urlArray.Length > 3)
{
string ip = urlArray[2];
Ping pingSender = new Ping();
PingReply reply = pingSender.Send(ip, ms);//第一个参数为ip地址,第二个参数为ping的时间
if (reply.Status == IPStatus.Success)
{
//通
return true;
}
else
{
LogUtil.error("Ping IP " + ip + " : false");
//不通
return false;
}
}
return true;
}
//public static readonly ILog LOGGER = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static string Post(string url, string paramData, int timeOut = 2000)
{
return Post(url, paramData, Encoding.UTF8, timeOut);
}
private static int isLog = ConfigAppSettings.GetIntValue(Setting_Init.Server_Log_Open);
public static string Post(string url, string paramData, Encoding encoding, int timeOut = 2000)
{
if (paramData.Equals(""))
{
int index = url.IndexOf("?");
if (index > 0)
{
paramData = url.Substring(index + 1, url.Length - index - 1);
url = url.Substring(0, index);
}
}
if (isLog == 1)
{
LogUtil.info("给服务器发送数据【" + url + "】【" + paramData + "】 ");
}
string result = "";
if (url.ToLower().IndexOf("https", System.StringComparison.Ordinal) > -1)
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback((sender, certificate, chain, errors) => { return true; });
}
try
{
using (var wc = new MyWebClient(timeOut))
{
if (string.IsNullOrEmpty(wc.Headers["Content-Type"]))
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
wc.Encoding = encoding;
result = wc.UploadString(url, "POST", paramData);
} //LogUtil.info(result);
}
catch (WebException ex)
{
LogUtil.error("POST [" + url + "] WebException :" + ex.ToString(), 101);
}
catch (Exception e)
{
LogUtil.error("POST [" + url + "] ERROR:" + e.ToString(), 101);
}
if (!result.Contains("null") && result.Length != 0)
{
//LogUtil.debug(LOGGER,"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, 1002);
}
return "";
}
}
}
\ No newline at end of file
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());
}
}
}
}
using System;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using log4net;
namespace OnlineStore.Common
{
public class TcpServer
{
//public static readonly ILog LOGGER = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// 接受消息时的间隔
/// </summary>
public static int ReviceMsgMS = 100;
private Thread m_serverThread;
private Socket m_serverSocket;
public delegate void ReviceMsg(Client client, string Msg);
public event ReviceMsg ReviceMsgEvent;
private delegate void ReceiveMessageDelegate(Client client);
public event AcceptClientDelegate AcceptClientEvent;
public delegate void AcceptClientDelegate(Client client);
ReceiveMessageDelegate receiveMessageDelegate;
private bool isRun = true;
private int serverPort = 0;
private void logLocalIp()
{
string[] addresses = GetLocalAddresses();
string iplist = "本机IP:[";
if (addresses.Length > 0)
{
for (int i = 0; i < addresses.Length; i++)
{
if (addresses.Length != 0)
{
iplist = iplist + " " + addresses[i];
}
}
}
LogUtil.info(iplist + "]");
}
/// <summary>
/// 开始服务
/// </summary>
public void Start(int m_serverPort)
{
try
{
isRun = true;
m_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, m_serverPort);
this.serverPort = m_serverPort;
m_serverSocket.Bind(localEndPoint);
m_serverSocket.Listen(10);
m_serverThread = new Thread(new ThreadStart(ReceiveAccept));
m_serverThread.Start();
LogUtil.info(" Server start listen : " + m_serverPort);
logLocalIp();
//this.AddRunningInfo(">> " + DateTime.Now.ToString() + " Server started.");
}
catch (SocketException se)
{
throw new Exception(se.Message);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 停止服务
/// </summary>
public void Stop()
{
try
{
isRun = false;
m_serverThread.Interrupt(); // 线程终止
m_serverSocket.Close(); // Socket Close
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private void ReceiveAccept()
{
while (isRun)
{
Client client = new Client();
try
{
client.ClientSocket = m_serverSocket.Accept();
IPEndPoint clientipe = (IPEndPoint)client.ClientSocket.RemoteEndPoint;
client.ipAdd = clientipe.Address;
LogUtil.info("[" + serverPort + "]有新的客户端链接上:[" + client.ipAdd.ToString() + "]");
AcceptClientEvent?.Invoke(client);
receiveMessageDelegate = new ReceiveMessageDelegate(ReceiveMessages);
receiveMessageDelegate.BeginInvoke(client, ReceiveMessagesCallback, "");
}
catch (Exception ex)
{
LogUtil.error("ReceiveAccept方法,客户端【" + client.ipAdd.ToString() + "】:" + ex.Message);
//throw new Exception(ex.Message);
}
}
}
// private StringBuilder sb = new StringBuilder(); //这个是用来保存:接收到了的,但是还没有结束的消息
private int receiveBufferSize = 1024;
private string terminateString = ";";
public void ReceiveMessages(Client client) //这个函数会被以线程方式运行
{
try
{
StringBuilder sb = new StringBuilder();
Socket socket = (Socket)client.ClientSocket;
while (true)
{
byte[] buffer = new byte[receiveBufferSize]; //buffer大小,此处为1024
int receivedSize = socket.Receive(buffer);
if (receivedSize > 0)
{
string rawMsg = Encoding.ASCII.GetString(buffer, 0, receivedSize);
int rnFixLength = terminateString.Length; //这个是指消息结束符的长度,此处为\r\n
for (int i = 0; i < rawMsg.Length;) //遍历接收到的整个buffer文本
{
if (i <= rawMsg.Length - rnFixLength)
{
if (rawMsg.Substring(i, rnFixLength) != terminateString)//非消息结束符,则加入sb
{
sb.Append(rawMsg[i]);
i++;
}
else
{
this.ReviceMsgEvent.Invoke(client, sb.ToString());//找到了消息结束符,触发消息接收完成事件
sb = new StringBuilder();
i += rnFixLength;
}
}
else
{
sb.Append(rawMsg[i]);
i++;
}
}
}
Thread.Sleep(ReviceMsgMS);
}
}
catch (SocketException e)
{
LogUtil.error("客户端{" + client.ipAdd.ToString() + "]:" + e.ToString(), 106);
}
catch (Exception ex)
{
LogUtil.error("客户端{" + client.ipAdd.ToString() + "]:" + ex.ToString(), 105);
}
}
//private void ReceiveMessages(Client client)
//{
// try
// {
// while (true)
// {
// byte[] receiveBuffer = new byte[1024];
// //int size = ;
// int size = client.ClientSocket.Receive(receiveBuffer);
// string strReceiveData = Encoding.ASCII.GetString(receiveBuffer, 0, size);
// if (!string.IsNullOrEmpty(strReceiveData))
// {
// LogUtil.info(LOGGER, "收到数据:" + strReceiveData);
// // this.AddRunningInfo(">> Receive data from [" + client.ClientSocket.RemoteEndPoint.ToString()+ "]:" + strReceiveData);
// string strSendData = "OK. The content is:" + strReceiveData;
// //LogUtil.info(LOGGER, "OK. The content is:" + strReceiveData);
// int sendBufferSize = Encoding.Unicode.GetByteCount(strSendData);
// byte[] sendBuffer = new byte[sendBufferSize];
// sendBuffer = Encoding.Unicode.GetBytes(strSendData);
// client.ClientSocket.Send(sendBuffer);
// }
// }
// }
// catch (SocketException e)
// {
// LogUtil.error(LOGGER, e.ToString());
// }
// catch (Exception ex)
// {
// LOGGER.Error(ex.ToString());
// }
//}
private void ReceiveMessagesCallback(IAsyncResult AR)
{
try
{
receiveMessageDelegate.EndInvoke(AR);
}
catch (Exception ex)
{
LogUtil.error(ex.ToString());
}
}
/// <summary>
/// 获取本机地址列表
/// </summary>
public string[] GetLocalAddresses()
{
// 获取主机名
string strHostName = Dns.GetHostName();
// 根据主机名进行查找
IPHostEntry iphostentry = Dns.GetHostEntry(strHostName);
string[] retval = new string[iphostentry.AddressList.Length];
int i = 0;
foreach (IPAddress ipaddress in iphostentry.AddressList)
{
if (ipaddress.AddressFamily != AddressFamily.InterNetworkV6)
{
retval[i] = ipaddress.ToString();
i++;
}
}
return retval;
}
}
/// <summary>
/// 客户端会话信息类
/// </summary>
public class Client
{
Socket m_clientSocket;
public Client() { }
public IPAddress ipAdd { get; set; }
public Socket ClientSocket
{
get { return m_clientSocket; }
set { this.m_clientSocket = value; }
}
}
}
文件属性发生变化
<?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>
<LangVersion>7.3</LangVersion>
</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>
<LangVersion>7.3</LangVersion>
</PropertyGroup>
<ItemGroup>
<Reference Include="ABB.Robotics.Controllers.PC">
<HintPath>..\..\dll\ABB\ABB.Robotics.Controllers.PC.dll</HintPath>
</Reference>
<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="AsaPL.AgvClient">
<HintPath>..\..\dll\AsaPL.AgvClient.dll</HintPath>
</Reference>
<Reference Include="Client, Version=1.0.0.1, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<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="RestSharp">
<HintPath>..\..\dll\RestSharp.dll</HintPath>
</Reference>
<Reference Include="RFIDLibrary">
<HintPath>..\..\dll\RFID\RFIDLibrary.dll</HintPath>
</Reference>
<Reference Include="RobotStudio.Services.RobApi">
<HintPath>..\..\dll\ABB\RobotStudio.Services.RobApi.dll</HintPath>
</Reference>
<Reference Include="RobotStudio.Services.RobApi.Desktop">
<HintPath>..\..\dll\ABB\RobotStudio.Services.RobApi.Desktop.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Extensions" />
<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="agvClient\AgvClient_Dbline.cs" />
<Compile Include="bean\RobotBase.cs" />
<Compile Include="deviceLibrary\ABB\ABBControl.cs" />
<Compile Include="doubleLine\DoubleLineBean.cs" />
<Compile Include="doubleLine\DoubleLineBean_bufShelf.cs" />
<Compile Include="doubleLine\DoubleLineBean_lineShelf.cs" />
<Compile Include="doubleLine\DoubleLineBean_S1Shelf.cs" />
<Compile Include="doubleLine\RobotMoveBean.cs" />
<Compile Include="manager\BenQ_AGV.cs" />
<Compile Include="manager\LineManager.cs" />
<Compile Include="bean\WaitUtil.cs" />
<Compile Include="agvClient\AgvClient.cs" />
<Compile Include="bean\LineMoveInfo.cs" />
<Compile Include="deviceLibrary\IO\AIOBOX\AIOBOXManager.cs" />
<Compile Include="deviceLibrary\IO\IOManager.cs" />
<Compile Include="deviceLibrary\IO\KangNaiDe\KNDManager.cs" />
<Compile Include="deviceLibrary\IO\KangNaiDe\MasterTcpClient.cs" />
<Compile Include="manager\HttpServer.cs" />
<Compile Include="manager\RFIDManager.cs" />
<Compile Include="manager\Static_String.cs" />
<Compile Include="packageLine\AgvProcess.cs" />
<Compile Include="packageLine\bean\StepInfo.cs" />
<Compile Include="packageLine\PackageLine.cs" />
<Compile Include="packageLine\BenQProcess.cs" />
<Compile Include="packageLine\PackageLine_BuffShelf.cs" />
<Compile Include="packageLine\PackageLine_BenQInShelf.cs" />
<Compile Include="packageLine\PackageLine_PkgInShelf.cs" />
<Compile Include="packageLine\PackageLine_PkgStation.cs" />
<Compile Include="packageLine\PackageLine_S2Station.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="bean\MoveStep.cs">
<SubType>Code</SubType>
</Compile>
</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\DoubleLineConfig.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 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 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 content)
{
//RFIDData data = new RFIDData(content);
LogUtil.debug ("收到 AgvClient_CloseDoor [" + id + "] [" + content + "] ");
}
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.OutL_AgvName))
{
//if (IOManager.IOValue(IO_Type.OutL_InCheck).Equals(IO_VALUE.LOW))
//{
// Task.Factory.StartNew(delegate
// {
// // SetStatus(id, "", ClientAction.MayEnter);
// LogUtil.info(logName + " ,等待OutL_InCheck");
// try
// {
// WaitUtil.Wait(60000, delegate
// {
// return IOManager.IOValue(IO_Type.OutL_InCheck).Equals(IO_VALUE.HIGH);
// }, "等待OutL_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 + " OutL_InCheck 检测到有料架,AGV的料架无法进入");
// SetStatus(id, "", ClientAction.None, ClientLevel.High);
//}
}
// else if (id.Equals(LineManager.Config.InL_AgvName))
{
//string shefId = LineManager.VMILine.LastOutShelfId;
//if (IOManager.IOValue(IO_Type.InL_OutStopCheck).Equals(IO_VALUE.HIGH))
//{
// LineManager.VMILine.StopIOMove(IO_Type.InL_OutStopDown, 1500);
// //agvClient.MayLeave(id);
// // SetStatus(id, shefId, ClientAction.MayLeave);
// LogUtil.info(logName + "下降 InL_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 + " InL_OutStopCheck 未检测到料架,无法将料架进入AGV");
// SetStatus(id, "", ClientAction.None, ClientLevel.High);
//}
}
}
private static void AgvClient_Arrive(string id, string content)
{
UpdateAction(id, Asa.ClientAction.Arrive);
//RFIDData data = new RFIDData(content);
LogUtil.info("收到 AgvClient_Arrive [" + id + "] [" + content + "] ");
}
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 System;
using System.Collections.Generic;
using AsaPL;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace OnlineStore.DeviceLibrary
{
public class AgvClient_Dbline
{
private static string ServerIp = ConfigAppSettings.GetValue(Setting_Init.BenQ_AGV);
public AsaPL.AgvClient agvClient;
private static bool isInit = false;
public static Dictionary<string, AsaPL.ClientAction> actionMap = new Dictionary<string, AsaPL.ClientAction>();
public bool A5_InProcess = false;
public bool A6_InProcess = false;
public string A6_RFID { get; set; } = "";
#region A5 Action
/// <summary>
/// 上下满
/// </summary>
public void A5_None()
{
SetStatus("A5", "", ClientAction.None,ClientLevel.Low);
}
public void A5_NeedD()
{
SetStatus("A5", "", ClientAction.NeedD,ClientLevel.Low);
}
public void A5_NeedD_High()
{
SetStatus("A5", "", ClientAction.NeedD,ClientLevel.High);
}
public void A5_NeedC()
{
SetStatus("A5", "", ClientAction.NeedC,ClientLevel.Low);
}
/// <summary>
/// 上下都未满(正常)
/// </summary>
public void A5_NeedEnter()
{
SetStatus("A5", "", ClientAction.NeedEnter,ClientLevel.Low);
}
public void A5_NeedEnter_High()
{
SetStatus("A5", "", ClientAction.NeedEnter, ClientLevel.High);
}
#endregion
#region A6 Action
/// <summary>
/// 上ON,下OFF
/// </summary>
public void A6_None()
{
SetStatus("A6", "", ClientAction.None);
}
/// <summary>
/// 上OFF,下OFF
/// </summary>
public void A6_NeedEnter()
{
SetStatus("A6", "", ClientAction.NeedEnter);
}
/// <summary>
/// 上ON,下ON
/// </summary>
public void A6_NeedLeave()
{
SetStatus("A6", A6_RFID, ClientAction.NeedLeave);
}
/// <summary>
/// 上OFF,下ON
/// </summary>
public void A6_NeedEnterLeave()
{
SetStatus("A6", A6_RFID, ClientAction.NeedEnterLeave);
}
#endregion
public void Init()
{
try
{
if (!isInit)
{
isInit = true;
agvClient = new AsaPL.AgvClient(ServerIp);
agvClient.CancelState = false;
agvClient.ReadyEnter += AgvClient_ReadyEnter;
agvClient.ReadyLeave += AgvClient_ReadyLeave;
agvClient.AGVFinishEnter += AgvClient_FinishEnter;
agvClient.AGVFinishLeave += AgvClient_FinishLeave;
}
actionMap = new Dictionary<string, AsaPL.ClientAction>();
agvClient.SetStatus("A5", "", ClientAction.None);
agvClient.SetStatus("A6", "", ClientAction.None);
agvClient.Connect();
LogUtil.info("初始化AGV服务");
}
catch (Exception ex)
{
LogUtil.error("初始化AGV服务 " + ServerIp + " 出错:", ex);
}
}
/// <summary>
/// 设置取消状态
/// </summary>
/// <param name="isCancel">true则ClientAction为None</param>
public void SetCancelState(bool isCancel)
{
agvClient.CancelState = isCancel;
}
/// <summary>
/// 小车准备进入
/// </summary>
/// <param name="name">节点名称</param>
private void AgvClient_ReadyEnter(string name)
{
if (name.Equals("A5"))
{
A5_InProcess = true;
A5_ReadyEnter = true;
}
else if (name.Equals("A6"))
{
A6_InProcess = true;
A6_ReadyEnter = true;
}
LogUtil.info("收到 AgvClient_ReadyEnter [" + name + "]");
}
/// <summary>
///料架准备离开
/// </summary>
/// <param name="name">节点名称</param>
private void AgvClient_ReadyLeave(string name)
{
//SetStatus(name, "", ClientAction.ReadyLeave);
if (name.Equals("A6"))
{
A6_InProcess = true;
A6_ReadyLeave = true;
}
LogUtil.info("收到 AgvClient_ReadyLeave [" + name + "] ");
}
/// <summary>
/// 料架离开小车完成
/// </summary>
/// <param name="name"></param>
private void AgvClient_FinishLeave(string name)
{
//if (name.Equals("A5"))
//{
// A5_InProcess = false;
//}
//else if (name.Equals("A6"))
//{
// A6_InProcess = false;
//}
LogUtil.info("收到 AgvClient_FinishLeave [" + name + "] ");
}
/// <summary>
/// 料架进入小车完成
/// </summary>
/// <param name="name"></param>
private void AgvClient_FinishEnter(string name)
{
//if (name.Equals("A5"))
//{
// A5_InProcess = false;
//}
//else if (name.Equals("A6"))
//{
// A6_InProcess = false;
//}
LogUtil.info("收到 AgvClient_FinishEnter [" + name + "] ");
}
/// <summary>
/// 左侧料架可以进入
/// </summary>
public bool A5_ReadyEnter { private set; get; }
/// <summary>
/// 右侧料架可以进入
/// </summary>
public bool A6_ReadyEnter { private set; get; }
/// <summary>
/// 右侧料架可以出去
/// </summary>
public bool A6_ReadyLeave { private set; get; }
public void MayEnter(string name)
{
SetStatus(name, "", ClientAction.MayEnter);
if (name.Equals("A5"))
{
A5_ReadyEnter = false;
}
else if (name.Equals("A6"))
{
A6_ReadyEnter = false;
}
}
public void MayLeave(string name)
{
SetStatus(name, "", ClientAction.MayLeave);
if (name.Equals("A6"))
{
A6_ReadyLeave = false;
}
}
public void FinishEnter(string name)
{
Task.Factory.StartNew(delegate {
SetStatus(name, "", ClientAction.FinishEnter);
Thread.Sleep(15000);
if (name.Equals("A5"))
{
A5_InProcess = false;
}
else if (name.Equals("A6"))
{
A6_InProcess = false;
}
});
}
public void FinishLeave(string name)
{
Task.Factory.StartNew(delegate
{
SetStatus(name, "", ClientAction.FinishLeave);
Thread.Sleep(15000);
if (name.Equals("A5"))
{
A5_InProcess = false;
}
else if (name.Equals("A6"))
{
A6_InProcess = false;
}
});
}
private bool SetStatus(string name, string shelfId = "", ClientAction action = ClientAction.None, ClientLevel level = ClientLevel.Low)
{
// if (!agvClient.IsConn)
// {
// LogUtil.error("SetStatus AGV服务未连接!");
// return false;
// }
if (actionMap.ContainsKey(name))
{
ClientAction currA = actionMap[name]; //相同状态就设置一次
if (currA.Equals(action) && shelfId == "")
{
return false;
}
// actionMap[name] = action;
// agvClient.SetStatus(name, shelfId, action, level);
//LogUtil.info("设置 " + name + " [" + shelfId + "] " + action.ToString());
return true;
}
agvClient.SetStatus(name, shelfId, action, level);
//actionMap.Add(name, action);
//LogUtil.info("设置 " + name + " ["+ shelfId + "] "+ action.ToString());
return true;
}
public bool ISConnected()
{
if (agvClient == null)
{
return false;
}
return agvClient.IsConn;
}
public void Dispose()
{
try
{
if (agvClient != null)
{
agvClient.Close();
LogUtil.info("关闭AGV服务");
}
}
catch (Exception ex)
{
LogUtil.error("关闭AGV服务 " + 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>
/// 双层流水线当前运动信息类(出入库状态,步骤记录)
/// </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; }
}
public bool IsTimeOut(int timeOutSeconds = 60)
{
TimeSpan span = DateTime.Now - LastSetpTime;
if (span.TotalSeconds > timeOutSeconds)
{
return true;
}
return false;
}
public string SLog
{
get { return " "+moveType+" " + MoveStep + " "; }
}
public TimeSpan StepSpan()
{
TimeSpan span = DateTime.Now - LastSetpTime;
return span;
}
/// <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>
/// 双层流水线运动步骤记录
/// </summary>
public MoveStep MoveStep
{
get { return moveStep; }
}
/// <summary>
/// 是否可以重写IO
/// </summary>
public bool CanRMoveIO = true;
public void NextMoveStep(MoveStep step)
{
PreMoveStep = moveStep;
moveStep = step;
LastSetpTime = DateTime.Now;
IsInWait = true;
WaitList = new List<WaitResultInfo>();
OneWaitCanEndStep = false;
CanWhileCount = 5;
TimeOutSeconds = 60;
CanRMoveIO = true;
}
/// <summary>
/// 当前步骤执行完成
/// </summary>
public void EndStepWait()
{
IsInWait = false;
WaitList = new List<WaitResultInfo>();
}
public void NewMove(LineMoveType type ,MoveStep step=MoveStep.Wait )
{
moveStep = step;
this.moveType = type;
LastSetpTime = DateTime.Now;
IsInWait = true;
WaitList = new List<WaitResultInfo>();
OneWaitCanEndStep = false;
CanWhileCount = 5;
TimeOutSeconds = 60;
CanRMoveIO = true;
}
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;
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 static WaitResultInfo WaitAbb(string abbip)
{
WaitResultInfo wait = new WaitResultInfo();
wait.CanWhileMoveCount = 0;
wait.WaitType = 7;
wait.IoType = abbip;
return wait;
}
public string ToStr()
{
if (WaitType == 1)
{
}
else if (WaitType == 2)
{
return "IO[" + IoType + "=" + IoValue + "]";
}
else if (WaitType == 3)
{
return "Time[" + TimeMSeconds + "ms]";
}
else if (WaitType == 7)
{
return "ABB["+IoType+"]";
}
else
{
return "[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;
/// <summary>
/// 等待机器人运动
/// </summary>
internal static int W007_WaitAbb = 7;
}
public enum LineMoveType
{
/// <summary>
/// 没有任何操作
/// </summary>
None = 0,
/// <summary>
/// 料架入流水线处理
/// </summary>
LeftShelf = 1,
/// <summary>
/// S1工位料架处理
/// </summary>
S1Shelf = 2,
/// <summary>
/// 机器人放料
/// </summary>
PutTray = 3,
/// <summary>
/// 原点返回
/// </summary>
ReturnHome = 4,
/// <summary>
/// 重置
/// </summary>
StoreReset = 5,
/// <summary>
/// 左侧工作位到缓存
/// </summary>
LTransWork2Buf,
/// <summary>
/// 左侧缓存到工作
/// </summary>
LTransBuf2Work,
/// <summary>
/// 右侧工作位到缓存
/// </summary>
RTransWork2Buf,
/// <summary>
/// 右侧缓存到工作
/// </summary>
RTransBuf2Work,
}
}
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 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.DOList.ContainsKey(ioType))
{
ConfigIO configIo = LineManager.Config.DOList[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.None;
if (LineManager.Config.DIList.ContainsKey(ioType))
{
ConfigIO configIo = LineManager.Config.DIList[ioType];
ioValue = instance.GetDIValue(configIo.IO_IP, configIo.SlaveID, configIo.GetIOAddr());
//UpdateDoValue(ioType, ioValue);
}
else if (LineManager.Config.DOList.ContainsKey(ioType))
{
ConfigIO configIo = LineManager.Config.DOList[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.None;
ConfigIO configIo = GetDO(ioType );
if (configIo != null)
{
ioValue = instance.GetDOValue(configIo.IO_IP, configIo.SlaveID, configIo.GetIOAddr());
}
else
{
LogUtil.error("没有DO=" + ioType);
}
return ioValue;
}
public static IO_VALUE DIValue(string ioType )
{
IO_VALUE ioValue = IO_VALUE.None;
ConfigIO configIo = GetDI(ioType );
if (configIo != null)
{
ioValue = instance.GetDIValue(configIo.IO_IP, configIo.SlaveID, configIo.GetIOAddr());
}
else
{
LogUtil.error("未找到 DI [" + ioType + "] ");
}
return ioValue;
}
private static ConfigIO GetDI(string ioType )
{
ConfigIO configIo = null;
if (LineManager.Config.DIList.ContainsKey(ioType))
{
return LineManager.Config.DIList[ioType];
}
return configIo;
}
private static ConfigIO GetDO(string ioType )
{
ConfigIO configIo = null;
if (LineManager.Config.DOList.ContainsKey(ioType))
{
return LineManager.Config.DOList[ioType];
}
return configIo;
}
#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();
}
}
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
{
private static bool IsOpen = false;
public static void Open(string[] iparray)
{
if (IsOpen)
{
return;
}
try
{
RFIDAutoReader.Open(null, iparray);
IsOpen = true;
}
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);
//if (bdata == null || data.NumStr().EndsWith("00"))
//{
// LogUtil.error("RFID [ " + ip + " ] 读到数据 [" + data.NumStr() + "] ,重连rfid并重新读取一次");
// RFIDAutoReader.ReOpen(ip);
// bdata = RFIDAutoReader.Read(ip, isClear);
// data = new RFIDData(bdata);
// LogUtil.error("RFID [ " + ip + " ] 重连后读取到数据 [" + data.NumStr() + "] ");
//}
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() + "";
}
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;
}
}
}
此文件类型无法预览
此文件类型无法预览
此文件类型无法预览
此文件的差异被折叠, 点击展开。
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!